diff --git a/.clang-format b/.clang-format index bd446022df..46e7bbce94 100644 --- a/.clang-format +++ b/.clang-format @@ -37,7 +37,7 @@ BinPackParameters: false BreakBeforeBinaryOperators: false BreakBeforeTernaryOperators: true BreakConstructorInitializersBeforeComma: true -ColumnLimit: 80 +ColumnLimit: 120 CommentPragmas: "^ IWYU pragma:" ConstructorInitializerAllOnOneLineOrOnePerLine: true ConstructorInitializerIndentWidth: 4 diff --git a/.cmake-format.yaml b/.cmake-format.yaml new file mode 100644 index 0000000000..1a3337fe8c --- /dev/null +++ b/.cmake-format.yaml @@ -0,0 +1,247 @@ +_help_parse: Options affecting listfile parsing +parse: + _help_additional_commands: + - Specify structure for custom cmake functions + additional_commands: + target_protobuf_sources: + pargs: + - target + - prefix + kwargs: + PROTOS: "*" + LANGUAGE: cpp + IMPORT_DIRS: "*" + GENERATE_EXTENSIONS: "*" + PLUGIN: "*" + _help_override_spec: + - Override configurations per-command where available + override_spec: {} + _help_vartags: + - Specify variable tags. + vartags: [] + _help_proptags: + - Specify property tags. + proptags: [] +_help_format: Options affecting formatting. +format: + _help_disable: + - Disable formatting entirely, making cmake-format a no-op + disable: false + _help_line_width: + - How wide to allow formatted cmake files + line_width: 120 + _help_tab_size: + - How many spaces to tab for indent + tab_size: 4 + _help_use_tabchars: + - If true, lines are indented using tab characters (utf-8 + - 0x09) instead of space characters (utf-8 0x20). + - In cases where the layout would require a fractional tab + - character, the behavior of the fractional indentation is + - governed by + use_tabchars: false + _help_fractional_tab_policy: + - If is True, then the value of this variable + - indicates how fractional indentions are handled during + - whitespace replacement. If set to 'use-space', fractional + - indentation is left as spaces (utf-8 0x20). If set to + - "`round-up` fractional indentation is replaced with a single" + - tab character (utf-8 0x09) effectively shifting the column + - to the next tabstop + fractional_tab_policy: use-space + _help_max_subgroups_hwrap: + - If an argument group contains more than this many sub-groups + - (parg or kwarg groups) then force it to a vertical layout. + max_subgroups_hwrap: 4 + _help_max_pargs_hwrap: + - If a positional argument group contains more than this many + - arguments, then force it to a vertical layout. + max_pargs_hwrap: 5 + _help_max_rows_cmdline: + - If a cmdline positional group consumes more than this many + - lines without nesting, then invalidate the layout (and nest) + max_rows_cmdline: 2 + _help_separate_ctrl_name_with_space: + - If true, separate flow control names from their parentheses + - with a space + separate_ctrl_name_with_space: true + _help_separate_fn_name_with_space: + - If true, separate function names from parentheses with a + - space + separate_fn_name_with_space: false + _help_dangle_parens: + - If a statement is wrapped to more than one line, than dangle + - the closing parenthesis on its own line. + dangle_parens: false + _help_dangle_align: + - If the trailing parenthesis must be 'dangled' on its on + - "line, then align it to this reference: `prefix`: the start" + - "of the statement, `prefix-indent`: the start of the" + - "statement, plus one indentation level, `child`: align to" + - the column of the arguments + dangle_align: prefix + _help_min_prefix_chars: + - If the statement spelling length (including space and + - parenthesis) is smaller than this amount, then force reject + - nested layouts. + min_prefix_chars: 18 + _help_max_prefix_chars: + - If the statement spelling length (including space and + - parenthesis) is larger than the tab width by more than this + - amount, then force reject un-nested layouts. + max_prefix_chars: 10 + _help_max_lines_hwrap: + - If a candidate layout is wrapped horizontally but it exceeds + - this many lines, then reject the layout. + max_lines_hwrap: 2 + _help_line_ending: + - What style line endings to use in the output. + line_ending: unix + _help_command_case: + - Format command names consistently as 'lower' or 'upper' case + command_case: canonical + _help_keyword_case: + - Format keywords consistently as 'lower' or 'upper' case + keyword_case: unchanged + _help_always_wrap: + - A list of command names which should always be wrapped + always_wrap: [] + _help_enable_sort: + - If true, the argument lists which are known to be sortable + - will be sorted lexicographicall + enable_sort: true + _help_autosort: + - If true, the parsers may infer whether or not an argument + - list is sortable (without annotation). + autosort: true + _help_require_valid_layout: + - By default, if cmake-format cannot successfully fit + - everything into the desired linewidth it will apply the + - last, most aggressive attempt that it made. If this flag is + - True, however, cmake-format will print error, exit with non- + - zero status code, and write-out nothing + require_valid_layout: false + _help_layout_passes: + - A dictionary mapping layout nodes to a list of wrap + - decisions. See the documentation for more information. + layout_passes: {} +_help_markup: Options affecting comment reflow and formatting. +markup: + _help_bullet_char: + - What character to use for bulleted lists + bullet_char: "-" + _help_enum_char: + - What character to use as punctuation after numerals in an + - enumerated list + enum_char: . + _help_first_comment_is_literal: + - If comment markup is enabled, don't reflow the first comment + - block in each listfile. Use this to preserve formatting of + - your copyright/license statements. + first_comment_is_literal: false + _help_literal_comment_pattern: + - If comment markup is enabled, don't reflow any comment block + - which matches this (regex) pattern. Default is `None` + - (disabled). + literal_comment_pattern: null + _help_fence_pattern: + - Regular expression to match preformat fences in comments + - default= ``r'^\s*([`~]{3}[`~]*)(.*)$'`` + fence_pattern: ^\s*([`~]{3}[`~]*)(.*)$ + _help_ruler_pattern: + - Regular expression to match rulers in comments default= + - '``r''^\s*[^\w\s]{3}.*[^\w\s]{3}$''``' + ruler_pattern: ^\s*[^\w\s]{3}.*[^\w\s]{3}$ + _help_explicit_trailing_pattern: + - If a comment line matches starts with this pattern then it + - is explicitly a trailing comment for the preceding + - argument. Default is '#<' + explicit_trailing_pattern: "#<" + _help_hashruler_min_length: + - If a comment line starts with at least this many consecutive + - hash characters, then don't lstrip() them off. This allows + - for lazy hash rulers where the first hash char is not + - separated by space + hashruler_min_length: 10 + _help_canonicalize_hashrulers: + - If true, then insert a space between the first hash char and + - remaining hash chars in a hash ruler, and normalize its + - length to fill the column + canonicalize_hashrulers: true + _help_enable_markup: + - enable comment markup parsing and reflow + enable_markup: false +_help_lint: Options affecting the linter +lint: + _help_disabled_codes: + - a list of lint codes to disable + disabled_codes: [] + _help_function_pattern: + - regular expression pattern describing valid function names + function_pattern: "[0-9a-z_]+" + _help_macro_pattern: + - regular expression pattern describing valid macro names + macro_pattern: "[0-9A-Z_]+" + _help_global_var_pattern: + - regular expression pattern describing valid names for + - variables with global (cache) scope + global_var_pattern: "[A-Z][0-9A-Z_]+" + _help_internal_var_pattern: + - regular expression pattern describing valid names for + - variables with global scope (but internal semantic) + internal_var_pattern: _[A-Z][0-9A-Z_]+ + _help_local_var_pattern: + - regular expression pattern describing valid names for + - variables with local scope + local_var_pattern: "[a-z][a-z0-9_]+" + _help_private_var_pattern: + - regular expression pattern describing valid names for + - privatedirectory variables + private_var_pattern: _[0-9a-z_]+ + _help_public_var_pattern: + - regular expression pattern describing valid names for public + - directory variables + public_var_pattern: "[A-Z][0-9A-Z_]+" + _help_argument_var_pattern: + - regular expression pattern describing valid names for + - function/macro arguments and loop variables. + argument_var_pattern: "[a-z][a-z0-9_]+" + _help_keyword_pattern: + - regular expression pattern describing valid names for + - keywords used in functions or macros + keyword_pattern: "[A-Z][0-9A-Z_]+" + _help_max_conditionals_custom_parser: + - In the heuristic for C0201, how many conditionals to match + - within a loop in before considering the loop a parser. + max_conditionals_custom_parser: 2 + _help_min_statement_spacing: + - Require at least this many newlines between statements + min_statement_spacing: 1 + _help_max_statement_spacing: + - Require no more than this many newlines between statements + max_statement_spacing: 2 + max_returns: 6 + max_branches: 12 + max_arguments: 5 + max_localvars: 15 + max_statements: 50 +_help_encode: Options affecting file encoding +encode: + _help_emit_byteorder_mark: + - If true, emit the unicode byte-order mark (BOM) at the start + - of the file + emit_byteorder_mark: false + _help_input_encoding: + - Specify the encoding of the input file. Defaults to utf-8 + input_encoding: utf-8 + _help_output_encoding: + - Specify the encoding of the output file. Defaults to utf-8. + - Note that cmake only claims to support utf-8 so be careful + - when using anything else + output_encoding: utf-8 +_help_misc: Miscellaneous configurations options. +misc: + _help_per_command: + - A dictionary containing any per-command configuration + - overrides. Currently only `command_case` is supported. + per_command: {} diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS deleted file mode 100644 index bc4fe2febd..0000000000 --- a/.github/CODEOWNERS +++ /dev/null @@ -1,8 +0,0 @@ -# Allow anyone to review any change by default. -* - -# Require the rpc-reviewers team to review changes to the rpc code. -include/xrpl/protocol/ @xrplf/rpc-reviewers -src/libxrpl/protocol/ @xrplf/rpc-reviewers -src/xrpld/rpc/ @xrplf/rpc-reviewers -src/xrpld/app/misc/ @xrplf/rpc-reviewers diff --git a/.github/actions/generate-version/action.yml b/.github/actions/generate-version/action.yml new file mode 100644 index 0000000000..6b84aac2f3 --- /dev/null +++ b/.github/actions/generate-version/action.yml @@ -0,0 +1,44 @@ +name: Generate build version number +description: "Generate build version number." + +outputs: + version: + description: "The generated build version number." + value: ${{ steps.version.outputs.version }} + +runs: + using: composite + steps: + # When a tag is pushed, the version is used as-is. + - name: Generate version for tag event + if: ${{ github.event_name == 'tag' }} + shell: bash + env: + VERSION: ${{ github.ref_name }} + run: echo "VERSION=${VERSION}" >> "${GITHUB_ENV}" + + # When a tag is not pushed, then the version (e.g. 1.2.3-b0) is extracted + # from the BuildInfo.cpp file and the shortened commit hash appended to it. + # We use a plus sign instead of a hyphen because Conan recipe versions do + # not support two hyphens. + - name: Generate version for non-tag event + if: ${{ github.event_name != 'tag' }} + shell: bash + run: | + echo 'Extracting version from BuildInfo.cpp.' + VERSION="$(cat src/libxrpl/protocol/BuildInfo.cpp | grep "versionString =" | awk -F '"' '{print $2}')" + if [[ -z "${VERSION}" ]]; then + echo 'Unable to extract version from BuildInfo.cpp.' + exit 1 + fi + + echo 'Appending shortened commit hash to version.' + SHA='${{ github.sha }}' + VERSION="${VERSION}+${SHA:0:7}" + + echo "VERSION=${VERSION}" >> "${GITHUB_ENV}" + + - name: Output version + id: version + shell: bash + run: echo "version=${VERSION}" >> "${GITHUB_OUTPUT}" diff --git a/.github/actions/setup-conan/action.yml b/.github/actions/setup-conan/action.yml index dedf53f109..9d834884d2 100644 --- a/.github/actions/setup-conan/action.yml +++ b/.github/actions/setup-conan/action.yml @@ -2,11 +2,11 @@ name: Setup Conan description: "Set up Conan configuration, profile, and remote." inputs: - conan_remote_name: + remote_name: description: "The name of the Conan remote to use." required: false default: xrplf - conan_remote_url: + remote_url: description: "The URL of the Conan endpoint to use." required: false default: https://conan.ripplex.io @@ -31,16 +31,16 @@ runs: conan config install conan/profiles/ -tf $(conan config home)/profiles/ echo 'Conan profile:' - conan profile show + conan profile show --profile ci - name: Set up Conan remote shell: bash env: - CONAN_REMOTE_NAME: ${{ inputs.conan_remote_name }} - CONAN_REMOTE_URL: ${{ inputs.conan_remote_url }} + REMOTE_NAME: ${{ inputs.remote_name }} + REMOTE_URL: ${{ inputs.remote_url }} run: | - echo "Adding Conan remote '${CONAN_REMOTE_NAME}' at '${CONAN_REMOTE_URL}'." - conan remote add --index 0 --force "${CONAN_REMOTE_NAME}" "${CONAN_REMOTE_URL}" + echo "Adding Conan remote '${REMOTE_NAME}' at '${REMOTE_URL}'." + conan remote add --index 0 --force "${REMOTE_NAME}" "${REMOTE_URL}" echo 'Listing Conan remotes.' conan remote list diff --git a/.github/scripts/levelization/results/loops.txt b/.github/scripts/levelization/results/loops.txt index d15843ceb0..7914704f9d 100644 --- a/.github/scripts/levelization/results/loops.txt +++ b/.github/scripts/levelization/results/loops.txt @@ -4,14 +4,11 @@ Loop: test.jtx test.toplevel Loop: test.jtx test.unit_test test.unit_test == test.jtx -Loop: xrpld.app xrpld.core - xrpld.app > xrpld.core - Loop: xrpld.app xrpld.overlay - xrpld.overlay > xrpld.app + xrpld.overlay ~= xrpld.app Loop: xrpld.app xrpld.peerfinder - xrpld.peerfinder ~= xrpld.app + xrpld.peerfinder == xrpld.app Loop: xrpld.app xrpld.rpc xrpld.rpc > xrpld.app diff --git a/.github/scripts/levelization/results/ordering.txt b/.github/scripts/levelization/results/ordering.txt index c9c65fb0dd..5f8812c49b 100644 --- a/.github/scripts/levelization/results/ordering.txt +++ b/.github/scripts/levelization/results/ordering.txt @@ -1,4 +1,6 @@ libxrpl.basics > xrpl.basics +libxrpl.conditions > xrpl.basics +libxrpl.conditions > xrpl.conditions libxrpl.core > xrpl.basics libxrpl.core > xrpl.core libxrpl.crypto > xrpl.basics @@ -17,12 +19,15 @@ libxrpl.nodestore > xrpl.protocol libxrpl.protocol > xrpl.basics libxrpl.protocol > xrpl.json libxrpl.protocol > xrpl.protocol +libxrpl.rdb > xrpl.basics +libxrpl.rdb > xrpl.rdb libxrpl.resource > xrpl.basics libxrpl.resource > xrpl.json libxrpl.resource > xrpl.resource libxrpl.server > xrpl.basics libxrpl.server > xrpl.json libxrpl.server > xrpl.protocol +libxrpl.server > xrpl.rdb libxrpl.server > xrpl.server libxrpl.shamap > xrpl.basics libxrpl.shamap > xrpl.protocol @@ -41,7 +46,9 @@ test.app > xrpl.json test.app > xrpl.ledger test.app > xrpl.nodestore test.app > xrpl.protocol +test.app > xrpl.rdb test.app > xrpl.resource +test.app > xrpl.server test.basics > test.jtx test.basics > test.unit_test test.basics > xrpl.basics @@ -51,7 +58,7 @@ test.basics > xrpl.json test.basics > xrpl.protocol test.beast > xrpl.basics test.conditions > xrpl.basics -test.conditions > xrpld.conditions +test.conditions > xrpl.conditions test.consensus > test.csf test.consensus > test.toplevel test.consensus > test.unit_test @@ -67,6 +74,7 @@ test.core > xrpl.basics test.core > xrpl.core test.core > xrpld.core test.core > xrpl.json +test.core > xrpl.rdb test.core > xrpl.server test.csf > xrpl.basics test.csf > xrpld.consensus @@ -95,8 +103,8 @@ test.nodestore > test.jtx test.nodestore > test.toplevel test.nodestore > test.unit_test test.nodestore > xrpl.basics -test.nodestore > xrpld.core test.nodestore > xrpl.nodestore +test.nodestore > xrpl.rdb test.overlay > test.jtx test.overlay > test.toplevel test.overlay > test.unit_test @@ -104,6 +112,7 @@ test.overlay > xrpl.basics test.overlay > xrpld.app test.overlay > xrpld.overlay test.overlay > xrpld.peerfinder +test.overlay > xrpl.nodestore test.overlay > xrpl.protocol test.overlay > xrpl.shamap test.peerfinder > test.beast @@ -130,6 +139,7 @@ test.rpc > xrpld.rpc test.rpc > xrpl.json test.rpc > xrpl.protocol test.rpc > xrpl.resource +test.rpc > xrpl.server test.server > test.jtx test.server > test.toplevel test.server > test.unit_test @@ -150,39 +160,52 @@ test.unit_test > xrpl.basics tests.libxrpl > xrpl.basics tests.libxrpl > xrpl.json tests.libxrpl > xrpl.net +xrpl.conditions > xrpl.basics +xrpl.conditions > xrpl.protocol xrpl.core > xrpl.basics xrpl.core > xrpl.json +xrpl.core > xrpl.ledger +xrpl.core > xrpl.protocol xrpl.json > xrpl.basics xrpl.ledger > xrpl.basics xrpl.ledger > xrpl.protocol +xrpl.ledger > xrpl.server xrpl.net > xrpl.basics xrpl.nodestore > xrpl.basics xrpl.nodestore > xrpl.protocol xrpl.protocol > xrpl.basics xrpl.protocol > xrpl.json +xrpl.rdb > xrpl.basics +xrpl.rdb > xrpl.core +xrpl.rdb > xrpl.protocol xrpl.resource > xrpl.basics xrpl.resource > xrpl.json xrpl.resource > xrpl.protocol xrpl.server > xrpl.basics +xrpl.server > xrpl.core xrpl.server > xrpl.json xrpl.server > xrpl.protocol +xrpl.server > xrpl.rdb +xrpl.server > xrpl.resource +xrpl.server > xrpl.shamap xrpl.shamap > xrpl.basics xrpl.shamap > xrpl.nodestore xrpl.shamap > xrpl.protocol xrpld.app > test.unit_test xrpld.app > xrpl.basics +xrpld.app > xrpl.conditions xrpld.app > xrpl.core -xrpld.app > xrpld.conditions xrpld.app > xrpld.consensus +xrpld.app > xrpld.core xrpld.app > xrpl.json xrpld.app > xrpl.ledger xrpld.app > xrpl.net xrpld.app > xrpl.nodestore xrpld.app > xrpl.protocol +xrpld.app > xrpl.rdb xrpld.app > xrpl.resource +xrpld.app > xrpl.server xrpld.app > xrpl.shamap -xrpld.conditions > xrpl.basics -xrpld.conditions > xrpl.protocol xrpld.consensus > xrpl.basics xrpld.consensus > xrpl.json xrpld.consensus > xrpl.protocol @@ -191,17 +214,20 @@ xrpld.core > xrpl.core xrpld.core > xrpl.json xrpld.core > xrpl.net xrpld.core > xrpl.protocol +xrpld.core > xrpl.rdb xrpld.overlay > xrpl.basics xrpld.overlay > xrpl.core xrpld.overlay > xrpld.core xrpld.overlay > xrpld.peerfinder xrpld.overlay > xrpl.json xrpld.overlay > xrpl.protocol +xrpld.overlay > xrpl.rdb xrpld.overlay > xrpl.resource xrpld.overlay > xrpl.server xrpld.peerfinder > xrpl.basics xrpld.peerfinder > xrpld.core xrpld.peerfinder > xrpl.protocol +xrpld.peerfinder > xrpl.rdb xrpld.perflog > xrpl.basics xrpld.perflog > xrpl.core xrpld.perflog > xrpld.rpc @@ -214,6 +240,7 @@ xrpld.rpc > xrpl.ledger xrpld.rpc > xrpl.net xrpld.rpc > xrpl.nodestore xrpld.rpc > xrpl.protocol +xrpld.rpc > xrpl.rdb xrpld.rpc > xrpl.resource xrpld.rpc > xrpl.server xrpld.shamap > xrpl.shamap diff --git a/.github/scripts/rename/include.sh b/.github/scripts/rename/include.sh new file mode 100755 index 0000000000..fbf165b975 --- /dev/null +++ b/.github/scripts/rename/include.sh @@ -0,0 +1,30 @@ +#!/bin/bash + +# Exit the script as soon as an error occurs. +set -e + +# This script checks whether there are no new include guards introduced by a new +# PR, as header files should use "#pragma once" instead. The script assumes any +# include guards will use "XRPL_" as prefix. +# Usage: .github/scripts/rename/include.sh + +if [ "$#" -ne 1 ]; then + echo "Usage: $0 " + exit 1 +fi + +DIRECTORY=$1 +echo "Processing directory: ${DIRECTORY}" +if [ ! -d "${DIRECTORY}" ]; then + echo "Error: Directory '${DIRECTORY}' does not exist." + exit 1 +fi + +find "${DIRECTORY}" -type f \( -name "*.h" -o -name "*.hpp" -o -name "*.ipp" \) | while read -r FILE; do + echo "Processing file: ${FILE}" + if grep -q "#ifndef XRPL_" "${FILE}"; then + echo "Please replace all include guards by #pragma once." + exit 1 + fi +done +echo "Checking complete." diff --git a/.github/scripts/strategy-matrix/generate.py b/.github/scripts/strategy-matrix/generate.py index 5527d4e631..dd25af9368 100755 --- a/.github/scripts/strategy-matrix/generate.py +++ b/.github/scripts/strategy-matrix/generate.py @@ -20,8 +20,8 @@ class Config: Generate a strategy matrix for GitHub Actions CI. On each PR commit we will build a selection of Debian, RHEL, Ubuntu, MacOS, and -Windows configurations, while upon merge into the develop, release, or master -branches, we will build all configurations, and test most of them. +Windows configurations, while upon merge into the develop or release branches, +we will build all configurations, and test most of them. We will further set additional CMake arguments as follows: - All builds will have the `tests`, `werr`, and `xrpld` options. @@ -51,22 +51,20 @@ def generate_strategy_matrix(all: bool, config: Config) -> list: # Only generate a subset of configurations in PRs. if not all: # Debian: - # - Bookworm using GCC 13: Release and Unity on linux/amd64, set - # the reference fee to 500. - # - Bookworm using GCC 15: Debug and no Unity on linux/amd64, enable - # code coverage (which will be done below). - # - Bookworm using Clang 16: Debug and no Unity on linux/arm64, - # enable voidstar. - # - Bookworm using Clang 17: Release and no Unity on linux/amd64, - # set the reference fee to 1000. - # - Bookworm using Clang 20: Debug and Unity on linux/amd64. + # - Bookworm using GCC 13: Release on linux/amd64, set the reference + # fee to 500. + # - Bookworm using GCC 15: Debug on linux/amd64, enable code + # coverage (which will be done below). + # - Bookworm using Clang 16: Debug on linux/arm64, enable voidstar. + # - Bookworm using Clang 17: Release on linux/amd64, set the + # reference fee to 1000. + # - Bookworm using Clang 20: Debug on linux/amd64. if os["distro_name"] == "debian": skip = True if os["distro_version"] == "bookworm": if ( f"{os['compiler_name']}-{os['compiler_version']}" == "gcc-13" and build_type == "Release" - and "-Dunity=ON" in cmake_args and architecture["platform"] == "linux/amd64" ): cmake_args = f"-DUNIT_TEST_REFERENCE_FEE=500 {cmake_args}" @@ -74,14 +72,12 @@ def generate_strategy_matrix(all: bool, config: Config) -> list: if ( f"{os['compiler_name']}-{os['compiler_version']}" == "gcc-15" and build_type == "Debug" - and "-Dunity=OFF" in cmake_args and architecture["platform"] == "linux/amd64" ): skip = False if ( f"{os['compiler_name']}-{os['compiler_version']}" == "clang-16" and build_type == "Debug" - and "-Dunity=OFF" in cmake_args and architecture["platform"] == "linux/arm64" ): cmake_args = f"-Dvoidstar=ON {cmake_args}" @@ -89,7 +85,6 @@ def generate_strategy_matrix(all: bool, config: Config) -> list: if ( f"{os['compiler_name']}-{os['compiler_version']}" == "clang-17" and build_type == "Release" - and "-Dunity=ON" in cmake_args and architecture["platform"] == "linux/amd64" ): cmake_args = f"-DUNIT_TEST_REFERENCE_FEE=1000 {cmake_args}" @@ -97,7 +92,6 @@ def generate_strategy_matrix(all: bool, config: Config) -> list: if ( f"{os['compiler_name']}-{os['compiler_version']}" == "clang-20" and build_type == "Debug" - and "-Dunity=ON" in cmake_args and architecture["platform"] == "linux/amd64" ): skip = False @@ -105,15 +99,14 @@ def generate_strategy_matrix(all: bool, config: Config) -> list: continue # RHEL: - # - 9 using GCC 12: Debug and Unity on linux/amd64. - # - 10 using Clang: Release and no Unity on linux/amd64. + # - 9 using GCC 12: Debug on linux/amd64. + # - 10 using Clang: Release on linux/amd64. if os["distro_name"] == "rhel": skip = True if os["distro_version"] == "9": if ( f"{os['compiler_name']}-{os['compiler_version']}" == "gcc-12" and build_type == "Debug" - and "-Dunity=ON" in cmake_args and architecture["platform"] == "linux/amd64" ): skip = False @@ -121,7 +114,6 @@ def generate_strategy_matrix(all: bool, config: Config) -> list: if ( f"{os['compiler_name']}-{os['compiler_version']}" == "clang-any" and build_type == "Release" - and "-Dunity=OFF" in cmake_args and architecture["platform"] == "linux/amd64" ): skip = False @@ -129,17 +121,16 @@ def generate_strategy_matrix(all: bool, config: Config) -> list: continue # Ubuntu: - # - Jammy using GCC 12: Debug and no Unity on linux/arm64. - # - Noble using GCC 14: Release and Unity on linux/amd64. - # - Noble using Clang 18: Debug and no Unity on linux/amd64. - # - Noble using Clang 19: Release and Unity on linux/arm64. + # - Jammy using GCC 12: Debug on linux/arm64. + # - Noble using GCC 14: Release on linux/amd64. + # - Noble using Clang 18: Debug on linux/amd64. + # - Noble using Clang 19: Release on linux/arm64. if os["distro_name"] == "ubuntu": skip = True if os["distro_version"] == "jammy": if ( f"{os['compiler_name']}-{os['compiler_version']}" == "gcc-12" and build_type == "Debug" - and "-Dunity=OFF" in cmake_args and architecture["platform"] == "linux/arm64" ): skip = False @@ -147,21 +138,18 @@ def generate_strategy_matrix(all: bool, config: Config) -> list: if ( f"{os['compiler_name']}-{os['compiler_version']}" == "gcc-14" and build_type == "Release" - and "-Dunity=ON" in cmake_args and architecture["platform"] == "linux/amd64" ): skip = False if ( f"{os['compiler_name']}-{os['compiler_version']}" == "clang-18" and build_type == "Debug" - and "-Dunity=OFF" in cmake_args and architecture["platform"] == "linux/amd64" ): skip = False if ( f"{os['compiler_name']}-{os['compiler_version']}" == "clang-19" and build_type == "Release" - and "-Dunity=ON" in cmake_args and architecture["platform"] == "linux/arm64" ): skip = False @@ -169,20 +157,16 @@ def generate_strategy_matrix(all: bool, config: Config) -> list: continue # MacOS: - # - Debug and no Unity on macos/arm64. + # - Debug on macos/arm64. if os["distro_name"] == "macos" and not ( - build_type == "Debug" - and "-Dunity=OFF" in cmake_args - and architecture["platform"] == "macos/arm64" + build_type == "Debug" and architecture["platform"] == "macos/arm64" ): continue # Windows: - # - Release and Unity on windows/amd64. + # - Release on windows/amd64. if os["distro_name"] == "windows" and not ( - build_type == "Release" - and "-Dunity=ON" in cmake_args - and architecture["platform"] == "windows/amd64" + build_type == "Release" and architecture["platform"] == "windows/amd64" ): continue @@ -209,18 +193,28 @@ def generate_strategy_matrix(all: bool, config: Config) -> list: ): continue - # Enable code coverage for Debian Bookworm using GCC 15 in Debug and no - # Unity on linux/amd64 + # Enable code coverage for Debian Bookworm using GCC 15 in Debug on + # linux/amd64 if ( - f"{os['compiler_name']}-{os['compiler_version']}" == "gcc-15" + f"{os['distro_name']}-{os['distro_version']}" == "debian-bookworm" + and f"{os['compiler_name']}-{os['compiler_version']}" == "gcc-15" and build_type == "Debug" - and "-Dunity=OFF" in cmake_args and architecture["platform"] == "linux/amd64" ): - cmake_args = f"-Dcoverage=ON -Dcoverage_format=xml -DCODE_COVERAGE_VERBOSE=ON -DCMAKE_C_FLAGS=-O0 -DCMAKE_CXX_FLAGS=-O0 {cmake_args}" + cmake_args = f"{cmake_args} -Dcoverage=ON -Dcoverage_format=xml -DCODE_COVERAGE_VERBOSE=ON -DCMAKE_C_FLAGS=-O0 -DCMAKE_CXX_FLAGS=-O0" + + # Enable unity build for Ubuntu Jammy using GCC 12 in Debug on + # linux/amd64. + if ( + f"{os['distro_name']}-{os['distro_version']}" == "ubuntu-jammy" + and f"{os['compiler_name']}-{os['compiler_version']}" == "gcc-12" + and build_type == "Debug" + and architecture["platform"] == "linux/amd64" + ): + cmake_args = f"{cmake_args} -Dunity=ON" # Generate a unique name for the configuration, e.g. macos-arm64-debug - # or debian-bookworm-gcc-12-amd64-release-unity. + # or debian-bookworm-gcc-12-amd64-release. config_name = os["distro_name"] if (n := os["distro_version"]) != "": config_name += f"-{n}" diff --git a/.github/scripts/strategy-matrix/linux.json b/.github/scripts/strategy-matrix/linux.json index e64a05f925..4943579be8 100644 --- a/.github/scripts/strategy-matrix/linux.json +++ b/.github/scripts/strategy-matrix/linux.json @@ -208,5 +208,5 @@ } ], "build_type": ["Debug", "Release"], - "cmake_args": ["-Dunity=OFF", "-Dunity=ON"] + "cmake_args": [""] } diff --git a/.github/scripts/strategy-matrix/macos.json b/.github/scripts/strategy-matrix/macos.json index 14b6089620..6fc44d0f80 100644 --- a/.github/scripts/strategy-matrix/macos.json +++ b/.github/scripts/strategy-matrix/macos.json @@ -15,8 +15,5 @@ } ], "build_type": ["Debug", "Release"], - "cmake_args": [ - "-Dunity=OFF -DCMAKE_POLICY_VERSION_MINIMUM=3.5", - "-Dunity=ON -DCMAKE_POLICY_VERSION_MINIMUM=3.5" - ] + "cmake_args": ["-DCMAKE_POLICY_VERSION_MINIMUM=3.5"] } diff --git a/.github/scripts/strategy-matrix/windows.json b/.github/scripts/strategy-matrix/windows.json index 8637b31012..8c536c70f2 100644 --- a/.github/scripts/strategy-matrix/windows.json +++ b/.github/scripts/strategy-matrix/windows.json @@ -15,5 +15,5 @@ } ], "build_type": ["Debug", "Release"], - "cmake_args": ["-Dunity=OFF", "-Dunity=ON"] + "cmake_args": [""] } diff --git a/.github/workflows/on-pr.yml b/.github/workflows/on-pr.yml index 3aa48ac070..46f6b7500a 100644 --- a/.github/workflows/on-pr.yml +++ b/.github/workflows/on-pr.yml @@ -1,7 +1,8 @@ # This workflow runs all workflows to check, build and test the project on # various Linux flavors, as well as on MacOS and Windows, on every push to a # user branch. However, it will not run if the pull request is a draft unless it -# has the 'DraftRunCI' label. +# has the 'DraftRunCI' label. For commits to PRs that target a release branch, +# it also uploads the libxrpl recipe to the Conan remote. name: PR on: @@ -53,12 +54,12 @@ jobs: .github/scripts/rename/** .github/workflows/reusable-check-levelization.yml .github/workflows/reusable-check-rename.yml - .github/workflows/reusable-notify-clio.yml .github/workflows/on-pr.yml # Keep the paths below in sync with those in `on-trigger.yml`. .github/actions/build-deps/** .github/actions/build-test/** + .github/actions/generate-version/** .github/actions/setup-conan/** .github/scripts/strategy-matrix/** .github/workflows/reusable-build.yml @@ -66,6 +67,7 @@ jobs: .github/workflows/reusable-build-test.yml .github/workflows/reusable-strategy-matrix.yml .github/workflows/reusable-test.yml + .github/workflows/reusable-upload-recipe.yml .codecov.yml cmake/** conan/** @@ -121,22 +123,42 @@ jobs: secrets: CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} - notify-clio: + upload-recipe: needs: - should-run - build-test - if: ${{ needs.should-run.outputs.go == 'true' && (startsWith(github.base_ref, 'release') || github.base_ref == 'master') }} - uses: ./.github/workflows/reusable-notify-clio.yml + # Only run when committing to a PR that targets a release branch in the + # XRPLF repository. + if: ${{ github.repository_owner == 'XRPLF' && needs.should-run.outputs.go == 'true' && startsWith(github.ref, 'refs/heads/release') }} + uses: ./.github/workflows/reusable-upload-recipe.yml secrets: - clio_notify_token: ${{ secrets.CLIO_NOTIFY_TOKEN }} - conan_remote_username: ${{ secrets.CONAN_REMOTE_USERNAME }} - conan_remote_password: ${{ secrets.CONAN_REMOTE_PASSWORD }} + remote_username: ${{ secrets.CONAN_REMOTE_USERNAME }} + remote_password: ${{ secrets.CONAN_REMOTE_PASSWORD }} + + notify-clio: + needs: upload-recipe + runs-on: ubuntu-latest + steps: + # Notify the Clio repository about the newly proposed release version, so + # it can be checked for compatibility before the release is actually made. + - name: Notify Clio + env: + GH_TOKEN: ${{ secrets.CLIO_NOTIFY_TOKEN }} + PR_URL: ${{ github.event.pull_request.html_url }} + run: | + gh api --method POST -H "Accept: application/vnd.github+json" -H "X-GitHub-Api-Version: 2022-11-28" \ + /repos/xrplf/clio/dispatches -f "event_type=check_libxrpl" \ + -F "client_payload[ref]=${{ needs.upload-recipe.outputs.recipe_ref }}" \ + -F "client_payload[pr_url]=${PR_URL}" passed: if: failure() || cancelled() needs: - - build-test - check-levelization + - check-rename + - build-test + - upload-recipe + - notify-clio runs-on: ubuntu-latest steps: - name: Fail diff --git a/.github/workflows/on-tag.yml b/.github/workflows/on-tag.yml new file mode 100644 index 0000000000..c6361b4016 --- /dev/null +++ b/.github/workflows/on-tag.yml @@ -0,0 +1,25 @@ +# This workflow uploads the libxrpl recipe to the Conan remote when a versioned +# tag is pushed. +name: Tag + +on: + push: + tags: + - "v*" + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +defaults: + run: + shell: bash + +jobs: + upload-recipe: + # Only run when a tag is pushed to the XRPLF repository. + if: ${{ github.repository_owner == 'XRPLF' }} + uses: ./.github/workflows/reusable-upload-recipe.yml + secrets: + remote_username: ${{ secrets.CONAN_REMOTE_USERNAME }} + remote_password: ${{ secrets.CONAN_REMOTE_PASSWORD }} diff --git a/.github/workflows/on-trigger.yml b/.github/workflows/on-trigger.yml index 2c63c2baa5..210670f5a1 100644 --- a/.github/workflows/on-trigger.yml +++ b/.github/workflows/on-trigger.yml @@ -1,9 +1,7 @@ -# This workflow runs all workflows to build the dependencies required for the -# project on various Linux flavors, as well as on MacOS and Windows, on a -# scheduled basis, on merge into the 'develop', 'release', or 'master' branches, -# or manually. The missing commits check is only run when the code is merged -# into the 'develop' or 'release' branches, and the documentation is built when -# the code is merged into the 'develop' branch. +# This workflow runs all workflows to build and test the code on various Linux +# flavors, as well as on MacOS and Windows, on a scheduled basis, on merge into +# the 'develop' or 'release*' branches, or when requested manually. Upon pushes +# to the develop branch it also uploads the libxrpl recipe to the Conan remote. name: Trigger on: @@ -11,7 +9,6 @@ on: branches: - "develop" - "release*" - - "master" paths: # These paths are unique to `on-trigger.yml`. - ".github/workflows/on-trigger.yml" @@ -19,6 +16,7 @@ on: # Keep the paths below in sync with those in `on-pr.yml`. - ".github/actions/build-deps/**" - ".github/actions/build-test/**" + - ".github/actions/generate-version/**" - ".github/actions/setup-conan/**" - ".github/scripts/strategy-matrix/**" - ".github/workflows/reusable-build.yml" @@ -26,6 +24,7 @@ on: - ".github/workflows/reusable-build-test.yml" - ".github/workflows/reusable-strategy-matrix.yml" - ".github/workflows/reusable-test.yml" + - ".github/workflows/reusable-upload-recipe.yml" - ".codecov.yml" - "cmake/**" - "conan/**" @@ -70,11 +69,20 @@ jobs: with: # Enable ccache only for events targeting the XRPLF repository, since # other accounts will not have access to our remote cache storage. - # However, we do not enable ccache for events targeting the master or a - # release branch, to protect against the rare case that the output - # produced by ccache is not identical to a regular compilation. - ccache_enabled: ${{ github.repository_owner == 'XRPLF' && !(github.base_ref == 'master' || startsWith(github.base_ref, 'release')) }} + # However, we do not enable ccache for events targeting a release branch, + # to protect against the rare case that the output produced by ccache is + # not identical to a regular compilation. + ccache_enabled: ${{ github.repository_owner == 'XRPLF' && !startsWith(github.ref, 'refs/heads/release') }} os: ${{ matrix.os }} strategy_matrix: ${{ github.event_name == 'schedule' && 'all' || 'minimal' }} secrets: CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} + + upload-recipe: + needs: build-test + # Only run when pushing to the develop branch in the XRPLF repository. + if: ${{ github.repository_owner == 'XRPLF' && github.event_name == 'push' && github.ref == 'refs/heads/develop' }} + uses: ./.github/workflows/reusable-upload-recipe.yml + secrets: + remote_username: ${{ secrets.CONAN_REMOTE_USERNAME }} + remote_password: ${{ secrets.CONAN_REMOTE_PASSWORD }} diff --git a/.github/workflows/pre-commit.yml b/.github/workflows/pre-commit.yml index 00754e5eae..f43275201c 100644 --- a/.github/workflows/pre-commit.yml +++ b/.github/workflows/pre-commit.yml @@ -3,13 +3,15 @@ name: Run pre-commit hooks on: pull_request: push: - branches: [develop, release, master] + branches: + - "develop" + - "release*" workflow_dispatch: jobs: # Call the workflow in the XRPLF/actions repo that runs the pre-commit hooks. run-hooks: - uses: XRPLF/actions/.github/workflows/pre-commit.yml@282890f46d6921249d5659dd38babcb0bd8aef48 + uses: XRPLF/actions/.github/workflows/pre-commit.yml@320be44621ca2a080f05aeb15817c44b84518108 with: runs_on: ubuntu-latest container: '{ "image": "ghcr.io/xrplf/ci/tools-rippled-pre-commit:sha-ab4d1f0" }' diff --git a/.github/workflows/publish-docs.yml b/.github/workflows/publish-docs.yml index c37a82a2f3..f61559d6d3 100644 --- a/.github/workflows/publish-docs.yml +++ b/.github/workflows/publish-docs.yml @@ -36,7 +36,7 @@ jobs: uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0 - name: Get number of processors - uses: XRPLF/actions/get-nproc@2ece4ec6ab7de266859a6f053571425b2bd684b6 + uses: XRPLF/actions/get-nproc@cf0433aa74563aead044a1e395610c96d65a37cf id: nproc with: subtract: ${{ env.NPROC_SUBTRACT }} diff --git a/.github/workflows/reusable-build-test-config.yml b/.github/workflows/reusable-build-test-config.yml index eae9570f5a..b976054164 100644 --- a/.github/workflows/reusable-build-test-config.yml +++ b/.github/workflows/reusable-build-test-config.yml @@ -101,13 +101,13 @@ jobs: steps: - name: Cleanup workspace (macOS and Windows) if: ${{ runner.os == 'macOS' || runner.os == 'Windows' }} - uses: XRPLF/actions/cleanup-workspace@2ece4ec6ab7de266859a6f053571425b2bd684b6 + uses: XRPLF/actions/cleanup-workspace@cf0433aa74563aead044a1e395610c96d65a37cf - name: Checkout repository uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0 - name: Prepare runner - uses: XRPLF/actions/prepare-runner@f05cab7b8541eee6473aa42beb9d2fe35608a190 + uses: XRPLF/actions/prepare-runner@2cbf481018d930656e9276fcc20dc0e3a0be5b6d with: enable_ccache: ${{ inputs.ccache_enabled }} @@ -119,12 +119,14 @@ jobs: uses: ./.github/actions/print-env - name: Get number of processors - uses: XRPLF/actions/get-nproc@2ece4ec6ab7de266859a6f053571425b2bd684b6 + uses: XRPLF/actions/get-nproc@cf0433aa74563aead044a1e395610c96d65a37cf id: nproc with: subtract: ${{ inputs.nproc_subtract }} - name: Setup Conan + env: + SANITIZERS: ${{ inputs.sanitizers }} uses: ./.github/actions/setup-conan - name: Build dependencies diff --git a/.github/workflows/reusable-check-rename.yml b/.github/workflows/reusable-check-rename.yml index af55084405..a73ac49b7d 100644 --- a/.github/workflows/reusable-check-rename.yml +++ b/.github/workflows/reusable-check-rename.yml @@ -31,6 +31,8 @@ jobs: run: .github/scripts/rename/namespace.sh . - name: Check config name run: .github/scripts/rename/config.sh . + - name: Check include guards + run: .github/scripts/rename/include.sh . - name: Check for differences env: MESSAGE: | diff --git a/.github/workflows/reusable-notify-clio.yml b/.github/workflows/reusable-notify-clio.yml deleted file mode 100644 index 0941d5f2e3..0000000000 --- a/.github/workflows/reusable-notify-clio.yml +++ /dev/null @@ -1,91 +0,0 @@ -# This workflow exports the built libxrpl package to the Conan remote on a -# a channel named after the pull request, and notifies the Clio repository about -# the new version so it can check for compatibility. -name: Notify Clio - -# This workflow can only be triggered by other workflows. -on: - workflow_call: - inputs: - conan_remote_name: - description: "The name of the Conan remote to use." - required: false - type: string - default: xrplf - conan_remote_url: - description: "The URL of the Conan endpoint to use." - required: false - type: string - default: https://conan.ripplex.io - secrets: - clio_notify_token: - description: "The GitHub token to notify Clio about new versions." - required: true - conan_remote_username: - description: "The username for logging into the Conan remote." - required: true - conan_remote_password: - description: "The password for logging into the Conan remote." - required: true - -concurrency: - group: ${{ github.workflow }}-${{ github.ref }}-clio - cancel-in-progress: true - -defaults: - run: - shell: bash - -jobs: - upload: - if: ${{ github.event.pull_request.head.repo.full_name == github.repository }} - runs-on: ubuntu-latest - container: ghcr.io/xrplf/ci/ubuntu-noble:gcc-13-sha-5dd7158 - steps: - - name: Checkout repository - uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0 - - name: Generate outputs - id: generate - env: - PR_NUMBER: ${{ github.event.pull_request.number }} - run: | - echo 'Generating user and channel.' - echo "user=clio" >> "${GITHUB_OUTPUT}" - echo "channel=pr_${PR_NUMBER}" >> "${GITHUB_OUTPUT}" - echo 'Extracting version.' - echo "version=$(cat src/libxrpl/protocol/BuildInfo.cpp | grep "versionString =" | awk -F '"' '{print $2}')" >> "${GITHUB_OUTPUT}" - - name: Calculate conan reference - id: conan_ref - run: | - echo "conan_ref=${{ steps.generate.outputs.version }}@${{ steps.generate.outputs.user }}/${{ steps.generate.outputs.channel }}" >> "${GITHUB_OUTPUT}" - - name: Set up Conan - uses: ./.github/actions/setup-conan - with: - conan_remote_name: ${{ inputs.conan_remote_name }} - conan_remote_url: ${{ inputs.conan_remote_url }} - - name: Log into Conan remote - env: - CONAN_REMOTE_NAME: ${{ inputs.conan_remote_name }} - run: conan remote login "${CONAN_REMOTE_NAME}" "${{ secrets.conan_remote_username }}" --password "${{ secrets.conan_remote_password }}" - - name: Upload package - env: - CONAN_REMOTE_NAME: ${{ inputs.conan_remote_name }} - run: | - conan export --user=${{ steps.generate.outputs.user }} --channel=${{ steps.generate.outputs.channel }} . - conan upload --confirm --check --remote="${CONAN_REMOTE_NAME}" xrpl/${{ steps.conan_ref.outputs.conan_ref }} - outputs: - conan_ref: ${{ steps.conan_ref.outputs.conan_ref }} - - notify: - needs: upload - runs-on: ubuntu-latest - steps: - - name: Notify Clio - env: - GH_TOKEN: ${{ secrets.clio_notify_token }} - PR_URL: ${{ github.event.pull_request.html_url }} - run: | - gh api --method POST -H "Accept: application/vnd.github+json" -H "X-GitHub-Api-Version: 2022-11-28" \ - /repos/xrplf/clio/dispatches -f "event_type=check_libxrpl" \ - -F "client_payload[conan_ref]=${{ needs.upload.outputs.conan_ref }}" \ - -F "client_payload[pr_url]=${PR_URL}" diff --git a/.github/workflows/reusable-upload-recipe.yml b/.github/workflows/reusable-upload-recipe.yml new file mode 100644 index 0000000000..79af516fb3 --- /dev/null +++ b/.github/workflows/reusable-upload-recipe.yml @@ -0,0 +1,97 @@ +# This workflow exports the built libxrpl package to the Conan remote. +name: Upload Conan recipe + +# This workflow can only be triggered by other workflows. +on: + workflow_call: + inputs: + remote_name: + description: "The name of the Conan remote to use." + required: false + type: string + default: xrplf + remote_url: + description: "The URL of the Conan endpoint to use." + required: false + type: string + default: https://conan.ripplex.io + + secrets: + remote_username: + description: "The username for logging into the Conan remote." + required: true + remote_password: + description: "The password for logging into the Conan remote." + required: true + + outputs: + recipe_ref: + description: "The Conan recipe reference ('name/version') that was uploaded." + value: ${{ jobs.upload.outputs.ref }} + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }}-upload-recipe + cancel-in-progress: true + +defaults: + run: + shell: bash + +jobs: + upload: + runs-on: ubuntu-latest + container: ghcr.io/xrplf/ci/ubuntu-noble:gcc-13-sha-5dd7158 + steps: + - name: Checkout repository + uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0 + + - name: Generate build version number + id: version + uses: ./.github/actions/generate-version + + - name: Set up Conan + uses: ./.github/actions/setup-conan + with: + remote_name: ${{ inputs.remote_name }} + remote_url: ${{ inputs.remote_url }} + + - name: Log into Conan remote + env: + REMOTE_NAME: ${{ inputs.remote_name }} + REMOTE_USERNAME: ${{ secrets.remote_username }} + REMOTE_PASSWORD: ${{ secrets.remote_password }} + run: conan remote login "${REMOTE_NAME}" "${REMOTE_USERNAME}" --password "${REMOTE_PASSWORD}" + + - name: Upload Conan recipe (version) + env: + REMOTE_NAME: ${{ inputs.remote_name }} + run: | + conan export . --version=${{ steps.version.outputs.version }} + conan upload --confirm --check --remote="${REMOTE_NAME}" xrpl/${{ steps.version.outputs.version }} + + - name: Upload Conan recipe (develop) + if: ${{ github.ref == 'refs/heads/develop' }} + env: + REMOTE_NAME: ${{ inputs.remote_name }} + run: | + conan export . --version=develop + conan upload --confirm --check --remote="${REMOTE_NAME}" xrpl/develop + + - name: Upload Conan recipe (rc) + if: ${{ startsWith(github.ref, 'refs/heads/release') }} + env: + REMOTE_NAME: ${{ inputs.remote_name }} + run: | + conan export . --version=rc + conan upload --confirm --check --remote="${REMOTE_NAME}" xrpl/rc + + - name: Upload Conan recipe (release) + if: ${{ github.event_name == 'tag' }} + env: + REMOTE_NAME: ${{ inputs.remote_name }} + run: | + conan export . --version=release + conan upload --confirm --check --remote="${REMOTE_NAME}" xrpl/release + + outputs: + ref: xrpl/${{ steps.version.outputs.version }} diff --git a/.github/workflows/upload-conan-deps.yml b/.github/workflows/upload-conan-deps.yml index 29ae95fce5..60696a9769 100644 --- a/.github/workflows/upload-conan-deps.yml +++ b/.github/workflows/upload-conan-deps.yml @@ -64,13 +64,13 @@ jobs: steps: - name: Cleanup workspace (macOS and Windows) if: ${{ runner.os == 'macOS' || runner.os == 'Windows' }} - uses: XRPLF/actions/cleanup-workspace@2ece4ec6ab7de266859a6f053571425b2bd684b6 + uses: XRPLF/actions/cleanup-workspace@cf0433aa74563aead044a1e395610c96d65a37cf - name: Checkout repository uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0 - name: Prepare runner - uses: XRPLF/actions/prepare-runner@f05cab7b8541eee6473aa42beb9d2fe35608a190 + uses: XRPLF/actions/prepare-runner@2cbf481018d930656e9276fcc20dc0e3a0be5b6d with: enable_ccache: false @@ -78,16 +78,18 @@ jobs: uses: ./.github/actions/print-env - name: Get number of processors - uses: XRPLF/actions/get-nproc@2ece4ec6ab7de266859a6f053571425b2bd684b6 + uses: XRPLF/actions/get-nproc@cf0433aa74563aead044a1e395610c96d65a37cf id: nproc with: subtract: ${{ env.NPROC_SUBTRACT }} - name: Setup Conan + env: + SANITIZERS: ${{ matrix.sanitizers }} uses: ./.github/actions/setup-conan with: - conan_remote_name: ${{ env.CONAN_REMOTE_NAME }} - conan_remote_url: ${{ env.CONAN_REMOTE_URL }} + remote_name: ${{ env.CONAN_REMOTE_NAME }} + remote_url: ${{ env.CONAN_REMOTE_URL }} - name: Build dependencies uses: ./.github/actions/build-deps @@ -98,6 +100,7 @@ jobs: # Set the verbosity to "quiet" for Windows to avoid an excessive # amount of logs. For other OSes, the "verbose" logs are more useful. log_verbosity: ${{ runner.os == 'Windows' && 'quiet' || 'verbose' }} + sanitizers: ${{ matrix.sanitizers }} - name: Log into Conan remote if: ${{ github.repository_owner == 'XRPLF' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch') }} diff --git a/.gitignore b/.gitignore index b899cf8436..2692d707e7 100644 --- a/.gitignore +++ b/.gitignore @@ -64,6 +64,9 @@ DerivedData /.vs/ /.vscode/ +# zed IDE. +/.zed/ + # AI tools. /.augment /.claude diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 603cf39375..79a3e4e7ec 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -26,6 +26,12 @@ repos: args: [--style=file] "types_or": [c++, c, proto] + - repo: https://github.com/cheshirekow/cmake-format-precommit + rev: e2c2116d86a80e72e7146a06e68b7c228afc6319 # frozen: v0.6.13 + hooks: + - id: cmake-format + additional_dependencies: [PyYAML] + - repo: https://github.com/rbubley/mirrors-prettier rev: 5ba47274f9b181bce26a5150a725577f3c336011 # frozen: v3.6.2 hooks: diff --git a/API-CHANGELOG.md b/API-CHANGELOG.md index dd3fcd018b..c7a31d27fa 100644 --- a/API-CHANGELOG.md +++ b/API-CHANGELOG.md @@ -6,90 +6,85 @@ For info about how [API versioning](https://xrpl.org/request-formatting.html#api The API version controls the API behavior you see. This includes what properties you see in responses, what parameters you're permitted to send in requests, and so on. You specify the API version in each of your requests. When a breaking change is introduced to the `rippled` API, a new version is released. To avoid breaking your code, you should set (or increase) your version when you're ready to upgrade. +The [commandline](https://xrpl.org/docs/references/http-websocket-apis/api-conventions/request-formatting/#commandline-format) always uses the latest API version. The command line is intended for ad-hoc usage by humans, not programs or automated scripts. The command line is not meant for use in production code. + For a log of breaking changes, see the **API Version [number]** headings. In general, breaking changes are associated with a particular API Version number. For non-breaking changes, scroll to the **XRP Ledger version [x.y.z]** headings. Non-breaking changes are associated with a particular XRP Ledger (`rippled`) release. +## API Version 3 (Beta) + +API version 3 is currently a beta API. It requires enabling `[beta_rpc_api]` in the rippled configuration to use. See [API-VERSION-3.md](API-VERSION-3.md) for the full list of changes in API version 3. + ## API Version 2 -API version 2 is available in `rippled` version 2.0.0 and later. To use this API, clients specify `"api_version" : 2` in each request. - -#### Removed methods - -In API version 2, the following deprecated methods are no longer available: (https://github.com/XRPLF/rippled/pull/4759) - -- `tx_history` - Instead, use other methods such as `account_tx` or `ledger` with the `transactions` field set to `true`. -- `ledger_header` - Instead, use the `ledger` method. - -#### Modifications to JSON transaction element in V2 - -In API version 2, JSON elements for transaction output have been changed and made consistent for all methods which output transactions. (https://github.com/XRPLF/rippled/pull/4775) -This helps to unify the JSON serialization format of transactions. (https://github.com/XRPLF/clio/issues/722, https://github.com/XRPLF/rippled/issues/4727) - -- JSON transaction element is named `tx_json` -- Binary transaction element is named `tx_blob` -- JSON transaction metadata element is named `meta` -- Binary transaction metadata element is named `meta_blob` - -Additionally, these elements are now consistently available next to `tx_json` (i.e. sibling elements), where possible: - -- `hash` - Transaction ID. This data was stored inside transaction output in API version 1, but in API version 2 is a sibling element. -- `ledger_index` - Ledger index (only set on validated ledgers) -- `ledger_hash` - Ledger hash (only set on closed or validated ledgers) -- `close_time_iso` - Ledger close time expressed in ISO 8601 time format (only set on validated ledgers) -- `validated` - Bool element set to `true` if the transaction is in a validated ledger, otherwise `false` - -This change affects the following methods: - -- `tx` - Transaction data moved into element `tx_json` (was inline inside `result`) or, if binary output was requested, moved from `tx` to `tx_blob`. Renamed binary transaction metadata element (if it was requested) from `meta` to `meta_blob`. Changed location of `hash` and added new elements -- `account_tx` - Renamed transaction element from `tx` to `tx_json`. Renamed binary transaction metadata element (if it was requested) from `meta` to `meta_blob`. Changed location of `hash` and added new elements -- `transaction_entry` - Renamed transaction metadata element from `metadata` to `meta`. Changed location of `hash` and added new elements -- `subscribe` - Renamed transaction element from `transaction` to `tx_json`. Changed location of `hash` and added new elements -- `sign`, `sign_for`, `submit` and `submit_multisigned` - Changed location of `hash` element. - -#### Modification to `Payment` transaction JSON schema - -When reading Payments, the `Amount` field should generally **not** be used. Instead, use [delivered_amount](https://xrpl.org/partial-payments.html#the-delivered_amount-field) to see the amount that the Payment delivered. To clarify its meaning, the `Amount` field is being renamed to `DeliverMax`. (https://github.com/XRPLF/rippled/pull/4733) - -- In `Payment` transaction type, JSON RPC field `Amount` is renamed to `DeliverMax`. To enable smooth client transition, `Amount` is still handled, as described below: (https://github.com/XRPLF/rippled/pull/4733) - - On JSON RPC input (e.g. `submit_multisigned` etc. methods), `Amount` is recognized as an alias to `DeliverMax` for both API version 1 and version 2 clients. - - On JSON RPC input, submitting both `Amount` and `DeliverMax` fields is allowed _only_ if they are identical; otherwise such input is rejected with `rpcINVALID_PARAMS` error. - - On JSON RPC output (e.g. `subscribe`, `account_tx` etc. methods), `DeliverMax` is present in both API version 1 and version 2. - - On JSON RPC output, `Amount` is only present in API version 1 and _not_ in version 2. - -#### Modifications to account_info response - -- `signer_lists` is returned in the root of the response. (In API version 1, it was nested under `account_data`.) (https://github.com/XRPLF/rippled/pull/3770) -- When using an invalid `signer_lists` value, the API now returns an "invalidParams" error. (https://github.com/XRPLF/rippled/pull/4585) - - (`signer_lists` must be a boolean. In API version 1, strings were accepted and may return a normal response - i.e. as if `signer_lists` were `true`.) - -#### Modifications to [account_tx](https://xrpl.org/account_tx.html#account_tx) response - -- Using `ledger_index_min`, `ledger_index_max`, and `ledger_index` returns `invalidParams` because if you use `ledger_index_min` or `ledger_index_max`, then it does not make sense to also specify `ledger_index`. In API version 1, no error was returned. (https://github.com/XRPLF/rippled/pull/4571) - - The same applies for `ledger_index_min`, `ledger_index_max`, and `ledger_hash`. (https://github.com/XRPLF/rippled/issues/4545#issuecomment-1565065579) -- Using a `ledger_index_min` or `ledger_index_max` beyond the range of ledgers that the server has: - - returns `lgrIdxMalformed` in API version 2. Previously, in API version 1, no error was returned. (https://github.com/XRPLF/rippled/issues/4288) -- Attempting to use a non-boolean value (such as a string) for the `binary` or `forward` parameters returns `invalidParams` (`rpcINVALID_PARAMS`). Previously, in API version 1, no error was returned. (https://github.com/XRPLF/rippled/pull/4620) - -#### Modifications to [noripple_check](https://xrpl.org/noripple_check.html#noripple_check) response - -- Attempting to use a non-boolean value (such as a string) for the `transactions` parameter returns `invalidParams` (`rpcINVALID_PARAMS`). Previously, in API version 1, no error was returned. (https://github.com/XRPLF/rippled/pull/4620) +API version 2 is available in `rippled` version 2.0.0 and later. See [API-VERSION-2.md](API-VERSION-2.md) for the full list of changes in API version 2. ## API Version 1 This version is supported by all `rippled` versions. For WebSocket and HTTP JSON-RPC requests, it is currently the default API version used when no `api_version` is specified. -The [commandline](https://xrpl.org/docs/references/http-websocket-apis/api-conventions/request-formatting/#commandline-format) always uses the latest API version. The command line is intended for ad-hoc usage by humans, not programs or automated scripts. The command line is not meant for use in production code. +## XRP Ledger server version 3.1.0 -### Inconsistency: server_info - network_id +[Version 3.1.0](https://github.com/XRPLF/rippled/releases/tag/3.1.0) was released on Jan 27, 2026. -The `network_id` field was added in the `server_info` response in version 1.5.0 (2019), but it is not returned in [reporting mode](https://xrpl.org/rippled-server-modes.html#reporting-mode). However, use of reporting mode is now discouraged, in favor of using [Clio](https://github.com/XRPLF/clio) instead. +### Additions in 3.1.0 + +- `vault_info`: New RPC method to retrieve information about a specific vault (part of XLS-66 Lending Protocol). ([#6156](https://github.com/XRPLF/rippled/pull/6156)) + +## XRP Ledger server version 3.0.0 + +[Version 3.0.0](https://github.com/XRPLF/rippled/releases/tag/3.0.0) was released on Dec 9, 2025. + +### Additions in 3.0.0 + +- `ledger_entry`: Supports all ledger entry types with dedicated parsers. ([#5237](https://github.com/XRPLF/rippled/pull/5237)) +- `ledger_entry`: New error codes `entryNotFound` and `unexpectedLedgerType` for more specific error handling. ([#5237](https://github.com/XRPLF/rippled/pull/5237)) +- `ledger_entry`: Improved error messages with more context (e.g., specifying which field is invalid or missing). ([#5237](https://github.com/XRPLF/rippled/pull/5237)) +- `ledger_entry`: Assorted bug fixes in RPC processing. ([#5237](https://github.com/XRPLF/rippled/pull/5237)) +- `simulate`: Supports additional metadata in the response. ([#5754](https://github.com/XRPLF/rippled/pull/5754)) + +## XRP Ledger server version 2.6.2 + +[Version 2.6.2](https://github.com/XRPLF/rippled/releases/tag/2.6.2) was released on Nov 19, 2025. + +This release contains bug fixes only and no API changes. + +## XRP Ledger server version 2.6.1 + +[Version 2.6.1](https://github.com/XRPLF/rippled/releases/tag/2.6.1) was released on Sep 30, 2025. + +This release contains bug fixes only and no API changes. + +## XRP Ledger server version 2.6.0 + +[Version 2.6.0](https://github.com/XRPLF/rippled/releases/tag/2.6.0) was released on Aug 27, 2025. + +### Additions in 2.6.0 + +- `account_info`: Added `allowTrustLineLocking` flag in response. ([#5525](https://github.com/XRPLF/rippled/pull/5525)) +- `ledger`: Removed the type filter from the RPC command. ([#4934](https://github.com/XRPLF/rippled/pull/4934)) +- `subscribe` (`validations` stream): `network_id` is now included. ([#5579](https://github.com/XRPLF/rippled/pull/5579)) +- `subscribe` (`transactions` stream): `nftoken_id`, `nftoken_ids`, and `offer_id` are now included in transaction metadata. ([#5230](https://github.com/XRPLF/rippled/pull/5230)) + +## XRP Ledger server version 2.5.1 + +[Version 2.5.1](https://github.com/XRPLF/rippled/releases/tag/2.5.1) was released on Sep 17, 2025. + +This release contains bug fixes only and no API changes. ## XRP Ledger server version 2.5.0 -As of 2025-04-04, version 2.5.0 is in development. You can use a pre-release version by building from source or [using the `nightly` package](https://xrpl.org/docs/infrastructure/installation/install-rippled-on-ubuntu). +[Version 2.5.0](https://github.com/XRPLF/rippled/releases/tag/2.5.0) was released on Jun 24, 2025. ### Additions and bugfixes in 2.5.0 -- `channel_authorize`: If `signing_support` is not enabled in the config, the RPC is disabled. +- `tx`: Added `ctid` field to the response and improved error handling. ([#4738](https://github.com/XRPLF/rippled/pull/4738)) +- `ledger_entry`: Improved error messages in `permissioned_domain`. ([#5344](https://github.com/XRPLF/rippled/pull/5344)) +- `simulate`: Improved multi-sign usage. ([#5479](https://github.com/XRPLF/rippled/pull/5479)) +- `channel_authorize`: If `signing_support` is not enabled in the config, the RPC is disabled. ([#5385](https://github.com/XRPLF/rippled/pull/5385)) +- `subscribe` (admin): Removed webhook queue limit to prevent dropping notifications; reduced HTTP timeout from 10 minutes to 30 seconds. ([#5163](https://github.com/XRPLF/rippled/pull/5163)) +- `ledger_data` (gRPC): Fixed crashing issue with some invalid markers. ([#5137](https://github.com/XRPLF/rippled/pull/5137)) +- `account_lines`: Fixed error with `no_ripple` and `no_ripple_peer` sometimes showing up incorrectly. ([#5345](https://github.com/XRPLF/rippled/pull/5345)) +- `account_tx`: Fixed issue with incorrect CTIDs. ([#5408](https://github.com/XRPLF/rippled/pull/5408)) ## XRP Ledger server version 2.4.0 @@ -97,11 +92,19 @@ As of 2025-04-04, version 2.5.0 is in development. You can use a pre-release ver ### Additions and bugfixes in 2.4.0 -- `ledger_entry`: `state` is added an alias for `ripple_state`. -- `ledger_entry`: Enables case-insensitive filtering by canonical name in addition to case-sensitive filtering by RPC name. -- `validators`: Added new field `validator_list_threshold` in response. -- `simulate`: A new RPC that executes a [dry run of a transaction submission](https://github.com/XRPLF/XRPL-Standards/tree/master/XLS-0069d-simulate#2-rpc-simulate) -- Signing methods autofill fees better and properly handle transactions that don't have a base fee, and will also autofill the `NetworkID` field. +- `simulate`: A new RPC that executes a [dry run of a transaction submission](https://github.com/XRPLF/XRPL-Standards/tree/master/XLS-0069d-simulate#2-rpc-simulate). ([#5069](https://github.com/XRPLF/rippled/pull/5069)) +- Signing methods (`sign`, `sign_for`, `submit`): Autofill fees better, properly handle transactions without a base fee, and autofill the `NetworkID` field. ([#5069](https://github.com/XRPLF/rippled/pull/5069)) +- `ledger_entry`: `state` is added as an alias for `ripple_state`. ([#5199](https://github.com/XRPLF/rippled/pull/5199)) +- `ledger`, `ledger_data`, `account_objects`: Support filtering ledger entry types by their canonical names (case-insensitive). ([#5271](https://github.com/XRPLF/rippled/pull/5271)) +- `validators`: Added new field `validator_list_threshold` in response. ([#5112](https://github.com/XRPLF/rippled/pull/5112)) +- `server_info`: Added git commit hash info on admin connection. ([#5225](https://github.com/XRPLF/rippled/pull/5225)) +- `server_definitions`: Changed larger `UInt` serialized types to `Hash`. ([#5231](https://github.com/XRPLF/rippled/pull/5231)) + +## XRP Ledger server version 2.3.1 + +[Version 2.3.1](https://github.com/XRPLF/rippled/releases/tag/2.3.1) was released on Jan 29, 2025. + +This release contains bug fixes only and no API changes. ## XRP Ledger server version 2.3.0 @@ -109,19 +112,30 @@ As of 2025-04-04, version 2.5.0 is in development. You can use a pre-release ver ### Breaking changes in 2.3.0 -- `book_changes`: If the requested ledger version is not available on this node, a `ledgerNotFound` error is returned and the node does not attempt to acquire the ledger from the p2p network (as with other non-admin RPCs). - -Admins can still attempt to retrieve old ledgers with the `ledger_request` RPC. +- `book_changes`: If the requested ledger version is not available on this node, a `ledgerNotFound` error is returned and the node does not attempt to acquire the ledger from the p2p network (as with other non-admin RPCs). Admins can still attempt to retrieve old ledgers with the `ledger_request` RPC. ### Additions and bugfixes in 2.3.0 -- `book_changes`: Returns a `validated` field in its response, which was missing in prior versions. +- `book_changes`: Returns a `validated` field in its response. ([#5096](https://github.com/XRPLF/rippled/pull/5096)) +- `book_changes`: Accepts shortcut strings (`current`, `closed`, `validated`) for the `ledger_index` parameter. ([#5096](https://github.com/XRPLF/rippled/pull/5096)) +- `server_definitions`: Include `index` in response. ([#5190](https://github.com/XRPLF/rippled/pull/5190)) +- `account_nfts`: Fix issue where unassociated marker would return incorrect results. ([#5045](https://github.com/XRPLF/rippled/pull/5045)) +- `account_objects`: Fix issue where invalid marker would not return an error. ([#5046](https://github.com/XRPLF/rippled/pull/5046)) +- `account_objects`: Disallow filtering by ledger entry types that an account cannot hold. ([#5056](https://github.com/XRPLF/rippled/pull/5056)) +- `tx`: Allow lowercase CTID. ([#5049](https://github.com/XRPLF/rippled/pull/5049)) +- `feature`: Better error handling for invalid values of `feature`. ([#5063](https://github.com/XRPLF/rippled/pull/5063)) ## XRP Ledger server version 2.2.0 [Version 2.2.0](https://github.com/XRPLF/rippled/releases/tag/2.2.0) was released on Jun 5, 2024. The following additions are non-breaking (because they are purely additive): -- The `feature` method now has a non-admin mode for users. (It was previously only available to admin connections.) The method returns an updated list of amendments, including their names and other information. ([#4781](https://github.com/XRPLF/rippled/pull/4781)) +- `feature`: Add a non-admin mode for users. (It was previously only available to admin connections.) The method returns an updated list of amendments, including their names and other information. ([#4781](https://github.com/XRPLF/rippled/pull/4781)) + +## XRP Ledger server version 2.0.1 + +[Version 2.0.1](https://github.com/XRPLF/rippled/releases/tag/2.0.1) was released on Jan 29, 2024. The following additions are non-breaking: + +- `path_find`: Fixes unbounded memory growth. ([#4822](https://github.com/XRPLF/rippled/pull/4822)) ## XRP Ledger server version 2.0.0 @@ -129,24 +143,18 @@ Admins can still attempt to retrieve old ledgers with the `ledger_request` RPC. - `server_definitions`: A new RPC that generates a `definitions.json`-like output that can be used in XRPL libraries. - In `Payment` transactions, `DeliverMax` has been added. This is a replacement for the `Amount` field, which should not be used. Typically, the `delivered_amount` (in transaction metadata) should be used. To ease the transition, `DeliverMax` is present regardless of API version, since adding a field is non-breaking. -- API version 2 has been moved from beta to supported, meaning that it is generally available (regardless of the `beta_rpc_api` setting). - -## XRP Ledger server version 2.2.0 - -The following is a non-breaking addition to the API. - -- The `feature` method now has a non-admin mode for users. (It was previously only available to admin connections.) The method returns an updated list of amendments, including their names and other information. ([#4781](https://github.com/XRPLF/rippled/pull/4781)) +- API version 2 has been moved from beta to supported, meaning that it is generally available (regardless of the `beta_rpc_api` setting). The full list of changes is in [API-VERSION-2.md](API-VERSION-2.md). ## XRP Ledger server version 1.12.0 -[Version 1.12.0](https://github.com/XRPLF/rippled/releases/tag/1.12.0) was released on Sep 6, 2023. The following additions are non-breaking (because they are purely additive). +[Version 1.12.0](https://github.com/XRPLF/rippled/releases/tag/1.12.0) was released on Sep 6, 2023. The following additions are non-breaking (because they are purely additive): -- `server_info`: Added `ports`, an array which advertises the RPC and WebSocket ports. This information is also included in the `/crawl` endpoint (which calls `server_info` internally). `grpc` and `peer` ports are also included. (https://github.com/XRPLF/rippled/pull/4427) +- `server_info`: Added `ports`, an array which advertises the RPC and WebSocket ports. This information is also included in the `/crawl` endpoint (which calls `server_info` internally). `grpc` and `peer` ports are also included. ([#4427](https://github.com/XRPLF/rippled/pull/4427)) - `ports` contains objects, each containing a `port` for the listening port (a number string), and a `protocol` array listing the supported protocols on that port. - This allows crawlers to build a more detailed topology without needing to port-scan nodes. - (For peers and other non-admin clients, the info about admin ports is excluded.) -- Clawback: The following additions are gated by the Clawback amendment (`featureClawback`). (https://github.com/XRPLF/rippled/pull/4553) - - Adds an [AccountRoot flag](https://xrpl.org/accountroot.html#accountroot-flags) called `lsfAllowTrustLineClawback` (https://github.com/XRPLF/rippled/pull/4617) +- Clawback: The following additions are gated by the Clawback amendment (`featureClawback`). ([#4553](https://github.com/XRPLF/rippled/pull/4553)) + - Adds an [AccountRoot flag](https://xrpl.org/accountroot.html#accountroot-flags) called `lsfAllowTrustLineClawback`. ([#4617](https://github.com/XRPLF/rippled/pull/4617)) - Adds the corresponding `asfAllowTrustLineClawback` [AccountSet Flag](https://xrpl.org/accountset.html#accountset-flags) as well. - Clawback is disabled by default, so if an issuer desires the ability to claw back funds, they must use an `AccountSet` transaction to set the AllowTrustLineClawback flag. They must do this before creating any trust lines, offers, escrows, payment channels, or checks. - Adds the [Clawback transaction type](https://github.com/XRPLF/XRPL-Standards/blob/master/XLS-39d-clawback/README.md#331-clawback-transaction), containing these fields: @@ -181,16 +189,16 @@ The following is a non-breaking addition to the API. ### Breaking changes in 1.11 -- Added the ability to mark amendments as obsolete. For the `feature` admin API, there is a new possible value for the `vetoed` field. (https://github.com/XRPLF/rippled/pull/4291) +- Added the ability to mark amendments as obsolete. For the `feature` admin API, there is a new possible value for the `vetoed` field. ([#4291](https://github.com/XRPLF/rippled/pull/4291)) - The value of `vetoed` can now be `true`, `false`, or `"Obsolete"`. -- Removed the acceptance of seeds or public keys in place of account addresses. (https://github.com/XRPLF/rippled/pull/4404) +- Removed the acceptance of seeds or public keys in place of account addresses. ([#4404](https://github.com/XRPLF/rippled/pull/4404)) - This simplifies the API and encourages better security practices (i.e. seeds should never be sent over the network). -- For the `ledger_data` method, when all entries are filtered out, the `state` field of the response is now an empty list (in other words, an empty array, `[]`). (Previously, it would return `null`.) While this is technically a breaking change, the new behavior is consistent with the documentation, so this is considered only a bug fix. (https://github.com/XRPLF/rippled/pull/4398) +- For the `ledger_data` method, when all entries are filtered out, the `state` field of the response is now an empty list (in other words, an empty array, `[]`). (Previously, it would return `null`.) While this is technically a breaking change, the new behavior is consistent with the documentation, so this is considered only a bug fix. ([#4398](https://github.com/XRPLF/rippled/pull/4398)) - If and when the `fixNFTokenRemint` amendment activates, there will be a new AccountRoot field, `FirstNFTSequence`. This field is set to the current account sequence when the account issues their first NFT. If an account has not issued any NFTs, then the field is not set. ([#4406](https://github.com/XRPLF/rippled/pull/4406)) - There is a new account deletion restriction: an account can only be deleted if `FirstNFTSequence` + `MintedNFTokens` + `256` is less than the current ledger sequence. - This is potentially a breaking change if clients have logic for determining whether an account can be deleted. - NetworkID - - For sidechains and networks with a network ID greater than 1024, there is a new [transaction common field](https://xrpl.org/transaction-common-fields.html), `NetworkID`. (https://github.com/XRPLF/rippled/pull/4370) + - For sidechains and networks with a network ID greater than 1024, there is a new [transaction common field](https://xrpl.org/transaction-common-fields.html), `NetworkID`. ([#4370](https://github.com/XRPLF/rippled/pull/4370)) - This field helps to prevent replay attacks and is now required for chains whose network ID is 1025 or higher. - The field must be omitted for Mainnet, so there is no change for Mainnet users. - There are three new local error codes: @@ -200,10 +208,10 @@ The following is a non-breaking addition to the API. ### Additions and bug fixes in 1.11 -- Added `nftoken_id`, `nftoken_ids` and `offer_id` meta fields into NFT `tx` and `account_tx` responses. (https://github.com/XRPLF/rippled/pull/4447) -- Added an `account_flags` object to the `account_info` method response. (https://github.com/XRPLF/rippled/pull/4459) -- Added `NFTokenPages` to the `account_objects` RPC. (https://github.com/XRPLF/rippled/pull/4352) -- Fixed: `marker` returned from the `account_lines` command would not work on subsequent commands. (https://github.com/XRPLF/rippled/pull/4361) +- Added `nftoken_id`, `nftoken_ids` and `offer_id` meta fields into NFT `tx` and `account_tx` responses. ([#4447](https://github.com/XRPLF/rippled/pull/4447)) +- Added an `account_flags` object to the `account_info` method response. ([#4459](https://github.com/XRPLF/rippled/pull/4459)) +- Added `NFTokenPages` to the `account_objects` RPC. ([#4352](https://github.com/XRPLF/rippled/pull/4352)) +- Fixed: `marker` returned from the `account_lines` command would not work on subsequent commands. ([#4361](https://github.com/XRPLF/rippled/pull/4361)) ## XRP Ledger server version 1.10.0 diff --git a/API-VERSION-2.md b/API-VERSION-2.md new file mode 100644 index 0000000000..2296795271 --- /dev/null +++ b/API-VERSION-2.md @@ -0,0 +1,66 @@ +# API Version 2 + +API version 2 is available in `rippled` version 2.0.0 and later. To use this API, clients specify `"api_version" : 2` in each request. + +For info about how [API versioning](https://xrpl.org/request-formatting.html#api-versioning) works, including examples, please view the [XLS-22d spec](https://github.com/XRPLF/XRPL-Standards/discussions/54). For details about the implementation of API versioning, view the [implementation PR](https://github.com/XRPLF/rippled/pull/3155). API versioning ensures existing integrations and users continue to receive existing behavior, while those that request a higher API version will experience new behavior. + +## Removed methods + +In API version 2, the following deprecated methods are no longer available: ([#4759](https://github.com/XRPLF/rippled/pull/4759)) + +- `tx_history` - Instead, use other methods such as `account_tx` or `ledger` with the `transactions` field set to `true`. +- `ledger_header` - Instead, use the `ledger` method. + +## Modifications to JSON transaction element in API version 2 + +In API version 2, JSON elements for transaction output have been changed and made consistent for all methods which output transactions. ([#4775](https://github.com/XRPLF/rippled/pull/4775)) +This helps to unify the JSON serialization format of transactions. ([clio#722](https://github.com/XRPLF/clio/issues/722), [#4727](https://github.com/XRPLF/rippled/issues/4727)) + +- JSON transaction element is named `tx_json` +- Binary transaction element is named `tx_blob` +- JSON transaction metadata element is named `meta` +- Binary transaction metadata element is named `meta_blob` + +Additionally, these elements are now consistently available next to `tx_json` (i.e. sibling elements), where possible: + +- `hash` - Transaction ID. This data was stored inside transaction output in API version 1, but in API version 2 is a sibling element. +- `ledger_index` - Ledger index (only set on validated ledgers) +- `ledger_hash` - Ledger hash (only set on closed or validated ledgers) +- `close_time_iso` - Ledger close time expressed in ISO 8601 time format (only set on validated ledgers) +- `validated` - Bool element set to `true` if the transaction is in a validated ledger, otherwise `false` + +This change affects the following methods: + +- `tx` - Transaction data moved into element `tx_json` (was inline inside `result`) or, if binary output was requested, moved from `tx` to `tx_blob`. Renamed binary transaction metadata element (if it was requested) from `meta` to `meta_blob`. Changed location of `hash` and added new elements +- `account_tx` - Renamed transaction element from `tx` to `tx_json`. Renamed binary transaction metadata element (if it was requested) from `meta` to `meta_blob`. Changed location of `hash` and added new elements +- `transaction_entry` - Renamed transaction metadata element from `metadata` to `meta`. Changed location of `hash` and added new elements +- `subscribe` - Renamed transaction element from `transaction` to `tx_json`. Changed location of `hash` and added new elements +- `sign`, `sign_for`, `submit` and `submit_multisigned` - Changed location of `hash` element. + +## Modifications to `Payment` transaction JSON schema + +When reading Payments, the `Amount` field should generally **not** be used. Instead, use [delivered_amount](https://xrpl.org/partial-payments.html#the-delivered_amount-field) to see the amount that the Payment delivered. To clarify its meaning, the `Amount` field is being renamed to `DeliverMax`. ([#4733](https://github.com/XRPLF/rippled/pull/4733)) + +- In `Payment` transaction type, JSON RPC field `Amount` is renamed to `DeliverMax`. To enable smooth client transition, `Amount` is still handled, as described below: ([#4733](https://github.com/XRPLF/rippled/pull/4733)) + - On JSON RPC input (e.g. `submit_multisigned` etc. methods), `Amount` is recognized as an alias to `DeliverMax` for both API version 1 and version 2 clients. + - On JSON RPC input, submitting both `Amount` and `DeliverMax` fields is allowed _only_ if they are identical; otherwise such input is rejected with `rpcINVALID_PARAMS` error. + - On JSON RPC output (e.g. `subscribe`, `account_tx` etc. methods), `DeliverMax` is present in both API version 1 and version 2. + - On JSON RPC output, `Amount` is only present in API version 1 and _not_ in version 2. + +## Modifications to account_info response + +- `signer_lists` is returned in the root of the response. (In API version 1, it was nested under `account_data`.) ([#3770](https://github.com/XRPLF/rippled/pull/3770)) +- When using an invalid `signer_lists` value, the API now returns an "invalidParams" error. ([#4585](https://github.com/XRPLF/rippled/pull/4585)) + - (`signer_lists` must be a boolean. In API version 1, strings were accepted and may return a normal response - i.e. as if `signer_lists` were `true`.) + +## Modifications to [account_tx](https://xrpl.org/account_tx.html#account_tx) response + +- Using `ledger_index_min`, `ledger_index_max`, and `ledger_index` returns `invalidParams` because if you use `ledger_index_min` or `ledger_index_max`, then it does not make sense to also specify `ledger_index`. In API version 1, no error was returned. ([#4571](https://github.com/XRPLF/rippled/pull/4571)) + - The same applies for `ledger_index_min`, `ledger_index_max`, and `ledger_hash`. ([#4545](https://github.com/XRPLF/rippled/issues/4545#issuecomment-1565065579)) +- Using a `ledger_index_min` or `ledger_index_max` beyond the range of ledgers that the server has: + - returns `lgrIdxMalformed` in API version 2. Previously, in API version 1, no error was returned. ([#4288](https://github.com/XRPLF/rippled/issues/4288)) +- Attempting to use a non-boolean value (such as a string) for the `binary` or `forward` parameters returns `invalidParams` (`rpcINVALID_PARAMS`). Previously, in API version 1, no error was returned. ([#4620](https://github.com/XRPLF/rippled/pull/4620)) + +## Modifications to [noripple_check](https://xrpl.org/noripple_check.html#noripple_check) response + +- Attempting to use a non-boolean value (such as a string) for the `transactions` parameter returns `invalidParams` (`rpcINVALID_PARAMS`). Previously, in API version 1, no error was returned. ([#4620](https://github.com/XRPLF/rippled/pull/4620)) diff --git a/API-VERSION-3.md b/API-VERSION-3.md new file mode 100644 index 0000000000..46dc3f504d --- /dev/null +++ b/API-VERSION-3.md @@ -0,0 +1,27 @@ +# API Version 3 + +API version 3 is currently a **beta API**. It requires enabling `[beta_rpc_api]` in the rippled configuration to use. To use this API, clients specify `"api_version" : 3` in each request. + +For info about how [API versioning](https://xrpl.org/request-formatting.html#api-versioning) works, including examples, please view the [XLS-22d spec](https://github.com/XRPLF/XRPL-Standards/discussions/54). For details about the implementation of API versioning, view the [implementation PR](https://github.com/XRPLF/rippled/pull/3155). API versioning ensures existing integrations and users continue to receive existing behavior, while those that request a higher API version will experience new behavior. + +## Breaking Changes + +### Modifications to `amm_info` + +The order of error checks has been changed to provide more specific error messages. ([#4924](https://github.com/XRPLF/rippled/pull/4924)) + +- **Before (API v2)**: When sending an invalid account or asset to `amm_info` while other parameters are not set as expected, the method returns a generic `rpcINVALID_PARAMS` error. +- **After (API v3)**: The same scenario returns a more specific error: `rpcISSUE_MALFORMED` for malformed assets or `rpcACT_MALFORMED` for malformed accounts. + +### Modifications to `ledger_entry` + +Added support for string shortcuts to look up fixed-location ledger entries using the `"index"` parameter. ([#5644](https://github.com/XRPLF/rippled/pull/5644)) + +In API version 3, the following string values can be used with the `"index"` parameter: + +- `"index": "amendments"` - Returns the `Amendments` ledger entry +- `"index": "fee"` - Returns the `FeeSettings` ledger entry +- `"index": "nunl"` - Returns the `NegativeUNL` ledger entry +- `"index": "hashes"` - Returns the "short" `LedgerHashes` ledger entry (recent ledger hashes) + +These shortcuts are only available in API version 3 and later. In API versions 1 and 2, these string values would result in an error. diff --git a/BUILD.md b/BUILD.md index b239b10be6..4d01700a61 100644 --- a/BUILD.md +++ b/BUILD.md @@ -148,8 +148,8 @@ function extract_version { } # Define which recipes to export. -recipes=('ed25519' 'grpc' 'openssl' 'secp256k1' 'snappy' 'soci') -folders=('all' 'all' '3.x.x' 'all' 'all' 'all') +recipes=('ed25519' 'grpc' 'nudb' 'openssl' 'secp256k1' 'snappy' 'soci') +folders=('all' 'all' 'all' '3.x.x' 'all' 'all' 'all') # Selectively check out the recipes from our CCI fork. cd external @@ -368,6 +368,36 @@ The workaround for this error is to add two lines to your profile: tools.build:cxxflags=['-DBOOST_ASIO_DISABLE_CONCEPTS'] ``` +### Set Up Ccache + +To speed up repeated compilations, we recommend that you install +[ccache](https://ccache.dev), a tool that wraps your compiler so that it can +cache build objects locally. + +#### Linux + +You can install it using the package manager, e.g. `sudo apt install ccache` +(Ubuntu) or `sudo dnf install ccache` (RHEL). + +#### macOS + +You can install it using Homebrew, i.e. `brew install ccache`. + +#### Windows + +You can install it using Chocolatey, i.e. `choco install ccache`. If you already +have Ccache installed, then `choco upgrade ccache` will update it to the latest +version. However, if you see an error such as: + +``` +terminate called after throwing an instance of 'std::bad_alloc' + what(): std::bad_alloc +C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Microsoft\VC\v170\Microsoft.CppCommon.targets(617,5): error MSB6006: "cl.exe" exited with code 3. +``` + +then please install a specific version of Ccache that we know works, via: `choco +install ccache --version 4.11.3 --allow-downgrade`. + ### Build and Test 1. Create a build directory and move into it. @@ -550,10 +580,10 @@ See [Sanitizers docs](./docs/build/sanitizers.md) for more details. | `werr` | OFF | Treat compilation warnings as errors | | `wextra` | OFF | Enable additional compilation warnings | -[Unity builds][5] may be faster for the first build -(at the cost of much more memory) since they concatenate sources into fewer -translation units. Non-unity builds may be faster for incremental builds, -and can be helpful for detecting `#include` omissions. +[Unity builds][5] may be faster for the first build (at the cost of much more +memory) since they concatenate sources into fewer translation units. Non-unity +builds may be faster for incremental builds, and can be helpful for detecting +`#include` omissions. ## Troubleshooting diff --git a/CMakeLists.txt b/CMakeLists.txt index ee0484e79d..3c434506f7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,14 +1,16 @@ cmake_minimum_required(VERSION 3.16) -if(POLICY CMP0074) - cmake_policy(SET CMP0074 NEW) -endif() -if(POLICY CMP0077) - cmake_policy(SET CMP0077 NEW) -endif() +if (POLICY CMP0074) + cmake_policy(SET CMP0074 NEW) +endif () +if (POLICY CMP0077) + cmake_policy(SET CMP0077 NEW) +endif () # Fix "unrecognized escape" issues when passing CMAKE_MODULE_PATH on Windows. -file(TO_CMAKE_PATH "${CMAKE_MODULE_PATH}" CMAKE_MODULE_PATH) +if (DEFINED CMAKE_MODULE_PATH) + file(TO_CMAKE_PATH "${CMAKE_MODULE_PATH}" CMAKE_MODULE_PATH) +endif () list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake") project(xrpl) @@ -18,65 +20,65 @@ set(CMAKE_CXX_STANDARD_REQUIRED ON) include(CompilationEnv) -if(is_gcc) +if (is_gcc) # GCC-specific fixes add_compile_options(-Wno-unknown-pragmas -Wno-subobject-linkage) # -Wno-subobject-linkage can be removed when we upgrade GCC version to at least 13.3 -elseif(is_clang) +elseif (is_clang) # Clang-specific fixes add_compile_options(-Wno-unknown-warning-option) # Ignore unknown warning options -elseif(is_msvc) +elseif (is_msvc) # MSVC-specific fixes add_compile_options(/wd4068) # Ignore unknown pragmas -endif() +endif () # Enable ccache to speed up builds. include(Ccache) # make GIT_COMMIT_HASH define available to all sources find_package(Git) -if(Git_FOUND) +if (Git_FOUND) execute_process(COMMAND ${GIT_EXECUTABLE} --git-dir=${CMAKE_CURRENT_SOURCE_DIR}/.git rev-parse HEAD - OUTPUT_STRIP_TRAILING_WHITESPACE OUTPUT_VARIABLE gch) - if(gch) + OUTPUT_STRIP_TRAILING_WHITESPACE OUTPUT_VARIABLE gch) + if (gch) set(GIT_COMMIT_HASH "${gch}") message(STATUS gch: ${GIT_COMMIT_HASH}) add_definitions(-DGIT_COMMIT_HASH="${GIT_COMMIT_HASH}") - endif() + endif () execute_process(COMMAND ${GIT_EXECUTABLE} --git-dir=${CMAKE_CURRENT_SOURCE_DIR}/.git rev-parse --abbrev-ref HEAD - OUTPUT_STRIP_TRAILING_WHITESPACE OUTPUT_VARIABLE gb) - if(gb) + OUTPUT_STRIP_TRAILING_WHITESPACE OUTPUT_VARIABLE gb) + if (gb) set(GIT_BRANCH "${gb}") message(STATUS gb: ${GIT_BRANCH}) add_definitions(-DGIT_BRANCH="${GIT_BRANCH}") - endif() -endif() #git + endif () +endif () # git -if(thread_safety_analysis) - add_compile_options(-Wthread-safety -D_LIBCPP_ENABLE_THREAD_SAFETY_ANNOTATIONS -DXRPL_ENABLE_THREAD_SAFETY_ANNOTATIONS) - add_compile_options("-stdlib=libc++") - add_link_options("-stdlib=libc++") -endif() +if (thread_safety_analysis) + add_compile_options(-Wthread-safety -D_LIBCPP_ENABLE_THREAD_SAFETY_ANNOTATIONS + -DXRPL_ENABLE_THREAD_SAFETY_ANNOTATIONS) + add_compile_options("-stdlib=libc++") + add_link_options("-stdlib=libc++") +endif () -include (CheckCXXCompilerFlag) -include (FetchContent) -include (ExternalProject) -include (CMakeFuncs) # must come *after* ExternalProject b/c it overrides one function in EP +include(CheckCXXCompilerFlag) +include(FetchContent) +include(ExternalProject) +include(CMakeFuncs) # must come *after* ExternalProject b/c it overrides one function in EP if (target) - message (FATAL_ERROR "The target option has been removed - use native cmake options to control build") + message(FATAL_ERROR "The target option has been removed - use native cmake options to control build") endif () include(XrplSanity) include(XrplVersion) include(XrplSettings) -# this check has to remain in the top-level cmake -# because of the early return statement +# this check has to remain in the top-level cmake because of the early return statement if (packages_only) - if (NOT TARGET rpm) - message (FATAL_ERROR "packages_only requested, but targets were not created - is docker installed?") - endif() - return () + if (NOT TARGET rpm) + message(FATAL_ERROR "packages_only requested, but targets were not created - is docker installed?") + endif () + return() endif () include(XrplCompiler) include(XrplSanitizers) @@ -84,11 +86,9 @@ include(XrplInterface) option(only_docs "Include only the docs target?" FALSE) include(XrplDocs) -if(only_docs) - return() -endif() - -### +if (only_docs) + return() +endif () include(deps/Boost) @@ -105,45 +105,43 @@ find_package(SOCI REQUIRED) find_package(SQLite3 REQUIRED) find_package(xxHash REQUIRED) -target_link_libraries(xrpl_libs INTERFACE - ed25519::ed25519 - lz4::lz4 - OpenSSL::Crypto - OpenSSL::SSL - secp256k1::secp256k1 - soci::soci - SQLite::SQLite3 -) +target_link_libraries( + xrpl_libs + INTERFACE ed25519::ed25519 + lz4::lz4 + OpenSSL::Crypto + OpenSSL::SSL + secp256k1::secp256k1 + soci::soci + SQLite::SQLite3) option(rocksdb "Enable RocksDB" ON) -if(rocksdb) +if (rocksdb) find_package(RocksDB REQUIRED) - set_target_properties(RocksDB::rocksdb PROPERTIES - INTERFACE_COMPILE_DEFINITIONS XRPL_ROCKSDB_AVAILABLE=1 - ) + set_target_properties(RocksDB::rocksdb PROPERTIES INTERFACE_COMPILE_DEFINITIONS XRPL_ROCKSDB_AVAILABLE=1) target_link_libraries(xrpl_libs INTERFACE RocksDB::rocksdb) -endif() +endif () # Work around changes to Conan recipe for now. -if(TARGET nudb::core) - set(nudb nudb::core) -elseif(TARGET NuDB::nudb) - set(nudb NuDB::nudb) -else() - message(FATAL_ERROR "unknown nudb target") -endif() +if (TARGET nudb::core) + set(nudb nudb::core) +elseif (TARGET NuDB::nudb) + set(nudb NuDB::nudb) +else () + message(FATAL_ERROR "unknown nudb target") +endif () target_link_libraries(xrpl_libs INTERFACE ${nudb}) -if(coverage) - include(XrplCov) -endif() +if (coverage) + include(XrplCov) +endif () set(PROJECT_EXPORT_SET XrplExports) include(XrplCore) include(XrplInstall) include(XrplValidatorKeys) -if(tests) - include(CTest) - add_subdirectory(src/tests/libxrpl) -endif() +if (tests) + include(CTest) + add_subdirectory(src/tests/libxrpl) +endif () diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4f99972713..808d553e17 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -872,7 +872,8 @@ git push --delete upstream-push master-next 11. [Create a new release on Github](https://github.com/XRPLF/rippled/releases). Be sure that "Set as the latest release" is checked. -12. Finally [reverse merge the release into `develop`](#follow-up-reverse-merge). +12. Open a PR to update the [API-CHANGELOG](API-CHANGELOG.md) and `API-VERSION-[n].md` with the changes for this release (if any are missing). +13. Finally, [reverse merge the release into `develop`](#follow-up-reverse-merge). #### Special cases: point releases, hotfixes, etc. diff --git a/SECURITY.md b/SECURITY.md index 18eec312ed..1be412ae2a 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -78,72 +78,61 @@ To report a qualifying bug, please send a detailed report to: | Email Address | bugs@ripple.com | | :-----------: | :-------------------------------------------------- | -| Short Key ID | `0xC57929BE` | -| Long Key ID | `0xCD49A0AFC57929BE` | -| Fingerprint | `24E6 3B02 37E0 FA9C 5E96 8974 CD49 A0AF C579 29BE` | +| Short Key ID | `0xA9F514E0` | +| Long Key ID | `0xD900855AA9F514E0` | +| Fingerprint | `B72C 0654 2F2A E250 2763 A268 D900 855A A9F5 14E0` | The full PGP key for this address, which is also available on several key servers (e.g. on [keyserver.ubuntu.com](https://keyserver.ubuntu.com)), is: ``` -----BEGIN PGP PUBLIC KEY BLOCK----- -mQINBFUwGHYBEAC0wpGpBPkd8W1UdQjg9+cEFzeIEJRaoZoeuJD8mofwI5Ejnjdt -kCpUYEDal0ygkKobu8SzOoATcDl18iCrScX39VpTm96vISFZMhmOryYCIp4QLJNN -4HKc2ZdBj6W4igNi6vj5Qo6JMyGpLY2mz4CZskbt0TNuUxWrGood+UrCzpY8x7/N -a93fcvNw+prgCr0rCH3hAPmAFfsOBbtGzNnmq7xf3jg5r4Z4sDiNIF1X1y53DAfV -rWDx49IKsuCEJfPMp1MnBSvDvLaQ2hKXs+cOpx1BCZgHn3skouEUxxgqbtTzBLt1 -xXpmuijsaltWngPnGO7mOAzbpZSdBm82/Emrk9bPMuD0QaLQjWr7HkTSUs6ZsKt4 -7CLPdWqxyY/QVw9UaxeHEtWGQGMIQGgVJGh1fjtUr5O1sC9z9jXcQ0HuIHnRCTls -GP7hklJmfH5V4SyAJQ06/hLuEhUJ7dn+BlqCsT0tLmYTgZYNzNcLHcqBFMEZHvHw -9GENMx/tDXgajKql4bJnzuTK0iGU/YepanANLd1JHECJ4jzTtmKOus9SOGlB2/l1 -0t0ADDYAS3eqOdOcUvo9ElSLCI5vSVHhShSte/n2FMWU+kMUboTUisEG8CgQnrng -g2CvvQvqDkeOtZeqMcC7HdiZS0q3LJUWtwA/ViwxrVlBDCxiTUXCotyBWwARAQAB -tDBSaXBwbGUgTGFicyBCdWcgQm91bnR5IFByb2dyYW0gPGJ1Z3NAcmlwcGxlLmNv -bT6JAjcEEwEKACEFAlUwGHYCGwMFCwkIBwMFFQoJCAsFFgIDAQACHgECF4AACgkQ -zUmgr8V5Kb6R0g//SwY/mVJY59k87iL26/KayauSoOcz7xjcST26l4ZHVVX85gOY -HYZl8k0+m8X3zxeYm9a3QAoAml8sfoaFRFQP8ynnefRrLUPaZ2MjbJ0SACMwZNef -T6o7Mi8LBAaiNZdYVyIfX1oM6YXtqYkuJdav6ZCyvVYqc9OvMJPY2ZzJYuI/ZtvQ -/lTndxCeg9ALNX/iezOLGdfMpf4HuIFVwcPPlwGi+HDlB9/bggDEHC8z434SXVFc -aQatXAPcDkjMUweU7y0CZtYEj00HITd4pSX6MqGiHrxlDZTqinCOPs1Ieqp7qufs -MzlM6irLGucxj1+wa16ieyYvEtGaPIsksUKkywx0O7cf8N2qKg+eIkUk6O0Uc6eO -CszizmiXIXy4O6OiLlVHGKkXHMSW9Nwe9GE95O8G9WR8OZCEuDv+mHPAutO+IjdP -PDAAUvy+3XnkceO+HGWRpVvJZfFP2YH4A33InFL5yqlJmSoR/yVingGLxk55bZDM -+HYGR3VeMb8Xj1rf/02qERsZyccMCFdAvKDbTwmvglyHdVLu5sPmktxbBYiemfyJ -qxMxmYXCc9S0hWrWZW7edktBa9NpE58z1mx+hRIrDNbS2sDHrib9PULYCySyVYcF -P+PWEe1CAS5jqkR2ker5td2/pHNnJIycynBEs7l6zbc9fu+nktFJz0q2B+GJAhwE -EAEKAAYFAlUwGaQACgkQ+tiY1qQ2QkjMFw//f2hNY3BPNe+1qbhzumMDCnbTnGif -kLuAGl9OKt81VHG1f6RnaGiLpR696+6Ja45KzH15cQ5JJl5Bgs1YkR/noTGX8IAD -c70eNwiFu8JXTaaeeJrsmFkF9Tueufb364risYkvPP8tNUD3InBFEZT3WN7JKwix -coD4/BwekUwOZVDd/uCFEyhlhZsROxdKNisNo3VtAq2s+3tIBAmTrriFUl0K+ZC5 -zgavcpnPN57zMtW9aK+VO3wXqAKYLYmtgxkVzSLUZt2M7JuwOaAdyuYWAneKZPCu -1AXkmyo+d84sd5mZaKOr5xArAFiNMWPUcZL4rkS1Fq4dKtGAqzzR7a7hWtA5o27T -6vynuxZ1n0PPh0er2O/zF4znIjm5RhTlfjp/VmhZdQfpulFEQ/dMxxGkQ9z5IYbX -mTlSDbCSb+FMsanRBJ7Drp5EmBIudVGY6SHI5Re1RQiEh7GoDfUMUwZO+TVDII5R -Ra7WyuimYleJgDo/+7HyfuIyGDaUCVj6pwVtYtYIdOI3tTw1R1Mr0V8yaNVnJghL -CHcEJQL+YHSmiMM3ySil3O6tm1By6lFz8bVe/rgG/5uklQrnjMR37jYboi1orCC4 -yeIoQeV0ItlxeTyBwYIV/o1DBNxDevTZvJabC93WiGLw2XFjpZ0q/9+zI2rJUZJh -qxmKP+D4e27lCI65Ag0EVTAYdgEQAMvttYNqeRNBRpSX8fk45WVIV8Fb21fWdwk6 -2SkZnJURbiC0LxQnOi7wrtii7DeFZtwM2kFHihS1VHekBnIKKZQSgGoKuFAQMGyu -a426H4ZsSmA9Ufd7kRbvdtEcp7/RTAanhrSL4lkBhaKJrXlxBJ27o3nd7/rh7r3a -OszbPY6DJ5bWClX3KooPTDl/RF2lHn+fweFk58UvuunHIyo4BWJUdilSXIjLun+P -Qaik4ZAsZVwNhdNz05d+vtai4AwbYoO7adboMLRkYaXSQwGytkm+fM6r7OpXHYuS -cR4zB/OK5hxCVEpWfiwN71N2NMvnEMaWd/9uhqxJzyvYgkVUXV9274TUe16pzXnW -ZLfmitjwc91e7mJBBfKNenDdhaLEIlDRwKTLj7k58f9srpMnyZFacntu5pUMNblB -cjXwWxz5ZaQikLnKYhIvrIEwtWPyjqOzNXNvYfZamve/LJ8HmWGCKao3QHoAIDvB -9XBxrDyTJDpxbog6Qu4SY8AdgVlan6c/PsLDc7EUegeYiNTzsOK+eq3G5/E92eIu -TsUXlciypFcRm1q8vLRr+HYYe2mJDo4GetB1zLkAFBcYJm/x9iJQbu0hn5NxJvZO -R0Y5nOJQdyi+muJzKYwhkuzaOlswzqVXkq/7+QCjg7QsycdcwDjiQh3OrsgXHrwl -M7gyafL9ABEBAAGJAh8EGAEKAAkFAlUwGHYCGwwACgkQzUmgr8V5Kb50BxAAhj9T -TwmNrgRldTHszj+Qc+v8RWqV6j+R+zc0cn5XlUa6XFaXI1OFFg71H4dhCPEiYeN0 -IrnocyMNvCol+eKIlPKbPTmoixjQ4udPTR1DC1Bx1MyW5FqOrsgBl5t0e1VwEViM -NspSStxu5Hsr6oWz2GD48lXZWJOgoL1RLs+uxjcyjySD/em2fOKASwchYmI+ezRv -plfhAFIMKTSCN2pgVTEOaaz13M0U+MoprThqF1LWzkGkkC7n/1V1f5tn83BWiagG -2N2Q4tHLfyouzMUKnX28kQ9sXfxwmYb2sA9FNIgxy+TdKU2ofLxivoWT8zS189z/ -Yj9fErmiMjns2FzEDX+bipAw55X4D/RsaFgC+2x2PDbxeQh6JalRA2Wjq32Ouubx -u+I4QhEDJIcVwt9x6LPDuos1F+M5QW0AiUhKrZJ17UrxOtaquh/nPUL9T3l2qPUn -1ChrZEEEhHO6vA8+jn0+cV9n5xEz30Str9iHnDQ5QyR5LyV4UBPgTdWyQzNVKA69 -KsSr9lbHEtQFRzGuBKwt6UlSFv9vPWWJkJit5XDKAlcKuGXj0J8OlltToocGElkF -+gEBZfoOWi/IBjRLrFW2cT3p36DTR5O1Ud/1DLnWRqgWNBLrbs2/KMKE6EnHttyD -7Tz8SQkuxltX/yBXMV3Ddy0t6nWV2SZEfuxJAQI= -=spg4 +mQINBGkSZAQBEACprU199OhgdsOsygNjiQV4msuN3vDOUooehL+NwfsGfW79Tbqq +Q2u7uQ3NZjW+M2T4nsDwuhkr7pe7xSReR5W8ssaczvtUyxkvbMClilcgZ2OSCAuC +N9tzJsqOqkwBvXoNXkn//T2jnPz0ZU2wSF+NrEibq5FeuyGdoX3yXXBxq9pW9HzK +HkQll63QSl6BzVSGRQq+B6lGgaZGLwf3mzmIND9Z5VGLNK2jKynyz9z091whNG/M +kV+E7/r/bujHk7WIVId07G5/COTXmSr7kFnNEkd2Umw42dkgfiNKvlmJ9M7c1wLK +KbL9Eb4ADuW6rRc5k4s1e6GT8R4/VPliWbCl9SE32hXH8uTkqVIFZP2eyM5WRRHs +aKzitkQG9UK9gcb0kdgUkxOvvgPHAe5IuZlcHFzU4y0dBbU1VEFWVpiLU0q+IuNw +5BRemeHc59YNsngkmAZ+/9zouoShRusZmC8Wzotv75C2qVBcjijPvmjWAUz0Zunm +Lsr+O71vqHE73pERjD07wuD/ISjiYRYYE/bVrXtXLZijC7qAH4RE3nID+2ojcZyO +/2jMQvt7un56RsGH4UBHi3aBHi9bUoDGCXKiQY981cEuNaOxpou7Mh3x/ONzzSvk +sTV6nl1LOZHykN1JyKwaNbTSAiuyoN+7lOBqbV04DNYAHL88PrT21P83aQARAQAB +tB1SaXBwbGUgTGFicyA8YnVnc0ByaXBwbGUuY29tPokCTgQTAQgAOBYhBLcsBlQv +KuJQJ2OiaNkAhVqp9RTgBQJpEmQEAhsDBQsJCAcCBhUKCQgLAgQWAgMBAh4BAheA +AAoJENkAhVqp9RTgBzgP/i7y+aDWl1maig1XMdyb+o0UGusumFSW4Hmj278wlKVv +usgLPihYgHE0PKrv6WRyKOMC1tQEcYYN93M+OeQ1vFhS2YyURq6RCMmh4zq/awXG +uZbG36OURB5NH8lGBOHiN/7O+nY0CgenBT2JWm+GW3nEOAVOVm4+r5GlpPlv+Dp1 +NPBThcKXFMnH73++NpSQoDzTfRYHPxhDAX3jkLi/moXfSanOLlR6l94XNNN0jBHW +Quao0rzf4WSXq9g6AS224xhAA5JyIcFl8TX7hzj5HaFn3VWo3COoDu4U7H+BM0fl +85yqiMQypp7EhN2gxpMMWaHY5TFM85U/bFXFYfEgihZ4/gt4uoIzsNI9jlX7mYvG +KFdDij+oTlRsuOxdIy60B3dKcwOH9nZZCz0SPsN/zlRWgKzK4gDKdGhFkU9OlvPu +94ZqscanoiWKDoZkF96+sjgfjkuHsDK7Lwc1Xi+T4drHG/3aVpkYabXox+lrKB/S +yxZjeqOIQzWPhnLgCaLyvsKo5hxKzL0w3eURu8F3IS7RgOOlljv4M+Me9sEVcdNV +aN3/tQwbaomSX1X5D5YXqhBwC3rU3wXwamsscRTGEpkV+JCX6KUqGP7nWmxCpAly +FL05XuOd5SVHJjXLeuje0JqLUpN514uL+bThWwDbDTdAdwW3oK/2WbXz7IfJRLBj +uQINBGkSZAQBEADdI3SL2F72qkrgFqXWE6HSRBu9bsAvTE5QrRPWk7ux6at537r4 +S4sIw2dOwLvbyIrDgKNq3LQ5wCK88NO/NeCOFm4AiCJSl3pJHXYnTDoUxTrrxx+o +vSRI4I3fHEql/MqzgiAb0YUezjgFdh3vYheMPp/309PFbOLhiFqEcx80Mx5h06UH +gDzu1qNj3Ec+31NLic5zwkrAkvFvD54d6bqYR3SEgMau6aYEewpGHbWBi2pLqSi2 +lQcAeOFixqGpTwDmAnYR8YtjBYepy0MojEAdTHcQQlOYSDk4q4elG+io2N8vECfU +rD6ORecN48GXdZINYWTAdslrUeanmBdgQrYkSpce8TSghgT9P01SNaXxmyaehVUO +lqI4pcg5G2oojAE8ncNS3TwDtt7daTaTC3bAdr4PXDVAzNAiewjMNZPB7xidkDGQ +Y4W1LxTMXyJVWxehYOH7tsbBRKninlfRnLgYzmtIbNRAAvNcsxU6ihv3AV0WFknN +YbSzotEv1Xq/5wk309x8zCDe+sP0cQicvbXafXmUzPAZzeqFg+VLFn7F9MP1WGlW +B1u7VIvBF1Mp9Nd3EAGBAoLRdRu+0dVWIjPTQuPIuD9cCatJA0wVaKUrjYbBMl88 +a12LixNVGeSFS9N7ADHx0/o7GNT6l88YbaLP6zggUHpUD/bR+cDN7vllIQARAQAB +iQI2BBgBCAAgFiEEtywGVC8q4lAnY6Jo2QCFWqn1FOAFAmkSZAQCGwwACgkQ2QCF +Wqn1FOAfAA/8CYq4p0p4bobY20CKEMsZrkBTFJyPDqzFwMeTjgpzqbD7Y3Qq5QCK +OBbvY02GWdiIsNOzKdBxiuam2xYP9WHZj4y7/uWEvT0qlPVmDFu+HXjoJ43oxwFd +CUp2gMuQ4cSL3X94VRJ3BkVL+tgBm8CNY0vnTLLOO3kum/R69VsGJS1JSGUWjNM+ +4qwS3mz+73xJu1HmERyN2RZF/DGIZI2PyONQQ6aH85G1Dd2ohu2/DBAkQAMBrPbj +FrbDaBLyFhODxU3kTWqnfLlaElSm2EGdIU2yx7n4BggEa//NZRMm5kyeo4vzhtlQ +YIVUMLAOLZvnEqDnsLKp+22FzNR/O+htBQC4lPywl53oYSALdhz1IQlcAC1ru5KR +XPzhIXV6IIzkcx9xNkEclZxmsuy5ERXyKEmLbIHAlzFmnrldlt2ZgXDtzaorLmxj +klKibxd5tF50qOpOivz+oPtFo7n+HmFa1nlVAMxlDCUdM0pEVeYDKI5zfVwalyhZ +NnjpakdZSXMwgc7NP/hH9buF35hKDp7EckT2y3JNYwHsDdy1icXN2q40XZw5tSIn +zkPWdu3OUY8PISohN6Pw4h0RH4ZmoX97E8sEfmdKaT58U4Hf2aAv5r9IWCSrAVqY +u5jvac29CzQR9Kal0A+8phHAXHNFD83SwzIC0syaT9ficAguwGH8X6Q= +=nGuD -----END PGP PUBLIC KEY BLOCK----- ``` diff --git a/cfg/xrpld-example.cfg b/cfg/xrpld-example.cfg index 93fab4a9ba..995d4e65ff 100644 --- a/cfg/xrpld-example.cfg +++ b/cfg/xrpld-example.cfg @@ -940,23 +940,7 @@ # # path Location to store the database # -# Optional keys -# -# cache_size Size of cache for database records. Default is 16384. -# Setting this value to 0 will use the default value. -# -# cache_age Length of time in minutes to keep database records -# cached. Default is 5 minutes. Setting this value to -# 0 will use the default value. -# -# Note: if neither cache_size nor cache_age is -# specified, the cache for database records will not -# be created. If only one of cache_size or cache_age -# is specified, the cache will be created using the -# default value for the unspecified parameter. -# -# Note: the cache will not be created if online_delete -# is specified. +# Optional keys for NuDB and RocksDB: # # fast_load Boolean. If set, load the last persisted ledger # from disk upon process start before syncing to @@ -964,8 +948,6 @@ # if sufficient IOPS capacity is available. # Default 0. # -# Optional keys for NuDB or RocksDB: -# # earliest_seq The default is 32570 to match the XRP ledger # network's earliest allowed sequence. Alternate # networks may set this value. Minimum value of 1. diff --git a/cmake/CMakeFuncs.cmake b/cmake/CMakeFuncs.cmake index e5b2a451f4..ec2d9db330 100644 --- a/cmake/CMakeFuncs.cmake +++ b/cmake/CMakeFuncs.cmake @@ -1,30 +1,29 @@ macro (exclude_from_default target_) - set_target_properties (${target_} PROPERTIES EXCLUDE_FROM_ALL ON) - set_target_properties (${target_} PROPERTIES EXCLUDE_FROM_DEFAULT_BUILD ON) + set_target_properties(${target_} PROPERTIES EXCLUDE_FROM_ALL ON) + set_target_properties(${target_} PROPERTIES EXCLUDE_FROM_DEFAULT_BUILD ON) endmacro () macro (exclude_if_included target_) - get_directory_property(has_parent PARENT_DIRECTORY) - if (has_parent) - exclude_from_default (${target_}) - endif () + get_directory_property(has_parent PARENT_DIRECTORY) + if (has_parent) + exclude_from_default(${target_}) + endif () endmacro () find_package(Git) function (git_branch branch_val) - if (NOT GIT_FOUND) - return () - endif () - set (_branch "") - execute_process (COMMAND ${GIT_EXECUTABLE} "rev-parse" "--abbrev-ref" "HEAD" - WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} - RESULT_VARIABLE _git_exit_code - OUTPUT_VARIABLE _temp_branch - OUTPUT_STRIP_TRAILING_WHITESPACE - ERROR_QUIET) - if (_git_exit_code EQUAL 0) - set (_branch ${_temp_branch}) - endif () - set (${branch_val} "${_branch}" PARENT_SCOPE) + if (NOT GIT_FOUND) + return() + endif () + set(_branch "") + execute_process(COMMAND ${GIT_EXECUTABLE} "rev-parse" "--abbrev-ref" "HEAD" + WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} + RESULT_VARIABLE _git_exit_code + OUTPUT_VARIABLE _temp_branch + OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET) + if (_git_exit_code EQUAL 0) + set(_branch ${_temp_branch}) + endif () + set(${branch_val} "${_branch}" PARENT_SCOPE) endfunction () diff --git a/cmake/Ccache.cmake b/cmake/Ccache.cmake index aa8d3ac59d..000883cf6a 100644 --- a/cmake/Ccache.cmake +++ b/cmake/Ccache.cmake @@ -15,18 +15,17 @@ endif () # https://github.com/ccache/ccache/wiki/MS-Visual-Studio#usage-with-cmake. if ("${CCACHE_PATH}" MATCHES "chocolatey") message(DEBUG "Ccache path: ${CCACHE_PATH}") - # Chocolatey uses a shim executable that we cannot use directly, in which - # case we have to find the executable it points to. If we cannot find the - # target executable then we cannot use ccache. + # Chocolatey uses a shim executable that we cannot use directly, in which case we have to find the executable it + # points to. If we cannot find the target executable then we cannot use ccache. find_program(BASH_PATH "bash") if (NOT BASH_PATH) message(WARNING "Could not find bash.") return() endif () - execute_process( - COMMAND bash -c "export LC_ALL='en_US.UTF-8'; ${CCACHE_PATH} --shimgen-noop | grep -oP 'path to executable: \\K.+' | head -c -1" - OUTPUT_VARIABLE CCACHE_PATH) + execute_process(COMMAND bash -c + "export LC_ALL='en_US.UTF-8'; ${CCACHE_PATH} --shimgen-noop | grep -oP 'path to executable: \\K.+' | head -c -1" + OUTPUT_VARIABLE CCACHE_PATH) if (NOT CCACHE_PATH) message(WARNING "Could not find ccache target.") @@ -37,21 +36,14 @@ endif () message(STATUS "Found ccache: ${CCACHE_PATH}") # Tell cmake to use ccache for compiling with Visual Studio. -file(COPY_FILE - ${CCACHE_PATH} ${CMAKE_BINARY_DIR}/cl.exe - ONLY_IF_DIFFERENT) -set(CMAKE_VS_GLOBALS - "CLToolExe=cl.exe" - "CLToolPath=${CMAKE_BINARY_DIR}" - "TrackFileAccess=false" - "UseMultiToolTask=true") +file(COPY_FILE ${CCACHE_PATH} ${CMAKE_BINARY_DIR}/cl.exe ONLY_IF_DIFFERENT) +set(CMAKE_VS_GLOBALS "CLToolExe=cl.exe" "CLToolPath=${CMAKE_BINARY_DIR}" "TrackFileAccess=false" + "UseMultiToolTask=true") -# By default Visual Studio generators will use /Zi to capture debug information, -# which is not compatible with ccache, so tell it to use /Z7 instead. +# By default Visual Studio generators will use /Zi to capture debug information, which is not compatible with ccache, so +# tell it to use /Z7 instead. if (MSVC) - foreach (var_ - CMAKE_C_FLAGS_DEBUG CMAKE_C_FLAGS_RELEASE - CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE) - string (REPLACE "/Zi" "/Z7" ${var_} "${${var_}}") + foreach (var_ CMAKE_C_FLAGS_DEBUG CMAKE_C_FLAGS_RELEASE CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE) + string(REPLACE "/Zi" "/Z7" ${var_} "${${var_}}") endforeach () endif () diff --git a/cmake/CodeCoverage.cmake b/cmake/CodeCoverage.cmake index e1b44e656d..fcc4d44133 100644 --- a/cmake/CodeCoverage.cmake +++ b/cmake/CodeCoverage.cmake @@ -172,51 +172,47 @@ include(CMakeParseArguments) option(CODE_COVERAGE_VERBOSE "Verbose information" FALSE) # Check prereqs -find_program( GCOVR_PATH gcovr PATHS ${CMAKE_SOURCE_DIR}/scripts/test) +find_program(GCOVR_PATH gcovr PATHS ${CMAKE_SOURCE_DIR}/scripts/test) -if(DEFINED CODE_COVERAGE_GCOV_TOOL) - set(GCOV_TOOL "${CODE_COVERAGE_GCOV_TOOL}") -elseif(DEFINED ENV{CODE_COVERAGE_GCOV_TOOL}) - set(GCOV_TOOL "$ENV{CODE_COVERAGE_GCOV_TOOL}") -elseif("${CMAKE_CXX_COMPILER_ID}" MATCHES "(Apple)?[Cc]lang") - if(APPLE) - execute_process( COMMAND xcrun -f llvm-cov - OUTPUT_VARIABLE LLVMCOV_PATH - OUTPUT_STRIP_TRAILING_WHITESPACE - ) - else() - find_program( LLVMCOV_PATH llvm-cov ) - endif() - if(LLVMCOV_PATH) - set(GCOV_TOOL "${LLVMCOV_PATH} gcov") - endif() -elseif("${CMAKE_CXX_COMPILER_ID}" MATCHES "GNU") - find_program( GCOV_PATH gcov ) - set(GCOV_TOOL "${GCOV_PATH}") -endif() +if (DEFINED CODE_COVERAGE_GCOV_TOOL) + set(GCOV_TOOL "${CODE_COVERAGE_GCOV_TOOL}") +elseif (DEFINED ENV{CODE_COVERAGE_GCOV_TOOL}) + set(GCOV_TOOL "$ENV{CODE_COVERAGE_GCOV_TOOL}") +elseif ("${CMAKE_CXX_COMPILER_ID}" MATCHES "(Apple)?[Cc]lang") + if (APPLE) + execute_process(COMMAND xcrun -f llvm-cov OUTPUT_VARIABLE LLVMCOV_PATH OUTPUT_STRIP_TRAILING_WHITESPACE) + else () + find_program(LLVMCOV_PATH llvm-cov) + endif () + if (LLVMCOV_PATH) + set(GCOV_TOOL "${LLVMCOV_PATH} gcov") + endif () +elseif ("${CMAKE_CXX_COMPILER_ID}" MATCHES "GNU") + find_program(GCOV_PATH gcov) + set(GCOV_TOOL "${GCOV_PATH}") +endif () # Check supported compiler (Clang, GNU and Flang) get_property(LANGUAGES GLOBAL PROPERTY ENABLED_LANGUAGES) -foreach(LANG ${LANGUAGES}) - if("${CMAKE_${LANG}_COMPILER_ID}" MATCHES "(Apple)?[Cc]lang") - if("${CMAKE_${LANG}_COMPILER_VERSION}" VERSION_LESS 3) - message(FATAL_ERROR "Clang version must be 3.0.0 or greater! Aborting...") - endif() - elseif(NOT "${CMAKE_${LANG}_COMPILER_ID}" MATCHES "GNU" - AND NOT "${CMAKE_${LANG}_COMPILER_ID}" MATCHES "(LLVM)?[Ff]lang") - message(FATAL_ERROR "Compiler is not GNU or Flang! Aborting...") - endif() -endforeach() +foreach (LANG ${LANGUAGES}) + if ("${CMAKE_${LANG}_COMPILER_ID}" MATCHES "(Apple)?[Cc]lang") + if ("${CMAKE_${LANG}_COMPILER_VERSION}" VERSION_LESS 3) + message(FATAL_ERROR "Clang version must be 3.0.0 or greater! Aborting...") + endif () + elseif (NOT "${CMAKE_${LANG}_COMPILER_ID}" MATCHES "GNU" AND NOT "${CMAKE_${LANG}_COMPILER_ID}" MATCHES + "(LLVM)?[Ff]lang") + message(FATAL_ERROR "Compiler is not GNU or Flang! Aborting...") + endif () +endforeach () -set(COVERAGE_COMPILER_FLAGS "-g --coverage" - CACHE INTERNAL "") +set(COVERAGE_COMPILER_FLAGS "-g --coverage" CACHE INTERNAL "") set(COVERAGE_CXX_COMPILER_FLAGS "") set(COVERAGE_C_COMPILER_FLAGS "") set(COVERAGE_CXX_LINKER_FLAGS "") set(COVERAGE_C_LINKER_FLAGS "") -if(CMAKE_CXX_COMPILER_ID MATCHES "(GNU|Clang)") +if (CMAKE_CXX_COMPILER_ID MATCHES "(GNU|Clang)") include(CheckCXXCompilerFlag) include(CheckCCompilerFlag) include(CheckLinkerFlag) @@ -227,51 +223,51 @@ if(CMAKE_CXX_COMPILER_ID MATCHES "(GNU|Clang)") set(COVERAGE_C_LINKER_FLAGS ${COVERAGE_COMPILER_FLAGS}) check_cxx_compiler_flag(-fprofile-abs-path HAVE_cxx_fprofile_abs_path) - if(HAVE_cxx_fprofile_abs_path) + if (HAVE_cxx_fprofile_abs_path) set(COVERAGE_CXX_COMPILER_FLAGS "${COVERAGE_CXX_COMPILER_FLAGS} -fprofile-abs-path") - endif() + endif () check_c_compiler_flag(-fprofile-abs-path HAVE_c_fprofile_abs_path) - if(HAVE_c_fprofile_abs_path) + if (HAVE_c_fprofile_abs_path) set(COVERAGE_C_COMPILER_FLAGS "${COVERAGE_C_COMPILER_FLAGS} -fprofile-abs-path") - endif() + endif () check_linker_flag(CXX -fprofile-abs-path HAVE_cxx_linker_fprofile_abs_path) - if(HAVE_cxx_linker_fprofile_abs_path) + if (HAVE_cxx_linker_fprofile_abs_path) set(COVERAGE_CXX_LINKER_FLAGS "${COVERAGE_CXX_LINKER_FLAGS} -fprofile-abs-path") - endif() + endif () check_linker_flag(C -fprofile-abs-path HAVE_c_linker_fprofile_abs_path) - if(HAVE_c_linker_fprofile_abs_path) + if (HAVE_c_linker_fprofile_abs_path) set(COVERAGE_C_LINKER_FLAGS "${COVERAGE_C_LINKER_FLAGS} -fprofile-abs-path") - endif() + endif () check_cxx_compiler_flag(-fprofile-update=atomic HAVE_cxx_fprofile_update) - if(HAVE_cxx_fprofile_update) + if (HAVE_cxx_fprofile_update) set(COVERAGE_CXX_COMPILER_FLAGS "${COVERAGE_CXX_COMPILER_FLAGS} -fprofile-update=atomic") - endif() + endif () check_c_compiler_flag(-fprofile-update=atomic HAVE_c_fprofile_update) - if(HAVE_c_fprofile_update) + if (HAVE_c_fprofile_update) set(COVERAGE_C_COMPILER_FLAGS "${COVERAGE_C_COMPILER_FLAGS} -fprofile-update=atomic") - endif() + endif () check_linker_flag(CXX -fprofile-update=atomic HAVE_cxx_linker_fprofile_update) - if(HAVE_cxx_linker_fprofile_update) + if (HAVE_cxx_linker_fprofile_update) set(COVERAGE_CXX_LINKER_FLAGS "${COVERAGE_CXX_LINKER_FLAGS} -fprofile-update=atomic") - endif() + endif () check_linker_flag(C -fprofile-update=atomic HAVE_c_linker_fprofile_update) - if(HAVE_c_linker_fprofile_update) + if (HAVE_c_linker_fprofile_update) set(COVERAGE_C_LINKER_FLAGS "${COVERAGE_C_LINKER_FLAGS} -fprofile-update=atomic") - endif() + endif () -endif() +endif () get_property(GENERATOR_IS_MULTI_CONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) -if(NOT (CMAKE_BUILD_TYPE STREQUAL "Debug" OR GENERATOR_IS_MULTI_CONFIG)) +if (NOT (CMAKE_BUILD_TYPE STREQUAL "Debug" OR GENERATOR_IS_MULTI_CONFIG)) message(WARNING "Code coverage results with an optimised (non-Debug) build may be misleading") -endif() # NOT (CMAKE_BUILD_TYPE STREQUAL "Debug" OR GENERATOR_IS_MULTI_CONFIG) +endif () # NOT (CMAKE_BUILD_TYPE STREQUAL "Debug" OR GENERATOR_IS_MULTI_CONFIG) # Defines a target for running and collection code coverage information # Builds dependencies, runs the given executable and outputs reports. @@ -295,193 +291,181 @@ endif() # NOT (CMAKE_BUILD_TYPE STREQUAL "Debug" OR GENERATOR_IS_MULTI_CONFIG) # ) # The user can set the variable GCOVR_ADDITIONAL_ARGS to supply additional flags to the # GCVOR command. -function(setup_target_for_coverage_gcovr) +function (setup_target_for_coverage_gcovr) set(options NONE) set(oneValueArgs BASE_DIRECTORY NAME FORMAT) set(multiValueArgs EXCLUDE EXECUTABLE EXECUTABLE_ARGS DEPENDENCIES) cmake_parse_arguments(Coverage "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) - if(NOT GCOV_TOOL) + if (NOT GCOV_TOOL) message(FATAL_ERROR "Could not find gcov or llvm-cov tool! Aborting...") - endif() + endif () - if(NOT GCOVR_PATH) + if (NOT GCOVR_PATH) message(FATAL_ERROR "Could not find gcovr tool! Aborting...") - endif() + endif () # Set base directory (as absolute path), or default to PROJECT_SOURCE_DIR - if(DEFINED Coverage_BASE_DIRECTORY) + if (DEFINED Coverage_BASE_DIRECTORY) get_filename_component(BASEDIR ${Coverage_BASE_DIRECTORY} ABSOLUTE) - else() + else () set(BASEDIR ${PROJECT_SOURCE_DIR}) - endif() + endif () - if(NOT DEFINED Coverage_FORMAT) + if (NOT DEFINED Coverage_FORMAT) set(Coverage_FORMAT xml) - endif() + endif () - if(NOT DEFINED Coverage_EXECUTABLE AND DEFINED Coverage_EXECUTABLE_ARGS) + if (NOT DEFINED Coverage_EXECUTABLE AND DEFINED Coverage_EXECUTABLE_ARGS) message(FATAL_ERROR "EXECUTABLE_ARGS must not be set if EXECUTABLE is not set") - endif() + endif () - if("--output" IN_LIST GCOVR_ADDITIONAL_ARGS) + if ("--output" IN_LIST GCOVR_ADDITIONAL_ARGS) message(FATAL_ERROR "Unsupported --output option detected in GCOVR_ADDITIONAL_ARGS! Aborting...") - else() - if((Coverage_FORMAT STREQUAL "html-details") - OR (Coverage_FORMAT STREQUAL "html-nested")) + else () + if ((Coverage_FORMAT STREQUAL "html-details") OR (Coverage_FORMAT STREQUAL "html-nested")) set(GCOVR_OUTPUT_FILE ${PROJECT_BINARY_DIR}/${Coverage_NAME}/index.html) set(GCOVR_CREATE_FOLDER ${PROJECT_BINARY_DIR}/${Coverage_NAME}) - elseif(Coverage_FORMAT STREQUAL "html-single") + elseif (Coverage_FORMAT STREQUAL "html-single") set(GCOVR_OUTPUT_FILE ${Coverage_NAME}.html) - elseif((Coverage_FORMAT STREQUAL "json-summary") - OR (Coverage_FORMAT STREQUAL "json-details") - OR (Coverage_FORMAT STREQUAL "coveralls")) + elseif ((Coverage_FORMAT STREQUAL "json-summary") OR (Coverage_FORMAT STREQUAL "json-details") + OR (Coverage_FORMAT STREQUAL "coveralls")) set(GCOVR_OUTPUT_FILE ${Coverage_NAME}.json) - elseif(Coverage_FORMAT STREQUAL "txt") + elseif (Coverage_FORMAT STREQUAL "txt") set(GCOVR_OUTPUT_FILE ${Coverage_NAME}.txt) - elseif(Coverage_FORMAT STREQUAL "csv") + elseif (Coverage_FORMAT STREQUAL "csv") set(GCOVR_OUTPUT_FILE ${Coverage_NAME}.csv) - elseif(Coverage_FORMAT STREQUAL "lcov") + elseif (Coverage_FORMAT STREQUAL "lcov") set(GCOVR_OUTPUT_FILE ${Coverage_NAME}.lcov) - else() + else () set(GCOVR_OUTPUT_FILE ${Coverage_NAME}.xml) - endif() - endif() + endif () + endif () - if((Coverage_FORMAT STREQUAL "cobertura") - OR (Coverage_FORMAT STREQUAL "xml")) - list(APPEND GCOVR_ADDITIONAL_ARGS --cobertura "${GCOVR_OUTPUT_FILE}" ) - list(APPEND GCOVR_ADDITIONAL_ARGS --cobertura-pretty ) + if ((Coverage_FORMAT STREQUAL "cobertura") OR (Coverage_FORMAT STREQUAL "xml")) + list(APPEND GCOVR_ADDITIONAL_ARGS --cobertura "${GCOVR_OUTPUT_FILE}") + list(APPEND GCOVR_ADDITIONAL_ARGS --cobertura-pretty) set(Coverage_FORMAT cobertura) # overwrite xml - elseif(Coverage_FORMAT STREQUAL "sonarqube") - list(APPEND GCOVR_ADDITIONAL_ARGS --sonarqube "${GCOVR_OUTPUT_FILE}" ) - elseif(Coverage_FORMAT STREQUAL "jacoco") - list(APPEND GCOVR_ADDITIONAL_ARGS --jacoco "${GCOVR_OUTPUT_FILE}" ) - list(APPEND GCOVR_ADDITIONAL_ARGS --jacoco-pretty ) - elseif(Coverage_FORMAT STREQUAL "clover") - list(APPEND GCOVR_ADDITIONAL_ARGS --clover "${GCOVR_OUTPUT_FILE}" ) - list(APPEND GCOVR_ADDITIONAL_ARGS --clover-pretty ) - elseif(Coverage_FORMAT STREQUAL "lcov") - list(APPEND GCOVR_ADDITIONAL_ARGS --lcov "${GCOVR_OUTPUT_FILE}" ) - elseif(Coverage_FORMAT STREQUAL "json-summary") - list(APPEND GCOVR_ADDITIONAL_ARGS --json-summary "${GCOVR_OUTPUT_FILE}" ) + elseif (Coverage_FORMAT STREQUAL "sonarqube") + list(APPEND GCOVR_ADDITIONAL_ARGS --sonarqube "${GCOVR_OUTPUT_FILE}") + elseif (Coverage_FORMAT STREQUAL "jacoco") + list(APPEND GCOVR_ADDITIONAL_ARGS --jacoco "${GCOVR_OUTPUT_FILE}") + list(APPEND GCOVR_ADDITIONAL_ARGS --jacoco-pretty) + elseif (Coverage_FORMAT STREQUAL "clover") + list(APPEND GCOVR_ADDITIONAL_ARGS --clover "${GCOVR_OUTPUT_FILE}") + list(APPEND GCOVR_ADDITIONAL_ARGS --clover-pretty) + elseif (Coverage_FORMAT STREQUAL "lcov") + list(APPEND GCOVR_ADDITIONAL_ARGS --lcov "${GCOVR_OUTPUT_FILE}") + elseif (Coverage_FORMAT STREQUAL "json-summary") + list(APPEND GCOVR_ADDITIONAL_ARGS --json-summary "${GCOVR_OUTPUT_FILE}") list(APPEND GCOVR_ADDITIONAL_ARGS --json-summary-pretty) - elseif(Coverage_FORMAT STREQUAL "json-details") - list(APPEND GCOVR_ADDITIONAL_ARGS --json "${GCOVR_OUTPUT_FILE}" ) + elseif (Coverage_FORMAT STREQUAL "json-details") + list(APPEND GCOVR_ADDITIONAL_ARGS --json "${GCOVR_OUTPUT_FILE}") list(APPEND GCOVR_ADDITIONAL_ARGS --json-pretty) - elseif(Coverage_FORMAT STREQUAL "coveralls") - list(APPEND GCOVR_ADDITIONAL_ARGS --coveralls "${GCOVR_OUTPUT_FILE}" ) + elseif (Coverage_FORMAT STREQUAL "coveralls") + list(APPEND GCOVR_ADDITIONAL_ARGS --coveralls "${GCOVR_OUTPUT_FILE}") list(APPEND GCOVR_ADDITIONAL_ARGS --coveralls-pretty) - elseif(Coverage_FORMAT STREQUAL "csv") - list(APPEND GCOVR_ADDITIONAL_ARGS --csv "${GCOVR_OUTPUT_FILE}" ) - elseif(Coverage_FORMAT STREQUAL "txt") - list(APPEND GCOVR_ADDITIONAL_ARGS --txt "${GCOVR_OUTPUT_FILE}" ) - elseif(Coverage_FORMAT STREQUAL "html-single") - list(APPEND GCOVR_ADDITIONAL_ARGS --html "${GCOVR_OUTPUT_FILE}" ) + elseif (Coverage_FORMAT STREQUAL "csv") + list(APPEND GCOVR_ADDITIONAL_ARGS --csv "${GCOVR_OUTPUT_FILE}") + elseif (Coverage_FORMAT STREQUAL "txt") + list(APPEND GCOVR_ADDITIONAL_ARGS --txt "${GCOVR_OUTPUT_FILE}") + elseif (Coverage_FORMAT STREQUAL "html-single") + list(APPEND GCOVR_ADDITIONAL_ARGS --html "${GCOVR_OUTPUT_FILE}") list(APPEND GCOVR_ADDITIONAL_ARGS --html-self-contained) - elseif(Coverage_FORMAT STREQUAL "html-nested") - list(APPEND GCOVR_ADDITIONAL_ARGS --html-nested "${GCOVR_OUTPUT_FILE}" ) - elseif(Coverage_FORMAT STREQUAL "html-details") - list(APPEND GCOVR_ADDITIONAL_ARGS --html-details "${GCOVR_OUTPUT_FILE}" ) - else() + elseif (Coverage_FORMAT STREQUAL "html-nested") + list(APPEND GCOVR_ADDITIONAL_ARGS --html-nested "${GCOVR_OUTPUT_FILE}") + elseif (Coverage_FORMAT STREQUAL "html-details") + list(APPEND GCOVR_ADDITIONAL_ARGS --html-details "${GCOVR_OUTPUT_FILE}") + else () message(FATAL_ERROR "Unsupported output style ${Coverage_FORMAT}! Aborting...") - endif() + endif () # Collect excludes (CMake 3.4+: Also compute absolute paths) set(GCOVR_EXCLUDES "") - foreach(EXCLUDE ${Coverage_EXCLUDE} ${COVERAGE_EXCLUDES} ${COVERAGE_GCOVR_EXCLUDES}) - if(CMAKE_VERSION VERSION_GREATER 3.4) + foreach (EXCLUDE ${Coverage_EXCLUDE} ${COVERAGE_EXCLUDES} ${COVERAGE_GCOVR_EXCLUDES}) + if (CMAKE_VERSION VERSION_GREATER 3.4) get_filename_component(EXCLUDE ${EXCLUDE} ABSOLUTE BASE_DIR ${BASEDIR}) - endif() + endif () list(APPEND GCOVR_EXCLUDES "${EXCLUDE}") - endforeach() + endforeach () list(REMOVE_DUPLICATES GCOVR_EXCLUDES) # Combine excludes to several -e arguments set(GCOVR_EXCLUDE_ARGS "") - foreach(EXCLUDE ${GCOVR_EXCLUDES}) + foreach (EXCLUDE ${GCOVR_EXCLUDES}) list(APPEND GCOVR_EXCLUDE_ARGS "-e") list(APPEND GCOVR_EXCLUDE_ARGS "${EXCLUDE}") - endforeach() + endforeach () # Set up commands which will be run to generate coverage data # If EXECUTABLE is not set, the user is expected to run the tests manually # before running the coverage target NAME - if(DEFINED Coverage_EXECUTABLE) - set(GCOVR_EXEC_TESTS_CMD - ${Coverage_EXECUTABLE} ${Coverage_EXECUTABLE_ARGS} - ) - endif() + if (DEFINED Coverage_EXECUTABLE) + set(GCOVR_EXEC_TESTS_CMD ${Coverage_EXECUTABLE} ${Coverage_EXECUTABLE_ARGS}) + endif () # Create folder - if(DEFINED GCOVR_CREATE_FOLDER) - set(GCOVR_FOLDER_CMD - ${CMAKE_COMMAND} -E make_directory ${GCOVR_CREATE_FOLDER}) - endif() + if (DEFINED GCOVR_CREATE_FOLDER) + set(GCOVR_FOLDER_CMD ${CMAKE_COMMAND} -E make_directory ${GCOVR_CREATE_FOLDER}) + endif () # Running gcovr set(GCOVR_CMD ${GCOVR_PATH} - --gcov-executable ${GCOV_TOOL} + --gcov-executable + ${GCOV_TOOL} --gcov-ignore-parse-errors=negative_hits.warn_once_per_file - -r ${BASEDIR} + -r + ${BASEDIR} ${GCOVR_ADDITIONAL_ARGS} ${GCOVR_EXCLUDE_ARGS} - --object-directory=${PROJECT_BINARY_DIR} - ) + --object-directory=${PROJECT_BINARY_DIR}) - if(CODE_COVERAGE_VERBOSE) + if (CODE_COVERAGE_VERBOSE) message(STATUS "Executed command report") - if(NOT "${GCOVR_EXEC_TESTS_CMD}" STREQUAL "") + if (NOT "${GCOVR_EXEC_TESTS_CMD}" STREQUAL "") message(STATUS "Command to run tests: ") string(REPLACE ";" " " GCOVR_EXEC_TESTS_CMD_SPACED "${GCOVR_EXEC_TESTS_CMD}") message(STATUS "${GCOVR_EXEC_TESTS_CMD_SPACED}") - endif() + endif () - if(NOT "${GCOVR_FOLDER_CMD}" STREQUAL "") + if (NOT "${GCOVR_FOLDER_CMD}" STREQUAL "") message(STATUS "Command to create a folder: ") string(REPLACE ";" " " GCOVR_FOLDER_CMD_SPACED "${GCOVR_FOLDER_CMD}") message(STATUS "${GCOVR_FOLDER_CMD_SPACED}") - endif() + endif () message(STATUS "Command to generate gcovr coverage data: ") string(REPLACE ";" " " GCOVR_CMD_SPACED "${GCOVR_CMD}") message(STATUS "${GCOVR_CMD_SPACED}") - endif() + endif () add_custom_target(${Coverage_NAME} - COMMAND ${GCOVR_EXEC_TESTS_CMD} - COMMAND ${GCOVR_FOLDER_CMD} - COMMAND ${GCOVR_CMD} - - BYPRODUCTS ${GCOVR_OUTPUT_FILE} - WORKING_DIRECTORY ${PROJECT_BINARY_DIR} - DEPENDS ${Coverage_DEPENDENCIES} - VERBATIM # Protect arguments to commands - COMMENT "Running gcovr to produce code coverage report." - ) + COMMAND ${GCOVR_EXEC_TESTS_CMD} + COMMAND ${GCOVR_FOLDER_CMD} + COMMAND ${GCOVR_CMD} + BYPRODUCTS ${GCOVR_OUTPUT_FILE} + WORKING_DIRECTORY ${PROJECT_BINARY_DIR} + DEPENDS ${Coverage_DEPENDENCIES} + VERBATIM # Protect arguments to commands + COMMENT "Running gcovr to produce code coverage report.") # Show info where to find the report - add_custom_command(TARGET ${Coverage_NAME} POST_BUILD - COMMAND echo - COMMENT "Code coverage report saved in ${GCOVR_OUTPUT_FILE} formatted as ${Coverage_FORMAT}" - ) -endfunction() # setup_target_for_coverage_gcovr + add_custom_command(TARGET ${Coverage_NAME} POST_BUILD COMMAND echo + COMMENT "Code coverage report saved in ${GCOVR_OUTPUT_FILE} formatted as ${Coverage_FORMAT}") +endfunction () # setup_target_for_coverage_gcovr -function(add_code_coverage_to_target name scope) +function (add_code_coverage_to_target name scope) separate_arguments(COVERAGE_CXX_COMPILER_FLAGS NATIVE_COMMAND "${COVERAGE_CXX_COMPILER_FLAGS}") separate_arguments(COVERAGE_C_COMPILER_FLAGS NATIVE_COMMAND "${COVERAGE_C_COMPILER_FLAGS}") separate_arguments(COVERAGE_CXX_LINKER_FLAGS NATIVE_COMMAND "${COVERAGE_CXX_LINKER_FLAGS}") separate_arguments(COVERAGE_C_LINKER_FLAGS NATIVE_COMMAND "${COVERAGE_C_LINKER_FLAGS}") # Add compiler options to the target - target_compile_options(${name} ${scope} - $<$:${COVERAGE_CXX_COMPILER_FLAGS}> - $<$:${COVERAGE_C_COMPILER_FLAGS}>) + target_compile_options(${name} ${scope} $<$:${COVERAGE_CXX_COMPILER_FLAGS}> + $<$:${COVERAGE_C_COMPILER_FLAGS}>) - target_link_libraries (${name} ${scope} - $<$:${COVERAGE_CXX_LINKER_FLAGS} gcov> - $<$:${COVERAGE_C_LINKER_FLAGS} gcov> - ) -endfunction() # add_code_coverage_to_target + target_link_libraries(${name} ${scope} $<$:${COVERAGE_CXX_LINKER_FLAGS}> + $<$:${COVERAGE_C_LINKER_FLAGS}>) +endfunction () # add_code_coverage_to_target diff --git a/cmake/CompilationEnv.cmake b/cmake/CompilationEnv.cmake index 345e4cdd62..59b903c13a 100644 --- a/cmake/CompilationEnv.cmake +++ b/cmake/CompilationEnv.cmake @@ -1,8 +1,7 @@ - # Shared detection of compiler, operating system, and architecture. - # - # This module centralizes environment detection so that other - # CMake modules can use the same variables instead of repeating - # checks on CMAKE_* and built-in platform variables. +# Shared detection of compiler, operating system, and architecture. +# +# This module centralizes environment detection so that other CMake modules can use the same variables instead of +# repeating checks on CMAKE_* and built-in platform variables. # Only run once per configure step. include_guard(GLOBAL) @@ -13,17 +12,22 @@ include_guard(GLOBAL) set(is_clang FALSE) set(is_gcc FALSE) set(is_msvc FALSE) +set(is_xcode FALSE) -if(CMAKE_CXX_COMPILER_ID MATCHES ".*Clang") # Clang or AppleClang - set(is_clang TRUE) -elseif(CMAKE_CXX_COMPILER_ID STREQUAL "GNU") - set(is_gcc TRUE) -elseif(MSVC) - set(is_msvc TRUE) -else() - message(FATAL_ERROR "Unsupported C++ compiler: ${CMAKE_CXX_COMPILER_ID}") -endif() +if (CMAKE_CXX_COMPILER_ID MATCHES ".*Clang") # Clang or AppleClang + set(is_clang TRUE) +elseif (CMAKE_CXX_COMPILER_ID STREQUAL "GNU") + set(is_gcc TRUE) +elseif (MSVC) + set(is_msvc TRUE) +else () + message(FATAL_ERROR "Unsupported C++ compiler: ${CMAKE_CXX_COMPILER_ID}") +endif () +# Xcode generator detection +if (CMAKE_GENERATOR STREQUAL "Xcode") + set(is_xcode TRUE) +endif () # -------------------------------------------------------------------- # Operating system detection @@ -32,23 +36,23 @@ set(is_linux FALSE) set(is_windows FALSE) set(is_macos FALSE) -if(CMAKE_SYSTEM_NAME STREQUAL "Linux") - set(is_linux TRUE) -elseif(CMAKE_SYSTEM_NAME STREQUAL "Windows") - set(is_windows TRUE) -elseif(CMAKE_SYSTEM_NAME STREQUAL "Darwin") - set(is_macos TRUE) -endif() +if (CMAKE_SYSTEM_NAME STREQUAL "Linux") + set(is_linux TRUE) +elseif (CMAKE_SYSTEM_NAME STREQUAL "Windows") + set(is_windows TRUE) +elseif (CMAKE_SYSTEM_NAME STREQUAL "Darwin") + set(is_macos TRUE) +endif () # -------------------------------------------------------------------- # Architecture # -------------------------------------------------------------------- set(is_amd64 FALSE) set(is_arm64 FALSE) -if(CMAKE_SYSTEM_PROCESSOR MATCHES "x86_64|AMD64") - set(is_amd64 TRUE) -elseif(CMAKE_SYSTEM_PROCESSOR MATCHES "aarch64|arm64") - set(is_arm64 TRUE) -else() - message(FATAL_ERROR "Unknown architecture: ${CMAKE_SYSTEM_PROCESSOR}") -endif() +if (CMAKE_SYSTEM_PROCESSOR MATCHES "x86_64|AMD64") + set(is_amd64 TRUE) +elseif (CMAKE_SYSTEM_PROCESSOR MATCHES "aarch64|arm64|ARM64") + set(is_arm64 TRUE) +else () + message(FATAL_ERROR "Unknown architecture: ${CMAKE_SYSTEM_PROCESSOR}") +endif () diff --git a/cmake/XrplAddTest.cmake b/cmake/XrplAddTest.cmake index 191a25c467..35189e203f 100644 --- a/cmake/XrplAddTest.cmake +++ b/cmake/XrplAddTest.cmake @@ -1,25 +1,13 @@ include(isolate_headers) -function(xrpl_add_test name) - set(target ${PROJECT_NAME}.test.${name}) +function (xrpl_add_test name) + set(target ${PROJECT_NAME}.test.${name}) - file(GLOB_RECURSE sources CONFIGURE_DEPENDS - "${CMAKE_CURRENT_SOURCE_DIR}/${name}/*.cpp" - "${CMAKE_CURRENT_SOURCE_DIR}/${name}.cpp" - ) - add_executable(${target} ${ARGN} ${sources}) + file(GLOB_RECURSE sources CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/${name}/*.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/${name}.cpp") + add_executable(${target} ${ARGN} ${sources}) - isolate_headers( - ${target} - "${CMAKE_SOURCE_DIR}" - "${CMAKE_SOURCE_DIR}/tests/${name}" - PRIVATE - ) + isolate_headers(${target} "${CMAKE_SOURCE_DIR}" "${CMAKE_SOURCE_DIR}/tests/${name}" PRIVATE) - # Make sure the test isn't optimized away in unity builds - set_target_properties(${target} PROPERTIES - UNITY_BUILD_MODE GROUP - UNITY_BUILD_BATCH_SIZE 0) # Adjust as needed - - add_test(NAME ${target} COMMAND ${target}) -endfunction() + add_test(NAME ${target} COMMAND ${target}) +endfunction () diff --git a/cmake/XrplCompiler.cmake b/cmake/XrplCompiler.cmake index a7c5ff0423..f7ac8c2b71 100644 --- a/cmake/XrplCompiler.cmake +++ b/cmake/XrplCompiler.cmake @@ -8,153 +8,155 @@ include(CompilationEnv) TODO some/most of these common settings belong in a toolchain file, especially the ABI-impacting ones #]=========================================================] -add_library (common INTERFACE) -add_library (Xrpl::common ALIAS common) +add_library(common INTERFACE) +add_library(Xrpl::common ALIAS common) include(XrplSanitizers) # add a single global dependency on this interface lib -link_libraries (Xrpl::common) +link_libraries(Xrpl::common) # Respect CMAKE_POSITION_INDEPENDENT_CODE setting (may be set by Conan toolchain) -if(NOT DEFINED CMAKE_POSITION_INDEPENDENT_CODE) - set(CMAKE_POSITION_INDEPENDENT_CODE ON) -endif() -set_target_properties (common - PROPERTIES INTERFACE_POSITION_INDEPENDENT_CODE ${CMAKE_POSITION_INDEPENDENT_CODE}) +if (NOT DEFINED CMAKE_POSITION_INDEPENDENT_CODE) + set(CMAKE_POSITION_INDEPENDENT_CODE ON) +endif () +set_target_properties(common PROPERTIES INTERFACE_POSITION_INDEPENDENT_CODE ${CMAKE_POSITION_INDEPENDENT_CODE}) set(CMAKE_CXX_EXTENSIONS OFF) -target_compile_definitions (common - INTERFACE - $<$:DEBUG _DEBUG> - #[===[ +target_compile_definitions( + common + INTERFACE $<$:DEBUG + _DEBUG> + #[===[ NOTE: CMAKE release builds already have NDEBUG defined, so no need to add it explicitly except for the special case of (profile ON) and (assert OFF). Presumably this is because we don't want profile builds asserting unless asserts were specifically requested. ]===] - $<$,$>>:NDEBUG> - # TODO: Remove once we have migrated functions from OpenSSL 1.x to 3.x. - OPENSSL_SUPPRESS_DEPRECATED -) + $<$,$>>:NDEBUG> + # TODO: Remove once we have migrated functions from OpenSSL 1.x to 3.x. + OPENSSL_SUPPRESS_DEPRECATED) if (MSVC) - # remove existing exception flag since we set it to -EHa - string (REGEX REPLACE "[-/]EH[a-z]+" "" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}") + # remove existing exception flag since we set it to -EHa + string(REGEX REPLACE "[-/]EH[a-z]+" "" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}") - foreach (var_ - CMAKE_C_FLAGS_DEBUG CMAKE_C_FLAGS_RELEASE - CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE) + foreach (var_ CMAKE_C_FLAGS_DEBUG CMAKE_C_FLAGS_RELEASE CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE) - # also remove dynamic runtime - string (REGEX REPLACE "[-/]MD[d]*" " " ${var_} "${${var_}}") + # also remove dynamic runtime + string(REGEX REPLACE "[-/]MD[d]*" " " ${var_} "${${var_}}") - # /ZI (Edit & Continue debugging information) is incompatible with Gy- - string (REPLACE "/ZI" "/Zi" ${var_} "${${var_}}") + # /ZI (Edit & Continue debugging information) is incompatible with Gy- + string(REPLACE "/ZI" "/Zi" ${var_} "${${var_}}") - # omit debug info completely under CI (not needed) - if (is_ci) - string (REPLACE "/Zi" " " ${var_} "${${var_}}") - string (REPLACE "/Z7" " " ${var_} "${${var_}}") - endif () - endforeach () + # omit debug info completely under CI (not needed) + if (is_ci) + string(REPLACE "/Zi" " " ${var_} "${${var_}}") + string(REPLACE "/Z7" " " ${var_} "${${var_}}") + endif () + endforeach () - target_compile_options (common - INTERFACE - -bigobj # Increase object file max size - -fp:precise # Floating point behavior - -Gd # __cdecl calling convention - -Gm- # Minimal rebuild: disabled - -Gy- # Function level linking: disabled - -MP # Multiprocessor compilation - -openmp- # pragma omp: disabled - -errorReport:none # No error reporting to Internet - -nologo # Suppress login banner - -wd4018 # Disable signed/unsigned comparison warnings - -wd4244 # Disable float to int possible loss of data warnings - -wd4267 # Disable size_t to T possible loss of data warnings - -wd4800 # Disable C4800(int to bool performance) - -wd4503 # Decorated name length exceeded, name was truncated - $<$: - -EHa - -GR - > - $<$:-Ox> - $<$,$>: - -GS - -Zc:forScope - > - # static runtime - $<$:-MTd> - $<$>:-MT> - $<$:-WX> - ) - target_compile_definitions (common - INTERFACE - _WIN32_WINNT=0x6000 - _SCL_SECURE_NO_WARNINGS - _CRT_SECURE_NO_WARNINGS - WIN32_CONSOLE - WIN32_LEAN_AND_MEAN - NOMINMAX - # TODO: Resolve these warnings, don't just silence them - _SILENCE_ALL_CXX17_DEPRECATION_WARNINGS - $<$,$>:_CRTDBG_MAP_ALLOC>) - target_link_libraries (common - INTERFACE - -errorreport:none - -machine:X64) + target_compile_options( + common + INTERFACE # Increase object file max size + -bigobj + # Floating point behavior + -fp:precise + # __cdecl calling convention + -Gd + # Minimal rebuild: disabled + -Gm- + # Function level linking: disabled + -Gy- + # Multiprocessor compilation + -MP + # pragma omp: disabled + -openmp- + # No error reporting to Internet + -errorReport:none + # Suppress login banner + -nologo + # Disable signed/unsigned comparison warnings + -wd4018 + # Disable float to int possible loss of data warnings + -wd4244 + # Disable size_t to T possible loss of data warnings + -wd4267 + # Disable C4800(int to bool performance) + -wd4800 + # Decorated name length exceeded, name was truncated + -wd4503 + $<$: + -EHa + -GR + > + $<$:-Ox> + $<$,$>: + -GS + -Zc:forScope + > + # static runtime + $<$:-MTd> + $<$>:-MT> + $<$:-WX>) + target_compile_definitions( + common + INTERFACE _WIN32_WINNT=0x6000 + _SCL_SECURE_NO_WARNINGS + _CRT_SECURE_NO_WARNINGS + WIN32_CONSOLE + WIN32_LEAN_AND_MEAN + NOMINMAX + # TODO: Resolve these warnings, don't just silence them + _SILENCE_ALL_CXX17_DEPRECATION_WARNINGS + $<$,$>:_CRTDBG_MAP_ALLOC>) + target_link_libraries(common INTERFACE -errorreport:none -machine:X64) else () - target_compile_options (common - INTERFACE - -Wall - -Wdeprecated - $<$:-Wno-deprecated-declarations> - $<$:-Wextra -Wno-unused-parameter> - $<$:-Werror> - -fstack-protector - -Wno-sign-compare - -Wno-unused-but-set-variable - $<$>:-fno-strict-aliasing> - # tweak gcc optimization for debug - $<$,$>:-O0> - # Add debug symbols to release config - $<$:-g>) - target_link_libraries (common - INTERFACE - -rdynamic - $<$:-Wl,-z,relro,-z,now,--build-id> - # link to static libc/c++ iff: - # * static option set and - # * NOT APPLE (AppleClang does not support static libc/c++) and - # * NOT SANITIZERS (sanitizers typically don't work with static libc/c++) - $<$,$>,$>>: - -static-libstdc++ - -static-libgcc - >) + target_compile_options( + common + INTERFACE -Wall + -Wdeprecated + $<$:-Wno-deprecated-declarations> + $<$:-Wextra + -Wno-unused-parameter> + $<$:-Werror> + -fstack-protector + -Wno-sign-compare + -Wno-unused-but-set-variable + $<$>:-fno-strict-aliasing> + # tweak gcc optimization for debug + $<$,$>:-O0> + # Add debug symbols to release config + $<$:-g>) + target_link_libraries( + common + INTERFACE -rdynamic + $<$:-Wl,-z,relro,-z,now,--build-id> + # link to static libc/c++ iff: * static option set and * NOT APPLE (AppleClang does not support static + # libc/c++) and * NOT SANITIZERS (sanitizers typically don't work with static libc/c++) + $<$,$>,$>>: + -static-libstdc++ + -static-libgcc + >) endif () # Antithesis instrumentation will only be built and deployed using machines running Linux. if (voidstar) - if (NOT CMAKE_BUILD_TYPE STREQUAL "Debug") - message(FATAL_ERROR "Antithesis instrumentation requires Debug build type, aborting...") - elseif (NOT is_linux) - message(FATAL_ERROR "Antithesis instrumentation requires Linux, aborting...") - elseif (NOT (is_clang AND CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 16.0)) - message(FATAL_ERROR "Antithesis instrumentation requires Clang version 16 or later, aborting...") - endif () + if (NOT CMAKE_BUILD_TYPE STREQUAL "Debug") + message(FATAL_ERROR "Antithesis instrumentation requires Debug build type, aborting...") + elseif (NOT is_linux) + message(FATAL_ERROR "Antithesis instrumentation requires Linux, aborting...") + elseif (NOT (is_clang AND CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 16.0)) + message(FATAL_ERROR "Antithesis instrumentation requires Clang version 16 or later, aborting...") + endif () endif () if (use_mold) - # use mold linker if available - execute_process ( - COMMAND ${CMAKE_CXX_COMPILER} -fuse-ld=mold -Wl,--version - ERROR_QUIET OUTPUT_VARIABLE LD_VERSION) - if ("${LD_VERSION}" MATCHES "mold") - target_link_libraries (common INTERFACE -fuse-ld=mold) - endif () - unset (LD_VERSION) + # use mold linker if available + execute_process(COMMAND ${CMAKE_CXX_COMPILER} -fuse-ld=mold -Wl,--version ERROR_QUIET OUTPUT_VARIABLE LD_VERSION) + if ("${LD_VERSION}" MATCHES "mold") + target_link_libraries(common INTERFACE -fuse-ld=mold) + endif () + unset(LD_VERSION) elseif (use_gold AND is_gcc) - # use gold linker if available - execute_process ( - COMMAND ${CMAKE_CXX_COMPILER} -fuse-ld=gold -Wl,--version - ERROR_QUIET OUTPUT_VARIABLE LD_VERSION) + # use gold linker if available + execute_process(COMMAND ${CMAKE_CXX_COMPILER} -fuse-ld=gold -Wl,--version ERROR_QUIET OUTPUT_VARIABLE LD_VERSION) #[=========================================================[ NOTE: THE gold linker inserts -rpath as DT_RUNPATH by default instead of DT_RPATH, so you might have slightly @@ -168,34 +170,31 @@ elseif (use_gold AND is_gcc) disabling would be to figure out all the settings required to make gold play nicely with jemalloc. #]=========================================================] - if (("${LD_VERSION}" MATCHES "GNU gold") AND (NOT jemalloc)) - target_link_libraries (common - INTERFACE - -fuse-ld=gold - -Wl,--no-as-needed - #[=========================================================[ + if (("${LD_VERSION}" MATCHES "GNU gold") AND (NOT jemalloc)) + target_link_libraries( + common + INTERFACE -fuse-ld=gold + -Wl,--no-as-needed + #[=========================================================[ see https://bugs.launchpad.net/ubuntu/+source/eglibc/+bug/1253638/comments/5 DT_RUNPATH does not work great for transitive dependencies (of which boost has a few) - so just switch to DT_RPATH if doing dynamic linking with gold #]=========================================================] - $<$>:-Wl,--disable-new-dtags>) - endif () - unset (LD_VERSION) + $<$>:-Wl,--disable-new-dtags>) + endif () + unset(LD_VERSION) elseif (use_lld) - # use lld linker if available - execute_process ( - COMMAND ${CMAKE_CXX_COMPILER} -fuse-ld=lld -Wl,--version - ERROR_QUIET OUTPUT_VARIABLE LD_VERSION) - if ("${LD_VERSION}" MATCHES "LLD") - target_link_libraries (common INTERFACE -fuse-ld=lld) - endif () - unset (LD_VERSION) -endif() - + # use lld linker if available + execute_process(COMMAND ${CMAKE_CXX_COMPILER} -fuse-ld=lld -Wl,--version ERROR_QUIET OUTPUT_VARIABLE LD_VERSION) + if ("${LD_VERSION}" MATCHES "LLD") + target_link_libraries(common INTERFACE -fuse-ld=lld) + endif () + unset(LD_VERSION) +endif () if (assert) - foreach (var_ CMAKE_C_FLAGS_RELEASE CMAKE_CXX_FLAGS_RELEASE) - STRING (REGEX REPLACE "[-/]DNDEBUG" "" ${var_} "${${var_}}") - endforeach () + foreach (var_ CMAKE_C_FLAGS_RELEASE CMAKE_CXX_FLAGS_RELEASE) + string(REGEX REPLACE "[-/]DNDEBUG" "" ${var_} "${${var_}}") + endforeach () endif () diff --git a/cmake/XrplConfig.cmake b/cmake/XrplConfig.cmake index 8a739d48a3..bf6aa475ba 100644 --- a/cmake/XrplConfig.cmake +++ b/cmake/XrplConfig.cmake @@ -1,54 +1,52 @@ -include (CMakeFindDependencyMacro) +include(CMakeFindDependencyMacro) # need to represent system dependencies of the lib here #[=========================================================[ Boost #]=========================================================] if (static OR APPLE OR MSVC) - set (Boost_USE_STATIC_LIBS ON) + set(Boost_USE_STATIC_LIBS ON) endif () -set (Boost_USE_MULTITHREADED ON) +set(Boost_USE_MULTITHREADED ON) if (static OR MSVC) - set (Boost_USE_STATIC_RUNTIME ON) + set(Boost_USE_STATIC_RUNTIME ON) else () - set (Boost_USE_STATIC_RUNTIME OFF) + set(Boost_USE_STATIC_RUNTIME OFF) endif () -find_dependency (Boost - COMPONENTS - chrono - container - context - coroutine - date_time - filesystem - program_options - regex - system - thread) +find_dependency(Boost + COMPONENTS + chrono + container + context + coroutine + date_time + filesystem + program_options + regex + system + thread) #[=========================================================[ OpenSSL #]=========================================================] if (NOT DEFINED OPENSSL_ROOT_DIR) - if (DEFINED ENV{OPENSSL_ROOT}) - set (OPENSSL_ROOT_DIR $ENV{OPENSSL_ROOT}) - elseif (APPLE) - find_program (homebrew brew) - if (homebrew) - execute_process (COMMAND ${homebrew} --prefix openssl - OUTPUT_VARIABLE OPENSSL_ROOT_DIR - OUTPUT_STRIP_TRAILING_WHITESPACE) + if (DEFINED ENV{OPENSSL_ROOT}) + set(OPENSSL_ROOT_DIR $ENV{OPENSSL_ROOT}) + elseif (APPLE) + find_program(homebrew brew) + if (homebrew) + execute_process(COMMAND ${homebrew} --prefix openssl OUTPUT_VARIABLE OPENSSL_ROOT_DIR + OUTPUT_STRIP_TRAILING_WHITESPACE) + endif () endif () - endif () - file (TO_CMAKE_PATH "${OPENSSL_ROOT_DIR}" OPENSSL_ROOT_DIR) + file(TO_CMAKE_PATH "${OPENSSL_ROOT_DIR}" OPENSSL_ROOT_DIR) endif () if (static OR APPLE OR MSVC) - set (OPENSSL_USE_STATIC_LIBS ON) + set(OPENSSL_USE_STATIC_LIBS ON) endif () -set (OPENSSL_MSVC_STATIC_RT ON) -find_dependency (OpenSSL REQUIRED) -find_dependency (ZLIB) -find_dependency (date) +set(OPENSSL_MSVC_STATIC_RT ON) +find_dependency(OpenSSL REQUIRED) +find_dependency(ZLIB) +find_dependency(date) if (TARGET ZLIB::ZLIB) - set_target_properties(OpenSSL::Crypto PROPERTIES - INTERFACE_LINK_LIBRARIES ZLIB::ZLIB) + set_target_properties(OpenSSL::Crypto PROPERTIES INTERFACE_LINK_LIBRARIES ZLIB::ZLIB) endif () diff --git a/cmake/XrplCore.cmake b/cmake/XrplCore.cmake index 0689fbe7b6..3380ca85cd 100644 --- a/cmake/XrplCore.cmake +++ b/cmake/XrplCore.cmake @@ -10,63 +10,44 @@ include(target_protobuf_sources) # so we just build them as a separate library. add_library(xrpl.libpb) set_target_properties(xrpl.libpb PROPERTIES UNITY_BUILD OFF) -target_protobuf_sources(xrpl.libpb xrpl/proto - LANGUAGE cpp - IMPORT_DIRS include/xrpl/proto - PROTOS include/xrpl/proto/xrpl.proto -) +target_protobuf_sources(xrpl.libpb xrpl/proto LANGUAGE cpp IMPORT_DIRS include/xrpl/proto + PROTOS include/xrpl/proto/xrpl.proto) file(GLOB_RECURSE protos "include/xrpl/proto/org/*.proto") -target_protobuf_sources(xrpl.libpb xrpl/proto - LANGUAGE cpp - IMPORT_DIRS include/xrpl/proto - PROTOS "${protos}" -) -target_protobuf_sources(xrpl.libpb xrpl/proto - LANGUAGE grpc - IMPORT_DIRS include/xrpl/proto - PROTOS "${protos}" - PLUGIN protoc-gen-grpc=$ - GENERATE_EXTENSIONS .grpc.pb.h .grpc.pb.cc -) +target_protobuf_sources(xrpl.libpb xrpl/proto LANGUAGE cpp IMPORT_DIRS include/xrpl/proto PROTOS "${protos}") +target_protobuf_sources( + xrpl.libpb xrpl/proto + LANGUAGE grpc + IMPORT_DIRS include/xrpl/proto + PROTOS "${protos}" + PLUGIN protoc-gen-grpc=$ + GENERATE_EXTENSIONS .grpc.pb.h .grpc.pb.cc) -target_compile_options(xrpl.libpb - PUBLIC - $<$:-wd4996> - $<$: - --system-header-prefix="google/protobuf" - -Wno-deprecated-dynamic-exception-spec - > - PRIVATE - $<$:-wd4065> - $<$>:-Wno-deprecated-declarations> -) +target_compile_options( + xrpl.libpb PUBLIC $<$:-wd4996> $<$: --system-header-prefix="google/protobuf" + -Wno-deprecated-dynamic-exception-spec > + PRIVATE $<$:-wd4065> $<$>:-Wno-deprecated-declarations>) -target_link_libraries(xrpl.libpb - PUBLIC - protobuf::libprotobuf - gRPC::grpc++ -) +target_link_libraries(xrpl.libpb PUBLIC protobuf::libprotobuf gRPC::grpc++) # TODO: Clean up the number of library targets later. add_library(xrpl.imports.main INTERFACE) -target_link_libraries(xrpl.imports.main - INTERFACE - absl::random_random - date::date - ed25519::ed25519 - LibArchive::LibArchive - OpenSSL::Crypto - Xrpl::boost - Xrpl::libs - Xrpl::opts - Xrpl::syslibs - secp256k1::secp256k1 - xrpl.libpb - xxHash::xxhash - $<$:antithesis-sdk-cpp> -) +target_link_libraries( + xrpl.imports.main + INTERFACE absl::random_random + date::date + ed25519::ed25519 + LibArchive::LibArchive + OpenSSL::Crypto + Xrpl::boost + Xrpl::libs + Xrpl::opts + Xrpl::syslibs + secp256k1::secp256k1 + xrpl.libpb + xxHash::xxhash + $<$:antithesis-sdk-cpp>) include(add_module) include(target_link_modules) @@ -88,18 +69,11 @@ target_link_libraries(xrpl.libxrpl.crypto PUBLIC xrpl.libxrpl.basics) # Level 04 add_module(xrpl protocol) -target_link_libraries(xrpl.libxrpl.protocol PUBLIC - xrpl.libxrpl.crypto - xrpl.libxrpl.json -) +target_link_libraries(xrpl.libxrpl.protocol PUBLIC xrpl.libxrpl.crypto xrpl.libxrpl.json) # Level 05 add_module(xrpl core) -target_link_libraries(xrpl.libxrpl.core PUBLIC - xrpl.libxrpl.basics - xrpl.libxrpl.json - xrpl.libxrpl.protocol -) +target_link_libraries(xrpl.libxrpl.core PUBLIC xrpl.libxrpl.basics xrpl.libxrpl.json xrpl.libxrpl.protocol) # Level 06 add_module(xrpl resource) @@ -107,62 +81,61 @@ target_link_libraries(xrpl.libxrpl.resource PUBLIC xrpl.libxrpl.protocol) # Level 07 add_module(xrpl net) -target_link_libraries(xrpl.libxrpl.net PUBLIC - xrpl.libxrpl.basics - xrpl.libxrpl.json - xrpl.libxrpl.protocol - xrpl.libxrpl.resource -) - -add_module(xrpl server) -target_link_libraries(xrpl.libxrpl.server PUBLIC xrpl.libxrpl.protocol) +target_link_libraries(xrpl.libxrpl.net PUBLIC xrpl.libxrpl.basics xrpl.libxrpl.json xrpl.libxrpl.protocol + xrpl.libxrpl.resource) add_module(xrpl nodestore) -target_link_libraries(xrpl.libxrpl.nodestore PUBLIC - xrpl.libxrpl.basics - xrpl.libxrpl.json - xrpl.libxrpl.protocol -) +target_link_libraries(xrpl.libxrpl.nodestore PUBLIC xrpl.libxrpl.basics xrpl.libxrpl.json xrpl.libxrpl.protocol) add_module(xrpl shamap) -target_link_libraries(xrpl.libxrpl.shamap PUBLIC - xrpl.libxrpl.basics - xrpl.libxrpl.crypto - xrpl.libxrpl.protocol - xrpl.libxrpl.nodestore -) +target_link_libraries(xrpl.libxrpl.shamap PUBLIC xrpl.libxrpl.basics xrpl.libxrpl.crypto xrpl.libxrpl.protocol + xrpl.libxrpl.nodestore) + +add_module(xrpl rdb) +target_link_libraries(xrpl.libxrpl.rdb PUBLIC xrpl.libxrpl.basics xrpl.libxrpl.core) + +add_module(xrpl server) +target_link_libraries(xrpl.libxrpl.server PUBLIC xrpl.libxrpl.protocol xrpl.libxrpl.core xrpl.libxrpl.rdb + xrpl.libxrpl.resource) + +add_module(xrpl conditions) +target_link_libraries(xrpl.libxrpl.conditions PUBLIC xrpl.libxrpl.server) add_module(xrpl ledger) -target_link_libraries(xrpl.libxrpl.ledger PUBLIC - xrpl.libxrpl.basics - xrpl.libxrpl.json - xrpl.libxrpl.protocol -) +target_link_libraries( + xrpl.libxrpl.ledger + PUBLIC xrpl.libxrpl.basics + xrpl.libxrpl.json + xrpl.libxrpl.protocol + xrpl.libxrpl.rdb + xrpl.libxrpl.server + xrpl.libxrpl.conditions) add_library(xrpl.libxrpl) set_target_properties(xrpl.libxrpl PROPERTIES OUTPUT_NAME xrpl) add_library(xrpl::libxrpl ALIAS xrpl.libxrpl) -file(GLOB_RECURSE sources CONFIGURE_DEPENDS - "${CMAKE_CURRENT_SOURCE_DIR}/src/libxrpl/*.cpp" -) +file(GLOB_RECURSE sources CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/libxrpl/*.cpp") target_sources(xrpl.libxrpl PRIVATE ${sources}) -target_link_modules(xrpl PUBLIC - basics - beast - core - crypto - json - protocol - resource - server - nodestore - shamap - net - ledger -) +target_link_modules( + xrpl + PUBLIC + basics + beast + conditions + core + crypto + json + ledger + net + nodestore + protocol + rdb + resource + server + shamap) # All headers in libxrpl are in modules. # Uncomment this stanza if you have not yet moved new headers into a module. @@ -173,63 +146,34 @@ target_link_modules(xrpl PUBLIC # $ # $) -if(xrpld) - add_executable(xrpld) - if(tests) - target_compile_definitions(xrpld PUBLIC ENABLE_TESTS) - target_compile_definitions(xrpld PRIVATE - UNIT_TEST_REFERENCE_FEE=${UNIT_TEST_REFERENCE_FEE} - ) - endif() - target_include_directories(xrpld - PRIVATE - $ - ) +if (xrpld) + add_executable(xrpld) + if (tests) + target_compile_definitions(xrpld PUBLIC ENABLE_TESTS) + target_compile_definitions(xrpld PRIVATE UNIT_TEST_REFERENCE_FEE=${UNIT_TEST_REFERENCE_FEE}) + endif () + target_include_directories(xrpld PRIVATE $) - file(GLOB_RECURSE sources CONFIGURE_DEPENDS - "${CMAKE_CURRENT_SOURCE_DIR}/src/xrpld/*.cpp" - ) - target_sources(xrpld PRIVATE ${sources}) - - if(tests) - file(GLOB_RECURSE sources CONFIGURE_DEPENDS - "${CMAKE_CURRENT_SOURCE_DIR}/src/test/*.cpp" - ) + file(GLOB_RECURSE sources CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/xrpld/*.cpp") target_sources(xrpld PRIVATE ${sources}) - endif() - target_link_libraries(xrpld - Xrpl::boost - Xrpl::opts - Xrpl::libs - xrpl.libxrpl - ) - exclude_if_included(xrpld) - # define a macro for tests that might need to - # be excluded or run differently in CI environment - if(is_ci) - target_compile_definitions(xrpld PRIVATE XRPL_RUNNING_IN_CI) - endif () + if (tests) + file(GLOB_RECURSE sources CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/test/*.cpp") + target_sources(xrpld PRIVATE ${sources}) + endif () - if(voidstar) - target_compile_options(xrpld - PRIVATE - -fsanitize-coverage=trace-pc-guard - ) - # xrpld requires access to antithesis-sdk-cpp implementation file - # antithesis_instrumentation.h, which is not exported as INTERFACE - target_include_directories(xrpld - PRIVATE - ${CMAKE_SOURCE_DIR}/external/antithesis-sdk - ) - endif() + target_link_libraries(xrpld Xrpl::boost Xrpl::opts Xrpl::libs xrpl.libxrpl) + exclude_if_included(xrpld) + # define a macro for tests that might need to + # be excluded or run differently in CI environment + if (is_ci) + target_compile_definitions(xrpld PRIVATE XRPL_RUNNING_IN_CI) + endif () - # any files that don't play well with unity should be added here - if(tests) - set_source_files_properties( - # these two seem to produce conflicts in beast teardown template methods - src/test/rpc/ValidatorRPC_test.cpp - src/test/ledger/Invariants_test.cpp - PROPERTIES SKIP_UNITY_BUILD_INCLUSION TRUE) - endif() -endif() + if (voidstar) + target_compile_options(xrpld PRIVATE -fsanitize-coverage=trace-pc-guard) + # xrpld requires access to antithesis-sdk-cpp implementation file + # antithesis_instrumentation.h, which is not exported as INTERFACE + target_include_directories(xrpld PRIVATE ${CMAKE_SOURCE_DIR}/external/antithesis-sdk) + endif () +endif () diff --git a/cmake/XrplCov.cmake b/cmake/XrplCov.cmake index b212d60b64..62c40407f2 100644 --- a/cmake/XrplCov.cmake +++ b/cmake/XrplCov.cmake @@ -2,40 +2,51 @@ coverage report target #]===================================================================] -if(NOT coverage) - message(FATAL_ERROR "Code coverage not enabled! Aborting ...") -endif() +if (NOT coverage) + message(FATAL_ERROR "Code coverage not enabled! Aborting ...") +endif () -if(CMAKE_CXX_COMPILER_ID MATCHES "MSVC") - message(WARNING "Code coverage on Windows is not supported, ignoring 'coverage' flag") - return() -endif() +if (CMAKE_CXX_COMPILER_ID MATCHES "MSVC") + message(WARNING "Code coverage on Windows is not supported, ignoring 'coverage' flag") + return() +endif () include(ProcessorCount) ProcessorCount(PROCESSOR_COUNT) include(CodeCoverage) -# The instructions for these commands come from the `CodeCoverage` module, -# which was copied from https://github.com/bilke/cmake-modules, commit fb7d2a3, -# then locally changed (see CHANGES: section in `CodeCoverage.cmake`) +# The instructions for these commands come from the `CodeCoverage` module, which was copied from +# https://github.com/bilke/cmake-modules, commit fb7d2a3, then locally changed (see CHANGES: section in +# `CodeCoverage.cmake`) set(GCOVR_ADDITIONAL_ARGS ${coverage_extra_args}) -if(NOT GCOVR_ADDITIONAL_ARGS STREQUAL "") - separate_arguments(GCOVR_ADDITIONAL_ARGS) -endif() +if (NOT GCOVR_ADDITIONAL_ARGS STREQUAL "") + separate_arguments(GCOVR_ADDITIONAL_ARGS) +endif () -list(APPEND GCOVR_ADDITIONAL_ARGS - --exclude-throw-branches - --exclude-noncode-lines - --exclude-unreachable-branches -s - -j ${PROCESSOR_COUNT}) +list(APPEND + GCOVR_ADDITIONAL_ARGS + --exclude-throw-branches + --exclude-noncode-lines + --exclude-unreachable-branches + -s + -j + ${PROCESSOR_COUNT}) setup_target_for_coverage_gcovr( - NAME coverage - FORMAT ${coverage_format} - EXCLUDE "src/test" "src/tests" "include/xrpl/beast/test" "include/xrpl/beast/unit_test" "${CMAKE_BINARY_DIR}/pb-xrpl.libpb" - DEPENDENCIES xrpld xrpl.tests -) + NAME + coverage + FORMAT + ${coverage_format} + EXCLUDE + "src/test" + "src/tests" + "include/xrpl/beast/test" + "include/xrpl/beast/unit_test" + "${CMAKE_BINARY_DIR}/pb-xrpl.libpb" + DEPENDENCIES + xrpld + xrpl.tests) add_code_coverage_to_target(opts INTERFACE) diff --git a/cmake/XrplDocs.cmake b/cmake/XrplDocs.cmake index a99bbe076b..69581a99c7 100644 --- a/cmake/XrplDocs.cmake +++ b/cmake/XrplDocs.cmake @@ -2,45 +2,44 @@ docs target (optional) #]===================================================================] -if(NOT only_docs) - return() -endif() +if (NOT only_docs) + return() +endif () find_package(Doxygen) -if(NOT TARGET Doxygen::doxygen) - message(STATUS "doxygen executable not found -- skipping docs target") - return() -endif() +if (NOT TARGET Doxygen::doxygen) + message(STATUS "doxygen executable not found -- skipping docs target") + return() +endif () set(doxygen_output_directory "${CMAKE_BINARY_DIR}/docs") set(doxygen_include_path "${CMAKE_CURRENT_SOURCE_DIR}/src") set(doxygen_index_file "${doxygen_output_directory}/html/index.html") set(doxyfile "${CMAKE_CURRENT_SOURCE_DIR}/docs/Doxyfile") -file(GLOB_RECURSE doxygen_input - docs/*.md - include/*.h - include/*.cpp - include/*.md - src/*.h - src/*.cpp - src/*.md - Builds/*.md - *.md) -list(APPEND doxygen_input - external/README.md - ) +file(GLOB_RECURSE + doxygen_input + docs/*.md + include/*.h + include/*.cpp + include/*.md + src/*.h + src/*.cpp + src/*.md + Builds/*.md + *.md) +list(APPEND doxygen_input external/README.md) set(dependencies "${doxygen_input}" "${doxyfile}") -function(verbose_find_path variable name) - # find_path sets a CACHE variable, so don't try using a "local" variable. - find_path(${variable} "${name}" ${ARGN}) - if(NOT ${variable}) - message(NOTICE "could not find ${name}") - else() - message(STATUS "found ${name}: ${${variable}}/${name}") - endif() -endfunction() +function (verbose_find_path variable name) + # find_path sets a CACHE variable, so don't try using a "local" variable. + find_path(${variable} "${name}" ${ARGN}) + if (NOT ${variable}) + message(NOTICE "could not find ${name}") + else () + message(STATUS "found ${name}: ${${variable}}/${name}") + endif () +endfunction () verbose_find_path(doxygen_plantuml_jar_path plantuml.jar PATH_SUFFIXES share/plantuml) verbose_find_path(doxygen_dot_path dot) @@ -48,36 +47,26 @@ verbose_find_path(doxygen_dot_path dot) # https://en.cppreference.com/w/Cppreference:Archives # https://stackoverflow.com/questions/60822559/how-to-move-a-file-download-from-configure-step-to-build-step set(download_script "${CMAKE_BINARY_DIR}/docs/download-cppreference.cmake") -file(WRITE - "${download_script}" - "file(DOWNLOAD \ +file(WRITE "${download_script}" + "file(DOWNLOAD \ https://github.com/PeterFeicht/cppreference-doc/releases/download/v20250209/html-book-20250209.zip \ ${CMAKE_BINARY_DIR}/docs/cppreference.zip \ EXPECTED_HASH MD5=bda585f72fbca4b817b29a3d5746567b \ )\n \ execute_process( \ COMMAND \"${CMAKE_COMMAND}\" -E tar -xf cppreference.zip \ - )\n" -) + )\n") set(tagfile "${CMAKE_BINARY_DIR}/docs/cppreference-doxygen-web.tag.xml") -add_custom_command( - OUTPUT "${tagfile}" - COMMAND "${CMAKE_COMMAND}" -P "${download_script}" - WORKING_DIRECTORY "${CMAKE_BINARY_DIR}/docs" -) +add_custom_command(OUTPUT "${tagfile}" COMMAND "${CMAKE_COMMAND}" -P "${download_script}" + WORKING_DIRECTORY "${CMAKE_BINARY_DIR}/docs") set(doxygen_tagfiles "${tagfile}=http://en.cppreference.com/w/") add_custom_command( - OUTPUT "${doxygen_index_file}" - COMMAND "${CMAKE_COMMAND}" -E env - "DOXYGEN_OUTPUT_DIRECTORY=${doxygen_output_directory}" - "DOXYGEN_INCLUDE_PATH=${doxygen_include_path}" - "DOXYGEN_TAGFILES=${doxygen_tagfiles}" - "DOXYGEN_PLANTUML_JAR_PATH=${doxygen_plantuml_jar_path}" - "DOXYGEN_DOT_PATH=${doxygen_dot_path}" - "${DOXYGEN_EXECUTABLE}" "${doxyfile}" - WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" - DEPENDS "${dependencies}" "${tagfile}") -add_custom_target(docs - DEPENDS "${doxygen_index_file}" - SOURCES "${dependencies}") + OUTPUT "${doxygen_index_file}" + COMMAND "${CMAKE_COMMAND}" -E env "DOXYGEN_OUTPUT_DIRECTORY=${doxygen_output_directory}" + "DOXYGEN_INCLUDE_PATH=${doxygen_include_path}" "DOXYGEN_TAGFILES=${doxygen_tagfiles}" + "DOXYGEN_PLANTUML_JAR_PATH=${doxygen_plantuml_jar_path}" "DOXYGEN_DOT_PATH=${doxygen_dot_path}" + "${DOXYGEN_EXECUTABLE}" "${doxyfile}" + WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" + DEPENDS "${dependencies}" "${tagfile}") +add_custom_target(docs DEPENDS "${doxygen_index_file}" SOURCES "${dependencies}") diff --git a/cmake/XrplInstall.cmake b/cmake/XrplInstall.cmake index 310436998d..d2fef5d488 100644 --- a/cmake/XrplInstall.cmake +++ b/cmake/XrplInstall.cmake @@ -4,57 +4,55 @@ include(create_symbolic_link) -install ( - TARGETS - common - opts - xrpl_boost - xrpl_libs - xrpl_syslibs - xrpl.imports.main - xrpl.libpb - xrpl.libxrpl - xrpl.libxrpl.basics - xrpl.libxrpl.beast - xrpl.libxrpl.core - xrpl.libxrpl.crypto - xrpl.libxrpl.json - xrpl.libxrpl.ledger - xrpl.libxrpl.net - xrpl.libxrpl.nodestore - xrpl.libxrpl.protocol - xrpl.libxrpl.resource - xrpl.libxrpl.server - xrpl.libxrpl.shamap - antithesis-sdk-cpp - EXPORT XrplExports - LIBRARY DESTINATION lib - ARCHIVE DESTINATION lib - RUNTIME DESTINATION bin - INCLUDES DESTINATION include) +# If no suffix is defined for executables (e.g. Windows uses .exe but Linux +# and macOS use none), then explicitly set it to the empty string. +if (NOT DEFINED suffix) + set(suffix "") +endif () -install( - DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/include/xrpl" - DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}" -) +install(TARGETS common + opts + xrpl_boost + xrpl_libs + xrpl_syslibs + xrpl.imports.main + xrpl.libpb + xrpl.libxrpl + xrpl.libxrpl.basics + xrpl.libxrpl.beast + xrpl.libxrpl.conditions + xrpl.libxrpl.core + xrpl.libxrpl.crypto + xrpl.libxrpl.json + xrpl.libxrpl.rdb + xrpl.libxrpl.ledger + xrpl.libxrpl.net + xrpl.libxrpl.nodestore + xrpl.libxrpl.protocol + xrpl.libxrpl.resource + xrpl.libxrpl.server + xrpl.libxrpl.shamap + antithesis-sdk-cpp + EXPORT XrplExports + LIBRARY DESTINATION lib + ARCHIVE DESTINATION lib + RUNTIME DESTINATION bin + INCLUDES + DESTINATION include) -install (EXPORT XrplExports - FILE XrplTargets.cmake - NAMESPACE Xrpl:: - DESTINATION lib/cmake/xrpl) -include (CMakePackageConfigHelpers) -write_basic_package_version_file ( - XrplConfigVersion.cmake - VERSION ${xrpld_version} - COMPATIBILITY SameMajorVersion) +install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/include/xrpl" DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}") + +install(EXPORT XrplExports FILE XrplTargets.cmake NAMESPACE Xrpl:: DESTINATION lib/cmake/xrpl) +include(CMakePackageConfigHelpers) +write_basic_package_version_file(XrplConfigVersion.cmake VERSION ${xrpld_version} COMPATIBILITY SameMajorVersion) if (is_root_project AND TARGET xrpld) - install (TARGETS xrpld RUNTIME DESTINATION bin) - set_target_properties(xrpld PROPERTIES INSTALL_RPATH_USE_LINK_PATH ON) - # sample configs should not overwrite existing files - # install if-not-exists workaround as suggested by - # https://cmake.org/Bug/view.php?id=12646 - install(CODE " + install(TARGETS xrpld RUNTIME DESTINATION bin) + set_target_properties(xrpld PROPERTIES INSTALL_RPATH_USE_LINK_PATH ON) + # sample configs should not overwrite existing files + # install if-not-exists workaround as suggested by + # https://cmake.org/Bug/view.php?id=12646 + install(CODE " macro (copy_if_not_exists SRC DEST NEWNAME) if (NOT EXISTS \"\$ENV{DESTDIR}\${CMAKE_INSTALL_PREFIX}/\${DEST}/\${NEWNAME}\") file (INSTALL FILE_PERMISSIONS OWNER_READ OWNER_WRITE DESTINATION \"\${CMAKE_INSTALL_PREFIX}/\${DEST}\" FILES \"\${SRC}\" RENAME \"\${NEWNAME}\") @@ -65,7 +63,7 @@ if (is_root_project AND TARGET xrpld) copy_if_not_exists(\"${CMAKE_CURRENT_SOURCE_DIR}/cfg/xrpld-example.cfg\" etc xrpld.cfg) copy_if_not_exists(\"${CMAKE_CURRENT_SOURCE_DIR}/cfg/validators-example.txt\" etc validators.txt) ") - install(CODE " + install(CODE " set(CMAKE_MODULE_PATH \"${CMAKE_MODULE_PATH}\") include(create_symbolic_link) create_symbolic_link(xrpld${suffix} \ @@ -73,8 +71,5 @@ if (is_root_project AND TARGET xrpld) ") endif () -install ( - FILES - ${CMAKE_CURRENT_SOURCE_DIR}/cmake/XrplConfig.cmake - ${CMAKE_CURRENT_BINARY_DIR}/XrplConfigVersion.cmake - DESTINATION lib/cmake/xrpl) +install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/cmake/XrplConfig.cmake ${CMAKE_CURRENT_BINARY_DIR}/XrplConfigVersion.cmake + DESTINATION lib/cmake/xrpl) diff --git a/cmake/XrplInterface.cmake b/cmake/XrplInterface.cmake index 6e0203c099..f471b37dd7 100644 --- a/cmake/XrplInterface.cmake +++ b/cmake/XrplInterface.cmake @@ -4,80 +4,80 @@ include(CompilationEnv) -add_library (opts INTERFACE) -add_library (Xrpl::opts ALIAS opts) -target_compile_definitions (opts - INTERFACE - BOOST_ASIO_DISABLE_HANDLER_TYPE_REQUIREMENTS - BOOST_ASIO_USE_TS_EXECUTOR_AS_DEFAULT - BOOST_CONTAINER_FWD_BAD_DEQUE - HAS_UNCAUGHT_EXCEPTIONS=1 - $<$: - BOOST_ASIO_NO_DEPRECATED - BOOST_FILESYSTEM_NO_DEPRECATED - > - $<$>: - BOOST_COROUTINES_NO_DEPRECATION_WARNING - BOOST_BEAST_ALLOW_DEPRECATED - BOOST_FILESYSTEM_DEPRECATED - > - $<$:BEAST_NO_UNIT_TEST_INLINE=1> - $<$:BEAST_DONT_AUTOLINK_TO_WIN32_LIBRARIES=1> - $<$:XRPL_SINGLE_IO_SERVICE_THREAD=1> - $<$:ENABLE_VOIDSTAR>) -target_compile_options (opts - INTERFACE - $<$,$>:-Wsuggest-override> - $<$:-Wno-maybe-uninitialized> - $<$:-fno-omit-frame-pointer> - $<$:-pg> - $<$,$>:-p>) +# Set defaults for optional variables to avoid uninitialized variable warnings +if (NOT DEFINED voidstar) + set(voidstar OFF) +endif () -target_link_libraries (opts - INTERFACE - $<$:-pg> - $<$,$>:-p>) +add_library(opts INTERFACE) +add_library(Xrpl::opts ALIAS opts) +target_compile_definitions( + opts + INTERFACE BOOST_ASIO_DISABLE_HANDLER_TYPE_REQUIREMENTS + BOOST_ASIO_USE_TS_EXECUTOR_AS_DEFAULT + BOOST_CONTAINER_FWD_BAD_DEQUE + HAS_UNCAUGHT_EXCEPTIONS=1 + $<$: + BOOST_ASIO_NO_DEPRECATED + BOOST_FILESYSTEM_NO_DEPRECATED + > + $<$>: + BOOST_COROUTINES_NO_DEPRECATION_WARNING + BOOST_BEAST_ALLOW_DEPRECATED + BOOST_FILESYSTEM_DEPRECATED + > + $<$:BEAST_NO_UNIT_TEST_INLINE=1> + $<$:BEAST_DONT_AUTOLINK_TO_WIN32_LIBRARIES=1> + $<$:XRPL_SINGLE_IO_SERVICE_THREAD=1> + $<$:ENABLE_VOIDSTAR>) +target_compile_options( + opts + INTERFACE $<$,$>:-Wsuggest-override> + $<$:-Wno-maybe-uninitialized> $<$:-fno-omit-frame-pointer> + $<$:-pg> $<$,$>:-p>) -if(jemalloc) - find_package(jemalloc REQUIRED) - target_compile_definitions(opts INTERFACE PROFILE_JEMALLOC) - target_link_libraries(opts INTERFACE jemalloc::jemalloc) +target_link_libraries(opts INTERFACE $<$:-pg> $<$,$>:-p>) + +if (jemalloc) + find_package(jemalloc REQUIRED) + target_compile_definitions(opts INTERFACE PROFILE_JEMALLOC) + target_link_libraries(opts INTERFACE jemalloc::jemalloc) endif () #[===================================================================[ xrpld transitive library deps via an interface library #]===================================================================] -add_library (xrpl_syslibs INTERFACE) -add_library (Xrpl::syslibs ALIAS xrpl_syslibs) -target_link_libraries (xrpl_syslibs - INTERFACE - $<$: - legacy_stdio_definitions.lib - Shlwapi - kernel32 - user32 - gdi32 - winspool - comdlg32 - advapi32 - shell32 - ole32 - oleaut32 - uuid - odbc32 - odbccp32 - crypt32 - > - $<$>:dl> - $<$,$>>:rt>) +add_library(xrpl_syslibs INTERFACE) +add_library(Xrpl::syslibs ALIAS xrpl_syslibs) +target_link_libraries( + xrpl_syslibs + INTERFACE $<$: + legacy_stdio_definitions.lib + Shlwapi + kernel32 + user32 + gdi32 + winspool + comdlg32 + advapi32 + shell32 + ole32 + oleaut32 + uuid + odbc32 + odbccp32 + crypt32 + > + $<$>:dl> + $<$,$>>:rt>) -if (NOT MSVC) - set (THREADS_PREFER_PTHREAD_FLAG ON) - find_package (Threads) - target_link_libraries (xrpl_syslibs INTERFACE Threads::Threads) +if (NOT is_msvc) + set(THREADS_PREFER_PTHREAD_FLAG ON) + find_package(Threads) + target_link_libraries(xrpl_syslibs INTERFACE Threads::Threads) endif () -add_library (xrpl_libs INTERFACE) -add_library (Xrpl::libs ALIAS xrpl_libs) -target_link_libraries (xrpl_libs INTERFACE Xrpl::syslibs) +add_library(xrpl_libs INTERFACE) +add_library(Xrpl::libs ALIAS xrpl_libs) +target_link_libraries(xrpl_libs INTERFACE Xrpl::syslibs) diff --git a/cmake/XrplSanitizers.cmake b/cmake/XrplSanitizers.cmake index 050a5ef6f0..6ddc0b7e7d 100644 --- a/cmake/XrplSanitizers.cmake +++ b/cmake/XrplSanitizers.cmake @@ -43,21 +43,24 @@ include(CompilationEnv) # Read environment variable -set(SANITIZERS $ENV{SANITIZERS}) +set(SANITIZERS "") +if (DEFINED ENV{SANITIZERS}) + set(SANITIZERS "$ENV{SANITIZERS}") +endif () # Set SANITIZERS_ENABLED flag for use in other modules -if(SANITIZERS MATCHES "address|thread|undefinedbehavior") +if (SANITIZERS MATCHES "address|thread|undefinedbehavior") set(SANITIZERS_ENABLED TRUE) -else() +else () set(SANITIZERS_ENABLED FALSE) return() -endif() +endif () # Sanitizers are not supported on Windows/MSVC -if(is_msvc) +if (is_msvc) message(FATAL_ERROR "Sanitizers are not supported on Windows/MSVC. " - "Please unset the SANITIZERS environment variable.") -endif() + "Please unset the SANITIZERS environment variable.") +endif () message(STATUS "Configuring sanitizers: ${SANITIZERS}") @@ -71,24 +74,24 @@ set(san_list "${SANITIZERS}") string(REPLACE "," ";" san_list "${san_list}") separate_arguments(san_list) -foreach(san IN LISTS san_list) - if(san STREQUAL "address") +foreach (san IN LISTS san_list) + if (san STREQUAL "address") set(enable_asan TRUE) - elseif(san STREQUAL "thread") + elseif (san STREQUAL "thread") set(enable_tsan TRUE) - elseif(san STREQUAL "undefinedbehavior") + elseif (san STREQUAL "undefinedbehavior") set(enable_ubsan TRUE) - else() + else () message(FATAL_ERROR "Unsupported sanitizer type: ${san}" - "Supported: address, thread, undefinedbehavior and their combinations.") - endif() -endforeach() + "Supported: address, thread, undefinedbehavior and their combinations.") + endif () +endforeach () # Validate sanitizer compatibility -if(enable_asan AND enable_tsan) +if (enable_asan AND enable_tsan) message(FATAL_ERROR "AddressSanitizer and ThreadSanitizer are incompatible and cannot be enabled simultaneously. " - "Use 'address' or 'thread', optionally with 'undefinedbehavior'.") -endif() + "Use 'address' or 'thread', optionally with 'undefinedbehavior'.") +endif () # Frame pointer is required for meaningful stack traces. Sanitizers recommend minimum of -O1 for reasonable performance set(SANITIZERS_COMPILE_FLAGS "-fno-omit-frame-pointer" "-O1") @@ -96,31 +99,31 @@ set(SANITIZERS_COMPILE_FLAGS "-fno-omit-frame-pointer" "-O1") # Build the sanitizer flags list set(SANITIZER_TYPES) -if(enable_asan) +if (enable_asan) list(APPEND SANITIZER_TYPES "address") -elseif(enable_tsan) +elseif (enable_tsan) list(APPEND SANITIZER_TYPES "thread") -endif() +endif () -if(enable_ubsan) +if (enable_ubsan) # UB sanitizer flags list(APPEND SANITIZER_TYPES "undefined" "float-divide-by-zero") - if(is_clang) - # Clang supports additional UB checks. More info here https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html + if (is_clang) + # Clang supports additional UB checks. More info here + # https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html list(APPEND SANITIZER_TYPES "unsigned-integer-overflow") - endif() -endif() + endif () +endif () -# Configure code model for GCC on amd64 -# Use large code model for ASAN to avoid relocation errors -# Use medium code model for TSAN (large is not compatible with TSAN) +# Configure code model for GCC on amd64 Use large code model for ASAN to avoid relocation errors Use medium code model +# for TSAN (large is not compatible with TSAN) set(SANITIZERS_RELOCATION_FLAGS) # Compiler-specific configuration -if(is_gcc) - # Disable mold, gold and lld linkers for GCC with sanitizers - # Use default linker (bfd/ld) which is more lenient with mixed code models - # This is needed since the size of instrumented binary exceeds the limits set by mold, lld and gold linkers +if (is_gcc) + # Disable mold, gold and lld linkers for GCC with sanitizers Use default linker (bfd/ld) which is more lenient with + # mixed code models This is needed since the size of instrumented binary exceeds the limits set by mold, lld and + # gold linkers set(use_mold OFF CACHE BOOL "Use mold linker" FORCE) set(use_gold OFF CACHE BOOL "Use gold linker" FORCE) set(use_lld OFF CACHE BOOL "Use lld linker" FORCE) @@ -129,17 +132,17 @@ if(is_gcc) # Suppress false positive warnings in GCC with stringop-overflow list(APPEND SANITIZERS_COMPILE_FLAGS "-Wno-stringop-overflow") - if(is_amd64 AND enable_asan) + if (is_amd64 AND enable_asan) message(STATUS " Using large code model (-mcmodel=large)") list(APPEND SANITIZERS_COMPILE_FLAGS "-mcmodel=large") list(APPEND SANITIZERS_RELOCATION_FLAGS "-mcmodel=large") - elseif(enable_tsan) + elseif (enable_tsan) # GCC doesn't support atomic_thread_fence with tsan. Suppress warnings. list(APPEND SANITIZERS_COMPILE_FLAGS "-Wno-tsan") message(STATUS " Using medium code model (-mcmodel=medium)") list(APPEND SANITIZERS_COMPILE_FLAGS "-mcmodel=medium") list(APPEND SANITIZERS_RELOCATION_FLAGS "-mcmodel=medium") - endif() + endif () # Join sanitizer flags with commas for -fsanitize option list(JOIN SANITIZER_TYPES "," SANITIZER_TYPES_STR) @@ -148,13 +151,12 @@ if(is_gcc) list(APPEND SANITIZERS_COMPILE_FLAGS "-fsanitize=${SANITIZER_TYPES_STR}") set(SANITIZERS_LINK_FLAGS "${SANITIZERS_RELOCATION_FLAGS}" "-fsanitize=${SANITIZER_TYPES_STR}") -elseif(is_clang) - # Add ignorelist for Clang (GCC doesn't support this) - # Use CMAKE_SOURCE_DIR to get the path to the ignorelist +elseif (is_clang) + # Add ignorelist for Clang (GCC doesn't support this) Use CMAKE_SOURCE_DIR to get the path to the ignorelist set(IGNORELIST_PATH "${CMAKE_SOURCE_DIR}/sanitizers/suppressions/sanitizer-ignorelist.txt") - if(NOT EXISTS "${IGNORELIST_PATH}") + if (NOT EXISTS "${IGNORELIST_PATH}") message(FATAL_ERROR "Sanitizer ignorelist not found: ${IGNORELIST_PATH}") - endif() + endif () list(APPEND SANITIZERS_COMPILE_FLAGS "-fsanitize-ignorelist=${IGNORELIST_PATH}") message(STATUS " Using sanitizer ignorelist: ${IGNORELIST_PATH}") @@ -165,34 +167,31 @@ elseif(is_clang) # Add sanitizer to compile and link flags list(APPEND SANITIZERS_COMPILE_FLAGS "-fsanitize=${SANITIZER_TYPES_STR}") set(SANITIZERS_LINK_FLAGS "-fsanitize=${SANITIZER_TYPES_STR}") -endif() +endif () message(STATUS " Compile flags: ${SANITIZERS_COMPILE_FLAGS}") message(STATUS " Link flags: ${SANITIZERS_LINK_FLAGS}") -# Apply the sanitizer flags to the 'common' interface library -# This is the same library used by XrplCompiler.cmake -target_compile_options(common INTERFACE - $<$:${SANITIZERS_COMPILE_FLAGS}> - $<$:${SANITIZERS_COMPILE_FLAGS}> -) +# Apply the sanitizer flags to the 'common' interface library This is the same library used by XrplCompiler.cmake +target_compile_options(common INTERFACE $<$:${SANITIZERS_COMPILE_FLAGS}> + $<$:${SANITIZERS_COMPILE_FLAGS}>) # Apply linker flags target_link_options(common INTERFACE ${SANITIZERS_LINK_FLAGS}) # Define SANITIZERS macro for BuildInfo.cpp set(sanitizers_list) -if(enable_asan) +if (enable_asan) list(APPEND sanitizers_list "ASAN") -endif() -if(enable_tsan) +endif () +if (enable_tsan) list(APPEND sanitizers_list "TSAN") -endif() -if(enable_ubsan) +endif () +if (enable_ubsan) list(APPEND sanitizers_list "UBSAN") -endif() +endif () -if(sanitizers_list) +if (sanitizers_list) list(JOIN sanitizers_list "." sanitizers_str) target_compile_definitions(common INTERFACE SANITIZERS=${sanitizers_str}) -endif() +endif () diff --git a/cmake/XrplSanity.cmake b/cmake/XrplSanity.cmake index 7464ca396c..5055414abd 100644 --- a/cmake/XrplSanity.cmake +++ b/cmake/XrplSanity.cmake @@ -6,40 +6,39 @@ include(CompilationEnv) get_property(is_multiconfig GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) -set (CMAKE_CONFIGURATION_TYPES "Debug;Release" CACHE STRING "" FORCE) +set(CMAKE_CONFIGURATION_TYPES "Debug;Release" CACHE STRING "" FORCE) if (NOT is_multiconfig) - if (NOT CMAKE_BUILD_TYPE) - message (STATUS "Build type not specified - defaulting to Release") - set (CMAKE_BUILD_TYPE Release CACHE STRING "build type" FORCE) - elseif (NOT (CMAKE_BUILD_TYPE STREQUAL Debug OR CMAKE_BUILD_TYPE STREQUAL Release)) - # for simplicity, these are the only two config types we care about. Limiting - # the build types simplifies dealing with external project builds especially - message (FATAL_ERROR " *** Only Debug or Release build types are currently supported ***") - endif () + if (NOT CMAKE_BUILD_TYPE) + message(STATUS "Build type not specified - defaulting to Release") + set(CMAKE_BUILD_TYPE Release CACHE STRING "build type" FORCE) + elseif (NOT (CMAKE_BUILD_TYPE STREQUAL Debug OR CMAKE_BUILD_TYPE STREQUAL Release)) + # for simplicity, these are the only two config types we care about. Limiting the build types simplifies dealing + # with external project builds especially + message(FATAL_ERROR " *** Only Debug or Release build types are currently supported ***") + endif () endif () if (is_clang) # both Clang and AppleClang - if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang" AND - CMAKE_CXX_COMPILER_VERSION VERSION_LESS 16.0) - message (FATAL_ERROR "This project requires clang 16 or later") - endif () + if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang" AND CMAKE_CXX_COMPILER_VERSION VERSION_LESS 16.0) + message(FATAL_ERROR "This project requires clang 16 or later") + endif () elseif (is_gcc) - if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 12.0) - message (FATAL_ERROR "This project requires GCC 12 or later") - endif () + if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 12.0) + message(FATAL_ERROR "This project requires GCC 12 or later") + endif () endif () # check for in-source build and fail if ("${CMAKE_CURRENT_SOURCE_DIR}" STREQUAL "${CMAKE_BINARY_DIR}") - message (FATAL_ERROR "Builds (in-source) are not allowed in " - "${CMAKE_CURRENT_SOURCE_DIR}. Please remove CMakeCache.txt and the CMakeFiles " - "directory from ${CMAKE_CURRENT_SOURCE_DIR} and try building in a separate directory.") + message(FATAL_ERROR "Builds (in-source) are not allowed in " + "${CMAKE_CURRENT_SOURCE_DIR}. Please remove CMakeCache.txt and the CMakeFiles " + "directory from ${CMAKE_CURRENT_SOURCE_DIR} and try building in a separate directory.") endif () if (MSVC AND CMAKE_GENERATOR_PLATFORM STREQUAL "Win32") - message (FATAL_ERROR "Visual Studio 32-bit build is not supported.") + message(FATAL_ERROR "Visual Studio 32-bit build is not supported.") endif () if (APPLE AND NOT HOMEBREW) - find_program (HOMEBREW brew) + find_program(HOMEBREW brew) endif () diff --git a/cmake/XrplSettings.cmake b/cmake/XrplSettings.cmake index 647e95837d..6d332be19d 100644 --- a/cmake/XrplSettings.cmake +++ b/cmake/XrplSettings.cmake @@ -4,125 +4,111 @@ include(CompilationEnv) -if("$ENV{CI}" STREQUAL "true" OR "$ENV{CONTINUOUS_INTEGRATION}" STREQUAL "true") - set(is_ci TRUE) -else() - set(is_ci FALSE) -endif() +set(is_ci FALSE) +if (DEFINED ENV{CI}) + if ("$ENV{CI}" STREQUAL "true") + set(is_ci TRUE) + endif () +endif () get_directory_property(has_parent PARENT_DIRECTORY) -if(has_parent) - set(is_root_project OFF) -else() - set(is_root_project ON) -endif() +if (has_parent) + set(is_root_project OFF) +else () + set(is_root_project ON) +endif () option(assert "Enables asserts, even in release builds" OFF) option(xrpld "Build xrpld" ON) option(tests "Build tests" ON) -if(tests) - # This setting allows making a separate workflow to test fees other than default 10 - if(NOT UNIT_TEST_REFERENCE_FEE) - set(UNIT_TEST_REFERENCE_FEE "10" CACHE STRING "") - endif() -endif() +if (tests) + # This setting allows making a separate workflow to test fees other than default 10 + if (NOT UNIT_TEST_REFERENCE_FEE) + set(UNIT_TEST_REFERENCE_FEE "10" CACHE STRING "") + endif () +endif () option(unity "Creates a build using UNITY support in cmake." OFF) -if(unity) - if(NOT is_ci) - set(CMAKE_UNITY_BUILD_BATCH_SIZE 15 CACHE STRING "") - endif() - set(CMAKE_UNITY_BUILD ON CACHE BOOL "Do a unity build") -endif() +if (unity) + if (NOT is_ci) + set(CMAKE_UNITY_BUILD_BATCH_SIZE 15 CACHE STRING "") + endif () + set(CMAKE_UNITY_BUILD ON CACHE BOOL "Do a unity build") +endif () -if(is_clang AND is_linux) - option(voidstar "Enable Antithesis instrumentation." OFF) -endif() +if (is_clang AND is_linux) + option(voidstar "Enable Antithesis instrumentation." OFF) +endif () -if(is_gcc OR is_clang) - include(ProcessorCount) - ProcessorCount(PROCESSOR_COUNT) +if (is_gcc OR is_clang) + include(ProcessorCount) + ProcessorCount(PROCESSOR_COUNT) - option(coverage "Generates coverage info." OFF) - option(profile "Add profiling flags" OFF) - set(coverage_format "html-details" CACHE STRING - "Output format of the coverage report.") - set(coverage_extra_args "" CACHE STRING - "Additional arguments to pass to gcovr.") - option(wextra "compile with extra gcc/clang warnings enabled" ON) -else() - set(profile OFF CACHE BOOL "gcc/clang only" FORCE) - set(coverage OFF CACHE BOOL "gcc/clang only" FORCE) - set(wextra OFF CACHE BOOL "gcc/clang only" FORCE) -endif() + option(coverage "Generates coverage info." OFF) + option(profile "Add profiling flags" OFF) + set(coverage_format "html-details" CACHE STRING "Output format of the coverage report.") + set(coverage_extra_args "" CACHE STRING "Additional arguments to pass to gcovr.") + option(wextra "compile with extra gcc/clang warnings enabled" ON) +else () + set(profile OFF CACHE BOOL "gcc/clang only" FORCE) + set(coverage OFF CACHE BOOL "gcc/clang only" FORCE) + set(wextra OFF CACHE BOOL "gcc/clang only" FORCE) +endif () -if(is_linux AND NOT SANITIZER) - option(BUILD_SHARED_LIBS "build shared xrpl libraries" OFF) - option(static "link protobuf, openssl, libc++, and boost statically" ON) - option(perf "Enables flags that assist with perf recording" OFF) - option(use_gold "enables detection of gold (binutils) linker" ON) - option(use_mold "enables detection of mold (binutils) linker" ON) - # Set a default value for the log flag based on the build type. - # This provides a sensible default (on for debug, off for release) - # while still allowing the user to override it for any build. - if(CMAKE_BUILD_TYPE STREQUAL "Debug") - set(TRUNCATED_LOGS_DEFAULT ON) - else() - set(TRUNCATED_LOGS_DEFAULT OFF) - endif() - option(TRUNCATED_THREAD_NAME_LOGS - "Show warnings about truncated thread names on Linux." - ${TRUNCATED_LOGS_DEFAULT} - ) - if(TRUNCATED_THREAD_NAME_LOGS) - add_compile_definitions(TRUNCATED_THREAD_NAME_LOGS) - endif() -else() - # we are not ready to allow shared-libs on windows because it would require - # export declarations. On macos it's more feasible, but static openssl - # produces odd linker errors, thus we disable shared lib builds for now. - set(BUILD_SHARED_LIBS OFF CACHE BOOL "build shared xrpl libraries - OFF for win/macos" FORCE) - set(static ON CACHE BOOL "static link, linux only. ON for WIN/macos" FORCE) - set(perf OFF CACHE BOOL "perf flags, linux only" FORCE) - set(use_gold OFF CACHE BOOL "gold linker, linux only" FORCE) - set(use_mold OFF CACHE BOOL "mold linker, linux only" FORCE) -endif() +if (is_linux AND NOT SANITIZER) + option(BUILD_SHARED_LIBS "build shared xrpl libraries" OFF) + option(static "link protobuf, openssl, libc++, and boost statically" ON) + option(perf "Enables flags that assist with perf recording" OFF) + option(use_gold "enables detection of gold (binutils) linker" ON) + option(use_mold "enables detection of mold (binutils) linker" ON) + # Set a default value for the log flag based on the build type. This provides a sensible default (on for debug, off + # for release) while still allowing the user to override it for any build. + if (CMAKE_BUILD_TYPE STREQUAL "Debug") + set(TRUNCATED_LOGS_DEFAULT ON) + else () + set(TRUNCATED_LOGS_DEFAULT OFF) + endif () + option(TRUNCATED_THREAD_NAME_LOGS "Show warnings about truncated thread names on Linux." ${TRUNCATED_LOGS_DEFAULT}) + if (TRUNCATED_THREAD_NAME_LOGS) + add_compile_definitions(TRUNCATED_THREAD_NAME_LOGS) + endif () +else () + # we are not ready to allow shared-libs on windows because it would require export declarations. On macos it's more + # feasible, but static openssl produces odd linker errors, thus we disable shared lib builds for now. + set(BUILD_SHARED_LIBS OFF CACHE BOOL "build shared xrpl libraries - OFF for win/macos" FORCE) + set(static ON CACHE BOOL "static link, linux only. ON for WIN/macos" FORCE) + set(perf OFF CACHE BOOL "perf flags, linux only" FORCE) + set(use_gold OFF CACHE BOOL "gold linker, linux only" FORCE) + set(use_mold OFF CACHE BOOL "mold linker, linux only" FORCE) +endif () -if(is_clang) - option(use_lld "enables detection of lld linker" ON) -else() - set(use_lld OFF CACHE BOOL "try lld linker, clang only" FORCE) -endif() +if (is_clang) + option(use_lld "enables detection of lld linker" ON) +else () + set(use_lld OFF CACHE BOOL "try lld linker, clang only" FORCE) +endif () option(jemalloc "Enables jemalloc for heap profiling" OFF) option(werr "treat warnings as errors" OFF) -option(local_protobuf - "Force a local build of protobuf instead of looking for an installed version." OFF) -option(local_grpc - "Force a local build of gRPC instead of looking for an installed version." OFF) +option(local_protobuf "Force a local build of protobuf instead of looking for an installed version." OFF) +option(local_grpc "Force a local build of gRPC instead of looking for an installed version." OFF) # the remaining options are obscure and rarely used -option(beast_no_unit_test_inline - "Prevents unit test definitions from being inserted into global table" - OFF) -option(single_io_service_thread - "Restricts the number of threads calling io_context::run to one. \ - This can be useful when debugging." - OFF) -option(boost_show_deprecated - "Allow boost to fail on deprecated usage. Only useful if you're trying\ - to find deprecated calls." - OFF) +option(beast_no_unit_test_inline "Prevents unit test definitions from being inserted into global table" OFF) +option(single_io_service_thread "Restricts the number of threads calling io_context::run to one. \ + This can be useful when debugging." OFF) +option(boost_show_deprecated "Allow boost to fail on deprecated usage. Only useful if you're trying\ + to find deprecated calls." OFF) -if(WIN32) - option(beast_disable_autolink "Disables autolinking of system libraries on WIN32" OFF) -else() - set(beast_disable_autolink OFF CACHE BOOL "WIN32 only" FORCE) -endif() +if (WIN32) + option(beast_disable_autolink "Disables autolinking of system libraries on WIN32" OFF) +else () + set(beast_disable_autolink OFF CACHE BOOL "WIN32 only" FORCE) +endif () -if(coverage) - message(STATUS "coverage build requested - forcing Debug build") - set(CMAKE_BUILD_TYPE Debug CACHE STRING "build type" FORCE) -endif() +if (coverage) + message(STATUS "coverage build requested - forcing Debug build") + set(CMAKE_BUILD_TYPE Debug CACHE STRING "build type" FORCE) +endif () diff --git a/cmake/XrplValidatorKeys.cmake b/cmake/XrplValidatorKeys.cmake index fa520ce9c1..5fa7e14886 100644 --- a/cmake/XrplValidatorKeys.cmake +++ b/cmake/XrplValidatorKeys.cmake @@ -1,20 +1,17 @@ -option (validator_keys "Enables building of validator-keys tool as a separate target (imported via FetchContent)" OFF) +option(validator_keys "Enables building of validator-keys tool as a separate target (imported via FetchContent)" OFF) if (validator_keys) - git_branch (current_branch) - # default to tracking VK master branch unless we are on release - if (NOT (current_branch STREQUAL "release")) - set (current_branch "master") - endif () - message (STATUS "Tracking ValidatorKeys branch: ${current_branch}") + git_branch(current_branch) + # default to tracking VK master branch unless we are on release + if (NOT (current_branch STREQUAL "release")) + set(current_branch "master") + endif () + message(STATUS "Tracking ValidatorKeys branch: ${current_branch}") - FetchContent_Declare ( - validator_keys - GIT_REPOSITORY https://github.com/ripple/validator-keys-tool.git - GIT_TAG "${current_branch}" - ) - FetchContent_MakeAvailable(validator_keys) - set_target_properties(validator-keys PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}") - install(TARGETS validator-keys RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}) + FetchContent_Declare(validator_keys GIT_REPOSITORY https://github.com/ripple/validator-keys-tool.git + GIT_TAG "${current_branch}") + FetchContent_MakeAvailable(validator_keys) + set_target_properties(validator-keys PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}") + install(TARGETS validator-keys RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}) endif () diff --git a/cmake/XrplVersion.cmake b/cmake/XrplVersion.cmake index e42f942ecb..6eeda7b1eb 100644 --- a/cmake/XrplVersion.cmake +++ b/cmake/XrplVersion.cmake @@ -3,13 +3,13 @@ #]===================================================================] file(STRINGS src/libxrpl/protocol/BuildInfo.cpp BUILD_INFO) -foreach(line_ ${BUILD_INFO}) - if(line_ MATCHES "versionString[ ]*=[ ]*\"(.+)\"") - set(xrpld_version ${CMAKE_MATCH_1}) - endif() -endforeach() -if(xrpld_version) - message(STATUS "xrpld version: ${xrpld_version}") -else() - message(FATAL_ERROR "unable to determine xrpld version") -endif() +foreach (line_ ${BUILD_INFO}) + if (line_ MATCHES "versionString[ ]*=[ ]*\"(.+)\"") + set(xrpld_version ${CMAKE_MATCH_1}) + endif () +endforeach () +if (xrpld_version) + message(STATUS "xrpld version: ${xrpld_version}") +else () + message(FATAL_ERROR "unable to determine xrpld version") +endif () diff --git a/cmake/add_module.cmake b/cmake/add_module.cmake index bcfce1bf60..a3cb247fd2 100644 --- a/cmake/add_module.cmake +++ b/cmake/add_module.cmake @@ -12,26 +12,14 @@ include(isolate_headers) # add_module(parent a) # add_module(parent b) # target_link_libraries(project.libparent.b PUBLIC project.libparent.a) -function(add_module parent name) - set(target ${PROJECT_NAME}.lib${parent}.${name}) - add_library(${target} OBJECT) - file(GLOB_RECURSE sources CONFIGURE_DEPENDS - "${CMAKE_CURRENT_SOURCE_DIR}/src/lib${parent}/${name}/*.cpp" - ) - target_sources(${target} PRIVATE ${sources}) - target_include_directories(${target} PUBLIC - "$" - ) - isolate_headers( - ${target} - "${CMAKE_CURRENT_SOURCE_DIR}/include" - "${CMAKE_CURRENT_SOURCE_DIR}/include/${parent}/${name}" - PUBLIC - ) - isolate_headers( - ${target} - "${CMAKE_CURRENT_SOURCE_DIR}/src" - "${CMAKE_CURRENT_SOURCE_DIR}/src/lib${parent}/${name}" - PRIVATE - ) -endfunction() +function (add_module parent name) + set(target ${PROJECT_NAME}.lib${parent}.${name}) + add_library(${target} OBJECT) + file(GLOB_RECURSE sources CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/lib${parent}/${name}/*.cpp") + target_sources(${target} PRIVATE ${sources}) + target_include_directories(${target} PUBLIC "$") + isolate_headers(${target} "${CMAKE_CURRENT_SOURCE_DIR}/include" + "${CMAKE_CURRENT_SOURCE_DIR}/include/${parent}/${name}" PUBLIC) + isolate_headers(${target} "${CMAKE_CURRENT_SOURCE_DIR}/src" "${CMAKE_CURRENT_SOURCE_DIR}/src/lib${parent}/${name}" + PRIVATE) +endfunction () diff --git a/cmake/create_symbolic_link.cmake b/cmake/create_symbolic_link.cmake index 60fcf2e0b5..82ca915f5c 100644 --- a/cmake/create_symbolic_link.cmake +++ b/cmake/create_symbolic_link.cmake @@ -1,20 +1,19 @@ -# file(CREATE_SYMLINK) only works on Windows with administrator privileges. -# https://stackoverflow.com/a/61244115/618906 -function(create_symbolic_link target link) - if(WIN32) - if(NOT IS_SYMLINK "${link}") - if(NOT IS_ABSOLUTE "${target}") - # Relative links work do not work on Windows. - set(target "${link}/../${target}") - endif() - file(TO_NATIVE_PATH "${target}" target) - file(TO_NATIVE_PATH "${link}" link) - execute_process(COMMAND cmd.exe /c mklink /J "${link}" "${target}") - endif() - else() - file(CREATE_LINK "${target}" "${link}" SYMBOLIC) - endif() - if(NOT IS_SYMLINK "${link}") - message(ERROR "failed to create symlink: <${link}>") - endif() -endfunction() +# file(CREATE_SYMLINK) only works on Windows with administrator privileges. https://stackoverflow.com/a/61244115/618906 +function (create_symbolic_link target link) + if (WIN32) + if (NOT IS_SYMLINK "${link}") + if (NOT IS_ABSOLUTE "${target}") + # Relative links work do not work on Windows. + set(target "${link}/../${target}") + endif () + file(TO_NATIVE_PATH "${target}" target) + file(TO_NATIVE_PATH "${link}" link) + execute_process(COMMAND cmd.exe /c mklink /J "${link}" "${target}") + endif () + else () + file(CREATE_LINK "${target}" "${link}" SYMBOLIC) + endif () + if (NOT IS_SYMLINK "${link}") + message(ERROR "failed to create symlink: <${link}>") + endif () +endfunction () diff --git a/cmake/deps/Boost.cmake b/cmake/deps/Boost.cmake index b73698efd8..fe62fcb79c 100644 --- a/cmake/deps/Boost.cmake +++ b/cmake/deps/Boost.cmake @@ -2,49 +2,43 @@ include(CompilationEnv) include(XrplSanitizers) find_package(Boost REQUIRED - COMPONENTS - chrono - container - coroutine - date_time - filesystem - json - program_options - regex - system - thread -) + COMPONENTS chrono + container + coroutine + date_time + filesystem + json + program_options + regex + system + thread) add_library(xrpl_boost INTERFACE) add_library(Xrpl::boost ALIAS xrpl_boost) -target_link_libraries(xrpl_boost - INTERFACE - Boost::headers - Boost::chrono - Boost::container - Boost::coroutine - Boost::date_time - Boost::filesystem - Boost::json - Boost::process - Boost::program_options - Boost::regex - Boost::system - Boost::thread) -if(Boost_COMPILER) - target_link_libraries(xrpl_boost INTERFACE Boost::disable_autolinking) -endif() -if(SANITIZERS_ENABLED AND is_clang) - # TODO: gcc does not support -fsanitize-blacklist...can we do something else - # for gcc ? - if(NOT Boost_INCLUDE_DIRS AND TARGET Boost::headers) - get_target_property(Boost_INCLUDE_DIRS Boost::headers INTERFACE_INCLUDE_DIRECTORIES) - endif() - message(STATUS "Adding [${Boost_INCLUDE_DIRS}] to sanitizer blacklist") - file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/san_bl.txt "src:${Boost_INCLUDE_DIRS}/*") - target_compile_options(opts - INTERFACE - # ignore boost headers for sanitizing - -fsanitize-blacklist=${CMAKE_CURRENT_BINARY_DIR}/san_bl.txt) -endif() +target_link_libraries( + xrpl_boost + INTERFACE Boost::headers + Boost::chrono + Boost::container + Boost::coroutine + Boost::date_time + Boost::filesystem + Boost::json + Boost::process + Boost::program_options + Boost::regex + Boost::thread) +if (Boost_COMPILER) + target_link_libraries(xrpl_boost INTERFACE Boost::disable_autolinking) +endif () +if (SANITIZERS_ENABLED AND is_clang) + # TODO: gcc does not support -fsanitize-blacklist...can we do something else for gcc ? + if (NOT Boost_INCLUDE_DIRS AND TARGET Boost::headers) + get_target_property(Boost_INCLUDE_DIRS Boost::headers INTERFACE_INCLUDE_DIRECTORIES) + endif () + message(STATUS "Adding [${Boost_INCLUDE_DIRS}] to sanitizer blacklist") + file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/san_bl.txt "src:${Boost_INCLUDE_DIRS}/*") + target_compile_options(opts INTERFACE # ignore boost headers for sanitizing + -fsanitize-blacklist=${CMAKE_CURRENT_BINARY_DIR}/san_bl.txt) +endif () diff --git a/cmake/isolate_headers.cmake b/cmake/isolate_headers.cmake index 0a5a43a6a2..ef53b3f20a 100644 --- a/cmake/isolate_headers.cmake +++ b/cmake/isolate_headers.cmake @@ -37,12 +37,12 @@ include(create_symbolic_link) # `${CMAKE_CURRENT_BINARY_DIR}/include/${target}`. # # isolate_headers(target A B scope) -function(isolate_headers target A B scope) - file(RELATIVE_PATH C "${A}" "${B}") - set(X "${CMAKE_CURRENT_BINARY_DIR}/modules/${target}") - set(Y "${X}/${C}") - cmake_path(GET Y PARENT_PATH parent) - file(MAKE_DIRECTORY "${parent}") - create_symbolic_link("${B}" "${Y}") - target_include_directories(${target} ${scope} "$") -endfunction() +function (isolate_headers target A B scope) + file(RELATIVE_PATH C "${A}" "${B}") + set(X "${CMAKE_CURRENT_BINARY_DIR}/modules/${target}") + set(Y "${X}/${C}") + cmake_path(GET Y PARENT_PATH parent) + file(MAKE_DIRECTORY "${parent}") + create_symbolic_link("${B}" "${Y}") + target_include_directories(${target} ${scope} "$") +endfunction () diff --git a/cmake/target_link_modules.cmake b/cmake/target_link_modules.cmake index acbf67903a..bcd80591b0 100644 --- a/cmake/target_link_modules.cmake +++ b/cmake/target_link_modules.cmake @@ -6,19 +6,19 @@ # target_link_libraries(project.libparent.b PUBLIC project.libparent.a) # add_library(project.libparent) # target_link_modules(parent PUBLIC a b) -function(target_link_modules parent scope) - set(library ${PROJECT_NAME}.lib${parent}) - foreach(name ${ARGN}) - set(module ${library}.${name}) - get_target_property(sources ${library} SOURCES) - list(LENGTH sources before) - get_target_property(dupes ${module} SOURCES) - list(LENGTH dupes expected) - list(REMOVE_ITEM sources ${dupes}) - list(LENGTH sources after) - math(EXPR actual "${before} - ${after}") - message(STATUS "${module} with ${expected} sources took ${actual} sources from ${library}") - set_target_properties(${library} PROPERTIES SOURCES "${sources}") - target_link_libraries(${library} ${scope} ${module}) - endforeach() -endfunction() +function (target_link_modules parent scope) + set(library ${PROJECT_NAME}.lib${parent}) + foreach (name ${ARGN}) + set(module ${library}.${name}) + get_target_property(sources ${library} SOURCES) + list(LENGTH sources before) + get_target_property(dupes ${module} SOURCES) + list(LENGTH dupes expected) + list(REMOVE_ITEM sources ${dupes}) + list(LENGTH sources after) + math(EXPR actual "${before} - ${after}") + message(STATUS "${module} with ${expected} sources took ${actual} sources from ${library}") + set_target_properties(${library} PROPERTIES SOURCES "${sources}") + target_link_libraries(${library} ${scope} ${module}) + endforeach () +endfunction () diff --git a/cmake/target_protobuf_sources.cmake b/cmake/target_protobuf_sources.cmake index da2ef6dc9a..bb5de02b53 100644 --- a/cmake/target_protobuf_sources.cmake +++ b/cmake/target_protobuf_sources.cmake @@ -35,28 +35,20 @@ find_package(Protobuf REQUIRED) # This prefix should appear at the start of all your consumer includes. # ARGN: # A list of .proto files. -function(target_protobuf_sources target prefix) - set(dir "${CMAKE_CURRENT_BINARY_DIR}/pb-${target}") - file(MAKE_DIRECTORY "${dir}/${prefix}") +function (target_protobuf_sources target prefix) + set(dir "${CMAKE_CURRENT_BINARY_DIR}/pb-${target}") + file(MAKE_DIRECTORY "${dir}/${prefix}") - protobuf_generate( - TARGET ${target} - PROTOC_OUT_DIR "${dir}/${prefix}" - "${ARGN}" - ) - target_include_directories(${target} SYSTEM PUBLIC - # Allows #include used by consumer files. - $ - # Allows #include "path/to/file.proto" used by generated files. - $ - # Allows #include used by consumer files. - $ - # Allows #include "path/to/file.proto" used by generated files. - $ - ) - install( - DIRECTORY ${dir}/ - DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} - FILES_MATCHING PATTERN "*.h" - ) -endfunction() + protobuf_generate(TARGET ${target} PROTOC_OUT_DIR "${dir}/${prefix}" "${ARGN}") + target_include_directories( + ${target} SYSTEM + PUBLIC # Allows #include used by consumer files. + $ + # Allows #include "path/to/file.proto" used by generated files. + $ + # Allows #include used by consumer files. + $ + # Allows #include "path/to/file.proto" used by generated files. + $) + install(DIRECTORY ${dir}/ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} FILES_MATCHING PATTERN "*.h") +endfunction () diff --git a/conan.lock b/conan.lock index f3fa1e5f6e..900d3526e1 100644 --- a/conan.lock +++ b/conan.lock @@ -6,12 +6,12 @@ "sqlite3/3.49.1#8631739a4c9b93bd3d6b753bac548a63%1765850149.926", "soci/4.0.3#a9f8d773cd33e356b5879a4b0564f287%1765850149.46", "snappy/1.1.10#968fef506ff261592ec30c574d4a7809%1765850147.878", - "secp256k1/0.7.0#9c4ab67bdc3860c16ea5b36aed8f74ea%1765850147.928", + "secp256k1/0.7.1#3a61e95e220062ef32c48d019e9c81f7%1770306721.686", "rocksdb/10.5.1#4a197eca381a3e5ae8adf8cffa5aacd0%1765850186.86", "re2/20230301#ca3b241baec15bd31ea9187150e0b333%1765850148.103", "protobuf/6.32.1#f481fd276fc23a33b85a3ed1e898b693%1765850161.038", - "openssl/3.5.4#1b986e61b38fdfda3b40bebc1b234393%1768312656.257", - "nudb/2.0.9#fb8dfd1a5557f5e0528114c2da17721e%1765850143.957", + "openssl/3.5.5#05a4ac5b7323f7a329b2db1391d9941f%1769599205.414", + "nudb/2.0.9#0432758a24204da08fee953ec9ea03cb%1769436073.32", "lz4/1.10.0#59fc63cac7f10fbe8e05c7e62c2f3504%1765850143.914", "libiconv/1.17#1e65319e945f2d31941a9d28cc13c058%1765842973.492", "libbacktrace/cci.20210118#a7691bfccd8caaf66309df196790a5a1%1765842973.03", @@ -23,7 +23,7 @@ "date/3.0.4#862e11e80030356b53c2c38599ceb32b%1765850143.772", "c-ares/1.34.5#5581c2b62a608b40bb85d965ab3ec7c8%1765850144.336", "bzip2/1.0.8#c470882369c2d95c5c77e970c0c7e321%1765850143.837", - "boost/1.88.0#8852c0b72ce8271fb8ff7c53456d4983%1765850172.862", + "boost/1.90.0#d5e8defe7355494953be18524a7f135b%1769454080.269", "abseil/20250127.0#99262a368bd01c0ccca8790dfced9719%1766517936.993" ], "build_requires": [ @@ -31,7 +31,7 @@ "strawberryperl/5.32.1.1#707032463aa0620fa17ec0d887f5fe41%1765850165.196", "protobuf/6.32.1#f481fd276fc23a33b85a3ed1e898b693%1765850161.038", "nasm/2.16.01#31e26f2ee3c4346ecd347911bd126904%1765850144.707", - "msys2/cci.latest#1996656c3c98e5765b25b60ff5cf77b4%1764840888.758", + "msys2/cci.latest#eea83308ad7e9023f7318c60d5a9e6cb%1770199879.083", "m4/1.4.19#70dc8bbb33e981d119d2acc0175cf381%1763158052.846", "cmake/4.2.0#ae0a44f44a1ef9ab68fd4b3e9a1f8671%1765850153.937", "cmake/3.31.10#313d16a1aa16bbdb2ca0792467214b76%1765850153.479", @@ -42,18 +42,22 @@ ], "python_requires": [], "overrides": { + "boost/1.90.0#d5e8defe7355494953be18524a7f135b": [ + null, + "boost/1.90.0" + ], "protobuf/5.27.0": [ "protobuf/6.32.1" ], "lz4/1.9.4": [ "lz4/1.10.0" ], - "boost/1.83.0": [ - "boost/1.88.0" - ], "sqlite3/3.44.2": [ "sqlite3/3.49.1" ], + "boost/1.83.0": [ + "boost/1.90.0" + ], "lz4/[>=1.9.4 <2]": [ "lz4/1.10.0#59fc63cac7f10fbe8e05c7e62c2f3504" ] diff --git a/conanfile.py b/conanfile.py index 8501909ce3..7300b537d9 100644 --- a/conanfile.py +++ b/conanfile.py @@ -32,8 +32,8 @@ class Xrpl(ConanFile): "grpc/1.72.0", "libarchive/3.8.1", "nudb/2.0.9", - "openssl/3.5.4", - "secp256k1/0.7.0", + "openssl/3.5.5", + "secp256k1/0.7.1", "soci/4.0.3", "zlib/1.3.1", ] @@ -131,7 +131,7 @@ class Xrpl(ConanFile): transitive_headers_opt = ( {"transitive_headers": True} if conan_version.split(".")[0] == "2" else {} ) - self.requires("boost/1.88.0", force=True, **transitive_headers_opt) + self.requires("boost/1.90.0", force=True, **transitive_headers_opt) self.requires("date/3.0.4", **transitive_headers_opt) self.requires("lz4/1.10.0", force=True) self.requires("protobuf/6.32.1", force=True) @@ -203,7 +203,6 @@ class Xrpl(ConanFile): "boost::program_options", "boost::process", "boost::regex", - "boost::system", "boost::thread", "date::date", "ed25519::ed25519", diff --git a/.config/cspell.config.yaml b/cspell.config.yaml similarity index 78% rename from .config/cspell.config.yaml rename to cspell.config.yaml index 73b0417d79..b2f4a33769 100644 --- a/.config/cspell.config.yaml +++ b/cspell.config.yaml @@ -1,14 +1,13 @@ ignorePaths: - build/** - src/libxrpl/crypto - - src/test/** # Will be removed in the future - CMakeUserPresets.json - Doxyfile - docs/**/*.puml - cmake/** - LICENSE.md language: en -allowCompoundWords: true +allowCompoundWords: true # TODO (#6334) ignoreRandomStrings: true minWordLength: 5 dictionaries: @@ -16,20 +15,29 @@ dictionaries: - en_US - en_GB ignoreRegExpList: - - /[rs][1-9A-HJ-NP-Za-km-z]{25,34}/g # addresses and seeds - - /(XRPL|BEAST)_[A-Z_0-9]+_H_INCLUDED+/g # include guards - - /(XRPL|BEAST)_[A-Z_0-9]+_H+/g # include guards + - /\b[rs][1-9A-HJ-NP-Za-km-z]{25,34}/g # addresses and seeds + - /\bC[A-Z0-9]{15}/g # CTIDs + - /\b(XRPL|BEAST)_[A-Z_0-9]+_H_INCLUDED+/g # include guards + - /\b(XRPL|BEAST)_[A-Z_0-9]+_H+/g # include guards - /::[a-z:_]+/g # things from other namespaces - - /lib[a-z]+/g # libraries - - /[0-9]{4}-[0-9]{2}-[0-9]{2}[,:][A-Za-zÀ-ÖØ-öø-ÿ.\s]+/g # copyright dates - - /[0-9]{4}[,:]?\s*[A-Za-zÀ-ÖØ-öø-ÿ.\s]+/g # copyright years + - /\blib[a-z]+/g # libraries + - /\b[0-9]{4}-[0-9]{2}-[0-9]{2}[,:][A-Za-zÀ-ÖØ-öø-ÿ.\s]+/g # copyright dates + - /\b[0-9]{4}[,:]?\s*[A-Za-zÀ-ÖØ-öø-ÿ.\s]+/g # copyright years - /\[[A-Za-z0-9-]+\]\(https:\/\/github.com\/[A-Za-z0-9-]+\)/g # Github usernames - /-[DWw][a-zA-Z0-9_-]+=/g # compile flags - /[\['"`]-[DWw][a-zA-Z0-9_-]+['"`\]]/g # compile flags + - ABCDEFGHIJKLMNOPQRSTUVWXYZ + - ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz +overrides: + - filename: "**/*_test.cpp" # all test files + ignoreRegExpList: + - /"[^"]*"/g # double-quoted strings + - /'[^']*'/g # single-quoted strings + - /`[^`]*`/g # backtick strings suggestWords: - xprl->xrpl - - xprld->xrpld - - unsynched->unsynced + - xprld->xrpld # cspell: disable-line not sure what this problem is.... + - unsynched->unsynced # cspell: disable-line not sure what this problem is.... - synched->synced - synch->sync words: @@ -51,6 +59,7 @@ words: - Britto - Btrfs - canonicality + - changespq - checkme - choco - chrono @@ -101,19 +110,24 @@ words: - gpgcheck - gpgkey - hotwallet + - hwrap - ifndef - inequation - insuf - insuff + - invasively - iou - ious - isrdc - itype - jemalloc - jlog + - jtnofill - keylet - keylets - keyvadb + - kwarg + - kwargs - ledgerentry - ledgerhash - ledgerindex @@ -135,6 +149,7 @@ words: - Metafuncton - misprediction - mptbalance + - MPTDEX - mptflags - mptid - mptissuance @@ -144,6 +159,7 @@ words: - mptokenissuance - mptokens - mpts + - mtgox - multisig - multisign - multisigned @@ -163,6 +179,7 @@ words: - nunl - Nyffenegger - ostr + - pargs - partitioner - paychan - paychans @@ -170,6 +187,7 @@ words: - perminute - permissioned - pointee + - populator - preauth - preauthorization - preauthorize @@ -178,6 +196,7 @@ words: - protobuf - protos - ptrs + - pushd - pyenv - qalloc - queuable diff --git a/docs/CodingStyle.md b/docs/CodingStyle.md index 3c26709047..2788f7b210 100644 --- a/docs/CodingStyle.md +++ b/docs/CodingStyle.md @@ -17,8 +17,8 @@ guideline is to maintain the standards that are used in those libraries. ## Guidelines If you want to do something contrary to these guidelines, understand -why you're doing it. Think, use common sense, and consider that this -your changes will probably need to be maintained long after you've +why you're doing it. Think, use common sense, and consider that these +changes will probably need to be maintained long after you've moved on to other projects. - Use white space and blank lines to guide the eye and keep your intent clear. diff --git a/include/xrpl/basics/Archive.h b/include/xrpl/basics/Archive.h index 5f7c624084..58e12bbb71 100644 --- a/include/xrpl/basics/Archive.h +++ b/include/xrpl/basics/Archive.h @@ -1,5 +1,4 @@ -#ifndef XRPL_BASICS_ARCHIVE_H_INCLUDED -#define XRPL_BASICS_ARCHIVE_H_INCLUDED +#pragma once #include @@ -13,10 +12,6 @@ namespace xrpl { @throws runtime_error */ void -extractTarLz4( - boost::filesystem::path const& src, - boost::filesystem::path const& dst); +extractTarLz4(boost::filesystem::path const& src, boost::filesystem::path const& dst); } // namespace xrpl - -#endif diff --git a/include/xrpl/basics/BasicConfig.h b/include/xrpl/basics/BasicConfig.h index 573b26ae75..d18019fa9f 100644 --- a/include/xrpl/basics/BasicConfig.h +++ b/include/xrpl/basics/BasicConfig.h @@ -1,5 +1,4 @@ -#ifndef XRPL_BASICS_BASICCONFIG_H_INCLUDED -#define XRPL_BASICS_BASICCONFIG_H_INCLUDED +#pragma once #include @@ -14,8 +13,7 @@ namespace xrpl { -using IniFileSections = - std::unordered_map>; +using IniFileSections = std::unordered_map>; //------------------------------------------------------------------------------ @@ -86,8 +84,7 @@ public: if (lines_.empty()) return ""; if (lines_.size() > 1) - Throw( - "A legacy value must have exactly one line. Section: " + name_); + Throw("A legacy value must have exactly one line. Section: " + name_); return lines_[0]; } @@ -233,10 +230,7 @@ public: The previous value, if any, is overwritten. */ void - overwrite( - std::string const& section, - std::string const& key, - std::string const& value); + overwrite(std::string const& section, std::string const& key, std::string const& value); /** Remove all the key/value pairs from the section. */ @@ -274,9 +268,7 @@ public: bool had_trailing_comments() const { - return std::any_of(map_.cbegin(), map_.cend(), [](auto s) { - return s.second.had_trailing_comments(); - }); + return std::any_of(map_.cbegin(), map_.cend(), [](auto s) { return s.second.had_trailing_comments(); }); } protected: @@ -315,10 +307,7 @@ set(T& target, std::string const& name, Section const& section) */ template bool -set(T& target, - T const& defaultValue, - std::string const& name, - Section const& section) +set(T& target, T const& defaultValue, std::string const& name, Section const& section) { bool found_and_valid = set(target, name, section); if (!found_and_valid) @@ -333,9 +322,7 @@ set(T& target, // NOTE This routine might be more clumsy than the previous two template T -get(Section const& section, - std::string const& name, - T const& defaultValue = T{}) +get(Section const& section, std::string const& name, T const& defaultValue = T{}) { try { @@ -381,5 +368,3 @@ get_if_exists(Section const& section, std::string const& name, bool& v) } } // namespace xrpl - -#endif diff --git a/include/xrpl/basics/Blob.h b/include/xrpl/basics/Blob.h index 986f829371..ee0d6cf3b5 100644 --- a/include/xrpl/basics/Blob.h +++ b/include/xrpl/basics/Blob.h @@ -1,5 +1,4 @@ -#ifndef XRPL_BASICS_BLOB_H_INCLUDED -#define XRPL_BASICS_BLOB_H_INCLUDED +#pragma once #include @@ -11,5 +10,3 @@ namespace xrpl { using Blob = std::vector; } // namespace xrpl - -#endif diff --git a/include/xrpl/basics/Buffer.h b/include/xrpl/basics/Buffer.h index 8ae745f6d1..5192daf632 100644 --- a/include/xrpl/basics/Buffer.h +++ b/include/xrpl/basics/Buffer.h @@ -1,5 +1,4 @@ -#ifndef XRPL_BASICS_BUFFER_H_INCLUDED -#define XRPL_BASICS_BUFFER_H_INCLUDED +#pragma once #include #include @@ -25,8 +24,7 @@ public: Buffer() = default; /** Create an uninitialized buffer with the given size. */ - explicit Buffer(std::size_t size) - : p_(size ? new std::uint8_t[size] : nullptr), size_(size) + explicit Buffer(std::size_t size) : p_(size ? new std::uint8_t[size] : nullptr), size_(size) { } @@ -62,8 +60,7 @@ public: /** Move-construct. The other buffer is reset. */ - Buffer(Buffer&& other) noexcept - : p_(std::move(other.p_)), size_(other.size_) + Buffer(Buffer&& other) noexcept : p_(std::move(other.p_)), size_(other.size_) { other.size_ = 0; } @@ -94,8 +91,7 @@ public: { // Ensure the slice isn't a subset of the buffer. XRPL_ASSERT( - s.size() == 0 || size_ == 0 || s.data() < p_.get() || - s.data() >= p_.get() + size_, + s.size() == 0 || size_ == 0 || s.data() < p_.get() || s.data() >= p_.get() + size_, "xrpl::Buffer::operator=(Slice) : input not a subset"); if (auto p = alloc(s.size())) @@ -216,5 +212,3 @@ operator!=(Buffer const& lhs, Buffer const& rhs) noexcept } } // namespace xrpl - -#endif diff --git a/include/xrpl/basics/ByteUtilities.h b/include/xrpl/basics/ByteUtilities.h index 88bb297346..cd10611a50 100644 --- a/include/xrpl/basics/ByteUtilities.h +++ b/include/xrpl/basics/ByteUtilities.h @@ -1,5 +1,4 @@ -#ifndef XRPL_BASICS_BYTEUTILITIES_H_INCLUDED -#define XRPL_BASICS_BYTEUTILITIES_H_INCLUDED +#pragma once namespace xrpl { @@ -20,5 +19,3 @@ megabytes(T value) noexcept static_assert(kilobytes(2) == 2048, "kilobytes(2) == 2048"); static_assert(megabytes(3) == 3145728, "megabytes(3) == 3145728"); } // namespace xrpl - -#endif diff --git a/include/xrpl/basics/CompressionAlgorithms.h b/include/xrpl/basics/CompressionAlgorithms.h index b373ac4605..b8fe4c8018 100644 --- a/include/xrpl/basics/CompressionAlgorithms.h +++ b/include/xrpl/basics/CompressionAlgorithms.h @@ -1,5 +1,4 @@ -#ifndef XRPL_COMPRESSIONALGORITHMS_H_INCLUDED -#define XRPL_COMPRESSIONALGORITHMS_H_INCLUDED +#pragma once #include @@ -36,10 +35,7 @@ lz4Compress(void const* in, std::size_t inSize, BufferFactory&& bf) auto compressed = bf(outCapacity); auto compressedSize = LZ4_compress_default( - reinterpret_cast(in), - reinterpret_cast(compressed), - inSize, - outCapacity); + reinterpret_cast(in), reinterpret_cast(compressed), inSize, outCapacity); if (compressedSize == 0) Throw("lz4 compress: failed"); @@ -70,10 +66,8 @@ lz4Decompress( Throw("lz4Decompress: integer overflow (output)"); if (LZ4_decompress_safe( - reinterpret_cast(in), - reinterpret_cast(decompressed), - inSize, - decompressedSize) != decompressedSize) + reinterpret_cast(in), reinterpret_cast(decompressed), inSize, decompressedSize) != + decompressedSize) Throw("lz4Decompress: failed"); return decompressedSize; @@ -89,11 +83,7 @@ lz4Decompress( */ template std::size_t -lz4Decompress( - InputStream& in, - std::size_t inSize, - std::uint8_t* decompressed, - std::size_t decompressedSize) +lz4Decompress(InputStream& in, std::size_t inSize, std::uint8_t* decompressed, std::size_t decompressedSize) { std::vector compressed; std::uint8_t const* chunk = nullptr; @@ -116,9 +106,7 @@ lz4Decompress( compressed.resize(inSize); } - chunkSize = chunkSize < (inSize - copiedInSize) - ? chunkSize - : (inSize - copiedInSize); + chunkSize = chunkSize < (inSize - copiedInSize) ? chunkSize : (inSize - copiedInSize); std::copy(chunk, chunk + chunkSize, compressed.data() + copiedInSize); @@ -135,8 +123,7 @@ lz4Decompress( if (in.ByteCount() > (currentBytes + copiedInSize)) in.BackUp(in.ByteCount() - currentBytes - copiedInSize); - if ((copiedInSize == 0 && chunkSize < inSize) || - (copiedInSize > 0 && copiedInSize != inSize)) + if ((copiedInSize == 0 && chunkSize < inSize) || (copiedInSize > 0 && copiedInSize != inSize)) Throw("lz4 decompress: insufficient input size"); return lz4Decompress(chunk, inSize, decompressed, decompressedSize); @@ -145,5 +132,3 @@ lz4Decompress( } // namespace compression_algorithms } // namespace xrpl - -#endif // XRPL_COMPRESSIONALGORITHMS_H_INCLUDED diff --git a/include/xrpl/basics/CountedObject.h b/include/xrpl/basics/CountedObject.h index e464e470af..55a895dbb1 100644 --- a/include/xrpl/basics/CountedObject.h +++ b/include/xrpl/basics/CountedObject.h @@ -1,5 +1,4 @@ -#ifndef XRPL_BASICS_COUNTEDOBJECT_H_INCLUDED -#define XRPL_BASICS_COUNTEDOBJECT_H_INCLUDED +#pragma once #include @@ -134,5 +133,3 @@ public: }; } // namespace xrpl - -#endif diff --git a/include/xrpl/basics/DecayingSample.h b/include/xrpl/basics/DecayingSample.h index c5e38d2e9a..e4c9ad5d7a 100644 --- a/include/xrpl/basics/DecayingSample.h +++ b/include/xrpl/basics/DecayingSample.h @@ -1,5 +1,4 @@ -#ifndef XRPL_BASICS_DECAYINGSAMPLE_H_INCLUDED -#define XRPL_BASICS_DECAYINGSAMPLE_H_INCLUDED +#pragma once #include #include @@ -56,9 +55,7 @@ private: if (m_value != value_type()) { - std::size_t elapsed = - std::chrono::duration_cast(now - m_when) - .count(); + std::size_t elapsed = std::chrono::duration_cast(now - m_when).count(); // A span larger than four times the window decays the // value to an insignificant amount so just reset it. @@ -132,5 +129,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/include/xrpl/basics/Expected.h b/include/xrpl/basics/Expected.h index 8cf479c1b6..7c98e72107 100644 --- a/include/xrpl/basics/Expected.h +++ b/include/xrpl/basics/Expected.h @@ -1,5 +1,4 @@ -#ifndef XRPL_BASICS_EXPECTED_H_INCLUDED -#define XRPL_BASICS_EXPECTED_H_INCLUDED +#pragma once #include @@ -108,23 +107,20 @@ Unexpected(E (&)[N]) -> Unexpected; // Definition of Expected. All of the machinery comes from boost::result. template -class [[nodiscard]] Expected - : private boost::outcome_v2::result +class [[nodiscard]] Expected : private boost::outcome_v2::result { using Base = boost::outcome_v2::result; public: template requires std::convertible_to - constexpr Expected(U&& r) - : Base(boost::outcome_v2::in_place_type_t{}, std::forward(r)) + constexpr Expected(U&& r) : Base(boost::outcome_v2::in_place_type_t{}, std::forward(r)) { } template requires std::convertible_to && (!std::is_reference_v) - constexpr Expected(Unexpected e) - : Base(boost::outcome_v2::in_place_type_t{}, std::move(e.value())) + constexpr Expected(Unexpected e) : Base(boost::outcome_v2::in_place_type_t{}, std::move(e.value())) { } @@ -195,8 +191,7 @@ public: // Specialization of Expected. Allows returning either success // (without a value) or the reason for the failure. template -class [[nodiscard]] Expected - : private boost::outcome_v2::result +class [[nodiscard]] Expected : private boost::outcome_v2::result { using Base = boost::outcome_v2::result; @@ -233,5 +228,3 @@ public: }; } // namespace xrpl - -#endif // XRPL_BASICS_EXPECTED_H_INCLUDED diff --git a/include/xrpl/basics/FileUtilities.h b/include/xrpl/basics/FileUtilities.h index c4bc2cbe68..299269703a 100644 --- a/include/xrpl/basics/FileUtilities.h +++ b/include/xrpl/basics/FileUtilities.h @@ -1,5 +1,4 @@ -#ifndef XRPL_BASICS_FILEUTILITIES_H_INCLUDED -#define XRPL_BASICS_FILEUTILITIES_H_INCLUDED +#pragma once #include #include @@ -15,11 +14,6 @@ getFileContents( std::optional maxSize = std::nullopt); void -writeFileContents( - boost::system::error_code& ec, - boost::filesystem::path const& destPath, - std::string const& contents); +writeFileContents(boost::system::error_code& ec, boost::filesystem::path const& destPath, std::string const& contents); } // namespace xrpl - -#endif diff --git a/include/xrpl/basics/IntrusivePointer.h b/include/xrpl/basics/IntrusivePointer.h index 101a4b6f16..4464c37dc5 100644 --- a/include/xrpl/basics/IntrusivePointer.h +++ b/include/xrpl/basics/IntrusivePointer.h @@ -1,5 +1,4 @@ -#ifndef XRPL_BASICS_INTRUSIVEPOINTER_H_INCLUDED -#define XRPL_BASICS_INTRUSIVEPOINTER_H_INCLUDED +#pragma once #include #include @@ -45,8 +44,8 @@ struct SharedIntrusiveAdoptNoIncrementTag // template -concept CAdoptTag = std::is_same_v || - std::is_same_v; +concept CAdoptTag = + std::is_same_v || std::is_same_v; //------------------------------------------------------------------------------ @@ -122,9 +121,7 @@ public: controlled by the rhs param. */ template - SharedIntrusive( - StaticCastTagSharedIntrusive, - SharedIntrusive const& rhs); + SharedIntrusive(StaticCastTagSharedIntrusive, SharedIntrusive const& rhs); /** Create a new SharedIntrusive by statically casting the pointer controlled by the rhs param. @@ -136,9 +133,7 @@ public: controlled by the rhs param. */ template - SharedIntrusive( - DynamicCastTagSharedIntrusive, - SharedIntrusive const& rhs); + SharedIntrusive(DynamicCastTagSharedIntrusive, SharedIntrusive const& rhs); /** Create a new SharedIntrusive by dynamically casting the pointer controlled by the rhs param. @@ -304,9 +299,7 @@ class SharedWeakUnion // Tagged pointer. Low bit determines if this is a strong or a weak // pointer. The low bit must be masked to zero when converting back to a // pointer. If the low bit is '1', this is a weak pointer. - static_assert( - alignof(T) >= 2, - "Bad alignment: Combo pointer requires low bit to be zero"); + static_assert(alignof(T) >= 2, "Bad alignment: Combo pointer requires low bit to be zero"); public: SharedWeakUnion() = default; @@ -450,9 +443,7 @@ make_SharedIntrusive(Args&&... args) auto p = new TT(std::forward(args)...); static_assert( - noexcept(SharedIntrusive( - std::declval(), - std::declval())), + noexcept(SharedIntrusive(std::declval(), std::declval())), "SharedIntrusive constructor should not throw or this can leak " "memory"); @@ -493,4 +484,3 @@ dynamic_pointer_cast(TT const& v) } } // namespace intr_ptr } // namespace xrpl -#endif diff --git a/include/xrpl/basics/IntrusivePointer.ipp b/include/xrpl/basics/IntrusivePointer.ipp index cfebb559fd..d52aa6299f 100644 --- a/include/xrpl/basics/IntrusivePointer.ipp +++ b/include/xrpl/basics/IntrusivePointer.ipp @@ -1,5 +1,4 @@ -#ifndef XRPL_BASICS_INTRUSIVEPOINTER_IPP_INCLUDED -#define XRPL_BASICS_INTRUSIVEPOINTER_IPP_INCLUDED +#pragma once #include #include @@ -12,9 +11,7 @@ template template SharedIntrusive::SharedIntrusive(T* p, TAdoptTag) noexcept : ptr_{p} { - if constexpr (std::is_same_v< - TAdoptTag, - SharedIntrusiveAdoptIncrementStrongTag>) + if constexpr (std::is_same_v) { if (p) p->addStrongRef(); @@ -46,16 +43,14 @@ SharedIntrusive::SharedIntrusive(SharedIntrusive const& rhs) } template -SharedIntrusive::SharedIntrusive(SharedIntrusive&& rhs) - : ptr_{rhs.unsafeExchange(nullptr)} +SharedIntrusive::SharedIntrusive(SharedIntrusive&& rhs) : ptr_{rhs.unsafeExchange(nullptr)} { } template template requires std::convertible_to -SharedIntrusive::SharedIntrusive(SharedIntrusive&& rhs) - : ptr_{rhs.unsafeExchange(nullptr)} +SharedIntrusive::SharedIntrusive(SharedIntrusive&& rhs) : ptr_{rhs.unsafeExchange(nullptr)} { } template @@ -112,9 +107,7 @@ requires std::convertible_to SharedIntrusive& SharedIntrusive::operator=(SharedIntrusive&& rhs) { - static_assert( - !std::is_same_v, - "This overload should not be instantiated for T == TT"); + static_assert(!std::is_same_v, "This overload should not be instantiated for T == TT"); unsafeReleaseAndStore(rhs.unsafeExchange(nullptr)); return *this; @@ -139,9 +132,7 @@ template void SharedIntrusive::adopt(T* p) { - if constexpr (std::is_same_v< - TAdoptTag, - SharedIntrusiveAdoptIncrementStrongTag>) + if constexpr (std::is_same_v) { if (p) p->addStrongRef(); @@ -157,9 +148,7 @@ SharedIntrusive::~SharedIntrusive() template template -SharedIntrusive::SharedIntrusive( - StaticCastTagSharedIntrusive, - SharedIntrusive const& rhs) +SharedIntrusive::SharedIntrusive(StaticCastTagSharedIntrusive, SharedIntrusive const& rhs) : ptr_{[&] { auto p = static_cast(rhs.unsafeGetRawPtr()); if (p) @@ -171,18 +160,14 @@ SharedIntrusive::SharedIntrusive( template template -SharedIntrusive::SharedIntrusive( - StaticCastTagSharedIntrusive, - SharedIntrusive&& rhs) +SharedIntrusive::SharedIntrusive(StaticCastTagSharedIntrusive, SharedIntrusive&& rhs) : ptr_{static_cast(rhs.unsafeExchange(nullptr))} { } template template -SharedIntrusive::SharedIntrusive( - DynamicCastTagSharedIntrusive, - SharedIntrusive const& rhs) +SharedIntrusive::SharedIntrusive(DynamicCastTagSharedIntrusive, SharedIntrusive const& rhs) : ptr_{[&] { auto p = dynamic_cast(rhs.unsafeGetRawPtr()); if (p) @@ -194,9 +179,7 @@ SharedIntrusive::SharedIntrusive( template template -SharedIntrusive::SharedIntrusive( - DynamicCastTagSharedIntrusive, - SharedIntrusive&& rhs) +SharedIntrusive::SharedIntrusive(DynamicCastTagSharedIntrusive, SharedIntrusive&& rhs) { // This can be simplified without the `exchange`, but the `exchange` is kept // in anticipation of supporting atomic operations. @@ -315,8 +298,7 @@ WeakIntrusive::WeakIntrusive(WeakIntrusive&& rhs) : ptr_{rhs.ptr_} } template -WeakIntrusive::WeakIntrusive(SharedIntrusive const& rhs) - : ptr_{rhs.unsafeGetRawPtr()} +WeakIntrusive::WeakIntrusive(SharedIntrusive const& rhs) : ptr_{rhs.unsafeGetRawPtr()} { if (ptr_) ptr_->addWeakRef(); @@ -720,4 +702,3 @@ SharedWeakUnion::unsafeReleaseNoStore() } } // namespace xrpl -#endif diff --git a/include/xrpl/basics/IntrusiveRefCounts.h b/include/xrpl/basics/IntrusiveRefCounts.h index 440ecdd19c..0273ed4647 100644 --- a/include/xrpl/basics/IntrusiveRefCounts.h +++ b/include/xrpl/basics/IntrusiveRefCounts.h @@ -1,5 +1,4 @@ -#ifndef XRPL_BASICS_INTRUSIVEREFCOUNTS_H_INCLUDED -#define XRPL_BASICS_INTRUSIVEREFCOUNTS_H_INCLUDED +#pragma once #include @@ -160,22 +159,19 @@ private: See description of the `refCounts` field for a fuller description of this field. */ - static constexpr FieldType partialDestroyStartedMask = - (one << (FieldTypeBits - 1)); + static constexpr FieldType partialDestroyStartedMask = (one << (FieldTypeBits - 1)); /** Flag that is set when the partialDestroy function has finished running See description of the `refCounts` field for a fuller description of this field. */ - static constexpr FieldType partialDestroyFinishedMask = - (one << (FieldTypeBits - 2)); + static constexpr FieldType partialDestroyFinishedMask = (one << (FieldTypeBits - 2)); /** Mask that will zero out all the `count` bits and leave the tag bits unchanged. */ - static constexpr FieldType tagMask = - partialDestroyStartedMask | partialDestroyFinishedMask; + static constexpr FieldType tagMask = partialDestroyStartedMask | partialDestroyFinishedMask; /** Mask that will zero out the `tag` bits and leave the count bits unchanged. @@ -184,13 +180,11 @@ private: /** Mask that will zero out everything except the strong count. */ - static constexpr FieldType strongMask = - ((one << StrongCountNumBits) - 1) & valueMask; + static constexpr FieldType strongMask = ((one << StrongCountNumBits) - 1) & valueMask; /** Mask that will zero out everything except the weak count. */ - static constexpr FieldType weakMask = - (((one << WeakCountNumBits) - 1) << StrongCountNumBits) & valueMask; + static constexpr FieldType weakMask = (((one << WeakCountNumBits) - 1) << StrongCountNumBits) & valueMask; /** Unpack the count and tag fields from the packed atomic integer form. */ struct RefCountPair @@ -215,10 +209,8 @@ private: FieldType combinedValue() const noexcept; - static constexpr CountType maxStrongValue = - static_cast((one << StrongCountNumBits) - 1); - static constexpr CountType maxWeakValue = - static_cast((one << WeakCountNumBits) - 1); + static constexpr CountType maxStrongValue = static_cast((one << StrongCountNumBits) - 1); + static constexpr CountType maxWeakValue = static_cast((one << WeakCountNumBits) - 1); /** Put an extra margin to detect when running up against limits. This is only used in debug code, and is useful if we reduce the number of bits in the strong and weak counts (to 16 and 14 bits). @@ -274,8 +266,7 @@ IntrusiveRefCounts::releaseStrongRef() const } } - if (refCounts.compare_exchange_weak( - prevIntVal, nextIntVal, std::memory_order_acq_rel)) + if (refCounts.compare_exchange_weak(prevIntVal, nextIntVal, std::memory_order_acq_rel)) { // Can't be in partial destroy because only decrementing the strong // count to zero can start a partial destroy, and that can't happen @@ -331,8 +322,7 @@ IntrusiveRefCounts::addWeakReleaseStrongRef() const action = partialDestroy; } } - if (refCounts.compare_exchange_weak( - prevIntVal, nextIntVal, std::memory_order_acq_rel)) + if (refCounts.compare_exchange_weak(prevIntVal, nextIntVal, std::memory_order_acq_rel)) { XRPL_ASSERT( (!(prevIntVal & partialDestroyStartedMask)), @@ -376,8 +366,7 @@ IntrusiveRefCounts::checkoutStrongRefFromWeak() const noexcept auto curValue = RefCountPair{1, 1}.combinedValue(); auto desiredValue = RefCountPair{2, 1}.combinedValue(); - while (!refCounts.compare_exchange_weak( - curValue, desiredValue, std::memory_order_acq_rel)) + while (!refCounts.compare_exchange_weak(curValue, desiredValue, std::memory_order_acq_rel)) { RefCountPair const prev{curValue}; if (!prev.strong) @@ -406,20 +395,15 @@ inline IntrusiveRefCounts::~IntrusiveRefCounts() noexcept { #ifndef NDEBUG auto v = refCounts.load(std::memory_order_acquire); - XRPL_ASSERT( - (!(v & valueMask)), - "xrpl::IntrusiveRefCounts::~IntrusiveRefCounts : count must be zero"); + XRPL_ASSERT((!(v & valueMask)), "xrpl::IntrusiveRefCounts::~IntrusiveRefCounts : count must be zero"); auto t = v & tagMask; - XRPL_ASSERT( - (!t || t == tagMask), - "xrpl::IntrusiveRefCounts::~IntrusiveRefCounts : valid tag"); + XRPL_ASSERT((!t || t == tagMask), "xrpl::IntrusiveRefCounts::~IntrusiveRefCounts : valid tag"); #endif } //------------------------------------------------------------------------------ -inline IntrusiveRefCounts::RefCountPair::RefCountPair( - IntrusiveRefCounts::FieldType v) noexcept +inline IntrusiveRefCounts::RefCountPair::RefCountPair(IntrusiveRefCounts::FieldType v) noexcept : strong{static_cast(v & strongMask)} , weak{static_cast((v & weakMask) >> StrongCountNumBits)} , partialDestroyStartedBit{v & partialDestroyStartedMask} @@ -449,10 +433,8 @@ IntrusiveRefCounts::RefCountPair::combinedValue() const noexcept (strong < checkStrongMaxValue && weak < checkWeakMaxValue), "xrpl::IntrusiveRefCounts::RefCountPair::combinedValue : inputs " "inside range"); - return (static_cast(weak) - << IntrusiveRefCounts::StrongCountNumBits) | - static_cast(strong) | - partialDestroyStartedBit | partialDestroyFinishedBit; + return (static_cast(weak) << IntrusiveRefCounts::StrongCountNumBits) | + static_cast(strong) | partialDestroyStartedBit | partialDestroyFinishedBit; } template @@ -460,11 +442,9 @@ inline void partialDestructorFinished(T** o) { T& self = **o; - IntrusiveRefCounts::RefCountPair p = - self.refCounts.fetch_or(IntrusiveRefCounts::partialDestroyFinishedMask); + IntrusiveRefCounts::RefCountPair p = self.refCounts.fetch_or(IntrusiveRefCounts::partialDestroyFinishedMask); XRPL_ASSERT( - (!p.partialDestroyFinishedBit && p.partialDestroyStartedBit && - !p.strong), + (!p.partialDestroyFinishedBit && p.partialDestroyStartedBit && !p.strong), "xrpl::partialDestructorFinished : not a weak ref"); if (!p.weak) { @@ -480,4 +460,3 @@ partialDestructorFinished(T** o) //------------------------------------------------------------------------------ } // namespace xrpl -#endif diff --git a/include/xrpl/basics/KeyCache.h b/include/xrpl/basics/KeyCache.h index 038bf7b9b7..4f2ca20cca 100644 --- a/include/xrpl/basics/KeyCache.h +++ b/include/xrpl/basics/KeyCache.h @@ -1,5 +1,4 @@ -#ifndef XRPL_BASICS_KEYCACHE_H -#define XRPL_BASICS_KEYCACHE_H +#pragma once #include #include @@ -9,5 +8,3 @@ namespace xrpl { using KeyCache = TaggedCache; } // namespace xrpl - -#endif // XRPL_BASICS_KEYCACHE_H diff --git a/include/xrpl/basics/LocalValue.h b/include/xrpl/basics/LocalValue.h index cc7c646fb0..94af41a41d 100644 --- a/include/xrpl/basics/LocalValue.h +++ b/include/xrpl/basics/LocalValue.h @@ -1,5 +1,4 @@ -#ifndef XRPL_BASICS_LOCALVALUE_H_INCLUDED -#define XRPL_BASICS_LOCALVALUE_H_INCLUDED +#pragma once #include @@ -55,8 +54,7 @@ template boost::thread_specific_ptr& getLocalValues() { - static boost::thread_specific_ptr tsp( - &detail::LocalValues::cleanup); + static boost::thread_specific_ptr tsp(&detail::LocalValues::cleanup); return tsp; } @@ -105,10 +103,6 @@ LocalValue::operator*() } return *reinterpret_cast( - lvs->values - .emplace(this, std::make_unique>(t_)) - .first->second->get()); + lvs->values.emplace(this, std::make_unique>(t_)).first->second->get()); } } // namespace xrpl - -#endif diff --git a/include/xrpl/basics/Log.h b/include/xrpl/basics/Log.h index f10f1ff64c..786fbc5da2 100644 --- a/include/xrpl/basics/Log.h +++ b/include/xrpl/basics/Log.h @@ -1,5 +1,4 @@ -#ifndef XRPL_BASICS_LOG_H_INCLUDED -#define XRPL_BASICS_LOG_H_INCLUDED +#pragma once #include #include @@ -39,22 +38,17 @@ private: std::string partition_; public: - Sink( - std::string const& partition, - beast::severities::Severity thresh, - Logs& logs); + Sink(std::string const& partition, beast::severities::Severity thresh, Logs& logs); Sink(Sink const&) = delete; Sink& operator=(Sink const&) = delete; void - write(beast::severities::Severity level, std::string const& text) - override; + write(beast::severities::Severity level, std::string const& text) override; void - writeAlways(beast::severities::Severity level, std::string const& text) - override; + writeAlways(beast::severities::Severity level, std::string const& text) override; }; /** Manages a system file containing logged output. @@ -140,11 +134,7 @@ private: }; std::mutex mutable mutex_; - std::map< - std::string, - std::unique_ptr, - boost::beast::iless> - sinks_; + std::map, boost::beast::iless> sinks_; beast::severities::Severity thresh_; File file_; bool silent_ = false; @@ -180,11 +170,7 @@ public: partition_severities() const; void - write( - beast::severities::Severity level, - std::string const& partition, - std::string const& text, - bool console); + write(beast::severities::Severity level, std::string const& partition, std::string const& text, bool console); std::string rotate(); @@ -201,9 +187,7 @@ public: } virtual std::unique_ptr - makeSink( - std::string const& partition, - beast::severities::Severity startingLevel); + makeSink(std::string const& partition, beast::severities::Severity startingLevel); public: static LogSeverity @@ -273,5 +257,3 @@ beast::Journal debugLog(); } // namespace xrpl - -#endif diff --git a/include/xrpl/basics/MathUtilities.h b/include/xrpl/basics/MathUtilities.h index bd8ea883fb..4552b335e1 100644 --- a/include/xrpl/basics/MathUtilities.h +++ b/include/xrpl/basics/MathUtilities.h @@ -1,5 +1,4 @@ -#ifndef XRPL_BASICS_MATHUTILITIES_H_INCLUDED -#define XRPL_BASICS_MATHUTILITIES_H_INCLUDED +#pragma once #include #include @@ -45,5 +44,3 @@ static_assert(calculatePercent(50'000'001, 100'000'000) == 51); static_assert(calculatePercent(99'999'999, 100'000'000) == 100); } // namespace xrpl - -#endif diff --git a/include/xrpl/basics/Number.h b/include/xrpl/basics/Number.h index d1ef749784..c269d27781 100644 --- a/include/xrpl/basics/Number.h +++ b/include/xrpl/basics/Number.h @@ -1,9 +1,9 @@ -#ifndef XRPL_BASICS_NUMBER_H_INCLUDED -#define XRPL_BASICS_NUMBER_H_INCLUDED +#pragma once #include #include +#include #include #include #include @@ -73,10 +73,7 @@ struct MantissaRange enum mantissa_scale { small, large }; explicit constexpr MantissaRange(mantissa_scale scale_) - : min(getMin(scale_)) - , max(min * 10 - 1) - , log(logTen(min).value_or(-1)) - , scale(scale_) + : min(getMin(scale_)), max(min * 10 - 1), log(logTen(min).value_or(-1)), scale(scale_) { } @@ -106,8 +103,7 @@ private: // Like std::integral, but only 64-bit integral types. template -concept Integral64 = - std::is_same_v || std::is_same_v; +concept Integral64 = std::is_same_v || std::is_same_v; /** Number is a floating point type that can represent a wide range of values. * @@ -244,22 +240,11 @@ public: Number(rep mantissa); explicit Number(rep mantissa, int exponent); - explicit constexpr Number( - bool negative, - internalrep mantissa, - int exponent, - unchecked) noexcept; + explicit constexpr Number(bool negative, internalrep mantissa, int exponent, unchecked) noexcept; // Assume unsigned values are... unsigned. i.e. positive - explicit constexpr Number( - internalrep mantissa, - int exponent, - unchecked) noexcept; + explicit constexpr Number(internalrep mantissa, int exponent, unchecked) noexcept; // Only unit tests are expected to use this ctor - explicit Number( - bool negative, - internalrep mantissa, - int exponent, - normalized); + explicit Number(bool negative, internalrep mantissa, int exponent, normalized); // Assume unsigned values are... unsigned. i.e. positive explicit Number(internalrep mantissa, int exponent, normalized); @@ -309,8 +294,7 @@ public: friend constexpr bool operator==(Number const& x, Number const& y) noexcept { - return x.negative_ == y.negative_ && x.mantissa_ == y.mantissa_ && - x.exponent_ == y.exponent_; + return x.negative_ == y.negative_ && x.mantissa_ == y.mantissa_ && x.exponent_ == y.exponent_; } friend constexpr bool @@ -518,37 +502,25 @@ private: class Guard; }; -inline constexpr Number::Number( - bool negative, - internalrep mantissa, - int exponent, - unchecked) noexcept +inline constexpr Number::Number(bool negative, internalrep mantissa, int exponent, unchecked) noexcept : negative_(negative), mantissa_{mantissa}, exponent_{exponent} { } -inline constexpr Number::Number( - internalrep mantissa, - int exponent, - unchecked) noexcept +inline constexpr Number::Number(internalrep mantissa, int exponent, unchecked) noexcept : Number(false, mantissa, exponent, unchecked{}) { } constexpr static Number numZero{}; -inline Number::Number( - bool negative, - internalrep mantissa, - int exponent, - normalized) +inline Number::Number(bool negative, internalrep mantissa, int exponent, normalized) : Number(negative, mantissa, exponent, unchecked{}) { normalize(); } -inline Number::Number(internalrep mantissa, int exponent, normalized) - : Number(false, mantissa, exponent, normalized{}) +inline Number::Number(internalrep mantissa, int exponent, normalized) : Number(false, mantissa, exponent, normalized{}) { } @@ -695,15 +667,13 @@ Number::min() noexcept inline Number Number::max() noexcept { - return Number{ - false, std::min(range_.get().max, maxRep), maxExponent, unchecked{}}; + return Number{false, std::min(range_.get().max, maxRep), maxExponent, unchecked{}}; } inline Number Number::lowest() noexcept { - return Number{ - true, std::min(range_.get().max, maxRep), maxExponent, unchecked{}}; + return Number{true, std::min(range_.get().max, maxRep), maxExponent, unchecked{}}; } inline bool @@ -712,8 +682,7 @@ Number::isnormal() const noexcept MantissaRange const& range = range_; auto const abs_m = mantissa_; return *this == Number{} || - (range.min <= abs_m && abs_m <= range.max && - (abs_m <= maxRep || abs_m % 10 == 0) && minExponent <= exponent_ && + (range.min <= abs_m && abs_m <= range.max && (abs_m <= maxRep || abs_m % 10 == 0) && minExponent <= exponent_ && exponent_ <= maxExponent); } @@ -726,10 +695,7 @@ Number::normalizeToRange(T minMantissa, T maxMantissa) const int exponent = exponent_; if constexpr (std::is_unsigned_v) - XRPL_ASSERT_PARTS( - !negative, - "xrpl::Number::normalizeToRange", - "Number is non-negative for unsigned range."); + XRPL_ASSERT_PARTS(!negative, "xrpl::Number::normalizeToRange", "Number is non-negative for unsigned range."); Number::normalize(negative, mantissa, exponent, minMantissa, maxMantissa); auto const sign = negative ? -1 : 1; @@ -798,8 +764,7 @@ public: { Number::setround(mode_); } - explicit saveNumberRoundMode(Number::rounding_mode mode) noexcept - : mode_{mode} + explicit saveNumberRoundMode(Number::rounding_mode mode) noexcept : mode_{mode} { } saveNumberRoundMode(saveNumberRoundMode const&) = delete; @@ -816,8 +781,7 @@ class NumberRoundModeGuard saveNumberRoundMode saved_; public: - explicit NumberRoundModeGuard(Number::rounding_mode mode) noexcept - : saved_{Number::setround(mode)} + explicit NumberRoundModeGuard(Number::rounding_mode mode) noexcept : saved_{Number::setround(mode)} { } @@ -837,9 +801,7 @@ class NumberMantissaScaleGuard MantissaRange::mantissa_scale const saved_; public: - explicit NumberMantissaScaleGuard( - MantissaRange::mantissa_scale scale) noexcept - : saved_{Number::getMantissaScale()} + explicit NumberMantissaScaleGuard(MantissaRange::mantissa_scale scale) noexcept : saved_{Number::getMantissaScale()} { Number::setMantissaScale(scale); } @@ -856,5 +818,3 @@ public: }; } // namespace xrpl - -#endif // XRPL_BASICS_NUMBER_H_INCLUDED diff --git a/include/xrpl/basics/RangeSet.h b/include/xrpl/basics/RangeSet.h index ee95577271..f6e03cac79 100644 --- a/include/xrpl/basics/RangeSet.h +++ b/include/xrpl/basics/RangeSet.h @@ -1,5 +1,4 @@ -#ifndef XRPL_BASICS_RANGESET_H_INCLUDED -#define XRPL_BASICS_RANGESET_H_INCLUDED +#pragma once #include @@ -173,5 +172,3 @@ prevMissing(RangeSet const& rs, T t, T minVal = 0) } } // namespace xrpl - -#endif diff --git a/include/xrpl/basics/Resolver.h b/include/xrpl/basics/Resolver.h index 088b2e1d5b..5bfa6796d2 100644 --- a/include/xrpl/basics/Resolver.h +++ b/include/xrpl/basics/Resolver.h @@ -1,5 +1,4 @@ -#ifndef XRPL_BASICS_RESOLVER_H_INCLUDED -#define XRPL_BASICS_RESOLVER_H_INCLUDED +#pragma once #include @@ -11,8 +10,7 @@ namespace xrpl { class Resolver { public: - using HandlerType = - std::function)>; + using HandlerType = std::function)>; virtual ~Resolver() = 0; @@ -41,12 +39,8 @@ public: } virtual void - resolve( - std::vector const& names, - HandlerType const& handler) = 0; + resolve(std::vector const& names, HandlerType const& handler) = 0; /** @} */ }; } // namespace xrpl - -#endif diff --git a/include/xrpl/basics/ResolverAsio.h b/include/xrpl/basics/ResolverAsio.h index f2a3da0d58..d0dcc9f185 100644 --- a/include/xrpl/basics/ResolverAsio.h +++ b/include/xrpl/basics/ResolverAsio.h @@ -1,5 +1,4 @@ -#ifndef XRPL_BASICS_RESOLVERASIO_H_INCLUDED -#define XRPL_BASICS_RESOLVERASIO_H_INCLUDED +#pragma once #include #include @@ -18,5 +17,3 @@ public: }; } // namespace xrpl - -#endif diff --git a/include/xrpl/basics/SHAMapHash.h b/include/xrpl/basics/SHAMapHash.h index eb635b516c..22f8505912 100644 --- a/include/xrpl/basics/SHAMapHash.h +++ b/include/xrpl/basics/SHAMapHash.h @@ -1,5 +1,4 @@ -#ifndef XRPL_BASICS_SHAMAP_HASH_H_INCLUDED -#define XRPL_BASICS_SHAMAP_HASH_H_INCLUDED +#pragma once #include #include @@ -98,5 +97,3 @@ extract(SHAMapHash const& key) } } // namespace xrpl - -#endif // XRPL_BASICS_SHAMAP_HASH_H_INCLUDED diff --git a/include/xrpl/basics/SharedWeakCachePointer.h b/include/xrpl/basics/SharedWeakCachePointer.h index 49369265eb..afc701ed5a 100644 --- a/include/xrpl/basics/SharedWeakCachePointer.h +++ b/include/xrpl/basics/SharedWeakCachePointer.h @@ -1,5 +1,4 @@ -#ifndef XRPL_BASICS_SHAREDWEAKCACHEPOINTER_H_INCLUDED -#define XRPL_BASICS_SHAREDWEAKCACHEPOINTER_H_INCLUDED +#pragma once #include #include @@ -113,4 +112,3 @@ private: std::variant, std::weak_ptr> combo_; }; } // namespace xrpl -#endif diff --git a/include/xrpl/basics/SharedWeakCachePointer.ipp b/include/xrpl/basics/SharedWeakCachePointer.ipp index 376bf73251..6e7514ffae 100644 --- a/include/xrpl/basics/SharedWeakCachePointer.ipp +++ b/include/xrpl/basics/SharedWeakCachePointer.ipp @@ -1,38 +1,31 @@ -#ifndef XRPL_BASICS_SHAREDWEAKCACHEPOINTER_IPP_INCLUDED -#define XRPL_BASICS_SHAREDWEAKCACHEPOINTER_IPP_INCLUDED +#pragma once #include namespace xrpl { template -SharedWeakCachePointer::SharedWeakCachePointer( - SharedWeakCachePointer const& rhs) = default; +SharedWeakCachePointer::SharedWeakCachePointer(SharedWeakCachePointer const& rhs) = default; template template requires std::convertible_to -SharedWeakCachePointer::SharedWeakCachePointer( - std::shared_ptr const& rhs) - : combo_{rhs} +SharedWeakCachePointer::SharedWeakCachePointer(std::shared_ptr const& rhs) : combo_{rhs} { } template -SharedWeakCachePointer::SharedWeakCachePointer( - SharedWeakCachePointer&& rhs) = default; +SharedWeakCachePointer::SharedWeakCachePointer(SharedWeakCachePointer&& rhs) = default; template template requires std::convertible_to -SharedWeakCachePointer::SharedWeakCachePointer(std::shared_ptr&& rhs) - : combo_{std::move(rhs)} +SharedWeakCachePointer::SharedWeakCachePointer(std::shared_ptr&& rhs) : combo_{std::move(rhs)} { } template SharedWeakCachePointer& -SharedWeakCachePointer::operator=(SharedWeakCachePointer const& rhs) = - default; +SharedWeakCachePointer::operator=(SharedWeakCachePointer const& rhs) = default; template template @@ -170,4 +163,3 @@ SharedWeakCachePointer::convertToWeak() return false; } } // namespace xrpl -#endif diff --git a/include/xrpl/basics/SlabAllocator.h b/include/xrpl/basics/SlabAllocator.h index c67d1ee318..2578afdc5a 100644 --- a/include/xrpl/basics/SlabAllocator.h +++ b/include/xrpl/basics/SlabAllocator.h @@ -1,7 +1,6 @@ // Copyright (c) 2022, Nikolaos D. Bougalis -#ifndef XRPL_BASICS_SLABALLOCATOR_H_INCLUDED -#define XRPL_BASICS_SLABALLOCATOR_H_INCLUDED +#pragma once #include #include @@ -51,11 +50,7 @@ class SlabAllocator // The extent of the underlying memory block: std::size_t const size_; - SlabBlock( - SlabBlock* next, - std::uint8_t* data, - std::size_t size, - std::size_t item) + SlabBlock(SlabBlock* next, std::uint8_t* data, std::size_t size, std::size_t item) : next_(next), p_(data), size_(size) { // We don't need to grab the mutex here, since we're the only @@ -126,9 +121,7 @@ class SlabAllocator void deallocate(std::uint8_t* ptr) noexcept { - XRPL_ASSERT( - own(ptr), - "xrpl::SlabAllocator::SlabBlock::deallocate : own input"); + XRPL_ASSERT(own(ptr), "xrpl::SlabAllocator::SlabBlock::deallocate : own input"); std::lock_guard l(m_); @@ -162,18 +155,13 @@ public: contexts (e.g. when minimal memory usage is needed) and allows for graceful failure. */ - constexpr explicit SlabAllocator( - std::size_t extra, - std::size_t alloc = 0, - std::size_t align = 0) + constexpr explicit SlabAllocator(std::size_t extra, std::size_t alloc = 0, std::size_t align = 0) : itemAlignment_(align ? align : alignof(Type)) - , itemSize_( - boost::alignment::align_up(sizeof(Type) + extra, itemAlignment_)) + , itemSize_(boost::alignment::align_up(sizeof(Type) + extra, itemAlignment_)) , slabSize_(alloc) { XRPL_ASSERT( - (itemAlignment_ & (itemAlignment_ - 1)) == 0, - "xrpl::SlabAllocator::SlabAllocator : valid alignment"); + (itemAlignment_ & (itemAlignment_ - 1)) == 0, "xrpl::SlabAllocator::SlabAllocator : valid alignment"); } SlabAllocator(SlabAllocator const& other) = delete; @@ -222,8 +210,7 @@ public: // We want to allocate the memory at a 2 MiB boundary, to make it // possible to use hugepage mappings on Linux: - auto buf = - boost::alignment::aligned_alloc(megabytes(std::size_t(2)), size); + auto buf = boost::alignment::aligned_alloc(megabytes(std::size_t(2)), size); // clang-format off if (!buf) [[unlikely]] @@ -241,31 +228,21 @@ public: // We need to carve out a bit of memory for the slab header // and then align the rest appropriately: - auto slabData = reinterpret_cast( - reinterpret_cast(buf) + sizeof(SlabBlock)); + auto slabData = reinterpret_cast(reinterpret_cast(buf) + sizeof(SlabBlock)); auto slabSize = size - sizeof(SlabBlock); // This operation is essentially guaranteed not to fail but // let's be careful anyways. - if (!boost::alignment::align( - itemAlignment_, itemSize_, slabData, slabSize)) + if (!boost::alignment::align(itemAlignment_, itemSize_, slabData, slabSize)) { boost::alignment::aligned_free(buf); return nullptr; } - slab = new (buf) SlabBlock( - slabs_.load(), - reinterpret_cast(slabData), - slabSize, - itemSize_); + slab = new (buf) SlabBlock(slabs_.load(), reinterpret_cast(slabData), slabSize, itemSize_); // Link the new slab - while (!slabs_.compare_exchange_weak( - slab->next_, - slab, - std::memory_order_release, - std::memory_order_relaxed)) + while (!slabs_.compare_exchange_weak(slab->next_, slab, std::memory_order_release, std::memory_order_relaxed)) { ; // Nothing to do } @@ -322,10 +299,7 @@ public: std::size_t align; public: - constexpr SlabConfig( - std::size_t extra_, - std::size_t alloc_ = 0, - std::size_t align_ = alignof(Type)) + constexpr SlabConfig(std::size_t extra_, std::size_t alloc_ = 0, std::size_t align_ = alignof(Type)) : extra(extra_), alloc(alloc_), align(align_) { } @@ -336,23 +310,14 @@ public: // Ensure that the specified allocators are sorted from smallest to // largest by size: std::sort( - std::begin(cfg), - std::end(cfg), - [](SlabConfig const& a, SlabConfig const& b) { - return a.extra < b.extra; - }); + std::begin(cfg), std::end(cfg), [](SlabConfig const& a, SlabConfig const& b) { return a.extra < b.extra; }); // We should never have two slabs of the same size - if (std::adjacent_find( - std::begin(cfg), - std::end(cfg), - [](SlabConfig const& a, SlabConfig const& b) { - return a.extra == b.extra; - }) != cfg.end()) + if (std::adjacent_find(std::begin(cfg), std::end(cfg), [](SlabConfig const& a, SlabConfig const& b) { + return a.extra == b.extra; + }) != cfg.end()) { - throw std::runtime_error( - "SlabAllocatorSet<" + beast::type_name() + - ">: duplicate slab size"); + throw std::runtime_error("SlabAllocatorSet<" + beast::type_name() + ">: duplicate slab size"); } for (auto const& c : cfg) @@ -420,5 +385,3 @@ public: }; } // namespace xrpl - -#endif // XRPL_BASICS_SLABALLOCATOR_H_INCLUDED diff --git a/include/xrpl/basics/Slice.h b/include/xrpl/basics/Slice.h index fba4b7733c..2f6081760f 100644 --- a/include/xrpl/basics/Slice.h +++ b/include/xrpl/basics/Slice.h @@ -1,5 +1,4 @@ -#ifndef XRPL_BASICS_SLICE_H_INCLUDED -#define XRPL_BASICS_SLICE_H_INCLUDED +#pragma once #include #include @@ -41,8 +40,7 @@ public: operator=(Slice const&) noexcept = default; /** Create a slice pointing to existing memory. */ - Slice(void const* data, std::size_t size) noexcept - : data_(reinterpret_cast(data)), size_(size) + Slice(void const* data, std::size_t size) noexcept : data_(reinterpret_cast(data)), size_(size) { } @@ -85,9 +83,7 @@ public: std::uint8_t operator[](std::size_t i) const noexcept { - XRPL_ASSERT( - i < size_, - "xrpl::Slice::operator[](std::size_t) const : valid input"); + XRPL_ASSERT(i < size_, "xrpl::Slice::operator[](std::size_t) const : valid input"); return data_[i]; } @@ -162,9 +158,7 @@ public: @throws std::out_of_range if pos > size() */ Slice - substr( - std::size_t pos, - std::size_t count = std::numeric_limits::max()) const + substr(std::size_t pos, std::size_t count = std::numeric_limits::max()) const { if (pos > size()) throw std::out_of_range("Requested sub-slice is out of bounds"); @@ -203,11 +197,7 @@ operator!=(Slice const& lhs, Slice const& rhs) noexcept inline bool operator<(Slice const& lhs, Slice const& rhs) noexcept { - return std::lexicographical_compare( - lhs.data(), - lhs.data() + lhs.size(), - rhs.data(), - rhs.data() + rhs.size()); + return std::lexicographical_compare(lhs.data(), lhs.data() + lhs.size(), rhs.data(), rhs.data() + rhs.size()); } template @@ -219,18 +209,14 @@ operator<<(Stream& s, Slice const& v) } template -std::enable_if_t< - std::is_same::value || std::is_same::value, - Slice> +std::enable_if_t::value || std::is_same::value, Slice> makeSlice(std::array const& a) { return Slice(a.data(), a.size()); } template -std::enable_if_t< - std::is_same::value || std::is_same::value, - Slice> +std::enable_if_t::value || std::is_same::value, Slice> makeSlice(std::vector const& v) { return Slice(v.data(), v.size()); @@ -244,5 +230,3 @@ makeSlice(std::basic_string const& s) } } // namespace xrpl - -#endif diff --git a/include/xrpl/basics/StringUtilities.h b/include/xrpl/basics/StringUtilities.h index 6314a56103..9b1cf4892d 100644 --- a/include/xrpl/basics/StringUtilities.h +++ b/include/xrpl/basics/StringUtilities.h @@ -1,5 +1,4 @@ -#ifndef XRPL_BASICS_STRINGUTILITIES_H_INCLUDED -#define XRPL_BASICS_STRINGUTILITIES_H_INCLUDED +#pragma once #include #include @@ -109,8 +108,7 @@ struct parsedURL bool operator==(parsedURL const& other) const { - return scheme == other.scheme && domain == other.domain && - port == other.port && path == other.path; + return scheme == other.scheme && domain == other.domain && port == other.port && path == other.path; } }; @@ -133,5 +131,3 @@ bool isProperlyFormedTomlDomain(std::string_view domain); } // namespace xrpl - -#endif diff --git a/include/xrpl/basics/TaggedCache.h b/include/xrpl/basics/TaggedCache.h index c1d4d26800..78c4ea7aeb 100644 --- a/include/xrpl/basics/TaggedCache.h +++ b/include/xrpl/basics/TaggedCache.h @@ -1,5 +1,4 @@ -#ifndef XRPL_BASICS_TAGGEDCACHE_H_INCLUDED -#define XRPL_BASICS_TAGGEDCACHE_H_INCLUDED +#pragma once #include #include @@ -56,8 +55,7 @@ public: clock_type::duration expiration, clock_type& clock, beast::Journal journal, - beast::insight::Collector::ptr const& collector = - beast::insight::NullCollector::New()); + beast::insight::Collector::ptr const& collector = beast::insight::NullCollector::New()); public: /** Return the clock associated with the cache. */ @@ -114,15 +112,10 @@ public: */ template bool - canonicalize( - key_type const& key, - SharedPointerType& data, - R&& replaceCallback); + canonicalize(key_type const& key, SharedPointerType& data, R&& replaceCallback); bool - canonicalize_replace_cache( - key_type const& key, - SharedPointerType const& data); + canonicalize_replace_cache(key_type const& key, SharedPointerType const& data); bool canonicalize_replace_client(key_type const& key, SharedPointerType& data); @@ -136,8 +129,7 @@ public: */ template auto - insert(key_type const& key, T const& value) - -> std::enable_if_t; + insert(key_type const& key, T const& value) -> std::enable_if_t; template auto @@ -183,10 +175,7 @@ private: struct Stats { template - Stats( - std::string const& prefix, - Handler const& handler, - beast::insight::Collector::ptr const& collector) + Stats(std::string const& prefix, Handler const& handler, beast::insight::Collector::ptr const& collector) : hook(collector->make_hook(handler)) , size(collector->make_gauge(prefix, "size")) , hit_rate(collector->make_gauge(prefix, "hit_rate")) @@ -208,8 +197,7 @@ private: public: clock_type::time_point last_access; - explicit KeyOnlyEntry(clock_type::time_point const& last_access_) - : last_access(last_access_) + explicit KeyOnlyEntry(clock_type::time_point const& last_access_) : last_access(last_access_) { } @@ -226,9 +214,7 @@ private: shared_weak_combo_pointer_type ptr; clock_type::time_point last_access; - ValueEntry( - clock_type::time_point const& last_access_, - shared_pointer_type const& ptr_) + ValueEntry(clock_type::time_point const& last_access_, shared_pointer_type const& ptr_) : ptr(ptr_), last_access(last_access_) { } @@ -262,18 +248,13 @@ private: } }; - typedef - typename std::conditional::type - Entry; + typedef typename std::conditional::type Entry; - using KeyOnlyCacheType = - hardened_partitioned_hash_map; + using KeyOnlyCacheType = hardened_partitioned_hash_map; - using KeyValueCacheType = - hardened_partitioned_hash_map; + using KeyValueCacheType = hardened_partitioned_hash_map; - using cache_type = - hardened_partitioned_hash_map; + using cache_type = hardened_partitioned_hash_map; [[nodiscard]] std::thread sweepHelper( @@ -316,5 +297,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/include/xrpl/basics/TaggedCache.ipp b/include/xrpl/basics/TaggedCache.ipp index 5114479921..3d0c0342cc 100644 --- a/include/xrpl/basics/TaggedCache.ipp +++ b/include/xrpl/basics/TaggedCache.ipp @@ -1,5 +1,4 @@ -#ifndef XRPL_BASICS_TAGGEDCACHE_IPP_INCLUDED -#define XRPL_BASICS_TAGGEDCACHE_IPP_INCLUDED +#pragma once #include #include @@ -15,22 +14,13 @@ template < class Hash, class KeyEqual, class Mutex> -inline TaggedCache< - Key, - T, - IsKeyCache, - SharedWeakUnionPointer, - SharedPointerType, - Hash, - KeyEqual, - Mutex>:: - TaggedCache( - std::string const& name, - int size, - clock_type::duration expiration, - clock_type& clock, - beast::Journal journal, - beast::insight::Collector::ptr const& collector) +inline TaggedCache::TaggedCache( + std::string const& name, + int size, + clock_type::duration expiration, + clock_type& clock, + beast::Journal journal, + beast::insight::Collector::ptr const& collector) : m_journal(journal) , m_clock(clock) , m_stats(name, std::bind(&TaggedCache::collect_metrics, this), collector) @@ -53,15 +43,8 @@ template < class KeyEqual, class Mutex> inline auto -TaggedCache< - Key, - T, - IsKeyCache, - SharedWeakUnionPointer, - SharedPointerType, - Hash, - KeyEqual, - Mutex>::clock() -> clock_type& +TaggedCache::clock() + -> clock_type& { return m_clock; } @@ -76,15 +59,7 @@ template < class KeyEqual, class Mutex> inline std::size_t -TaggedCache< - Key, - T, - IsKeyCache, - SharedWeakUnionPointer, - SharedPointerType, - Hash, - KeyEqual, - Mutex>::size() const +TaggedCache::size() const { std::lock_guard lock(m_mutex); return m_cache.size(); @@ -100,15 +75,7 @@ template < class KeyEqual, class Mutex> inline int -TaggedCache< - Key, - T, - IsKeyCache, - SharedWeakUnionPointer, - SharedPointerType, - Hash, - KeyEqual, - Mutex>::getCacheSize() const +TaggedCache::getCacheSize() const { std::lock_guard lock(m_mutex); return m_cache_count; @@ -124,15 +91,7 @@ template < class KeyEqual, class Mutex> inline int -TaggedCache< - Key, - T, - IsKeyCache, - SharedWeakUnionPointer, - SharedPointerType, - Hash, - KeyEqual, - Mutex>::getTrackSize() const +TaggedCache::getTrackSize() const { std::lock_guard lock(m_mutex); return m_cache.size(); @@ -148,15 +107,7 @@ template < class KeyEqual, class Mutex> inline float -TaggedCache< - Key, - T, - IsKeyCache, - SharedWeakUnionPointer, - SharedPointerType, - Hash, - KeyEqual, - Mutex>::getHitRate() +TaggedCache::getHitRate() { std::lock_guard lock(m_mutex); auto const total = static_cast(m_hits + m_misses); @@ -173,15 +124,7 @@ template < class KeyEqual, class Mutex> inline void -TaggedCache< - Key, - T, - IsKeyCache, - SharedWeakUnionPointer, - SharedPointerType, - Hash, - KeyEqual, - Mutex>::clear() +TaggedCache::clear() { std::lock_guard lock(m_mutex); m_cache.clear(); @@ -198,15 +141,7 @@ template < class KeyEqual, class Mutex> inline void -TaggedCache< - Key, - T, - IsKeyCache, - SharedWeakUnionPointer, - SharedPointerType, - Hash, - KeyEqual, - Mutex>::reset() +TaggedCache::reset() { std::lock_guard lock(m_mutex); m_cache.clear(); @@ -226,15 +161,8 @@ template < class Mutex> template inline bool -TaggedCache< - Key, - T, - IsKeyCache, - SharedWeakUnionPointer, - SharedPointerType, - Hash, - KeyEqual, - Mutex>::touch_if_exists(KeyComparable const& key) +TaggedCache::touch_if_exists( + KeyComparable const& key) { std::lock_guard lock(m_mutex); auto const iter(m_cache.find(key)); @@ -258,15 +186,7 @@ template < class KeyEqual, class Mutex> inline void -TaggedCache< - Key, - T, - IsKeyCache, - SharedWeakUnionPointer, - SharedPointerType, - Hash, - KeyEqual, - Mutex>::sweep() +TaggedCache::sweep() { // Keep references to all the stuff we sweep // For performance, each worker thread should exit before the swept data @@ -280,8 +200,7 @@ TaggedCache< { std::lock_guard lock(m_mutex); - if (m_target_size == 0 || - (static_cast(m_cache.size()) <= m_target_size)) + if (m_target_size == 0 || (static_cast(m_cache.size()) <= m_target_size)) { when_expire = now - m_target_age; } @@ -293,10 +212,8 @@ TaggedCache< if (when_expire > (now - minimumAge)) when_expire = now - minimumAge; - JLOG(m_journal.trace()) - << m_name << " is growing fast " << m_cache.size() << " of " - << m_target_size << " aging at " << (now - when_expire).count() - << " of " << m_target_age.count(); + JLOG(m_journal.trace()) << m_name << " is growing fast " << m_cache.size() << " of " << m_target_size + << " aging at " << (now - when_expire).count() << " of " << m_target_age.count(); } std::vector workers; @@ -305,13 +222,7 @@ TaggedCache< for (std::size_t p = 0; p < m_cache.partitions(); ++p) { - workers.push_back(sweepHelper( - when_expire, - now, - m_cache.map()[p], - allStuffToSweep[p], - allRemovals, - lock)); + workers.push_back(sweepHelper(when_expire, now, m_cache.map()[p], allStuffToSweep[p], allRemovals, lock)); } for (std::thread& worker : workers) worker.join(); @@ -322,9 +233,7 @@ TaggedCache< // and decrement the reference count on each strong pointer. JLOG(m_journal.debug()) << m_name << " TaggedCache sweep lock duration " - << std::chrono::duration_cast( - std::chrono::steady_clock::now() - start) - .count() + << std::chrono::duration_cast(std::chrono::steady_clock::now() - start).count() << "ms"; } @@ -338,15 +247,9 @@ template < class KeyEqual, class Mutex> inline bool -TaggedCache< - Key, - T, - IsKeyCache, - SharedWeakUnionPointer, - SharedPointerType, - Hash, - KeyEqual, - Mutex>::del(key_type const& key, bool valid) +TaggedCache::del( + key_type const& key, + bool valid) { // Remove from cache, if !valid, remove from map too. Returns true if // removed from cache @@ -385,19 +288,10 @@ template < class Mutex> template inline bool -TaggedCache< - Key, - T, - IsKeyCache, - SharedWeakUnionPointer, - SharedPointerType, - Hash, - KeyEqual, - Mutex>:: - canonicalize( - key_type const& key, - SharedPointerType& data, - R&& replaceCallback) +TaggedCache::canonicalize( + key_type const& key, + SharedPointerType& data, + R&& replaceCallback) { // Return canonical value, store if needed, refresh in cache // Return values: true=we had the data already @@ -408,9 +302,7 @@ TaggedCache< if (cit == m_cache.end()) { m_cache.emplace( - std::piecewise_construct, - std::forward_as_tuple(key), - std::forward_as_tuple(m_clock.now(), data)); + std::piecewise_construct, std::forward_as_tuple(key), std::forward_as_tuple(m_clock.now(), data)); ++m_cache_count; return false; } @@ -480,21 +372,10 @@ template < class KeyEqual, class Mutex> inline bool -TaggedCache< - Key, - T, - IsKeyCache, - SharedWeakUnionPointer, - SharedPointerType, - Hash, - KeyEqual, - Mutex>:: - canonicalize_replace_cache( - key_type const& key, - SharedPointerType const& data) +TaggedCache:: + canonicalize_replace_cache(key_type const& key, SharedPointerType const& data) { - return canonicalize( - key, const_cast(data), []() { return true; }); + return canonicalize(key, const_cast(data), []() { return true; }); } template < @@ -507,15 +388,7 @@ template < class KeyEqual, class Mutex> inline bool -TaggedCache< - Key, - T, - IsKeyCache, - SharedWeakUnionPointer, - SharedPointerType, - Hash, - KeyEqual, - Mutex>:: +TaggedCache:: canonicalize_replace_client(key_type const& key, SharedPointerType& data) { return canonicalize(key, data, []() { return false; }); @@ -531,15 +404,8 @@ template < class KeyEqual, class Mutex> inline SharedPointerType -TaggedCache< - Key, - T, - IsKeyCache, - SharedWeakUnionPointer, - SharedPointerType, - Hash, - KeyEqual, - Mutex>::fetch(key_type const& key) +TaggedCache::fetch( + key_type const& key) { std::lock_guard l(m_mutex); auto ret = initialFetch(key, l); @@ -559,16 +425,9 @@ template < class Mutex> template inline auto -TaggedCache< - Key, - T, - IsKeyCache, - SharedWeakUnionPointer, - SharedPointerType, - Hash, - KeyEqual, - Mutex>::insert(key_type const& key, T const& value) - -> std::enable_if_t +TaggedCache::insert( + key_type const& key, + T const& value) -> std::enable_if_t { static_assert( std::is_same_v, SharedPointerType> || @@ -597,23 +456,13 @@ template < class Mutex> template inline auto -TaggedCache< - Key, - T, - IsKeyCache, - SharedWeakUnionPointer, - SharedPointerType, - Hash, - KeyEqual, - Mutex>::insert(key_type const& key) - -> std::enable_if_t +TaggedCache::insert( + key_type const& key) -> std::enable_if_t { std::lock_guard lock(m_mutex); clock_type::time_point const now(m_clock.now()); - auto [it, inserted] = m_cache.emplace( - std::piecewise_construct, - std::forward_as_tuple(key), - std::forward_as_tuple(now)); + auto [it, inserted] = + m_cache.emplace(std::piecewise_construct, std::forward_as_tuple(key), std::forward_as_tuple(now)); if (!inserted) it->second.last_access = now; return inserted; @@ -629,15 +478,9 @@ template < class KeyEqual, class Mutex> inline bool -TaggedCache< - Key, - T, - IsKeyCache, - SharedWeakUnionPointer, - SharedPointerType, - Hash, - KeyEqual, - Mutex>::retrieve(key_type const& key, T& data) +TaggedCache::retrieve( + key_type const& key, + T& data) { // retrieve the value of the stored data auto entry = fetch(key); @@ -659,15 +502,8 @@ template < class KeyEqual, class Mutex> inline auto -TaggedCache< - Key, - T, - IsKeyCache, - SharedWeakUnionPointer, - SharedPointerType, - Hash, - KeyEqual, - Mutex>::peekMutex() -> mutex_type& +TaggedCache::peekMutex() + -> mutex_type& { return m_mutex; } @@ -682,15 +518,8 @@ template < class KeyEqual, class Mutex> inline auto -TaggedCache< - Key, - T, - IsKeyCache, - SharedWeakUnionPointer, - SharedPointerType, - Hash, - KeyEqual, - Mutex>::getKeys() const -> std::vector +TaggedCache::getKeys() const + -> std::vector { std::vector v; @@ -714,15 +543,7 @@ template < class KeyEqual, class Mutex> inline double -TaggedCache< - Key, - T, - IsKeyCache, - SharedWeakUnionPointer, - SharedPointerType, - Hash, - KeyEqual, - Mutex>::rate() const +TaggedCache::rate() const { std::lock_guard lock(m_mutex); auto const tot = m_hits + m_misses; @@ -742,15 +563,9 @@ template < class Mutex> template inline SharedPointerType -TaggedCache< - Key, - T, - IsKeyCache, - SharedWeakUnionPointer, - SharedPointerType, - Hash, - KeyEqual, - Mutex>::fetch(key_type const& digest, Handler const& h) +TaggedCache::fetch( + key_type const& digest, + Handler const& h) { { std::lock_guard l(m_mutex); @@ -764,8 +579,7 @@ TaggedCache< std::lock_guard l(m_mutex); ++m_misses; - auto const [it, inserted] = - m_cache.emplace(digest, Entry(m_clock.now(), std::move(sle))); + auto const [it, inserted] = m_cache.emplace(digest, Entry(m_clock.now(), std::move(sle))); if (!inserted) it->second.touch(m_clock.now()); return it->second.ptr.getStrong(); @@ -782,16 +596,9 @@ template < class KeyEqual, class Mutex> inline SharedPointerType -TaggedCache< - Key, - T, - IsKeyCache, - SharedWeakUnionPointer, - SharedPointerType, - Hash, - KeyEqual, - Mutex>:: - initialFetch(key_type const& key, std::lock_guard const& l) +TaggedCache::initialFetch( + key_type const& key, + std::lock_guard const& l) { auto cit = m_cache.find(key); if (cit == m_cache.end()) @@ -827,15 +634,7 @@ template < class KeyEqual, class Mutex> inline void -TaggedCache< - Key, - T, - IsKeyCache, - SharedWeakUnionPointer, - SharedPointerType, - Hash, - KeyEqual, - Mutex>::collect_metrics() +TaggedCache::collect_metrics() { m_stats.size.set(getCacheSize()); @@ -861,22 +660,13 @@ template < class KeyEqual, class Mutex> inline std::thread -TaggedCache< - Key, - T, - IsKeyCache, - SharedWeakUnionPointer, - SharedPointerType, - Hash, - KeyEqual, - Mutex>:: - sweepHelper( - clock_type::time_point const& when_expire, - [[maybe_unused]] clock_type::time_point const& now, - typename KeyValueCacheType::map_type& partition, - SweptPointersVector& stuffToSweep, - std::atomic& allRemovals, - std::lock_guard const&) +TaggedCache::sweepHelper( + clock_type::time_point const& when_expire, + [[maybe_unused]] clock_type::time_point const& now, + typename KeyValueCacheType::map_type& partition, + SweptPointersVector& stuffToSweep, + std::atomic& allRemovals, + std::lock_guard const&) { return std::thread([&, this]() { int cacheRemovals = 0; @@ -930,10 +720,8 @@ TaggedCache< if (mapRemovals || cacheRemovals) { - JLOG(m_journal.debug()) - << "TaggedCache partition sweep " << m_name - << ": cache = " << partition.size() << "-" << cacheRemovals - << ", map-=" << mapRemovals; + JLOG(m_journal.debug()) << "TaggedCache partition sweep " << m_name << ": cache = " << partition.size() + << "-" << cacheRemovals << ", map-=" << mapRemovals; } allRemovals += cacheRemovals; @@ -950,22 +738,13 @@ template < class KeyEqual, class Mutex> inline std::thread -TaggedCache< - Key, - T, - IsKeyCache, - SharedWeakUnionPointer, - SharedPointerType, - Hash, - KeyEqual, - Mutex>:: - sweepHelper( - clock_type::time_point const& when_expire, - clock_type::time_point const& now, - typename KeyOnlyCacheType::map_type& partition, - SweptPointersVector&, - std::atomic& allRemovals, - std::lock_guard const&) +TaggedCache::sweepHelper( + clock_type::time_point const& when_expire, + clock_type::time_point const& now, + typename KeyOnlyCacheType::map_type& partition, + SweptPointersVector&, + std::atomic& allRemovals, + std::lock_guard const&) { return std::thread([&, this]() { int cacheRemovals = 0; @@ -995,10 +774,8 @@ TaggedCache< if (mapRemovals || cacheRemovals) { - JLOG(m_journal.debug()) - << "TaggedCache partition sweep " << m_name - << ": cache = " << partition.size() << "-" << cacheRemovals - << ", map-=" << mapRemovals; + JLOG(m_journal.debug()) << "TaggedCache partition sweep " << m_name << ": cache = " << partition.size() + << "-" << cacheRemovals << ", map-=" << mapRemovals; } allRemovals += cacheRemovals; @@ -1006,5 +783,3 @@ TaggedCache< } } // namespace xrpl - -#endif diff --git a/include/xrpl/basics/ToString.h b/include/xrpl/basics/ToString.h index fe3a6a0893..a6254a1880 100644 --- a/include/xrpl/basics/ToString.h +++ b/include/xrpl/basics/ToString.h @@ -1,5 +1,4 @@ -#ifndef XRPL_BASICS_TOSTRING_H_INCLUDED -#define XRPL_BASICS_TOSTRING_H_INCLUDED +#pragma once #include #include @@ -44,5 +43,3 @@ to_string(char const* s) } } // namespace xrpl - -#endif diff --git a/include/xrpl/basics/UnorderedContainers.h b/include/xrpl/basics/UnorderedContainers.h index fdd2518b1e..c614f9ea80 100644 --- a/include/xrpl/basics/UnorderedContainers.h +++ b/include/xrpl/basics/UnorderedContainers.h @@ -1,5 +1,4 @@ -#ifndef XRPL_BASICS_UNORDEREDCONTAINERS_H_INCLUDED -#define XRPL_BASICS_UNORDEREDCONTAINERS_H_INCLUDED +#pragma once #include #include @@ -40,8 +39,7 @@ template < class Hash = beast::uhash<>, class Pred = std::equal_to, class Allocator = std::allocator>> -using hash_multimap = - std::unordered_multimap; +using hash_multimap = std::unordered_multimap; template < class Value, @@ -75,8 +73,7 @@ template < class Hash = hardened_hash, class Pred = std::equal_to, class Allocator = std::allocator>> -using hardened_partitioned_hash_map = - partitioned_unordered_map; +using hardened_partitioned_hash_map = partitioned_unordered_map; template < class Key, @@ -84,8 +81,7 @@ template < class Hash = hardened_hash, class Pred = std::equal_to, class Allocator = std::allocator>> -using hardened_hash_multimap = - std::unordered_multimap; +using hardened_hash_multimap = std::unordered_multimap; template < class Value, @@ -99,9 +95,6 @@ template < class Hash = hardened_hash, class Pred = std::equal_to, class Allocator = std::allocator> -using hardened_hash_multiset = - std::unordered_multiset; +using hardened_hash_multiset = std::unordered_multiset; } // namespace xrpl - -#endif diff --git a/include/xrpl/basics/UptimeClock.h b/include/xrpl/basics/UptimeClock.h index 9e1ef10d19..4edd38d274 100644 --- a/include/xrpl/basics/UptimeClock.h +++ b/include/xrpl/basics/UptimeClock.h @@ -1,5 +1,4 @@ -#ifndef XRPL_BASICS_UPTIMETIMER_H_INCLUDED -#define XRPL_BASICS_UPTIMETIMER_H_INCLUDED +#pragma once #include #include @@ -46,5 +45,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/include/xrpl/basics/algorithm.h b/include/xrpl/basics/algorithm.h index d62ff17a75..2378c695df 100644 --- a/include/xrpl/basics/algorithm.h +++ b/include/xrpl/basics/algorithm.h @@ -1,5 +1,4 @@ -#ifndef XRPL_ALGORITHM_H_INCLUDED -#define XRPL_ALGORITHM_H_INCLUDED +#pragma once #include @@ -52,13 +51,7 @@ generalized_set_intersection( // std::set_intersection. template FwdIter1 -remove_if_intersect_or_match( - FwdIter1 first1, - FwdIter1 last1, - InputIter2 first2, - InputIter2 last2, - Pred pred, - Comp comp) +remove_if_intersect_or_match(FwdIter1 first1, FwdIter1 last1, InputIter2 first2, InputIter2 last2, Pred pred, Comp comp) { // [original-first1, current-first1) is the set of elements to be preserved. // [current-first1, i) is the set of elements that have been removed. @@ -96,5 +89,3 @@ remove_if_intersect_or_match( } } // namespace xrpl - -#endif diff --git a/include/xrpl/basics/base64.h b/include/xrpl/basics/base64.h index 340e282f87..1725ee42f6 100644 --- a/include/xrpl/basics/base64.h +++ b/include/xrpl/basics/base64.h @@ -32,8 +32,7 @@ */ -#ifndef XRPL_BASICS_BASE64_H_INCLUDED -#define XRPL_BASICS_BASE64_H_INCLUDED +#pragma once #include #include @@ -46,13 +45,10 @@ base64_encode(std::uint8_t const* data, std::size_t len); inline std::string base64_encode(std::string const& s) { - return base64_encode( - reinterpret_cast(s.data()), s.size()); + return base64_encode(reinterpret_cast(s.data()), s.size()); } std::string base64_decode(std::string_view data); } // namespace xrpl - -#endif diff --git a/include/xrpl/basics/base_uint.h b/include/xrpl/basics/base_uint.h index a1ed223674..745cb7ab40 100644 --- a/include/xrpl/basics/base_uint.h +++ b/include/xrpl/basics/base_uint.h @@ -3,8 +3,7 @@ // Distributed under the MIT/X11 software license, see the accompanying // file license.txt or http://www.opensource.org/licenses/mit-license.php. -#ifndef XRPL_BASICS_BASE_UINT_H_INCLUDED -#define XRPL_BASICS_BASE_UINT_H_INCLUDED +#pragma once #include #include @@ -65,13 +64,9 @@ struct is_contiguous_container : std::true_type template class base_uint { - static_assert( - (Bits % 32) == 0, - "The length of a base_uint in bits must be a multiple of 32."); + static_assert((Bits % 32) == 0, "The length of a base_uint in bits must be a multiple of 32."); - static_assert( - Bits >= 64, - "The length of a base_uint in bits must be at least 64."); + static_assert(Bits >= 64, "The length of a base_uint in bits must be at least 64."); static constexpr std::size_t WIDTH = Bits / 32; @@ -182,9 +177,7 @@ private: { // Local lambda that converts a single hex char to four bits and // ORs those bits into a uint32_t. - auto hexCharToUInt = [](char c, - std::uint32_t shift, - std::uint32_t& accum) -> ParseResult { + auto hexCharToUInt = [](char c, std::uint32_t shift, std::uint32_t& accum) -> ParseResult { std::uint32_t nibble = 0xFFu; if (c < '0' || c > 'f') return ParseResult::badChar; @@ -221,8 +214,7 @@ private: std::uint32_t accum = {}; for (std::uint32_t shift : {4u, 0u, 12u, 8u, 20u, 16u, 28u, 24u}) { - if (auto const result = hexCharToUInt(*in++, shift, accum); - result != ParseResult::okay) + if (auto const result = hexCharToUInt(*in++, shift, accum); result != ParseResult::okay) return Unexpected(result); } ret[i++] = accum; @@ -261,8 +253,7 @@ public: // This constructor is intended to be used at compile time since it might // throw at runtime. Consider declaring this constructor consteval once // we get to C++23. - explicit constexpr base_uint(std::string_view sv) noexcept(false) - : data_(parseFromStringViewThrows(sv)) + explicit constexpr base_uint(std::string_view sv) noexcept(false) : data_(parseFromStringViewThrows(sv)) { } @@ -387,8 +378,7 @@ public: // prefix operator for (int i = WIDTH - 1; i >= 0; --i) { - data_[i] = boost::endian::native_to_big( - boost::endian::big_to_native(data_[i]) + 1); + data_[i] = boost::endian::native_to_big(boost::endian::big_to_native(data_[i]) + 1); if (data_[i] != 0) break; } @@ -412,8 +402,7 @@ public: for (int i = WIDTH - 1; i >= 0; --i) { auto prev = data_[i]; - data_[i] = boost::endian::native_to_big( - boost::endian::big_to_native(data_[i]) - 1); + data_[i] = boost::endian::native_to_big(boost::endian::big_to_native(data_[i]) - 1); if (prev != 0) break; @@ -453,11 +442,9 @@ public: for (int i = WIDTH; i--;) { - std::uint64_t n = carry + boost::endian::big_to_native(data_[i]) + - boost::endian::big_to_native(b.data_[i]); + std::uint64_t n = carry + boost::endian::big_to_native(data_[i]) + boost::endian::big_to_native(b.data_[i]); - data_[i] = - boost::endian::native_to_big(static_cast(n)); + data_[i] = boost::endian::native_to_big(static_cast(n)); carry = n >> 32; } @@ -557,8 +544,7 @@ operator<=>(base_uint const& lhs, base_uint const& rhs) if (ret.first == lhs.cend()) return std::strong_ordering::equivalent; - return (*ret.first > *ret.second) ? std::strong_ordering::greater - : std::strong_ordering::less; + return (*ret.first > *ret.second) ? std::strong_ordering::greater : std::strong_ordering::less; } template @@ -617,9 +603,7 @@ template inline std::string to_short_string(base_uint const& a) { - static_assert( - base_uint::bytes > 4, - "For 4 bytes or less, use a native type"); + static_assert(base_uint::bytes > 4, "For 4 bytes or less, use a native type"); return strHex(a.cbegin(), a.cbegin() + 4) + "..."; } @@ -653,12 +637,9 @@ static_assert(sizeof(uint256) == 256 / 8, "There should be no padding bytes"); namespace beast { template -struct is_uniquely_represented> - : public std::true_type +struct is_uniquely_represented> : public std::true_type { explicit is_uniquely_represented() = default; }; } // namespace beast - -#endif diff --git a/include/xrpl/basics/chrono.h b/include/xrpl/basics/chrono.h index e343e8b49f..bcf988b45e 100644 --- a/include/xrpl/basics/chrono.h +++ b/include/xrpl/basics/chrono.h @@ -1,5 +1,4 @@ -#ifndef XRPL_BASICS_CHRONO_H_INCLUDED -#define XRPL_BASICS_CHRONO_H_INCLUDED +#pragma once #include #include @@ -16,12 +15,9 @@ namespace xrpl { // A few handy aliases -using days = std::chrono::duration< - int, - std::ratio_multiply>>; +using days = std::chrono::duration>>; -using weeks = std::chrono:: - duration>>; +using weeks = std::chrono::duration>>; /** Clock for measuring the network time. @@ -34,8 +30,7 @@ using weeks = std::chrono:: */ constexpr static std::chrono::seconds epoch_offset = - date::sys_days{date::year{2000} / 1 / 1} - - date::sys_days{date::year{1970} / 1 / 1}; + date::sys_days{date::year{2000} / 1 / 1} - date::sys_days{date::year{1970} / 1 / 1}; static_assert(epoch_offset.count() == 946684800); @@ -64,8 +59,7 @@ to_string(NetClock::time_point tp) { // 2000-01-01 00:00:00 UTC is 946684800s from 1970-01-01 00:00:00 UTC using namespace std::chrono; - return to_string( - system_clock::time_point{tp.time_since_epoch() + epoch_offset}); + return to_string(system_clock::time_point{tp.time_since_epoch() + epoch_offset}); } template @@ -82,8 +76,7 @@ to_string_iso(NetClock::time_point tp) // 2000-01-01 00:00:00 UTC is 946684800s from 1970-01-01 00:00:00 UTC // Note, NetClock::duration is seconds, as checked by static_assert static_assert(std::is_same_v>); - return to_string_iso(date::sys_time{ - tp.time_since_epoch() + epoch_offset}); + return to_string_iso(date::sys_time{tp.time_since_epoch() + epoch_offset}); } /** A clock for measuring elapsed time. @@ -105,5 +98,3 @@ stopwatch() } } // namespace xrpl - -#endif diff --git a/include/xrpl/basics/comparators.h b/include/xrpl/basics/comparators.h index 7c848f0b3b..0e21d38d6b 100644 --- a/include/xrpl/basics/comparators.h +++ b/include/xrpl/basics/comparators.h @@ -1,5 +1,4 @@ -#ifndef XRPL_BASICS_COMPARATORS_H_INCLUDED -#define XRPL_BASICS_COMPARATORS_H_INCLUDED +#pragma once #include @@ -53,5 +52,3 @@ using equal_to = std::equal_to; #endif } // namespace xrpl - -#endif diff --git a/include/xrpl/basics/contract.h b/include/xrpl/basics/contract.h index 63d1bb5a84..8be257bb02 100644 --- a/include/xrpl/basics/contract.h +++ b/include/xrpl/basics/contract.h @@ -1,5 +1,4 @@ -#ifndef XRPL_BASICS_CONTRACT_H_INCLUDED -#define XRPL_BASICS_CONTRACT_H_INCLUDED +#pragma once #include @@ -36,15 +35,10 @@ template [[noreturn]] inline void Throw(Args&&... args) { - static_assert( - std::is_convertible::value, - "Exception must derive from std::exception."); + static_assert(std::is_convertible::value, "Exception must derive from std::exception."); E e(std::forward(args)...); - LogThrow( - std::string( - "Throwing exception of type " + beast::type_name() + ": ") + - e.what()); + LogThrow(std::string("Throwing exception of type " + beast::type_name() + ": ") + e.what()); throw e; } @@ -53,5 +47,3 @@ Throw(Args&&... args) LogicError(std::string const& how) noexcept; } // namespace xrpl - -#endif diff --git a/include/xrpl/basics/hardened_hash.h b/include/xrpl/basics/hardened_hash.h index a25dcb3c34..b05ecda7a6 100644 --- a/include/xrpl/basics/hardened_hash.h +++ b/include/xrpl/basics/hardened_hash.h @@ -1,5 +1,4 @@ -#ifndef XRPL_BASICS_HARDENED_HASH_H_INCLUDED -#define XRPL_BASICS_HARDENED_HASH_H_INCLUDED +#pragma once #include #include @@ -93,5 +92,3 @@ public: }; } // namespace xrpl - -#endif diff --git a/include/xrpl/basics/join.h b/include/xrpl/basics/join.h index 79f716ec43..16fae4ff87 100644 --- a/include/xrpl/basics/join.h +++ b/include/xrpl/basics/join.h @@ -1,5 +1,4 @@ -#ifndef JOIN_H_INCLUDED -#define JOIN_H_INCLUDED +#pragma once #include @@ -24,8 +23,7 @@ public: Collection const& collection; std::string const delimiter; - explicit CollectionAndDelimiter(Collection const& c, std::string delim) - : collection(c), delimiter(std::move(delim)) + explicit CollectionAndDelimiter(Collection const& c, std::string delim) : collection(c), delimiter(std::move(delim)) { } @@ -33,11 +31,7 @@ public: friend Stream& operator<<(Stream& s, CollectionAndDelimiter const& cd) { - return join( - s, - std::begin(cd.collection), - std::end(cd.collection), - cd.delimiter); + return join(s, std::begin(cd.collection), std::end(cd.collection), cd.delimiter); } }; @@ -69,8 +63,7 @@ public: char const* collection; std::string const delimiter; - explicit CollectionAndDelimiter(char const c[N], std::string delim) - : collection(c), delimiter(std::move(delim)) + explicit CollectionAndDelimiter(char const c[N], std::string delim) : collection(c), delimiter(std::move(delim)) { } @@ -86,5 +79,3 @@ public: }; } // namespace xrpl - -#endif diff --git a/include/xrpl/basics/make_SSLContext.h b/include/xrpl/basics/make_SSLContext.h index fb91dd40a9..1714d3e58c 100644 --- a/include/xrpl/basics/make_SSLContext.h +++ b/include/xrpl/basics/make_SSLContext.h @@ -1,5 +1,4 @@ -#ifndef XRPL_BASICS_MAKE_SSLCONTEXT_H_INCLUDED -#define XRPL_BASICS_MAKE_SSLCONTEXT_H_INCLUDED +#pragma once #include @@ -20,5 +19,3 @@ make_SSLContextAuthed( std::string const& cipherList); } // namespace xrpl - -#endif diff --git a/include/xrpl/basics/mulDiv.h b/include/xrpl/basics/mulDiv.h index fb38d0cd63..2495f07728 100644 --- a/include/xrpl/basics/mulDiv.h +++ b/include/xrpl/basics/mulDiv.h @@ -1,5 +1,4 @@ -#ifndef XRPL_BASICS_MULDIV_H_INCLUDED -#define XRPL_BASICS_MULDIV_H_INCLUDED +#pragma once #include #include @@ -22,5 +21,3 @@ std::optional mulDiv(std::uint64_t value, std::uint64_t mul, std::uint64_t div); } // namespace xrpl - -#endif diff --git a/include/xrpl/basics/partitioned_unordered_map.h b/include/xrpl/basics/partitioned_unordered_map.h index 518686c533..181597ca69 100644 --- a/include/xrpl/basics/partitioned_unordered_map.h +++ b/include/xrpl/basics/partitioned_unordered_map.h @@ -1,5 +1,4 @@ -#ifndef XRPL_BASICS_PARTITIONED_UNORDERED_MAP_H -#define XRPL_BASICS_PARTITIONED_UNORDERED_MAP_H +#pragma once #include #include @@ -51,8 +50,7 @@ public: using const_reference = value_type const&; using pointer = value_type*; using const_pointer = value_type const*; - using map_type = std:: - unordered_map; + using map_type = std::unordered_map; using partition_map_type = std::vector; struct iterator @@ -113,8 +111,7 @@ public: friend bool operator==(iterator const& lhs, iterator const& rhs) { - return lhs.map_ == rhs.map_ && lhs.ait_ == rhs.ait_ && - lhs.mit_ == rhs.mit_; + return lhs.map_ == rhs.map_ && lhs.ait_ == rhs.ait_ && lhs.mit_ == rhs.mit_; } friend bool @@ -190,8 +187,7 @@ public: friend bool operator==(const_iterator const& lhs, const_iterator const& rhs) { - return lhs.map_ == rhs.map_ && lhs.ait_ == rhs.ait_ && - lhs.mit_ == rhs.mit_; + return lhs.map_ == rhs.map_ && lhs.ait_ == rhs.ait_ && lhs.mit_ == rhs.mit_; } friend bool @@ -231,14 +227,11 @@ private: } public: - partitioned_unordered_map( - std::optional partitions = std::nullopt) + partitioned_unordered_map(std::optional partitions = std::nullopt) { // Set partitions to the number of hardware threads if the parameter // is either empty or set to 0. - partitions_ = partitions && *partitions - ? *partitions - : std::thread::hardware_concurrency(); + partitions_ = partitions && *partitions ? *partitions : std::thread::hardware_concurrency(); map_.resize(partitions_); XRPL_ASSERT( partitions_, @@ -337,10 +330,8 @@ public: auto const& key = std::get<0>(keyTuple); iterator it(&map_); it.ait_ = it.map_->begin() + partitioner(key); - auto [eit, inserted] = it.ait_->emplace( - std::piecewise_construct, - std::forward(keyTuple), - std::forward(valueTuple)); + auto [eit, inserted] = + it.ait_->emplace(std::piecewise_construct, std::forward(keyTuple), std::forward(valueTuple)); it.mit_ = eit; return {it, inserted}; } @@ -351,8 +342,7 @@ public: { iterator it(&map_); it.ait_ = it.map_->begin() + partitioner(key); - auto [eit, inserted] = - it.ait_->emplace(std::forward(key), std::forward(val)); + auto [eit, inserted] = it.ait_->emplace(std::forward(key), std::forward(val)); it.mit_ = eit; return {it, inserted}; } @@ -402,5 +392,3 @@ private: }; } // namespace xrpl - -#endif // XRPL_BASICS_PARTITIONED_UNORDERED_MAP_H diff --git a/include/xrpl/basics/random.h b/include/xrpl/basics/random.h index 737b8fef59..34e460fd8a 100644 --- a/include/xrpl/basics/random.h +++ b/include/xrpl/basics/random.h @@ -1,5 +1,4 @@ -#ifndef XRPL_BASICS_RANDOM_H_INCLUDED -#define XRPL_BASICS_RANDOM_H_INCLUDED +#pragma once #include #include @@ -20,8 +19,7 @@ static_assert( "The Ripple default PRNG engine must return an unsigned integral type."); static_assert( - std::numeric_limits::max() >= - std::numeric_limits::max(), + std::numeric_limits::max() >= std::numeric_limits::max(), "The Ripple default PRNG engine return must be at least 64 bits wide."); #endif @@ -90,9 +88,7 @@ default_prng() */ /** @{ */ template -std::enable_if_t< - std::is_integral::value && detail::is_engine::value, - Integral> +std::enable_if_t::value && detail::is_engine::value, Integral> rand_int(Engine& engine, Integral min, Integral max) { XRPL_ASSERT(max > min, "xrpl::rand_int : max over min inputs"); @@ -111,9 +107,7 @@ rand_int(Integral min, Integral max) } template -std::enable_if_t< - std::is_integral::value && detail::is_engine::value, - Integral> +std::enable_if_t::value && detail::is_engine::value, Integral> rand_int(Engine& engine, Integral max) { return rand_int(engine, Integral(0), max); @@ -127,9 +121,7 @@ rand_int(Integral max) } template -std::enable_if_t< - std::is_integral::value && detail::is_engine::value, - Integral> +std::enable_if_t::value && detail::is_engine::value, Integral> rand_int(Engine& engine) { return rand_int(engine, std::numeric_limits::max()); @@ -147,23 +139,17 @@ rand_int() /** @{ */ template std::enable_if_t< - (std::is_same::value || - std::is_same::value) && + (std::is_same::value || std::is_same::value) && detail::is_engine::value, Byte> rand_byte(Engine& engine) { - return static_cast(rand_int( - engine, - std::numeric_limits::min(), - std::numeric_limits::max())); + return static_cast( + rand_int(engine, std::numeric_limits::min(), std::numeric_limits::max())); } template -std::enable_if_t< - (std::is_same::value || - std::is_same::value), - Byte> +std::enable_if_t<(std::is_same::value || std::is_same::value), Byte> rand_byte() { return rand_byte(default_prng()); @@ -187,5 +173,3 @@ rand_bool() /** @} */ } // namespace xrpl - -#endif // XRPL_BASICS_RANDOM_H_INCLUDED diff --git a/include/xrpl/basics/rocksdb.h b/include/xrpl/basics/rocksdb.h index b9b89677f9..3d468b0f1b 100644 --- a/include/xrpl/basics/rocksdb.h +++ b/include/xrpl/basics/rocksdb.h @@ -1,5 +1,4 @@ -#ifndef XRPL_UNITY_ROCKSDB_H_INCLUDED -#define XRPL_UNITY_ROCKSDB_H_INCLUDED +#pragma once #if XRPL_ROCKSDB_AVAILABLE // #include @@ -28,5 +27,3 @@ #include #endif - -#endif diff --git a/include/xrpl/basics/safe_cast.h b/include/xrpl/basics/safe_cast.h index 89de0eda6a..285d76782a 100644 --- a/include/xrpl/basics/safe_cast.h +++ b/include/xrpl/basics/safe_cast.h @@ -1,5 +1,4 @@ -#ifndef XRPL_BASICS_SAFE_CAST_H_INCLUDED -#define XRPL_BASICS_SAFE_CAST_H_INCLUDED +#pragma once #include @@ -12,38 +11,29 @@ namespace xrpl { template concept SafeToCast = (std::is_integral_v && std::is_integral_v) && (std::is_signed::value || std::is_unsigned::value) && - (std::is_signed::value != std::is_signed::value - ? sizeof(Dest) > sizeof(Src) - : sizeof(Dest) >= sizeof(Src)); + (std::is_signed::value != std::is_signed::value ? sizeof(Dest) > sizeof(Src) + : sizeof(Dest) >= sizeof(Src)); template -inline constexpr std:: - enable_if_t && std::is_integral_v, Dest> - safe_cast(Src s) noexcept +inline constexpr std::enable_if_t && std::is_integral_v, Dest> +safe_cast(Src s) noexcept { - static_assert( - std::is_signed_v || std::is_unsigned_v, - "Cannot cast signed to unsigned"); - constexpr unsigned not_same = - std::is_signed_v != std::is_signed_v; - static_assert( - sizeof(Dest) >= sizeof(Src) + not_same, - "Destination is too small to hold all values of source"); + static_assert(std::is_signed_v || std::is_unsigned_v, "Cannot cast signed to unsigned"); + constexpr unsigned not_same = std::is_signed_v != std::is_signed_v; + static_assert(sizeof(Dest) >= sizeof(Src) + not_same, "Destination is too small to hold all values of source"); return static_cast(s); } template -inline constexpr std:: - enable_if_t && std::is_integral_v, Dest> - safe_cast(Src s) noexcept +inline constexpr std::enable_if_t && std::is_integral_v, Dest> +safe_cast(Src s) noexcept { return static_cast(safe_cast>(s)); } template -inline constexpr std:: - enable_if_t && std::is_enum_v, Dest> - safe_cast(Src s) noexcept +inline constexpr std::enable_if_t && std::is_enum_v, Dest> +safe_cast(Src s) noexcept { return safe_cast(static_cast>(s)); } @@ -53,9 +43,8 @@ inline constexpr std:: // underlying types become safe, it can be converted to a safe_cast. template -inline constexpr std:: - enable_if_t && std::is_integral_v, Dest> - unsafe_cast(Src s) noexcept +inline constexpr std::enable_if_t && std::is_integral_v, Dest> +unsafe_cast(Src s) noexcept { static_assert( !SafeToCast, @@ -65,21 +54,17 @@ inline constexpr std:: } template -inline constexpr std:: - enable_if_t && std::is_integral_v, Dest> - unsafe_cast(Src s) noexcept +inline constexpr std::enable_if_t && std::is_integral_v, Dest> +unsafe_cast(Src s) noexcept { return static_cast(unsafe_cast>(s)); } template -inline constexpr std:: - enable_if_t && std::is_enum_v, Dest> - unsafe_cast(Src s) noexcept +inline constexpr std::enable_if_t && std::is_enum_v, Dest> +unsafe_cast(Src s) noexcept { return unsafe_cast(static_cast>(s)); } } // namespace xrpl - -#endif diff --git a/include/xrpl/basics/scope.h b/include/xrpl/basics/scope.h index b7299a28fc..797a7d3fdc 100644 --- a/include/xrpl/basics/scope.h +++ b/include/xrpl/basics/scope.h @@ -1,5 +1,4 @@ -#ifndef XRPL_BASICS_SCOPE_H_INCLUDED -#define XRPL_BASICS_SCOPE_H_INCLUDED +#pragma once #include @@ -36,10 +35,8 @@ public: } scope_exit(scope_exit&& rhs) noexcept( - std::is_nothrow_move_constructible_v || - std::is_nothrow_copy_constructible_v) - : exit_function_{std::forward(rhs.exit_function_)} - , execute_on_destruction_{rhs.execute_on_destruction_} + std::is_nothrow_move_constructible_v || std::is_nothrow_copy_constructible_v) + : exit_function_{std::forward(rhs.exit_function_)}, execute_on_destruction_{rhs.execute_on_destruction_} { rhs.release(); } @@ -50,14 +47,11 @@ public: template explicit scope_exit( EFP&& f, - std::enable_if_t< - !std::is_same_v, scope_exit> && - std::is_constructible_v>* = 0) noexcept + std::enable_if_t, scope_exit> && std::is_constructible_v>* = + 0) noexcept : exit_function_{std::forward(f)} { - static_assert( - std:: - is_nothrow_constructible_v(f))>); + static_assert(std::is_nothrow_constructible_v(f))>); } void @@ -80,14 +74,12 @@ class scope_fail public: ~scope_fail() { - if (execute_on_destruction_ && - std::uncaught_exceptions() > uncaught_on_creation_) + if (execute_on_destruction_ && std::uncaught_exceptions() > uncaught_on_creation_) exit_function_(); } scope_fail(scope_fail&& rhs) noexcept( - std::is_nothrow_move_constructible_v || - std::is_nothrow_copy_constructible_v) + std::is_nothrow_move_constructible_v || std::is_nothrow_copy_constructible_v) : exit_function_{std::forward(rhs.exit_function_)} , execute_on_destruction_{rhs.execute_on_destruction_} , uncaught_on_creation_{rhs.uncaught_on_creation_} @@ -101,14 +93,11 @@ public: template explicit scope_fail( EFP&& f, - std::enable_if_t< - !std::is_same_v, scope_fail> && - std::is_constructible_v>* = 0) noexcept + std::enable_if_t, scope_fail> && std::is_constructible_v>* = + 0) noexcept : exit_function_{std::forward(f)} { - static_assert( - std:: - is_nothrow_constructible_v(f))>); + static_assert(std::is_nothrow_constructible_v(f))>); } void @@ -131,14 +120,12 @@ class scope_success public: ~scope_success() noexcept(noexcept(exit_function_())) { - if (execute_on_destruction_ && - std::uncaught_exceptions() <= uncaught_on_creation_) + if (execute_on_destruction_ && std::uncaught_exceptions() <= uncaught_on_creation_) exit_function_(); } scope_success(scope_success&& rhs) noexcept( - std::is_nothrow_move_constructible_v || - std::is_nothrow_copy_constructible_v) + std::is_nothrow_move_constructible_v || std::is_nothrow_copy_constructible_v) : exit_function_{std::forward(rhs.exit_function_)} , execute_on_destruction_{rhs.execute_on_destruction_} , uncaught_on_creation_{rhs.uncaught_on_creation_} @@ -152,9 +139,7 @@ public: template explicit scope_success( EFP&& f, - std::enable_if_t< - !std::is_same_v, scope_success> && - std::is_constructible_v>* = + std::enable_if_t, scope_success> && std::is_constructible_v>* = 0) noexcept(std::is_nothrow_constructible_v || std::is_nothrow_constructible_v) : exit_function_{std::forward(f)} { @@ -213,12 +198,9 @@ class scope_unlock std::unique_lock* plock; public: - explicit scope_unlock(std::unique_lock& lock) noexcept(true) - : plock(&lock) + explicit scope_unlock(std::unique_lock& lock) noexcept(true) : plock(&lock) { - XRPL_ASSERT( - plock->owns_lock(), - "xrpl::scope_unlock::scope_unlock : mutex must be locked"); + XRPL_ASSERT(plock->owns_lock(), "xrpl::scope_unlock::scope_unlock : mutex must be locked"); plock->unlock(); } @@ -237,5 +219,3 @@ template scope_unlock(std::unique_lock&) -> scope_unlock; } // namespace xrpl - -#endif diff --git a/include/xrpl/basics/spinlock.h b/include/xrpl/basics/spinlock.h index 71ab29f381..7b05b7c339 100644 --- a/include/xrpl/basics/spinlock.h +++ b/include/xrpl/basics/spinlock.h @@ -1,7 +1,6 @@ // Copyright (c) 2022, Nikolaos D. Bougalis -#ifndef XRPL_BASICS_SPINLOCK_H_INCLUDED -#define XRPL_BASICS_SPINLOCK_H_INCLUDED +#pragma once #include @@ -100,12 +99,9 @@ public: @note For performance reasons, you should strive to have `lock` be on a cacheline by itself. */ - packed_spinlock(std::atomic& lock, int index) - : bits_(lock), mask_(static_cast(1) << index) + packed_spinlock(std::atomic& lock, int index) : bits_(lock), mask_(static_cast(1) << index) { - XRPL_ASSERT( - index >= 0 && (mask_ != 0), - "xrpl::packed_spinlock::packed_spinlock : valid index and mask"); + XRPL_ASSERT(index >= 0 && (mask_ != 0), "xrpl::packed_spinlock::packed_spinlock : valid index and mask"); } [[nodiscard]] bool @@ -178,10 +174,7 @@ public: T expected = 0; return lock_.compare_exchange_weak( - expected, - std::numeric_limits::max(), - std::memory_order_acquire, - std::memory_order_relaxed); + expected, std::numeric_limits::max(), std::memory_order_acquire, std::memory_order_relaxed); } void @@ -207,5 +200,3 @@ public: /** @} */ } // namespace xrpl - -#endif diff --git a/include/xrpl/basics/strHex.h b/include/xrpl/basics/strHex.h index 1c1d94bf32..76a3d86ff3 100644 --- a/include/xrpl/basics/strHex.h +++ b/include/xrpl/basics/strHex.h @@ -1,5 +1,4 @@ -#ifndef XRPL_BASICS_STRHEX_H_INCLUDED -#define XRPL_BASICS_STRHEX_H_INCLUDED +#pragma once #include #include @@ -11,9 +10,7 @@ std::string strHex(FwdIt begin, FwdIt end) { static_assert( - std::is_convertible< - typename std::iterator_traits::iterator_category, - std::forward_iterator_tag>::value, + std::is_convertible::iterator_category, std::forward_iterator_tag>::value, "FwdIt must be a forward iterator"); std::string result; result.reserve(2 * std::distance(begin, end)); @@ -29,5 +26,3 @@ strHex(T const& from) } } // namespace xrpl - -#endif diff --git a/include/xrpl/basics/tagged_integer.h b/include/xrpl/basics/tagged_integer.h index 1d40b31cce..439cc537e2 100644 --- a/include/xrpl/basics/tagged_integer.h +++ b/include/xrpl/basics/tagged_integer.h @@ -1,7 +1,6 @@ // Copyright (c) 2014, Nikolaos D. Bougalis -#ifndef BEAST_UTILITY_TAGGED_INTEGER_H_INCLUDED -#define BEAST_UTILITY_TAGGED_INTEGER_H_INCLUDED +#pragma once #include @@ -31,9 +30,7 @@ class tagged_integer tagged_integer, boost::bitwise< tagged_integer, - boost::unit_steppable< - tagged_integer, - boost::shiftable>>>>> + boost::unit_steppable, boost::shiftable>>>>> { private: Int m_value; @@ -46,14 +43,10 @@ public: template < class OtherInt, - class = typename std::enable_if< - std::is_integral::value && - sizeof(OtherInt) <= sizeof(Int)>::type> + class = typename std::enable_if::value && sizeof(OtherInt) <= sizeof(Int)>::type> explicit constexpr tagged_integer(OtherInt value) noexcept : m_value(value) { - static_assert( - sizeof(tagged_integer) == sizeof(Int), - "tagged_integer is adding padding"); + static_assert(sizeof(tagged_integer) == sizeof(Int), "tagged_integer is adding padding"); } bool @@ -208,4 +201,3 @@ struct is_contiguously_hashable, HashAlgorithm> }; } // namespace beast -#endif diff --git a/include/xrpl/beast/asio/io_latency_probe.h b/include/xrpl/beast/asio/io_latency_probe.h index 726e8e1c76..347203acb3 100644 --- a/include/xrpl/beast/asio/io_latency_probe.h +++ b/include/xrpl/beast/asio/io_latency_probe.h @@ -1,5 +1,4 @@ -#ifndef BEAST_ASIO_IO_LATENCY_PROBE_H_INCLUDED -#define BEAST_ASIO_IO_LATENCY_PROBE_H_INCLUDED +#pragma once #include @@ -32,11 +31,7 @@ private: public: io_latency_probe(duration const& period, boost::asio::io_context& ios) - : m_count(1) - , m_period(period) - , m_ios(ios) - , m_timer(m_ios) - , m_cancel(false) + : m_count(1), m_period(period), m_ios(ios), m_timer(m_ios), m_cancel(false) { } @@ -91,10 +86,7 @@ public: std::lock_guard lock(m_mutex); if (m_cancel) throw std::logic_error("io_latency_probe is canceled"); - boost::asio::post( - m_ios, - sample_op( - std::forward(handler), Clock::now(), false, this)); + boost::asio::post(m_ios, sample_op(std::forward(handler), Clock::now(), false, this)); } /** Initiate continuous i/o latency sampling. @@ -108,10 +100,7 @@ public: std::lock_guard lock(m_mutex); if (m_cancel) throw std::logic_error("io_latency_probe is canceled"); - boost::asio::post( - m_ios, - sample_op( - std::forward(handler), Clock::now(), true, this)); + boost::asio::post(m_ios, sample_op(std::forward(handler), Clock::now(), true, this)); } private: @@ -151,15 +140,8 @@ private: bool m_repeat; io_latency_probe* m_probe; - sample_op( - Handler const& handler, - time_point const& start, - bool repeat, - io_latency_probe* probe) - : m_handler(handler) - , m_start(start) - , m_repeat(repeat) - , m_probe(probe) + sample_op(Handler const& handler, time_point const& start, bool repeat, io_latency_probe* probe) + : m_handler(handler), m_start(start), m_repeat(repeat), m_probe(probe) { XRPL_ASSERT( m_probe, @@ -214,23 +196,19 @@ private: // Calculate when we want to sample again, and // adjust for the expected latency. // - typename Clock::time_point const when( - now + m_probe->m_period - 2 * elapsed); + typename Clock::time_point const when(now + m_probe->m_period - 2 * elapsed); if (when <= now) { // The latency is too high to maintain the desired // period so don't bother with a timer. // - boost::asio::post( - m_probe->m_ios, - sample_op(m_handler, now, m_repeat, m_probe)); + boost::asio::post(m_probe->m_ios, sample_op(m_handler, now, m_repeat, m_probe)); } else { m_probe->m_timer.expires_after(when - now); - m_probe->m_timer.async_wait( - sample_op(m_handler, now, m_repeat, m_probe)); + m_probe->m_timer.async_wait(sample_op(m_handler, now, m_repeat, m_probe)); } } } @@ -241,13 +219,9 @@ private: if (!m_probe) return; typename Clock::time_point const now(Clock::now()); - boost::asio::post( - m_probe->m_ios, - sample_op(m_handler, now, m_repeat, m_probe)); + boost::asio::post(m_probe->m_ios, sample_op(m_handler, now, m_repeat, m_probe)); } }; }; } // namespace beast - -#endif diff --git a/include/xrpl/beast/clock/abstract_clock.h b/include/xrpl/beast/clock/abstract_clock.h index 6f71529fda..41b57fdd2c 100644 --- a/include/xrpl/beast/clock/abstract_clock.h +++ b/include/xrpl/beast/clock/abstract_clock.h @@ -1,5 +1,4 @@ -#ifndef BEAST_CHRONO_ABSTRACT_CLOCK_H_INCLUDED -#define BEAST_CHRONO_ABSTRACT_CLOCK_H_INCLUDED +#pragma once namespace beast { @@ -89,5 +88,3 @@ get_abstract_clock() } } // namespace beast - -#endif diff --git a/include/xrpl/beast/clock/basic_seconds_clock.h b/include/xrpl/beast/clock/basic_seconds_clock.h index 65dbe5abc7..5205d92fef 100644 --- a/include/xrpl/beast/clock/basic_seconds_clock.h +++ b/include/xrpl/beast/clock/basic_seconds_clock.h @@ -1,5 +1,4 @@ -#ifndef BEAST_CHRONO_BASIC_SECONDS_CLOCK_H_INCLUDED -#define BEAST_CHRONO_BASIC_SECONDS_CLOCK_H_INCLUDED +#pragma once #include @@ -33,5 +32,3 @@ public: }; } // namespace beast - -#endif diff --git a/include/xrpl/beast/clock/manual_clock.h b/include/xrpl/beast/clock/manual_clock.h index b3c98846f1..a301b4e1fe 100644 --- a/include/xrpl/beast/clock/manual_clock.h +++ b/include/xrpl/beast/clock/manual_clock.h @@ -1,5 +1,4 @@ -#ifndef BEAST_CHRONO_MANUAL_CLOCK_H_INCLUDED -#define BEAST_CHRONO_MANUAL_CLOCK_H_INCLUDED +#pragma once #include #include @@ -29,8 +28,7 @@ private: time_point now_; public: - explicit manual_clock(time_point const& now = time_point(duration(0))) - : now_(now) + explicit manual_clock(time_point const& now = time_point(duration(0))) : now_(now) { } @@ -44,9 +42,7 @@ public: void set(time_point const& when) { - XRPL_ASSERT( - !Clock::is_steady || when >= now_, - "beast::manual_clock::set(time_point) : forward input"); + XRPL_ASSERT(!Clock::is_steady || when >= now_, "beast::manual_clock::set(time_point) : forward input"); now_ = when; } @@ -64,8 +60,7 @@ public: advance(std::chrono::duration const& elapsed) { XRPL_ASSERT( - !Clock::is_steady || (now_ + elapsed) >= now_, - "beast::manual_clock::advance(duration) : forward input"); + !Clock::is_steady || (now_ + elapsed) >= now_, "beast::manual_clock::advance(duration) : forward input"); now_ += elapsed; } @@ -79,5 +74,3 @@ public: }; } // namespace beast - -#endif diff --git a/include/xrpl/beast/container/aged_container.h b/include/xrpl/beast/container/aged_container.h index 6051db7f69..dd622fcd9a 100644 --- a/include/xrpl/beast/container/aged_container.h +++ b/include/xrpl/beast/container/aged_container.h @@ -1,5 +1,4 @@ -#ifndef BEAST_CONTAINER_AGED_CONTAINER_H_INCLUDED -#define BEAST_CONTAINER_AGED_CONTAINER_H_INCLUDED +#pragma once #include @@ -12,5 +11,3 @@ struct is_aged_container : std::false_type }; } // namespace beast - -#endif diff --git a/include/xrpl/beast/container/aged_container_utility.h b/include/xrpl/beast/container/aged_container_utility.h index cc1b3a8479..fd5d481aa5 100644 --- a/include/xrpl/beast/container/aged_container_utility.h +++ b/include/xrpl/beast/container/aged_container_utility.h @@ -1,5 +1,4 @@ -#ifndef BEAST_CONTAINER_AGED_CONTAINER_UTILITY_H_INCLUDED -#define BEAST_CONTAINER_AGED_CONTAINER_UTILITY_H_INCLUDED +#pragma once #include @@ -10,14 +9,12 @@ namespace beast { /** Expire aged container items past the specified age. */ template -typename std::enable_if::value, std::size_t>:: - type - expire(AgedContainer& c, std::chrono::duration const& age) +typename std::enable_if::value, std::size_t>::type +expire(AgedContainer& c, std::chrono::duration const& age) { std::size_t n(0); auto const expired(c.clock().now() - age); - for (auto iter(c.chronological.cbegin()); - iter != c.chronological.cend() && iter.when() <= expired;) + for (auto iter(c.chronological.cbegin()); iter != c.chronological.cend() && iter.when() <= expired;) { iter = c.erase(iter); ++n; @@ -26,5 +23,3 @@ typename std::enable_if::value, std::size_t>:: } } // namespace beast - -#endif diff --git a/include/xrpl/beast/container/aged_map.h b/include/xrpl/beast/container/aged_map.h index 5f07f67260..e9505f2763 100644 --- a/include/xrpl/beast/container/aged_map.h +++ b/include/xrpl/beast/container/aged_map.h @@ -1,5 +1,4 @@ -#ifndef BEAST_CONTAINER_AGED_MAP_H_INCLUDED -#define BEAST_CONTAINER_AGED_MAP_H_INCLUDED +#pragma once #include @@ -15,9 +14,6 @@ template < class Clock = std::chrono::steady_clock, class Compare = std::less, class Allocator = std::allocator>> -using aged_map = detail:: - aged_ordered_container; +using aged_map = detail::aged_ordered_container; } - -#endif diff --git a/include/xrpl/beast/container/aged_multimap.h b/include/xrpl/beast/container/aged_multimap.h index e0fa8abe97..7625694f66 100644 --- a/include/xrpl/beast/container/aged_multimap.h +++ b/include/xrpl/beast/container/aged_multimap.h @@ -1,5 +1,4 @@ -#ifndef BEAST_CONTAINER_AGED_MULTIMAP_H_INCLUDED -#define BEAST_CONTAINER_AGED_MULTIMAP_H_INCLUDED +#pragma once #include @@ -15,9 +14,6 @@ template < class Clock = std::chrono::steady_clock, class Compare = std::less, class Allocator = std::allocator>> -using aged_multimap = detail:: - aged_ordered_container; +using aged_multimap = detail::aged_ordered_container; } - -#endif diff --git a/include/xrpl/beast/container/aged_multiset.h b/include/xrpl/beast/container/aged_multiset.h index 222bed71c4..2ad09344e5 100644 --- a/include/xrpl/beast/container/aged_multiset.h +++ b/include/xrpl/beast/container/aged_multiset.h @@ -1,5 +1,4 @@ -#ifndef BEAST_CONTAINER_AGED_MULTISET_H_INCLUDED -#define BEAST_CONTAINER_AGED_MULTISET_H_INCLUDED +#pragma once #include @@ -14,9 +13,6 @@ template < class Clock = std::chrono::steady_clock, class Compare = std::less, class Allocator = std::allocator> -using aged_multiset = detail:: - aged_ordered_container; +using aged_multiset = detail::aged_ordered_container; } - -#endif diff --git a/include/xrpl/beast/container/aged_set.h b/include/xrpl/beast/container/aged_set.h index cd792c9e84..2c601f5f41 100644 --- a/include/xrpl/beast/container/aged_set.h +++ b/include/xrpl/beast/container/aged_set.h @@ -1,5 +1,4 @@ -#ifndef BEAST_CONTAINER_AGED_SET_H_INCLUDED -#define BEAST_CONTAINER_AGED_SET_H_INCLUDED +#pragma once #include @@ -14,9 +13,6 @@ template < class Clock = std::chrono::steady_clock, class Compare = std::less, class Allocator = std::allocator> -using aged_set = detail:: - aged_ordered_container; +using aged_set = detail::aged_ordered_container; } - -#endif diff --git a/include/xrpl/beast/container/aged_unordered_map.h b/include/xrpl/beast/container/aged_unordered_map.h index 4434e858da..116d5669a1 100644 --- a/include/xrpl/beast/container/aged_unordered_map.h +++ b/include/xrpl/beast/container/aged_unordered_map.h @@ -1,5 +1,4 @@ -#ifndef BEAST_CONTAINER_AGED_UNORDERED_MAP_H_INCLUDED -#define BEAST_CONTAINER_AGED_UNORDERED_MAP_H_INCLUDED +#pragma once #include @@ -16,16 +15,6 @@ template < class Hash = std::hash, class KeyEqual = std::equal_to, class Allocator = std::allocator>> -using aged_unordered_map = detail::aged_unordered_container< - false, - true, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>; +using aged_unordered_map = detail::aged_unordered_container; } - -#endif diff --git a/include/xrpl/beast/container/aged_unordered_multimap.h b/include/xrpl/beast/container/aged_unordered_multimap.h index 9c903d7865..4c3333a099 100644 --- a/include/xrpl/beast/container/aged_unordered_multimap.h +++ b/include/xrpl/beast/container/aged_unordered_multimap.h @@ -1,5 +1,4 @@ -#ifndef BEAST_CONTAINER_AGED_UNORDERED_MULTIMAP_H_INCLUDED -#define BEAST_CONTAINER_AGED_UNORDERED_MULTIMAP_H_INCLUDED +#pragma once #include @@ -16,16 +15,6 @@ template < class Hash = std::hash, class KeyEqual = std::equal_to, class Allocator = std::allocator>> -using aged_unordered_multimap = detail::aged_unordered_container< - true, - true, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>; +using aged_unordered_multimap = detail::aged_unordered_container; } - -#endif diff --git a/include/xrpl/beast/container/aged_unordered_multiset.h b/include/xrpl/beast/container/aged_unordered_multiset.h index 04f64f7032..b251f20077 100644 --- a/include/xrpl/beast/container/aged_unordered_multiset.h +++ b/include/xrpl/beast/container/aged_unordered_multiset.h @@ -1,5 +1,4 @@ -#ifndef BEAST_CONTAINER_AGED_UNORDERED_MULTISET_H_INCLUDED -#define BEAST_CONTAINER_AGED_UNORDERED_MULTISET_H_INCLUDED +#pragma once #include @@ -15,16 +14,7 @@ template < class Hash = std::hash, class KeyEqual = std::equal_to, class Allocator = std::allocator> -using aged_unordered_multiset = detail::aged_unordered_container< - true, - false, - Key, - void, - Clock, - Hash, - KeyEqual, - Allocator>; +using aged_unordered_multiset = + detail::aged_unordered_container; } - -#endif diff --git a/include/xrpl/beast/container/aged_unordered_set.h b/include/xrpl/beast/container/aged_unordered_set.h index e0373cc0d8..a8ee61f1f5 100644 --- a/include/xrpl/beast/container/aged_unordered_set.h +++ b/include/xrpl/beast/container/aged_unordered_set.h @@ -1,5 +1,4 @@ -#ifndef BEAST_CONTAINER_AGED_UNORDERED_SET_H_INCLUDED -#define BEAST_CONTAINER_AGED_UNORDERED_SET_H_INCLUDED +#pragma once #include @@ -15,16 +14,6 @@ template < class Hash = std::hash, class KeyEqual = std::equal_to, class Allocator = std::allocator> -using aged_unordered_set = detail::aged_unordered_container< - false, - false, - Key, - void, - Clock, - Hash, - KeyEqual, - Allocator>; +using aged_unordered_set = detail::aged_unordered_container; } - -#endif diff --git a/include/xrpl/beast/container/detail/aged_associative_container.h b/include/xrpl/beast/container/detail/aged_associative_container.h index ab08484aa3..34e9560cbb 100644 --- a/include/xrpl/beast/container/detail/aged_associative_container.h +++ b/include/xrpl/beast/container/detail/aged_associative_container.h @@ -1,5 +1,4 @@ -#ifndef BEAST_CONTAINER_DETAIL_AGED_ASSOCIATIVE_CONTAINER_H_INCLUDED -#define BEAST_CONTAINER_DETAIL_AGED_ASSOCIATIVE_CONTAINER_H_INCLUDED +#pragma once namespace beast { namespace detail { @@ -33,5 +32,3 @@ struct aged_associative_container_extract_t } // namespace detail } // namespace beast - -#endif diff --git a/include/xrpl/beast/container/detail/aged_container_iterator.h b/include/xrpl/beast/container/detail/aged_container_iterator.h index 1e302cfc2c..12cd15f677 100644 --- a/include/xrpl/beast/container/detail/aged_container_iterator.h +++ b/include/xrpl/beast/container/detail/aged_container_iterator.h @@ -1,5 +1,4 @@ -#ifndef BEAST_CONTAINER_DETAIL_AGED_CONTAINER_ITERATOR_H_INCLUDED -#define BEAST_CONTAINER_DETAIL_AGED_CONTAINER_ITERATOR_H_INCLUDED +#pragma once #include #include @@ -16,14 +15,12 @@ template class aged_container_iterator { public: - using iterator_category = - typename std::iterator_traits::iterator_category; + using iterator_category = typename std::iterator_traits::iterator_category; using value_type = typename std::conditional< is_const, typename Iterator::value_type::stashed::value_type const, typename Iterator::value_type::stashed::value_type>::type; - using difference_type = - typename std::iterator_traits::difference_type; + using difference_type = typename std::iterator_traits::difference_type; using pointer = value_type*; using reference = value_type&; using time_point = typename Iterator::value_type::stashed::time_point; @@ -38,31 +35,22 @@ public: class = typename std::enable_if< (other_is_const == false || is_const == true) && std::is_same::value == false>::type> - explicit aged_container_iterator( - aged_container_iterator const& other) + explicit aged_container_iterator(aged_container_iterator const& other) : m_iter(other.m_iter) { } // Disable constructing a const_iterator from a non-const_iterator. - template < - bool other_is_const, - class = typename std::enable_if< - other_is_const == false || is_const == true>::type> - aged_container_iterator( - aged_container_iterator const& other) - : m_iter(other.m_iter) + template ::type> + aged_container_iterator(aged_container_iterator const& other) : m_iter(other.m_iter) { } // Disable assigning a const_iterator to a non-const iterator template auto - operator=( - aged_container_iterator const& other) -> - typename std::enable_if< - other_is_const == false || is_const == true, - aged_container_iterator&>::type + operator=(aged_container_iterator const& other) -> + typename std::enable_if::type { m_iter = other.m_iter; return *this; @@ -70,16 +58,14 @@ public: template bool - operator==(aged_container_iterator const& - other) const + operator==(aged_container_iterator const& other) const { return m_iter == other.m_iter; } template bool - operator!=(aged_container_iterator const& - other) const + operator!=(aged_container_iterator const& other) const { return m_iter != other.m_iter; } @@ -159,5 +145,3 @@ private: } // namespace detail } // namespace beast - -#endif diff --git a/include/xrpl/beast/container/detail/aged_ordered_container.h b/include/xrpl/beast/container/detail/aged_ordered_container.h index e9bac2879c..2f3d8973e9 100644 --- a/include/xrpl/beast/container/detail/aged_ordered_container.h +++ b/include/xrpl/beast/container/detail/aged_ordered_container.h @@ -1,5 +1,4 @@ -#ifndef BEAST_CONTAINER_DETAIL_AGED_ORDERED_CONTAINER_H_INCLUDED -#define BEAST_CONTAINER_DETAIL_AGED_ORDERED_CONTAINER_H_INCLUDED +#pragma once #include #include @@ -30,8 +29,7 @@ struct is_boost_reverse_iterator : std::false_type }; template -struct is_boost_reverse_iterator> - : std::true_type +struct is_boost_reverse_iterator> : std::true_type { explicit is_boost_reverse_iterator() = default; }; @@ -59,8 +57,7 @@ template < class T, class Clock = std::chrono::steady_clock, class Compare = std::less, - class Allocator = std::allocator< - typename std::conditional, Key>::type>> + class Allocator = std::allocator, Key>::type>> class aged_ordered_container { public: @@ -69,8 +66,7 @@ public: using duration = typename clock_type::duration; using key_type = Key; using mapped_type = T; - using value_type = - typename std::conditional, Key>::type; + using value_type = typename std::conditional, Key>::type; using size_type = std::size_t; using difference_type = std::ptrdiff_t; @@ -87,11 +83,8 @@ private: } // VFALCO TODO hoist to remove template argument dependencies - struct element - : boost::intrusive::set_base_hook< - boost::intrusive::link_mode>, - boost::intrusive::list_base_hook< - boost::intrusive::link_mode> + struct element : boost::intrusive::set_base_hook>, + boost::intrusive::list_base_hook> { // Stash types here so the iterator doesn't // need to see the container declaration. @@ -103,22 +96,18 @@ private: using time_point = typename aged_ordered_container::time_point; }; - element(time_point const& when_, value_type const& value_) - : value(value_), when(when_) + element(time_point const& when_, value_type const& value_) : value(value_), when(when_) { } - element(time_point const& when_, value_type&& value_) - : value(std::move(value_)), when(when_) + element(time_point const& when_, value_type&& value_) : value(std::move(value_)), when(when_) { } template < class... Args, - class = typename std::enable_if< - std::is_constructible::value>::type> - element(time_point const& when_, Args&&... args) - : value(std::forward(args)...), when(when_) + class = typename std::enable_if::value>::type> + element(time_point const& when_, Args&&... args) : value(std::forward(args)...), when(when_) { } @@ -202,8 +191,7 @@ private: } }; - using list_type = typename boost::intrusive:: - make_list>::type; + using list_type = typename boost::intrusive::make_list>::type; using cont_type = typename std::conditional< IsMulti, @@ -211,51 +199,39 @@ private: element, boost::intrusive::constant_time_size, boost::intrusive::compare>::type, - typename boost::intrusive::make_set< - element, - boost::intrusive::constant_time_size, - boost::intrusive::compare>::type>::type; + typename boost::intrusive:: + make_set, boost::intrusive::compare>:: + type>::type; - using ElementAllocator = typename std::allocator_traits< - Allocator>::template rebind_alloc; + using ElementAllocator = typename std::allocator_traits::template rebind_alloc; using ElementAllocatorTraits = std::allocator_traits; - class config_t - : private KeyValueCompare, - public beast::detail::empty_base_optimization + class config_t : private KeyValueCompare, public beast::detail::empty_base_optimization { public: explicit config_t(clock_type& clock_) : clock(clock_) { } - config_t(clock_type& clock_, Compare const& comp) - : KeyValueCompare(comp), clock(clock_) + config_t(clock_type& clock_, Compare const& comp) : KeyValueCompare(comp), clock(clock_) { } config_t(clock_type& clock_, Allocator const& alloc_) - : beast::detail::empty_base_optimization(alloc_) - , clock(clock_) + : beast::detail::empty_base_optimization(alloc_), clock(clock_) { } - config_t( - clock_type& clock_, - Compare const& comp, - Allocator const& alloc_) - : KeyValueCompare(comp) - , beast::detail::empty_base_optimization(alloc_) - , clock(clock_) + config_t(clock_type& clock_, Compare const& comp, Allocator const& alloc_) + : KeyValueCompare(comp), beast::detail::empty_base_optimization(alloc_), clock(clock_) { } config_t(config_t const& other) : KeyValueCompare(other.key_compare()) , beast::detail::empty_base_optimization( - ElementAllocatorTraits::select_on_container_copy_construction( - other.alloc())) + ElementAllocatorTraits::select_on_container_copy_construction(other.alloc())) , clock(other.clock) { } @@ -269,8 +245,7 @@ private: config_t(config_t&& other) : KeyValueCompare(std::move(other.key_compare())) - , beast::detail::empty_base_optimization( - std::move(other)) + , beast::detail::empty_base_optimization(std::move(other)) , clock(other.clock) { } @@ -330,15 +305,13 @@ private: ElementAllocator& alloc() { - return beast::detail::empty_base_optimization< - ElementAllocator>::member(); + return beast::detail::empty_base_optimization::member(); } ElementAllocator const& alloc() const { - return beast::detail::empty_base_optimization< - ElementAllocator>::member(); + return beast::detail::empty_base_optimization::member(); } std::reference_wrapper clock; @@ -363,13 +336,8 @@ private: }; std::unique_ptr p( - ElementAllocatorTraits::allocate(m_config.alloc(), 1), - Deleter(m_config.alloc())); - ElementAllocatorTraits::construct( - m_config.alloc(), - p.get(), - clock().now(), - std::forward(args)...); + ElementAllocatorTraits::allocate(m_config.alloc(), 1), Deleter(m_config.alloc())); + ElementAllocatorTraits::construct(m_config.alloc(), p.get(), clock().now(), std::forward(args)...); return p.release(); } @@ -377,8 +345,7 @@ private: delete_element(element const* p) { ElementAllocatorTraits::destroy(m_config.alloc(), p); - ElementAllocatorTraits::deallocate( - m_config.alloc(), const_cast(p), 1); + ElementAllocatorTraits::deallocate(m_config.alloc(), const_cast(p), 1); } void @@ -391,25 +358,19 @@ private: public: using key_compare = Compare; - using value_compare = - typename std::conditional::type; + using value_compare = typename std::conditional::type; using allocator_type = Allocator; using reference = value_type&; using const_reference = value_type const&; using pointer = typename std::allocator_traits::pointer; - using const_pointer = - typename std::allocator_traits::const_pointer; + using const_pointer = typename std::allocator_traits::const_pointer; // A set iterator (IsMap==false) is always const // because the elements of a set are immutable. - using iterator = beast::detail:: - aged_container_iterator; - using const_iterator = beast::detail:: - aged_container_iterator; - using reverse_iterator = beast::detail:: - aged_container_iterator; - using const_reverse_iterator = beast::detail:: - aged_container_iterator; + using iterator = beast::detail::aged_container_iterator; + using const_iterator = beast::detail::aged_container_iterator; + using reverse_iterator = beast::detail::aged_container_iterator; + using const_reverse_iterator = beast::detail::aged_container_iterator; //-------------------------------------------------------------------------- // @@ -425,15 +386,11 @@ public: public: // A set iterator (IsMap==false) is always const // because the elements of a set are immutable. - using iterator = beast::detail:: - aged_container_iterator; - using const_iterator = beast::detail:: - aged_container_iterator; - using reverse_iterator = beast::detail::aged_container_iterator< - !IsMap, - typename list_type::reverse_iterator>; - using const_reverse_iterator = beast::detail:: - aged_container_iterator; + using iterator = beast::detail::aged_container_iterator; + using const_iterator = beast::detail::aged_container_iterator; + using reverse_iterator = beast::detail::aged_container_iterator; + using const_reverse_iterator = + beast::detail::aged_container_iterator; iterator begin() @@ -510,23 +467,17 @@ public: iterator iterator_to(value_type& value) { - static_assert( - std::is_standard_layout::value, - "must be standard layout"); + static_assert(std::is_standard_layout::value, "must be standard layout"); return list.iterator_to(*reinterpret_cast( - reinterpret_cast(&value) - - ((std::size_t)std::addressof(((element*)0)->member)))); + reinterpret_cast(&value) - ((std::size_t)std::addressof(((element*)0)->member)))); } const_iterator iterator_to(value_type const& value) const { - static_assert( - std::is_standard_layout::value, - "must be standard layout"); + static_assert(std::is_standard_layout::value, "must be standard layout"); return list.iterator_to(*reinterpret_cast( - reinterpret_cast(&value) - - ((std::size_t)std::addressof(((element*)0)->member)))); + reinterpret_cast(&value) - ((std::size_t)std::addressof(((element*)0)->member)))); } private: @@ -555,61 +506,33 @@ public: aged_ordered_container(clock_type& clock, Allocator const& alloc); - aged_ordered_container( - clock_type& clock, - Compare const& comp, - Allocator const& alloc); + aged_ordered_container(clock_type& clock, Compare const& comp, Allocator const& alloc); template aged_ordered_container(InputIt first, InputIt last, clock_type& clock); template - aged_ordered_container( - InputIt first, - InputIt last, - clock_type& clock, - Compare const& comp); + aged_ordered_container(InputIt first, InputIt last, clock_type& clock, Compare const& comp); template - aged_ordered_container( - InputIt first, - InputIt last, - clock_type& clock, - Allocator const& alloc); + aged_ordered_container(InputIt first, InputIt last, clock_type& clock, Allocator const& alloc); template - aged_ordered_container( - InputIt first, - InputIt last, - clock_type& clock, - Compare const& comp, - Allocator const& alloc); + aged_ordered_container(InputIt first, InputIt last, clock_type& clock, Compare const& comp, Allocator const& alloc); aged_ordered_container(aged_ordered_container const& other); - aged_ordered_container( - aged_ordered_container const& other, - Allocator const& alloc); + aged_ordered_container(aged_ordered_container const& other, Allocator const& alloc); aged_ordered_container(aged_ordered_container&& other); - aged_ordered_container( - aged_ordered_container&& other, - Allocator const& alloc); + aged_ordered_container(aged_ordered_container&& other, Allocator const& alloc); - aged_ordered_container( - std::initializer_list init, - clock_type& clock); + aged_ordered_container(std::initializer_list init, clock_type& clock); - aged_ordered_container( - std::initializer_list init, - clock_type& clock, - Compare const& comp); + aged_ordered_container(std::initializer_list init, clock_type& clock, Compare const& comp); - aged_ordered_container( - std::initializer_list init, - clock_type& clock, - Allocator const& alloc); + aged_ordered_container(std::initializer_list init, clock_type& clock, Allocator const& alloc); aged_ordered_container( std::initializer_list init, @@ -763,21 +686,17 @@ public: iterator iterator_to(value_type& value) { - static_assert( - std::is_standard_layout::value, "must be standard layout"); + static_assert(std::is_standard_layout::value, "must be standard layout"); return m_cont.iterator_to(*reinterpret_cast( - reinterpret_cast(&value) - - ((std::size_t)std::addressof(((element*)0)->member)))); + reinterpret_cast(&value) - ((std::size_t)std::addressof(((element*)0)->member)))); } const_iterator iterator_to(value_type const& value) const { - static_assert( - std::is_standard_layout::value, "must be standard layout"); + static_assert(std::is_standard_layout::value, "must be standard layout"); return m_cont.iterator_to(*reinterpret_cast( - reinterpret_cast(&value) - - ((std::size_t)std::addressof(((element*)0)->member)))); + reinterpret_cast(&value) - ((std::size_t)std::addressof(((element*)0)->member)))); } //-------------------------------------------------------------------------- @@ -816,35 +735,29 @@ public: // map, set template auto - insert(value_type const& value) -> - typename std::enable_if>::type; + insert(value_type const& value) -> typename std::enable_if>::type; // multimap, multiset template auto - insert(value_type const& value) -> - typename std::enable_if::type; + insert(value_type const& value) -> typename std::enable_if::type; // set template auto - insert(value_type&& value) -> typename std::enable_if< - !maybe_multi && !maybe_map, - std::pair>::type; + insert(value_type&& value) -> typename std::enable_if>::type; // multiset template auto - insert(value_type&& value) -> - typename std::enable_if::type; + insert(value_type&& value) -> typename std::enable_if::type; //--- // map, set template auto - insert(const_iterator hint, value_type const& value) -> - typename std::enable_if::type; + insert(const_iterator hint, value_type const& value) -> typename std::enable_if::type; // multimap, multiset template @@ -858,8 +771,7 @@ public: // map, set template auto - insert(const_iterator hint, value_type&& value) -> - typename std::enable_if::type; + insert(const_iterator hint, value_type&& value) -> typename std::enable_if::type; // multimap, multiset template @@ -874,10 +786,8 @@ public: template typename std::enable_if< maybe_map && std::is_constructible::value, - typename std:: - conditional>::type>:: - type - insert(P&& value) + typename std::conditional>::type>::type + insert(P&& value) { return emplace(std::forward

(value)); } @@ -886,10 +796,8 @@ public: template typename std::enable_if< maybe_map && std::is_constructible::value, - typename std:: - conditional>::type>:: - type - insert(const_iterator hint, P&& value) + typename std::conditional>::type>::type + insert(const_iterator hint, P&& value) { return emplace_hint(hint, std::forward

(value)); } @@ -911,14 +819,12 @@ public: // map, set template auto - emplace(Args&&... args) -> - typename std::enable_if>::type; + emplace(Args&&... args) -> typename std::enable_if>::type; // multiset, multimap template auto - emplace(Args&&... args) -> - typename std::enable_if::type; + emplace(Args&&... args) -> typename std::enable_if::type; // map, set template @@ -936,19 +842,13 @@ public: } // enable_if prevents erase (reverse_iterator pos) from compiling - template < - bool is_const, - class Iterator, - class = std::enable_if_t::value>> + template ::value>> beast::detail::aged_container_iterator erase(beast::detail::aged_container_iterator pos); // enable_if prevents erase (reverse_iterator first, reverse_iterator last) // from compiling - template < - bool is_const, - class Iterator, - class = std::enable_if_t::value>> + template ::value>> beast::detail::aged_container_iterator erase( beast::detail::aged_container_iterator first, @@ -964,10 +864,7 @@ public: //-------------------------------------------------------------------------- // enable_if prevents touch (reverse_iterator pos) from compiling - template < - bool is_const, - class Iterator, - class = std::enable_if_t::value>> + template ::value>> void touch(beast::detail::aged_container_iterator pos) { @@ -1005,8 +902,7 @@ public: const_iterator find(K const& k) const { - return const_iterator( - m_cont.find(k, std::cref(m_config.key_compare()))); + return const_iterator(m_cont.find(k, std::cref(m_config.key_compare()))); } // VFALCO TODO Respect is_transparent (c++14) @@ -1024,8 +920,7 @@ public: equal_range(K const& k) const { auto const r(m_cont.equal_range(k, std::cref(m_config.key_compare()))); - return std::make_pair( - const_iterator(r.first), const_iterator(r.second)); + return std::make_pair(const_iterator(r.first), const_iterator(r.second)); } // VFALCO TODO Respect is_transparent (c++14) @@ -1033,8 +928,7 @@ public: iterator lower_bound(K const& k) { - return iterator( - m_cont.lower_bound(k, std::cref(m_config.key_compare()))); + return iterator(m_cont.lower_bound(k, std::cref(m_config.key_compare()))); } // VFALCO TODO Respect is_transparent (c++14) @@ -1042,8 +936,7 @@ public: const_iterator lower_bound(K const& k) const { - return const_iterator( - m_cont.lower_bound(k, std::cref(m_config.key_compare()))); + return const_iterator(m_cont.lower_bound(k, std::cref(m_config.key_compare()))); } // VFALCO TODO Respect is_transparent (c++14) @@ -1051,8 +944,7 @@ public: iterator upper_bound(K const& k) { - return iterator( - m_cont.upper_bound(k, std::cref(m_config.key_compare()))); + return iterator(m_cont.upper_bound(k, std::cref(m_config.key_compare()))); } // VFALCO TODO Respect is_transparent (c++14) @@ -1060,8 +952,7 @@ public: const_iterator upper_bound(K const& k) const { - return const_iterator( - m_cont.upper_bound(k, std::cref(m_config.key_compare()))); + return const_iterator(m_cont.upper_bound(k, std::cref(m_config.key_compare()))); } //-------------------------------------------------------------------------- @@ -1093,139 +984,69 @@ public: // is only done on the key portion of the value type, ignoring // the mapped type. // - template < - bool OtherIsMulti, - bool OtherIsMap, - class OtherT, - class OtherDuration, - class OtherAllocator> + template bool - operator==(aged_ordered_container< - OtherIsMulti, - OtherIsMap, - Key, - OtherT, - OtherDuration, - Compare, - OtherAllocator> const& other) const; + operator==( + aged_ordered_container const& + other) const; - template < - bool OtherIsMulti, - bool OtherIsMap, - class OtherT, - class OtherDuration, - class OtherAllocator> + template bool - operator!=(aged_ordered_container< - OtherIsMulti, - OtherIsMap, - Key, - OtherT, - OtherDuration, - Compare, - OtherAllocator> const& other) const + operator!=( + aged_ordered_container const& + other) const { return !(this->operator==(other)); } - template < - bool OtherIsMulti, - bool OtherIsMap, - class OtherT, - class OtherDuration, - class OtherAllocator> + template bool - operator<(aged_ordered_container< - OtherIsMulti, - OtherIsMap, - Key, - OtherT, - OtherDuration, - Compare, - OtherAllocator> const& other) const + operator<( + aged_ordered_container const& + other) const { value_compare const comp(value_comp()); - return std::lexicographical_compare( - cbegin(), cend(), other.cbegin(), other.cend(), comp); + return std::lexicographical_compare(cbegin(), cend(), other.cbegin(), other.cend(), comp); } - template < - bool OtherIsMulti, - bool OtherIsMap, - class OtherT, - class OtherDuration, - class OtherAllocator> + template bool - operator<=(aged_ordered_container< - OtherIsMulti, - OtherIsMap, - Key, - OtherT, - OtherDuration, - Compare, - OtherAllocator> const& other) const + operator<=( + aged_ordered_container const& + other) const { return !(other < *this); } - template < - bool OtherIsMulti, - bool OtherIsMap, - class OtherT, - class OtherDuration, - class OtherAllocator> + template bool - operator>(aged_ordered_container< - OtherIsMulti, - OtherIsMap, - Key, - OtherT, - OtherDuration, - Compare, - OtherAllocator> const& other) const + operator>( + aged_ordered_container const& + other) const { return other < *this; } - template < - bool OtherIsMulti, - bool OtherIsMap, - class OtherT, - class OtherDuration, - class OtherAllocator> + template bool - operator>=(aged_ordered_container< - OtherIsMulti, - OtherIsMap, - Key, - OtherT, - OtherDuration, - Compare, - OtherAllocator> const& other) const + operator>=( + aged_ordered_container const& + other) const { return !(*this < other); } private: // enable_if prevents erase (reverse_iterator pos, now) from compiling - template < - bool is_const, - class Iterator, - class = std::enable_if_t::value>> + template ::value>> void - touch( - beast::detail::aged_container_iterator pos, - typename clock_type::time_point const& now); + touch(beast::detail::aged_container_iterator pos, typename clock_type::time_point const& now); - template < - bool maybe_propagate = std::allocator_traits< - Allocator>::propagate_on_container_swap::value> + template ::propagate_on_container_swap::value> typename std::enable_if::type swap_data(aged_ordered_container& other) noexcept; - template < - bool maybe_propagate = std::allocator_traits< - Allocator>::propagate_on_container_swap::value> + template ::propagate_on_container_swap::value> typename std::enable_if::type swap_data(aged_ordered_container& other) noexcept; @@ -1236,152 +1057,88 @@ private: //------------------------------------------------------------------------------ -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> -aged_ordered_container:: - aged_ordered_container(clock_type& clock) +template +aged_ordered_container::aged_ordered_container(clock_type& clock) : m_config(clock) { } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> -aged_ordered_container:: - aged_ordered_container(clock_type& clock, Compare const& comp) +template +aged_ordered_container::aged_ordered_container( + clock_type& clock, + Compare const& comp) : m_config(clock, comp), m_cont(comp) { } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> -aged_ordered_container:: - aged_ordered_container(clock_type& clock, Allocator const& alloc) +template +aged_ordered_container::aged_ordered_container( + clock_type& clock, + Allocator const& alloc) : m_config(clock, alloc) { } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> -aged_ordered_container:: - aged_ordered_container( - clock_type& clock, - Compare const& comp, - Allocator const& alloc) +template +aged_ordered_container::aged_ordered_container( + clock_type& clock, + Compare const& comp, + Allocator const& alloc) : m_config(clock, comp, alloc), m_cont(comp) { } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> +template template -aged_ordered_container:: - aged_ordered_container(InputIt first, InputIt last, clock_type& clock) +aged_ordered_container::aged_ordered_container( + InputIt first, + InputIt last, + clock_type& clock) : m_config(clock) { insert(first, last); } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> +template template -aged_ordered_container:: - aged_ordered_container( - InputIt first, - InputIt last, - clock_type& clock, - Compare const& comp) +aged_ordered_container::aged_ordered_container( + InputIt first, + InputIt last, + clock_type& clock, + Compare const& comp) : m_config(clock, comp), m_cont(comp) { insert(first, last); } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> +template template -aged_ordered_container:: - aged_ordered_container( - InputIt first, - InputIt last, - clock_type& clock, - Allocator const& alloc) +aged_ordered_container::aged_ordered_container( + InputIt first, + InputIt last, + clock_type& clock, + Allocator const& alloc) : m_config(clock, alloc) { insert(first, last); } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> +template template -aged_ordered_container:: - aged_ordered_container( - InputIt first, - InputIt last, - clock_type& clock, - Compare const& comp, - Allocator const& alloc) +aged_ordered_container::aged_ordered_container( + InputIt first, + InputIt last, + clock_type& clock, + Compare const& comp, + Allocator const& alloc) : m_config(clock, comp, alloc), m_cont(comp) { insert(first, last); } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> -aged_ordered_container:: - aged_ordered_container(aged_ordered_container const& other) +template +aged_ordered_container::aged_ordered_container( + aged_ordered_container const& other) : m_config(other.m_config) #if BOOST_VERSION >= 108000 , m_cont(other.m_cont.get_comp()) @@ -1392,18 +1149,10 @@ aged_ordered_container:: insert(other.cbegin(), other.cend()); } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> -aged_ordered_container:: - aged_ordered_container( - aged_ordered_container const& other, - Allocator const& alloc) +template +aged_ordered_container::aged_ordered_container( + aged_ordered_container const& other, + Allocator const& alloc) : m_config(other.m_config, alloc) #if BOOST_VERSION >= 108000 , m_cont(other.m_cont.get_comp()) @@ -1414,33 +1163,18 @@ aged_ordered_container:: insert(other.cbegin(), other.cend()); } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> -aged_ordered_container:: - aged_ordered_container(aged_ordered_container&& other) +template +aged_ordered_container::aged_ordered_container( + aged_ordered_container&& other) : m_config(std::move(other.m_config)), m_cont(std::move(other.m_cont)) { chronological.list = std::move(other.chronological.list); } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> -aged_ordered_container:: - aged_ordered_container( - aged_ordered_container&& other, - Allocator const& alloc) +template +aged_ordered_container::aged_ordered_container( + aged_ordered_container&& other, + Allocator const& alloc) : m_config(std::move(other.m_config), alloc) #if BOOST_VERSION >= 108000 , m_cont(std::move(other.m_cont.get_comp())) @@ -1453,103 +1187,56 @@ aged_ordered_container:: other.clear(); } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> -aged_ordered_container:: - aged_ordered_container( - std::initializer_list init, - clock_type& clock) +template +aged_ordered_container::aged_ordered_container( + std::initializer_list init, + clock_type& clock) : m_config(clock) { insert(init.begin(), init.end()); } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> -aged_ordered_container:: - aged_ordered_container( - std::initializer_list init, - clock_type& clock, - Compare const& comp) +template +aged_ordered_container::aged_ordered_container( + std::initializer_list init, + clock_type& clock, + Compare const& comp) : m_config(clock, comp), m_cont(comp) { insert(init.begin(), init.end()); } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> -aged_ordered_container:: - aged_ordered_container( - std::initializer_list init, - clock_type& clock, - Allocator const& alloc) +template +aged_ordered_container::aged_ordered_container( + std::initializer_list init, + clock_type& clock, + Allocator const& alloc) : m_config(clock, alloc) { insert(init.begin(), init.end()); } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> -aged_ordered_container:: - aged_ordered_container( - std::initializer_list init, - clock_type& clock, - Compare const& comp, - Allocator const& alloc) +template +aged_ordered_container::aged_ordered_container( + std::initializer_list init, + clock_type& clock, + Compare const& comp, + Allocator const& alloc) : m_config(clock, comp, alloc), m_cont(comp) { insert(init.begin(), init.end()); } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> -aged_ordered_container:: - ~aged_ordered_container() +template +aged_ordered_container::~aged_ordered_container() { clear(); } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> +template auto -aged_ordered_container:: -operator=(aged_ordered_container const& other) -> aged_ordered_container& +aged_ordered_container::operator=( + aged_ordered_container const& other) -> aged_ordered_container& { if (this != &other) { @@ -1560,17 +1247,10 @@ operator=(aged_ordered_container const& other) -> aged_ordered_container& return *this; } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> +template auto -aged_ordered_container:: -operator=(aged_ordered_container&& other) -> aged_ordered_container& +aged_ordered_container::operator=(aged_ordered_container&& other) + -> aged_ordered_container& { clear(); this->m_config = std::move(other.m_config); @@ -1579,17 +1259,10 @@ operator=(aged_ordered_container&& other) -> aged_ordered_container& return *this; } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> +template auto -aged_ordered_container:: -operator=(std::initializer_list init) -> aged_ordered_container& +aged_ordered_container::operator=( + std::initializer_list init) -> aged_ordered_container& { clear(); insert(init); @@ -1598,18 +1271,10 @@ operator=(std::initializer_list init) -> aged_ordered_container& //------------------------------------------------------------------------------ -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> +template template typename std::conditional::type& -aged_ordered_container::at( - K const& k) +aged_ordered_container::at(K const& k) { auto const iter(m_cont.find(k, std::cref(m_config.key_compare()))); if (iter == m_cont.end()) @@ -1617,18 +1282,10 @@ aged_ordered_container::at( return iter->value.second; } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> +template template typename std::conditional::type const& -aged_ordered_container::at( - K const& k) const +aged_ordered_container::at(K const& k) const { auto const iter(m_cont.find(k, std::cref(m_config.key_compare()))); if (iter == m_cont.end()) @@ -1636,28 +1293,16 @@ aged_ordered_container::at( return iter->value.second; } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> +template template typename std::conditional::type& -aged_ordered_container:: -operator[](Key const& key) +aged_ordered_container::operator[](Key const& key) { typename cont_type::insert_commit_data d; - auto const result( - m_cont.insert_check(key, std::cref(m_config.key_compare()), d)); + auto const result(m_cont.insert_check(key, std::cref(m_config.key_compare()), d)); if (result.second) { - element* const p(new_element( - std::piecewise_construct, - std::forward_as_tuple(key), - std::forward_as_tuple())); + element* const p(new_element(std::piecewise_construct, std::forward_as_tuple(key), std::forward_as_tuple())); m_cont.insert_commit(*p, d); chronological.list.push_back(*p); return p->value.second; @@ -1665,28 +1310,17 @@ operator[](Key const& key) return result.first->value.second; } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> +template template typename std::conditional::type& -aged_ordered_container:: -operator[](Key&& key) +aged_ordered_container::operator[](Key&& key) { typename cont_type::insert_commit_data d; - auto const result( - m_cont.insert_check(key, std::cref(m_config.key_compare()), d)); + auto const result(m_cont.insert_check(key, std::cref(m_config.key_compare()), d)); if (result.second) { - element* const p(new_element( - std::piecewise_construct, - std::forward_as_tuple(std::move(key)), - std::forward_as_tuple())); + element* const p( + new_element(std::piecewise_construct, std::forward_as_tuple(std::move(key)), std::forward_as_tuple())); m_cont.insert_commit(*p, d); chronological.list.push_back(*p); return p->value.second; @@ -1696,43 +1330,25 @@ operator[](Key&& key) //------------------------------------------------------------------------------ -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> +template void -aged_ordered_container:: - clear() +aged_ordered_container::clear() { - for (auto iter(chronological.list.begin()); - iter != chronological.list.end();) + for (auto iter(chronological.list.begin()); iter != chronological.list.end();) delete_element(&*iter++); chronological.list.clear(); m_cont.clear(); } // map, set -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> +template template auto -aged_ordered_container:: - insert(value_type const& value) -> +aged_ordered_container::insert(value_type const& value) -> typename std::enable_if>::type { typename cont_type::insert_commit_data d; - auto const result(m_cont.insert_check( - extract(value), std::cref(m_config.key_compare()), d)); + auto const result(m_cont.insert_check(extract(value), std::cref(m_config.key_compare()), d)); if (result.second) { element* const p(new_element(value)); @@ -1744,22 +1360,13 @@ aged_ordered_container:: } // multimap, multiset -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> +template template auto -aged_ordered_container:: - insert(value_type const& value) -> +aged_ordered_container::insert(value_type const& value) -> typename std::enable_if::type { - auto const before( - m_cont.upper_bound(extract(value), std::cref(m_config.key_compare()))); + auto const before(m_cont.upper_bound(extract(value), std::cref(m_config.key_compare()))); element* const p(new_element(value)); chronological.list.push_back(*p); auto const iter(m_cont.insert_before(before, *p)); @@ -1767,24 +1374,14 @@ aged_ordered_container:: } // set -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> +template template auto -aged_ordered_container:: - insert(value_type&& value) -> - typename std:: - enable_if>::type +aged_ordered_container::insert(value_type&& value) -> + typename std::enable_if>::type { typename cont_type::insert_commit_data d; - auto const result(m_cont.insert_check( - extract(value), std::cref(m_config.key_compare()), d)); + auto const result(m_cont.insert_check(extract(value), std::cref(m_config.key_compare()), d)); if (result.second) { element* const p(new_element(std::move(value))); @@ -1796,22 +1393,13 @@ aged_ordered_container:: } // multiset -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> +template template auto -aged_ordered_container:: - insert(value_type&& value) -> +aged_ordered_container::insert(value_type&& value) -> typename std::enable_if::type { - auto const before( - m_cont.upper_bound(extract(value), std::cref(m_config.key_compare()))); + auto const before(m_cont.upper_bound(extract(value), std::cref(m_config.key_compare()))); element* const p(new_element(std::move(value))); chronological.list.push_back(*p); auto const iter(m_cont.insert_before(before, *p)); @@ -1821,23 +1409,15 @@ aged_ordered_container:: //--- // map, set -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> +template template auto -aged_ordered_container:: - insert(const_iterator hint, value_type const& value) -> - typename std::enable_if::type +aged_ordered_container::insert( + const_iterator hint, + value_type const& value) -> typename std::enable_if::type { typename cont_type::insert_commit_data d; - auto const result(m_cont.insert_check( - hint.iterator(), extract(value), std::cref(m_config.key_compare()), d)); + auto const result(m_cont.insert_check(hint.iterator(), extract(value), std::cref(m_config.key_compare()), d)); if (result.second) { element* const p(new_element(value)); @@ -1849,23 +1429,15 @@ aged_ordered_container:: } // map, set -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> +template template auto -aged_ordered_container:: - insert(const_iterator hint, value_type&& value) -> - typename std::enable_if::type +aged_ordered_container::insert( + const_iterator hint, + value_type&& value) -> typename std::enable_if::type { typename cont_type::insert_commit_data d; - auto const result(m_cont.insert_check( - hint.iterator(), extract(value), std::cref(m_config.key_compare()), d)); + auto const result(m_cont.insert_check(hint.iterator(), extract(value), std::cref(m_config.key_compare()), d)); if (result.second) { element* const p(new_element(std::move(value))); @@ -1877,26 +1449,17 @@ aged_ordered_container:: } // map, set -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> +template template auto -aged_ordered_container:: - emplace(Args&&... args) -> +aged_ordered_container::emplace(Args&&... args) -> typename std::enable_if>::type { // VFALCO NOTE Its unfortunate that we need to // construct element here element* const p(new_element(std::forward(args)...)); typename cont_type::insert_commit_data d; - auto const result(m_cont.insert_check( - extract(p->value), std::cref(m_config.key_compare()), d)); + auto const result(m_cont.insert_check(extract(p->value), std::cref(m_config.key_compare()), d)); if (result.second) { auto const iter(m_cont.insert_commit(*p, d)); @@ -1908,52 +1471,32 @@ aged_ordered_container:: } // multiset, multimap -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> +template template auto -aged_ordered_container:: - emplace(Args&&... args) -> +aged_ordered_container::emplace(Args&&... args) -> typename std::enable_if::type { element* const p(new_element(std::forward(args)...)); - auto const before(m_cont.upper_bound( - extract(p->value), std::cref(m_config.key_compare()))); + auto const before(m_cont.upper_bound(extract(p->value), std::cref(m_config.key_compare()))); chronological.list.push_back(*p); auto const iter(m_cont.insert_before(before, *p)); return iterator(iter); } // map, set -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> +template template auto -aged_ordered_container:: - emplace_hint(const_iterator hint, Args&&... args) -> - typename std::enable_if>::type +aged_ordered_container::emplace_hint( + const_iterator hint, + Args&&... args) -> typename std::enable_if>::type { // VFALCO NOTE Its unfortunate that we need to // construct element here element* const p(new_element(std::forward(args)...)); typename cont_type::insert_commit_data d; - auto const result(m_cont.insert_check( - hint.iterator(), - extract(p->value), - std::cref(m_config.key_compare()), - d)); + auto const result(m_cont.insert_check(hint.iterator(), extract(p->value), std::cref(m_config.key_compare()), d)); if (result.second) { auto const iter(m_cont.insert_commit(*p, d)); @@ -1964,58 +1507,33 @@ aged_ordered_container:: return std::make_pair(iterator(result.first), false); } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> +template template beast::detail::aged_container_iterator -aged_ordered_container:: - erase(beast::detail::aged_container_iterator pos) +aged_ordered_container::erase( + beast::detail::aged_container_iterator pos) { unlink_and_delete_element(&*((pos++).iterator())); - return beast::detail::aged_container_iterator( - pos.iterator()); + return beast::detail::aged_container_iterator(pos.iterator()); } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> +template template beast::detail::aged_container_iterator -aged_ordered_container:: - erase( - beast::detail::aged_container_iterator first, - beast::detail::aged_container_iterator last) +aged_ordered_container::erase( + beast::detail::aged_container_iterator first, + beast::detail::aged_container_iterator last) { for (; first != last;) unlink_and_delete_element(&*((first++).iterator())); - return beast::detail::aged_container_iterator( - first.iterator()); + return beast::detail::aged_container_iterator(first.iterator()); } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> +template template auto -aged_ordered_container:: - erase(K const& k) -> size_type +aged_ordered_container::erase(K const& k) -> size_type { auto iter(m_cont.find(k, std::cref(m_config.key_compare()))); if (iter == m_cont.end()) @@ -2033,17 +1551,9 @@ aged_ordered_container:: return n; } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> +template void -aged_ordered_container::swap( - aged_ordered_container& other) noexcept +aged_ordered_container::swap(aged_ordered_container& other) noexcept { swap_data(other); std::swap(chronological, other.chronological); @@ -2052,18 +1562,10 @@ aged_ordered_container::swap( //------------------------------------------------------------------------------ -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> +template template auto -aged_ordered_container:: - touch(K const& k) -> size_type +aged_ordered_container::touch(K const& k) -> size_type { auto const now(clock().now()); size_type n(0); @@ -2078,39 +1580,14 @@ aged_ordered_container:: //------------------------------------------------------------------------------ -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> -template < - bool OtherIsMulti, - bool OtherIsMap, - class OtherT, - class OtherDuration, - class OtherAllocator> +template +template bool -aged_ordered_container:: -operator==(aged_ordered_container< - OtherIsMulti, - OtherIsMap, - Key, - OtherT, - OtherDuration, - Compare, - OtherAllocator> const& other) const +aged_ordered_container::operator==( + aged_ordered_container const& other) + const { - using Other = aged_ordered_container< - OtherIsMulti, - OtherIsMap, - Key, - OtherT, - OtherDuration, - Compare, - OtherAllocator>; + using Other = aged_ordered_container; if (size() != other.size()) return false; std::equal_to eq; @@ -2119,28 +1596,19 @@ operator==(aged_ordered_container< cend(), other.cbegin(), other.cend(), - [&eq, &other]( - value_type const& lhs, typename Other::value_type const& rhs) { + [&eq, &other](value_type const& lhs, typename Other::value_type const& rhs) { return eq(extract(lhs), other.extract(rhs)); }); } //------------------------------------------------------------------------------ -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> +template template void -aged_ordered_container:: - touch( - beast::detail::aged_container_iterator pos, - typename clock_type::time_point const& now) +aged_ordered_container::touch( + beast::detail::aged_container_iterator pos, + typename clock_type::time_point const& now) { auto& e(*pos.iterator()); e.when = now; @@ -2148,36 +1616,22 @@ aged_ordered_container:: chronological.list.push_back(e); } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> +template template typename std::enable_if::type -aged_ordered_container:: - swap_data(aged_ordered_container& other) noexcept +aged_ordered_container::swap_data( + aged_ordered_container& other) noexcept { std::swap(m_config.key_compare(), other.m_config.key_compare()); std::swap(m_config.alloc(), other.m_config.alloc()); std::swap(m_config.clock, other.m_config.clock); } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> +template template typename std::enable_if::type -aged_ordered_container:: - swap_data(aged_ordered_container& other) noexcept +aged_ordered_container::swap_data( + aged_ordered_container& other) noexcept { std::swap(m_config.key_compare(), other.m_config.key_compare()); std::swap(m_config.clock, other.m_config.clock); @@ -2187,54 +1641,20 @@ aged_ordered_container:: //------------------------------------------------------------------------------ -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> -struct is_aged_container> : std::true_type +template +struct is_aged_container> + : std::true_type { explicit is_aged_container() = default; }; // Free functions -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Compare, - class Allocator> +template void swap( - beast::detail::aged_ordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Compare, - Allocator>& lhs, - beast::detail::aged_ordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Compare, - Allocator>& rhs) noexcept + beast::detail::aged_ordered_container& lhs, + beast::detail::aged_ordered_container& rhs) noexcept { lhs.swap(rhs); } @@ -2252,20 +1672,12 @@ template < class Period> std::size_t expire( - detail::aged_ordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Compare, - Allocator>& c, + detail::aged_ordered_container& c, std::chrono::duration const& age) { std::size_t n(0); auto const expired(c.clock().now() - age); - for (auto iter(c.chronological.cbegin()); - iter != c.chronological.cend() && iter.when() <= expired;) + for (auto iter(c.chronological.cbegin()); iter != c.chronological.cend() && iter.when() <= expired;) { iter = c.erase(iter); ++n; @@ -2274,5 +1686,3 @@ expire( } } // namespace beast - -#endif diff --git a/include/xrpl/beast/container/detail/aged_unordered_container.h b/include/xrpl/beast/container/detail/aged_unordered_container.h index e2ee3b24e0..a73ec107a7 100644 --- a/include/xrpl/beast/container/detail/aged_unordered_container.h +++ b/include/xrpl/beast/container/detail/aged_unordered_container.h @@ -1,5 +1,4 @@ -#ifndef BEAST_CONTAINER_DETAIL_AGED_UNORDERED_CONTAINER_H_INCLUDED -#define BEAST_CONTAINER_DETAIL_AGED_UNORDERED_CONTAINER_H_INCLUDED +#pragma once #include #include @@ -63,8 +62,7 @@ template < class Clock = std::chrono::steady_clock, class Hash = std::hash, class KeyEqual = std::equal_to, - class Allocator = std::allocator< - typename std::conditional, Key>::type>> + class Allocator = std::allocator, Key>::type>> class aged_unordered_container { public: @@ -73,8 +71,7 @@ public: using duration = typename clock_type::duration; using key_type = Key; using mapped_type = T; - using value_type = - typename std::conditional, Key>::type; + using value_type = typename std::conditional, Key>::type; using size_type = std::size_t; using difference_type = std::ptrdiff_t; @@ -92,10 +89,8 @@ private: // VFALCO TODO hoist to remove template argument dependencies struct element - : boost::intrusive::unordered_set_base_hook< - boost::intrusive::link_mode>, - boost::intrusive::list_base_hook< - boost::intrusive::link_mode> + : boost::intrusive::unordered_set_base_hook>, + boost::intrusive::list_base_hook> { // Stash types here so the iterator doesn't // need to see the container declaration. @@ -107,22 +102,18 @@ private: using time_point = typename aged_unordered_container::time_point; }; - element(time_point const& when_, value_type const& value_) - : value(value_), when(when_) + element(time_point const& when_, value_type const& value_) : value(value_), when(when_) { } - element(time_point const& when_, value_type&& value_) - : value(std::move(value_)), when(when_) + element(time_point const& when_, value_type&& value_) : value(std::move(value_)), when(when_) { } template < class... Args, - class = typename std::enable_if< - std::is_constructible::value>::type> - element(time_point const& when_, Args&&... args) - : value(std::forward(args)...), when(when_) + class = typename std::enable_if::value>::type> + element(time_point const& when_, Args&&... args) : value(std::forward(args)...), when(when_) { } @@ -212,8 +203,7 @@ private: } }; - using list_type = typename boost::intrusive:: - make_list>::type; + using list_type = typename boost::intrusive::make_list>::type; using cont_type = typename std::conditional< IsMulti, @@ -233,39 +223,33 @@ private: using bucket_type = typename cont_type::bucket_type; using bucket_traits = typename cont_type::bucket_traits; - using ElementAllocator = typename std::allocator_traits< - Allocator>::template rebind_alloc; + using ElementAllocator = typename std::allocator_traits::template rebind_alloc; using ElementAllocatorTraits = std::allocator_traits; - using BucketAllocator = typename std::allocator_traits< - Allocator>::template rebind_alloc; + using BucketAllocator = typename std::allocator_traits::template rebind_alloc; using BucketAllocatorTraits = std::allocator_traits; - class config_t - : private ValueHash, - private KeyValueEqual, - private beast::detail::empty_base_optimization + class config_t : private ValueHash, + private KeyValueEqual, + private beast::detail::empty_base_optimization { public: explicit config_t(clock_type& clock_) : clock(clock_) { } - config_t(clock_type& clock_, Hash const& hash) - : ValueHash(hash), clock(clock_) + config_t(clock_type& clock_, Hash const& hash) : ValueHash(hash), clock(clock_) { } - config_t(clock_type& clock_, KeyEqual const& keyEqual) - : KeyValueEqual(keyEqual), clock(clock_) + config_t(clock_type& clock_, KeyEqual const& keyEqual) : KeyValueEqual(keyEqual), clock(clock_) { } config_t(clock_type& clock_, Allocator const& alloc_) - : beast::detail::empty_base_optimization(alloc_) - , clock(clock_) + : beast::detail::empty_base_optimization(alloc_), clock(clock_) { } @@ -275,27 +259,16 @@ private: } config_t(clock_type& clock_, Hash const& hash, Allocator const& alloc_) - : ValueHash(hash) - , beast::detail::empty_base_optimization(alloc_) - , clock(clock_) + : ValueHash(hash), beast::detail::empty_base_optimization(alloc_), clock(clock_) { } - config_t( - clock_type& clock_, - KeyEqual const& keyEqual, - Allocator const& alloc_) - : KeyValueEqual(keyEqual) - , beast::detail::empty_base_optimization(alloc_) - , clock(clock_) + config_t(clock_type& clock_, KeyEqual const& keyEqual, Allocator const& alloc_) + : KeyValueEqual(keyEqual), beast::detail::empty_base_optimization(alloc_), clock(clock_) { } - config_t( - clock_type& clock_, - Hash const& hash, - KeyEqual const& keyEqual, - Allocator const& alloc_) + config_t(clock_type& clock_, Hash const& hash, KeyEqual const& keyEqual, Allocator const& alloc_) : ValueHash(hash) , KeyValueEqual(keyEqual) , beast::detail::empty_base_optimization(alloc_) @@ -307,8 +280,7 @@ private: : ValueHash(other.hash_function()) , KeyValueEqual(other.key_eq()) , beast::detail::empty_base_optimization( - ElementAllocatorTraits::select_on_container_copy_construction( - other.alloc())) + ElementAllocatorTraits::select_on_container_copy_construction(other.alloc())) , clock(other.clock) { } @@ -324,8 +296,7 @@ private: config_t(config_t&& other) : ValueHash(std::move(other.hash_function())) , KeyValueEqual(std::move(other.key_eq())) - , beast::detail::empty_base_optimization( - std::move(other.alloc())) + , beast::detail::empty_base_optimization(std::move(other.alloc())) , clock(other.clock) { } @@ -409,15 +380,13 @@ private: ElementAllocator& alloc() { - return beast::detail::empty_base_optimization< - ElementAllocator>::member(); + return beast::detail::empty_base_optimization::member(); } ElementAllocator const& alloc() const { - return beast::detail::empty_base_optimization< - ElementAllocator>::member(); + return beast::detail::empty_base_optimization::member(); } std::reference_wrapper clock; @@ -426,10 +395,8 @@ private: class Buckets { public: - using vec_type = std::vector< - bucket_type, - typename std::allocator_traits::template rebind_alloc< - bucket_type>>; + using vec_type = + std::vector::template rebind_alloc>; Buckets() : m_max_load_factor(1.f), m_vec() { @@ -508,8 +475,7 @@ private: void resize(size_type n, Container& c) { - size_type const suggested( - cont_type::suggested_upper_bucket_count(n)); + size_type const suggested(cont_type::suggested_upper_bucket_count(n)); rehash(suggested, c); } @@ -537,13 +503,8 @@ private: }; std::unique_ptr p( - ElementAllocatorTraits::allocate(m_config.alloc(), 1), - Deleter(m_config.alloc())); - ElementAllocatorTraits::construct( - m_config.alloc(), - p.get(), - clock().now(), - std::forward(args)...); + ElementAllocatorTraits::allocate(m_config.alloc(), 1), Deleter(m_config.alloc())); + ElementAllocatorTraits::construct(m_config.alloc(), p.get(), clock().now(), std::forward(args)...); return p.release(); } @@ -551,8 +512,7 @@ private: delete_element(element const* p) { ElementAllocatorTraits::destroy(m_config.alloc(), p); - ElementAllocatorTraits::deallocate( - m_config.alloc(), const_cast(p), 1); + ElementAllocatorTraits::deallocate(m_config.alloc(), const_cast(p), 1); } void @@ -570,20 +530,15 @@ public: using reference = value_type&; using const_reference = value_type const&; using pointer = typename std::allocator_traits::pointer; - using const_pointer = - typename std::allocator_traits::const_pointer; + using const_pointer = typename std::allocator_traits::const_pointer; // A set iterator (IsMap==false) is always const // because the elements of a set are immutable. - using iterator = beast::detail:: - aged_container_iterator; - using const_iterator = beast::detail:: - aged_container_iterator; + using iterator = beast::detail::aged_container_iterator; + using const_iterator = beast::detail::aged_container_iterator; - using local_iterator = beast::detail:: - aged_container_iterator; - using const_local_iterator = beast::detail:: - aged_container_iterator; + using local_iterator = beast::detail::aged_container_iterator; + using const_local_iterator = beast::detail::aged_container_iterator; //-------------------------------------------------------------------------- // @@ -599,15 +554,11 @@ public: public: // A set iterator (IsMap==false) is always const // because the elements of a set are immutable. - using iterator = beast::detail:: - aged_container_iterator; - using const_iterator = beast::detail:: - aged_container_iterator; - using reverse_iterator = beast::detail::aged_container_iterator< - !IsMap, - typename list_type::reverse_iterator>; - using const_reverse_iterator = beast::detail:: - aged_container_iterator; + using iterator = beast::detail::aged_container_iterator; + using const_iterator = beast::detail::aged_container_iterator; + using reverse_iterator = beast::detail::aged_container_iterator; + using const_reverse_iterator = + beast::detail::aged_container_iterator; iterator begin() @@ -684,23 +635,17 @@ public: iterator iterator_to(value_type& value) { - static_assert( - std::is_standard_layout::value, - "must be standard layout"); + static_assert(std::is_standard_layout::value, "must be standard layout"); return list.iterator_to(*reinterpret_cast( - reinterpret_cast(&value) - - ((std::size_t)std::addressof(((element*)0)->member)))); + reinterpret_cast(&value) - ((std::size_t)std::addressof(((element*)0)->member)))); } const_iterator iterator_to(value_type const& value) const { - static_assert( - std::is_standard_layout::value, - "must be standard layout"); + static_assert(std::is_standard_layout::value, "must be standard layout"); return list.iterator_to(*reinterpret_cast( - reinterpret_cast(&value) - - ((std::size_t)std::addressof(((element*)0)->member)))); + reinterpret_cast(&value) - ((std::size_t)std::addressof(((element*)0)->member)))); } private: @@ -731,66 +676,31 @@ public: aged_unordered_container(clock_type& clock, Allocator const& alloc); - aged_unordered_container( - clock_type& clock, - Hash const& hash, - KeyEqual const& key_eq); + aged_unordered_container(clock_type& clock, Hash const& hash, KeyEqual const& key_eq); - aged_unordered_container( - clock_type& clock, - Hash const& hash, - Allocator const& alloc); + aged_unordered_container(clock_type& clock, Hash const& hash, Allocator const& alloc); - aged_unordered_container( - clock_type& clock, - KeyEqual const& key_eq, - Allocator const& alloc); + aged_unordered_container(clock_type& clock, KeyEqual const& key_eq, Allocator const& alloc); - aged_unordered_container( - clock_type& clock, - Hash const& hash, - KeyEqual const& key_eq, - Allocator const& alloc); + aged_unordered_container(clock_type& clock, Hash const& hash, KeyEqual const& key_eq, Allocator const& alloc); template aged_unordered_container(InputIt first, InputIt last, clock_type& clock); template - aged_unordered_container( - InputIt first, - InputIt last, - clock_type& clock, - Hash const& hash); + aged_unordered_container(InputIt first, InputIt last, clock_type& clock, Hash const& hash); template - aged_unordered_container( - InputIt first, - InputIt last, - clock_type& clock, - KeyEqual const& key_eq); + aged_unordered_container(InputIt first, InputIt last, clock_type& clock, KeyEqual const& key_eq); template - aged_unordered_container( - InputIt first, - InputIt last, - clock_type& clock, - Allocator const& alloc); + aged_unordered_container(InputIt first, InputIt last, clock_type& clock, Allocator const& alloc); template - aged_unordered_container( - InputIt first, - InputIt last, - clock_type& clock, - Hash const& hash, - KeyEqual const& key_eq); + aged_unordered_container(InputIt first, InputIt last, clock_type& clock, Hash const& hash, KeyEqual const& key_eq); template - aged_unordered_container( - InputIt first, - InputIt last, - clock_type& clock, - Hash const& hash, - Allocator const& alloc); + aged_unordered_container(InputIt first, InputIt last, clock_type& clock, Hash const& hash, Allocator const& alloc); template aged_unordered_container( @@ -811,34 +721,19 @@ public: aged_unordered_container(aged_unordered_container const& other); - aged_unordered_container( - aged_unordered_container const& other, - Allocator const& alloc); + aged_unordered_container(aged_unordered_container const& other, Allocator const& alloc); aged_unordered_container(aged_unordered_container&& other); - aged_unordered_container( - aged_unordered_container&& other, - Allocator const& alloc); + aged_unordered_container(aged_unordered_container&& other, Allocator const& alloc); - aged_unordered_container( - std::initializer_list init, - clock_type& clock); + aged_unordered_container(std::initializer_list init, clock_type& clock); - aged_unordered_container( - std::initializer_list init, - clock_type& clock, - Hash const& hash); + aged_unordered_container(std::initializer_list init, clock_type& clock, Hash const& hash); - aged_unordered_container( - std::initializer_list init, - clock_type& clock, - KeyEqual const& key_eq); + aged_unordered_container(std::initializer_list init, clock_type& clock, KeyEqual const& key_eq); - aged_unordered_container( - std::initializer_list init, - clock_type& clock, - Allocator const& alloc); + aged_unordered_container(std::initializer_list init, clock_type& clock, Allocator const& alloc); aged_unordered_container( std::initializer_list init, @@ -975,21 +870,17 @@ public: iterator iterator_to(value_type& value) { - static_assert( - std::is_standard_layout::value, "must be standard layout"); + static_assert(std::is_standard_layout::value, "must be standard layout"); return m_cont.iterator_to(*reinterpret_cast( - reinterpret_cast(&value) - - ((std::size_t)std::addressof(((element*)0)->member)))); + reinterpret_cast(&value) - ((std::size_t)std::addressof(((element*)0)->member)))); } const_iterator iterator_to(value_type const& value) const { - static_assert( - std::is_standard_layout::value, "must be standard layout"); + static_assert(std::is_standard_layout::value, "must be standard layout"); return m_cont.iterator_to(*reinterpret_cast( - reinterpret_cast(&value) - - ((std::size_t)std::addressof(((element*)0)->member)))); + reinterpret_cast(&value) - ((std::size_t)std::addressof(((element*)0)->member)))); } //-------------------------------------------------------------------------- @@ -1028,27 +919,22 @@ public: // map, set template auto - insert(value_type const& value) -> - typename std::enable_if>::type; + insert(value_type const& value) -> typename std::enable_if>::type; // multimap, multiset template auto - insert(value_type const& value) -> - typename std::enable_if::type; + insert(value_type const& value) -> typename std::enable_if::type; // map, set template auto - insert(value_type&& value) -> typename std::enable_if< - !maybe_multi && !maybe_map, - std::pair>::type; + insert(value_type&& value) -> typename std::enable_if>::type; // multimap, multiset template auto - insert(value_type&& value) -> - typename std::enable_if::type; + insert(value_type&& value) -> typename std::enable_if::type; // map, set template @@ -1094,10 +980,8 @@ public: template typename std::enable_if< maybe_map && std::is_constructible::value, - typename std:: - conditional>::type>:: - type - insert(P&& value) + typename std::conditional>::type>::type + insert(P&& value) { return emplace(std::forward

(value)); } @@ -1106,10 +990,8 @@ public: template typename std::enable_if< maybe_map && std::is_constructible::value, - typename std:: - conditional>::type>:: - type - insert(const_iterator hint, P&& value) + typename std::conditional>::type>::type + insert(const_iterator hint, P&& value) { return emplace_hint(hint, std::forward

(value)); } @@ -1118,10 +1000,7 @@ public: void insert(InputIt first, InputIt last) { - insert( - first, - last, - typename std::iterator_traits::iterator_category()); + insert(first, last, typename std::iterator_traits::iterator_category()); } void @@ -1133,14 +1012,12 @@ public: // set, map template auto - emplace(Args&&... args) -> - typename std::enable_if>::type; + emplace(Args&&... args) -> typename std::enable_if>::type; // multiset, multimap template auto - emplace(Args&&... args) -> - typename std::enable_if::type; + emplace(Args&&... args) -> typename std::enable_if::type; // set, map template @@ -1197,10 +1074,7 @@ public: size_type count(K const& k) const { - return m_cont.count( - k, - std::cref(m_config.hash_function()), - std::cref(m_config.key_value_equal())); + return m_cont.count(k, std::cref(m_config.hash_function()), std::cref(m_config.key_value_equal())); } // VFALCO TODO Respect is_transparent (c++14) @@ -1208,10 +1082,7 @@ public: iterator find(K const& k) { - return iterator(m_cont.find( - k, - std::cref(m_config.hash_function()), - std::cref(m_config.key_value_equal()))); + return iterator(m_cont.find(k, std::cref(m_config.hash_function()), std::cref(m_config.key_value_equal()))); } // VFALCO TODO Respect is_transparent (c++14) @@ -1219,10 +1090,8 @@ public: const_iterator find(K const& k) const { - return const_iterator(m_cont.find( - k, - std::cref(m_config.hash_function()), - std::cref(m_config.key_value_equal()))); + return const_iterator( + m_cont.find(k, std::cref(m_config.hash_function()), std::cref(m_config.key_value_equal()))); } // VFALCO TODO Respect is_transparent (c++14) @@ -1230,10 +1099,7 @@ public: std::pair equal_range(K const& k) { - auto const r(m_cont.equal_range( - k, - std::cref(m_config.hash_function()), - std::cref(m_config.key_value_equal()))); + auto const r(m_cont.equal_range(k, std::cref(m_config.hash_function()), std::cref(m_config.key_value_equal()))); return std::make_pair(iterator(r.first), iterator(r.second)); } @@ -1242,12 +1108,8 @@ public: std::pair equal_range(K const& k) const { - auto const r(m_cont.equal_range( - k, - std::cref(m_config.hash_function()), - std::cref(m_config.key_value_equal()))); - return std::make_pair( - const_iterator(r.first), const_iterator(r.second)); + auto const r(m_cont.equal_range(k, std::cref(m_config.hash_function()), std::cref(m_config.key_value_equal()))); + return std::make_pair(const_iterator(r.first), const_iterator(r.second)); } //-------------------------------------------------------------------------- @@ -1466,14 +1328,12 @@ private: // map, set template auto - insert_unchecked(value_type const& value) -> - typename std::enable_if>::type; + insert_unchecked(value_type const& value) -> typename std::enable_if>::type; // multimap, multiset template auto - insert_unchecked(value_type const& value) -> - typename std::enable_if::type; + insert_unchecked(value_type const& value) -> typename std::enable_if::type; template void @@ -1502,9 +1362,7 @@ private: template void - touch( - beast::detail::aged_container_iterator pos, - typename clock_type::time_point const& now) + touch(beast::detail::aged_container_iterator pos, typename clock_type::time_point const& now) { auto& e(*pos.iterator()); e.when = now; @@ -1512,9 +1370,7 @@ private: chronological.list.push_back(e); } - template < - bool maybe_propagate = std::allocator_traits< - Allocator>::propagate_on_container_swap::value> + template ::propagate_on_container_swap::value> typename std::enable_if::type swap_data(aged_unordered_container& other) noexcept { @@ -1523,9 +1379,7 @@ private: std::swap(m_config.clock, other.m_config.clock); } - template < - bool maybe_propagate = std::allocator_traits< - Allocator>::propagate_on_container_swap::value> + template ::propagate_on_container_swap::value> typename std::enable_if::type swap_data(aged_unordered_container& other) noexcept { @@ -1541,920 +1395,336 @@ private: //------------------------------------------------------------------------------ -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>::aged_unordered_container(clock_type& clock) - : m_config(clock) - , m_cont( - m_buck, - std::cref(m_config.value_hash()), - std::cref(m_config.key_value_equal())) +template +aged_unordered_container::aged_unordered_container( + clock_type& clock) + : m_config(clock), m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) { } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>::aged_unordered_container(clock_type& clock, Hash const& hash) - : m_config(clock, hash) - , m_cont( - m_buck, - std::cref(m_config.value_hash()), - std::cref(m_config.key_value_equal())) +template +aged_unordered_container::aged_unordered_container( + clock_type& clock, + Hash const& hash) + : m_config(clock, hash), m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) { } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>:: - aged_unordered_container(clock_type& clock, KeyEqual const& key_eq) - : m_config(clock, key_eq) - , m_cont( - m_buck, - std::cref(m_config.value_hash()), - std::cref(m_config.key_value_equal())) +template +aged_unordered_container::aged_unordered_container( + clock_type& clock, + KeyEqual const& key_eq) + : m_config(clock, key_eq), m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) { } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>:: - aged_unordered_container(clock_type& clock, Allocator const& alloc) +template +aged_unordered_container::aged_unordered_container( + clock_type& clock, + Allocator const& alloc) : m_config(clock, alloc) , m_buck(alloc) - , m_cont( - m_buck, - std::cref(m_config.value_hash()), - std::cref(m_config.key_value_equal())) + , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) { } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>:: - aged_unordered_container( - clock_type& clock, - Hash const& hash, - KeyEqual const& key_eq) +template +aged_unordered_container::aged_unordered_container( + clock_type& clock, + Hash const& hash, + KeyEqual const& key_eq) : m_config(clock, hash, key_eq) - , m_cont( - m_buck, - std::cref(m_config.value_hash()), - std::cref(m_config.key_value_equal())) + , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) { } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>:: - aged_unordered_container( - clock_type& clock, - Hash const& hash, - Allocator const& alloc) +template +aged_unordered_container::aged_unordered_container( + clock_type& clock, + Hash const& hash, + Allocator const& alloc) : m_config(clock, hash, alloc) , m_buck(alloc) - , m_cont( - m_buck, - std::cref(m_config.value_hash()), - std::cref(m_config.key_value_equal())) + , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) { } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>:: - aged_unordered_container( - clock_type& clock, - KeyEqual const& key_eq, - Allocator const& alloc) +template +aged_unordered_container::aged_unordered_container( + clock_type& clock, + KeyEqual const& key_eq, + Allocator const& alloc) : m_config(clock, key_eq, alloc) , m_buck(alloc) - , m_cont( - m_buck, - std::cref(m_config.value_hash()), - std::cref(m_config.key_value_equal())) + , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) { } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>:: - aged_unordered_container( - clock_type& clock, - Hash const& hash, - KeyEqual const& key_eq, - Allocator const& alloc) +template +aged_unordered_container::aged_unordered_container( + clock_type& clock, + Hash const& hash, + KeyEqual const& key_eq, + Allocator const& alloc) : m_config(clock, hash, key_eq, alloc) , m_buck(alloc) - , m_cont( - m_buck, - std::cref(m_config.value_hash()), - std::cref(m_config.key_value_equal())) + , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) { } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> +template template -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>:: - aged_unordered_container(InputIt first, InputIt last, clock_type& clock) - : m_config(clock) - , m_cont( - m_buck, - std::cref(m_config.value_hash()), - std::cref(m_config.key_value_equal())) +aged_unordered_container::aged_unordered_container( + InputIt first, + InputIt last, + clock_type& clock) + : m_config(clock), m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) { insert(first, last); } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> +template template -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>:: - aged_unordered_container( - InputIt first, - InputIt last, - clock_type& clock, - Hash const& hash) - : m_config(clock, hash) - , m_cont( - m_buck, - std::cref(m_config.value_hash()), - std::cref(m_config.key_value_equal())) +aged_unordered_container::aged_unordered_container( + InputIt first, + InputIt last, + clock_type& clock, + Hash const& hash) + : m_config(clock, hash), m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) { insert(first, last); } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> +template template -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>:: - aged_unordered_container( - InputIt first, - InputIt last, - clock_type& clock, - KeyEqual const& key_eq) - : m_config(clock, key_eq) - , m_cont( - m_buck, - std::cref(m_config.value_hash()), - std::cref(m_config.key_value_equal())) +aged_unordered_container::aged_unordered_container( + InputIt first, + InputIt last, + clock_type& clock, + KeyEqual const& key_eq) + : m_config(clock, key_eq), m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) { insert(first, last); } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> +template template -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>:: - aged_unordered_container( - InputIt first, - InputIt last, - clock_type& clock, - Allocator const& alloc) +aged_unordered_container::aged_unordered_container( + InputIt first, + InputIt last, + clock_type& clock, + Allocator const& alloc) : m_config(clock, alloc) , m_buck(alloc) - , m_cont( - m_buck, - std::cref(m_config.value_hash()), - std::cref(m_config.key_value_equal())) + , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) { insert(first, last); } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> +template template -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>:: - aged_unordered_container( - InputIt first, - InputIt last, - clock_type& clock, - Hash const& hash, - KeyEqual const& key_eq) +aged_unordered_container::aged_unordered_container( + InputIt first, + InputIt last, + clock_type& clock, + Hash const& hash, + KeyEqual const& key_eq) : m_config(clock, hash, key_eq) - , m_cont( - m_buck, - std::cref(m_config.value_hash()), - std::cref(m_config.key_value_equal())) + , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) { insert(first, last); } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> +template template -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>:: - aged_unordered_container( - InputIt first, - InputIt last, - clock_type& clock, - Hash const& hash, - Allocator const& alloc) +aged_unordered_container::aged_unordered_container( + InputIt first, + InputIt last, + clock_type& clock, + Hash const& hash, + Allocator const& alloc) : m_config(clock, hash, alloc) , m_buck(alloc) - , m_cont( - m_buck, - std::cref(m_config.value_hash()), - std::cref(m_config.key_value_equal())) + , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) { insert(first, last); } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> +template template -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>:: - aged_unordered_container( - InputIt first, - InputIt last, - clock_type& clock, - KeyEqual const& key_eq, - Allocator const& alloc) +aged_unordered_container::aged_unordered_container( + InputIt first, + InputIt last, + clock_type& clock, + KeyEqual const& key_eq, + Allocator const& alloc) : m_config(clock, key_eq, alloc) , m_buck(alloc) - , m_cont( - m_buck, - std::cref(m_config.value_hash()), - std::cref(m_config.key_value_equal())) + , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) { insert(first, last); } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> +template template -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>:: - aged_unordered_container( - InputIt first, - InputIt last, - clock_type& clock, - Hash const& hash, - KeyEqual const& key_eq, - Allocator const& alloc) +aged_unordered_container::aged_unordered_container( + InputIt first, + InputIt last, + clock_type& clock, + Hash const& hash, + KeyEqual const& key_eq, + Allocator const& alloc) : m_config(clock, hash, key_eq, alloc) , m_buck(alloc) - , m_cont( - m_buck, - std::cref(m_config.value_hash()), - std::cref(m_config.key_value_equal())) + , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) { insert(first, last); } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>::aged_unordered_container(aged_unordered_container const& other) +template +aged_unordered_container::aged_unordered_container( + aged_unordered_container const& other) : m_config(other.m_config) , m_buck(m_config.alloc()) - , m_cont( - m_buck, - std::cref(m_config.value_hash()), - std::cref(m_config.key_value_equal())) + , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) { insert(other.cbegin(), other.cend()); } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>:: - aged_unordered_container( - aged_unordered_container const& other, - Allocator const& alloc) +template +aged_unordered_container::aged_unordered_container( + aged_unordered_container const& other, + Allocator const& alloc) : m_config(other.m_config, alloc) , m_buck(alloc) - , m_cont( - m_buck, - std::cref(m_config.value_hash()), - std::cref(m_config.key_value_equal())) + , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) { insert(other.cbegin(), other.cend()); } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>::aged_unordered_container(aged_unordered_container&& other) - : m_config(std::move(other.m_config)) - , m_buck(std::move(other.m_buck)) - , m_cont(std::move(other.m_cont)) +template +aged_unordered_container::aged_unordered_container( + aged_unordered_container&& other) + : m_config(std::move(other.m_config)), m_buck(std::move(other.m_buck)), m_cont(std::move(other.m_cont)) { chronological.list = std::move(other.chronological.list); } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>:: - aged_unordered_container( - aged_unordered_container&& other, - Allocator const& alloc) +template +aged_unordered_container::aged_unordered_container( + aged_unordered_container&& other, + Allocator const& alloc) : m_config(std::move(other.m_config), alloc) , m_buck(alloc) - , m_cont( - m_buck, - std::cref(m_config.value_hash()), - std::cref(m_config.key_value_equal())) + , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) { insert(other.cbegin(), other.cend()); other.clear(); } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>:: - aged_unordered_container( - std::initializer_list init, - clock_type& clock) - : m_config(clock) - , m_cont( - m_buck, - std::cref(m_config.value_hash()), - std::cref(m_config.key_value_equal())) +template +aged_unordered_container::aged_unordered_container( + std::initializer_list init, + clock_type& clock) + : m_config(clock), m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) { insert(init.begin(), init.end()); } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>:: - aged_unordered_container( - std::initializer_list init, - clock_type& clock, - Hash const& hash) - : m_config(clock, hash) - , m_cont( - m_buck, - std::cref(m_config.value_hash()), - std::cref(m_config.key_value_equal())) +template +aged_unordered_container::aged_unordered_container( + std::initializer_list init, + clock_type& clock, + Hash const& hash) + : m_config(clock, hash), m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) { insert(init.begin(), init.end()); } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>:: - aged_unordered_container( - std::initializer_list init, - clock_type& clock, - KeyEqual const& key_eq) - : m_config(clock, key_eq) - , m_cont( - m_buck, - std::cref(m_config.value_hash()), - std::cref(m_config.key_value_equal())) +template +aged_unordered_container::aged_unordered_container( + std::initializer_list init, + clock_type& clock, + KeyEqual const& key_eq) + : m_config(clock, key_eq), m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) { insert(init.begin(), init.end()); } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>:: - aged_unordered_container( - std::initializer_list init, - clock_type& clock, - Allocator const& alloc) +template +aged_unordered_container::aged_unordered_container( + std::initializer_list init, + clock_type& clock, + Allocator const& alloc) : m_config(clock, alloc) , m_buck(alloc) - , m_cont( - m_buck, - std::cref(m_config.value_hash()), - std::cref(m_config.key_value_equal())) + , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) { insert(init.begin(), init.end()); } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>:: - aged_unordered_container( - std::initializer_list init, - clock_type& clock, - Hash const& hash, - KeyEqual const& key_eq) +template +aged_unordered_container::aged_unordered_container( + std::initializer_list init, + clock_type& clock, + Hash const& hash, + KeyEqual const& key_eq) : m_config(clock, hash, key_eq) - , m_cont( - m_buck, - std::cref(m_config.value_hash()), - std::cref(m_config.key_value_equal())) + , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) { insert(init.begin(), init.end()); } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>:: - aged_unordered_container( - std::initializer_list init, - clock_type& clock, - Hash const& hash, - Allocator const& alloc) +template +aged_unordered_container::aged_unordered_container( + std::initializer_list init, + clock_type& clock, + Hash const& hash, + Allocator const& alloc) : m_config(clock, hash, alloc) , m_buck(alloc) - , m_cont( - m_buck, - std::cref(m_config.value_hash()), - std::cref(m_config.key_value_equal())) + , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) { insert(init.begin(), init.end()); } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>:: - aged_unordered_container( - std::initializer_list init, - clock_type& clock, - KeyEqual const& key_eq, - Allocator const& alloc) +template +aged_unordered_container::aged_unordered_container( + std::initializer_list init, + clock_type& clock, + KeyEqual const& key_eq, + Allocator const& alloc) : m_config(clock, key_eq, alloc) , m_buck(alloc) - , m_cont( - m_buck, - std::cref(m_config.value_hash()), - std::cref(m_config.key_value_equal())) + , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) { insert(init.begin(), init.end()); } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>:: - aged_unordered_container( - std::initializer_list init, - clock_type& clock, - Hash const& hash, - KeyEqual const& key_eq, - Allocator const& alloc) +template +aged_unordered_container::aged_unordered_container( + std::initializer_list init, + clock_type& clock, + Hash const& hash, + KeyEqual const& key_eq, + Allocator const& alloc) : m_config(clock, hash, key_eq, alloc) , m_buck(alloc) - , m_cont( - m_buck, - std::cref(m_config.value_hash()), - std::cref(m_config.key_value_equal())) + , m_cont(m_buck, std::cref(m_config.value_hash()), std::cref(m_config.key_value_equal())) { insert(init.begin(), init.end()); } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>::~aged_unordered_container() +template +aged_unordered_container::~aged_unordered_container() { clear(); } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> +template auto -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>::operator=(aged_unordered_container const& other) - -> aged_unordered_container& +aged_unordered_container::operator=( + aged_unordered_container const& other) -> aged_unordered_container& { if (this != &other) { @@ -2468,26 +1738,10 @@ aged_unordered_container< return *this; } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> +template auto -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>::operator=(aged_unordered_container&& other) - -> aged_unordered_container& +aged_unordered_container::operator=( + aged_unordered_container&& other) -> aged_unordered_container& { size_type const n(other.size()); clear(); @@ -2499,26 +1753,10 @@ aged_unordered_container< return *this; } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> +template auto -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>::operator=(std::initializer_list init) - -> aged_unordered_container& +aged_unordered_container::operator=( + std::initializer_list init) -> aged_unordered_container& { clear(); insert(init); @@ -2527,100 +1765,40 @@ aged_unordered_container< //------------------------------------------------------------------------------ -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> +template template typename std::conditional::type& -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>::at(K const& k) +aged_unordered_container::at(K const& k) { - auto const iter(m_cont.find( - k, - std::cref(m_config.hash_function()), - std::cref(m_config.key_value_equal()))); + auto const iter(m_cont.find(k, std::cref(m_config.hash_function()), std::cref(m_config.key_value_equal()))); if (iter == m_cont.end()) throw std::out_of_range("key not found"); return iter->value.second; } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> +template template typename std::conditional::type const& -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>::at(K const& k) const +aged_unordered_container::at(K const& k) const { - auto const iter(m_cont.find( - k, - std::cref(m_config.hash_function()), - std::cref(m_config.key_value_equal()))); + auto const iter(m_cont.find(k, std::cref(m_config.hash_function()), std::cref(m_config.key_value_equal()))); if (iter == m_cont.end()) throw std::out_of_range("key not found"); return iter->value.second; } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> +template template typename std::conditional::type& -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>::operator[](Key const& key) +aged_unordered_container::operator[](Key const& key) { maybe_rehash(1); typename cont_type::insert_commit_data d; - auto const result(m_cont.insert_check( - key, - std::cref(m_config.hash_function()), - std::cref(m_config.key_value_equal()), - d)); + auto const result( + m_cont.insert_check(key, std::cref(m_config.hash_function()), std::cref(m_config.key_value_equal()), d)); if (result.second) { - element* const p(new_element( - std::piecewise_construct, - std::forward_as_tuple(key), - std::forward_as_tuple())); + element* const p(new_element(std::piecewise_construct, std::forward_as_tuple(key), std::forward_as_tuple())); m_cont.insert_commit(*p, d); chronological.list.push_back(*p); return p->value.second; @@ -2628,40 +1806,19 @@ aged_unordered_container< return result.first->value.second; } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> +template template typename std::conditional::type& -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>::operator[](Key&& key) +aged_unordered_container::operator[](Key&& key) { maybe_rehash(1); typename cont_type::insert_commit_data d; - auto const result(m_cont.insert_check( - key, - std::cref(m_config.hash_function()), - std::cref(m_config.key_value_equal()), - d)); + auto const result( + m_cont.insert_check(key, std::cref(m_config.hash_function()), std::cref(m_config.key_value_equal()), d)); if (result.second) { - element* const p(new_element( - std::piecewise_construct, - std::forward_as_tuple(std::move(key)), - std::forward_as_tuple())); + element* const p( + new_element(std::piecewise_construct, std::forward_as_tuple(std::move(key)), std::forward_as_tuple())); m_cont.insert_commit(*p, d); chronological.list.push_back(*p); return p->value.second; @@ -2671,28 +1828,11 @@ aged_unordered_container< //------------------------------------------------------------------------------ -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> +template void -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>::clear() +aged_unordered_container::clear() { - for (auto iter(chronological.list.begin()); - iter != chronological.list.end();) + for (auto iter(chronological.list.begin()); iter != chronological.list.end();) unlink_and_delete_element(&*iter++); chronological.list.clear(); m_cont.clear(); @@ -2700,35 +1840,16 @@ aged_unordered_container< } // map, set -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> +template template auto -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>::insert(value_type const& value) -> +aged_unordered_container::insert(value_type const& value) -> typename std::enable_if>::type { maybe_rehash(1); typename cont_type::insert_commit_data d; auto const result(m_cont.insert_check( - extract(value), - std::cref(m_config.hash_function()), - std::cref(m_config.key_value_equal()), - d)); + extract(value), std::cref(m_config.hash_function()), std::cref(m_config.key_value_equal()), d)); if (result.second) { element* const p(new_element(value)); @@ -2740,26 +1861,10 @@ aged_unordered_container< } // multimap, multiset -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> +template template auto -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>::insert(value_type const& value) -> +aged_unordered_container::insert(value_type const& value) -> typename std::enable_if::type { maybe_rehash(1); @@ -2770,36 +1875,16 @@ aged_unordered_container< } // map, set -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> +template template auto -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>::insert(value_type&& value) -> - typename std:: - enable_if>::type +aged_unordered_container::insert(value_type&& value) -> + typename std::enable_if>::type { maybe_rehash(1); typename cont_type::insert_commit_data d; auto const result(m_cont.insert_check( - extract(value), - std::cref(m_config.hash_function()), - std::cref(m_config.key_value_equal()), - d)); + extract(value), std::cref(m_config.hash_function()), std::cref(m_config.key_value_equal()), d)); if (result.second) { element* const p(new_element(std::move(value))); @@ -2811,26 +1896,10 @@ aged_unordered_container< } // multimap, multiset -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> +template template auto -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>::insert(value_type&& value) -> +aged_unordered_container::insert(value_type&& value) -> typename std::enable_if::type { maybe_rehash(1); @@ -2842,26 +1911,10 @@ aged_unordered_container< #if 1 // Use insert() instead of insert_check() insert_commit() // set, map -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> +template template auto -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>::emplace(Args&&... args) -> +aged_unordered_container::emplace(Args&&... args) -> typename std::enable_if>::type { maybe_rehash(1); @@ -2879,26 +1932,10 @@ aged_unordered_container< } #else // As original, use insert_check() / insert_commit () pair. // set, map -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> +template template auto -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>::emplace(Args&&... args) -> +aged_unordered_container::emplace(Args&&... args) -> typename std::enable_if>::type { maybe_rehash(1); @@ -2907,10 +1944,7 @@ aged_unordered_container< element* const p(new_element(std::forward(args)...)); typename cont_type::insert_commit_data d; auto const result(m_cont.insert_check( - extract(p->value), - std::cref(m_config.hash_function()), - std::cref(m_config.key_value_equal()), - d)); + extract(p->value), std::cref(m_config.hash_function()), std::cref(m_config.key_value_equal()), d)); if (result.second) { auto const iter(m_cont.insert_commit(*p, d)); @@ -2923,26 +1957,10 @@ aged_unordered_container< #endif // 0 // multiset, multimap -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> +template template auto -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>::emplace(Args&&... args) -> +aged_unordered_container::emplace(Args&&... args) -> typename std::enable_if::type { maybe_rehash(1); @@ -2953,27 +1971,12 @@ aged_unordered_container< } // set, map -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> +template template auto -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>::emplace_hint(const_iterator /*hint*/, Args&&... args) -> - typename std::enable_if>::type +aged_unordered_container::emplace_hint( + const_iterator /*hint*/, + Args&&... args) -> typename std::enable_if>::type { maybe_rehash(1); // VFALCO NOTE Its unfortunate that we need to @@ -2981,10 +1984,7 @@ aged_unordered_container< element* const p(new_element(std::forward(args)...)); typename cont_type::insert_commit_data d; auto const result(m_cont.insert_check( - extract(p->value), - std::cref(m_config.hash_function()), - std::cref(m_config.key_value_equal()), - d)); + extract(p->value), std::cref(m_config.hash_function()), std::cref(m_config.key_value_equal()), d)); if (result.second) { auto const iter(m_cont.insert_commit(*p, d)); @@ -2995,89 +1995,35 @@ aged_unordered_container< return std::make_pair(iterator(result.first), false); } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> +template template beast::detail::aged_container_iterator -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>::erase(beast::detail::aged_container_iterator - pos) +aged_unordered_container::erase( + beast::detail::aged_container_iterator pos) { unlink_and_delete_element(&*((pos++).iterator())); - return beast::detail::aged_container_iterator( - pos.iterator()); + return beast::detail::aged_container_iterator(pos.iterator()); } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> +template template beast::detail::aged_container_iterator -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>:: - erase( - beast::detail::aged_container_iterator first, - beast::detail::aged_container_iterator last) +aged_unordered_container::erase( + beast::detail::aged_container_iterator first, + beast::detail::aged_container_iterator last) { for (; first != last;) unlink_and_delete_element(&*((first++).iterator())); - return beast::detail::aged_container_iterator( - first.iterator()); + return beast::detail::aged_container_iterator(first.iterator()); } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> +template template auto -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>::erase(K const& k) -> size_type +aged_unordered_container::erase(K const& k) -> size_type { - auto iter(m_cont.find( - k, - std::cref(m_config.hash_function()), - std::cref(m_config.key_value_equal()))); + auto iter(m_cont.find(k, std::cref(m_config.hash_function()), std::cref(m_config.key_value_equal()))); if (iter == m_cont.end()) return 0; size_type n(0); @@ -3093,51 +2039,20 @@ aged_unordered_container< return n; } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> +template void -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>::swap(aged_unordered_container& other) noexcept +aged_unordered_container::swap( + aged_unordered_container& other) noexcept { swap_data(other); std::swap(chronological, other.chronological); std::swap(m_cont, other.m_cont); } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> +template template auto -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>::touch(K const& k) -> size_type +aged_unordered_container::touch(K const& k) -> size_type { auto const now(clock().now()); size_type n(0); @@ -3150,15 +2065,7 @@ aged_unordered_container< return n; } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> +template template < bool OtherIsMap, class OtherKey, @@ -3168,30 +2075,20 @@ template < class OtherAllocator, bool maybe_multi> typename std::enable_if::type -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>:: -operator==(aged_unordered_container< - false, - OtherIsMap, - OtherKey, - OtherT, - OtherDuration, - OtherHash, - KeyEqual, - OtherAllocator> const& other) const +aged_unordered_container::operator==( + aged_unordered_container< + false, + OtherIsMap, + OtherKey, + OtherT, + OtherDuration, + OtherHash, + KeyEqual, + OtherAllocator> const& other) const { if (size() != other.size()) return false; - for (auto iter(cbegin()), last(cend()), otherLast(other.cend()); - iter != last; - ++iter) + for (auto iter(cbegin()), last(cend()), otherLast(other.cend()); iter != last; ++iter) { auto otherIter(other.find(extract(*iter))); if (otherIter == otherLast) @@ -3200,15 +2097,7 @@ operator==(aged_unordered_container< return true; } -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> +template template < bool OtherIsMap, class OtherKey, @@ -3218,24 +2107,16 @@ template < class OtherAllocator, bool maybe_multi> typename std::enable_if::type -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>:: -operator==(aged_unordered_container< - true, - OtherIsMap, - OtherKey, - OtherT, - OtherDuration, - OtherHash, - KeyEqual, - OtherAllocator> const& other) const +aged_unordered_container::operator==( + aged_unordered_container< + true, + OtherIsMap, + OtherKey, + OtherT, + OtherDuration, + OtherHash, + KeyEqual, + OtherAllocator> const& other) const { if (size() != other.size()) return false; @@ -3245,8 +2126,7 @@ operator==(aged_unordered_container< auto const eq(equal_range(k)); auto const oeq(other.equal_range(k)); #if BEAST_NO_CXX14_IS_PERMUTATION - if (std::distance(eq.first, eq.second) != - std::distance(oeq.first, oeq.second) || + if (std::distance(eq.first, eq.second) != std::distance(oeq.first, oeq.second) || !std::is_permutation(eq.first, eq.second, oeq.first)) return false; #else @@ -3261,34 +2141,15 @@ operator==(aged_unordered_container< //------------------------------------------------------------------------------ // map, set -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> +template template auto -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>::insert_unchecked(value_type const& value) -> - typename std::enable_if>::type +aged_unordered_container::insert_unchecked( + value_type const& value) -> typename std::enable_if>::type { typename cont_type::insert_commit_data d; auto const result(m_cont.insert_check( - extract(value), - std::cref(m_config.hash_function()), - std::cref(m_config.key_value_equal()), - d)); + extract(value), std::cref(m_config.hash_function()), std::cref(m_config.key_value_equal()), d)); if (result.second) { element* const p(new_element(value)); @@ -3300,27 +2161,11 @@ aged_unordered_container< } // multimap, multiset -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> +template template auto -aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>::insert_unchecked(value_type const& value) -> - typename std::enable_if::type +aged_unordered_container::insert_unchecked( + value_type const& value) -> typename std::enable_if::type { element* const p(new_element(value)); chronological.list.push_back(*p); @@ -3334,59 +2179,20 @@ aged_unordered_container< //------------------------------------------------------------------------------ -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> -struct is_aged_container> : std::true_type +template +struct is_aged_container< + beast::detail::aged_unordered_container> : std::true_type { explicit is_aged_container() = default; }; // Free functions -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock, - class Hash, - class KeyEqual, - class Allocator> +template void swap( - beast::detail::aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>& lhs, - beast::detail::aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>& rhs) noexcept + beast::detail::aged_unordered_container& lhs, + beast::detail::aged_unordered_container& rhs) noexcept { lhs.swap(rhs); } @@ -3405,21 +2211,12 @@ template < class Period> std::size_t expire( - beast::detail::aged_unordered_container< - IsMulti, - IsMap, - Key, - T, - Clock, - Hash, - KeyEqual, - Allocator>& c, + beast::detail::aged_unordered_container& c, std::chrono::duration const& age) noexcept { std::size_t n(0); auto const expired(c.clock().now() - age); - for (auto iter(c.chronological.cbegin()); - iter != c.chronological.cend() && iter.when() <= expired;) + for (auto iter(c.chronological.cbegin()); iter != c.chronological.cend() && iter.when() <= expired;) { iter = c.erase(iter); ++n; @@ -3428,5 +2225,3 @@ expire( } } // namespace beast - -#endif diff --git a/include/xrpl/beast/container/detail/empty_base_optimization.h b/include/xrpl/beast/container/detail/empty_base_optimization.h index 30f87a9bd2..21a9d13ce8 100644 --- a/include/xrpl/beast/container/detail/empty_base_optimization.h +++ b/include/xrpl/beast/container/detail/empty_base_optimization.h @@ -4,8 +4,7 @@ // Official repository: https://github.com/boostorg/beast // -#ifndef BEAST_CONTAINER_DETAIL_EMPTY_BASE_OPTIMIZATION_H_INCLUDED -#define BEAST_CONTAINER_DETAIL_EMPTY_BASE_OPTIMIZATION_H_INCLUDED +#pragma once #include @@ -17,16 +16,11 @@ namespace detail { template struct is_empty_base_optimization_derived - : std::integral_constant< - bool, - std::is_empty::value && !boost::is_final::value> + : std::integral_constant::value && !boost::is_final::value> { }; -template < - class T, - int UniqueID = 0, - bool isDerived = is_empty_base_optimization_derived::value> +template ::value> class empty_base_optimization : private T { public: @@ -94,5 +88,3 @@ public: } // namespace detail } // namespace beast - -#endif diff --git a/include/xrpl/beast/core/CurrentThreadName.h b/include/xrpl/beast/core/CurrentThreadName.h index 703246a76a..8e99ee90da 100644 --- a/include/xrpl/beast/core/CurrentThreadName.h +++ b/include/xrpl/beast/core/CurrentThreadName.h @@ -2,8 +2,7 @@ // Copyright (c) 2013 - Raw Material Software Ltd. // Please visit http://www.juce.com -#ifndef BEAST_CORE_CURRENT_THREAD_NAME_H_INCLUDED -#define BEAST_CORE_CURRENT_THREAD_NAME_H_INCLUDED +#pragma once #include @@ -35,9 +34,7 @@ template void setCurrentThreadName(char const (&newThreadName)[N]) { - static_assert( - N <= maxThreadNameLength + 1, - "Thread name cannot exceed 15 characters"); + static_assert(N <= maxThreadNameLength + 1, "Thread name cannot exceed 15 characters"); setCurrentThreadName(std::string_view(newThreadName, N - 1)); } @@ -55,5 +52,3 @@ std::string getCurrentThreadName(); } // namespace beast - -#endif diff --git a/include/xrpl/beast/core/LexicalCast.h b/include/xrpl/beast/core/LexicalCast.h index c5b7f5540a..a7c135f23f 100644 --- a/include/xrpl/beast/core/LexicalCast.h +++ b/include/xrpl/beast/core/LexicalCast.h @@ -1,5 +1,4 @@ -#ifndef BEAST_MODULE_CORE_TEXT_LEXICALCAST_H_INCLUDED -#define BEAST_MODULE_CORE_TEXT_LEXICALCAST_H_INCLUDED +#pragma once #include @@ -40,8 +39,7 @@ struct LexicalCast std::enable_if_t, bool> operator()(std::string& out, Enumeration in) { - out = std::to_string( - static_cast>(in)); + out = std::to_string(static_cast>(in)); return true; } }; @@ -52,14 +50,10 @@ struct LexicalCast { explicit LexicalCast() = default; - static_assert( - std::is_integral_v, - "beast::LexicalCast can only be used with integral types"); + static_assert(std::is_integral_v, "beast::LexicalCast can only be used with integral types"); template - std::enable_if_t< - std::is_integral_v && !std::is_same_v, - bool> + std::enable_if_t && !std::is_same_v, bool> operator()(Integral& out, std::string_view in) const { auto first = in.data(); @@ -79,10 +73,9 @@ struct LexicalCast std::string result; // Convert the input to lowercase - std::transform( - in.begin(), in.end(), std::back_inserter(result), [](auto c) { - return std::tolower(static_cast(c)); - }); + std::transform(in.begin(), in.end(), std::back_inserter(result), [](auto c) { + return std::tolower(static_cast(c)); + }); if (result == "1" || result == "true") { @@ -140,8 +133,7 @@ struct LexicalCast bool operator()(Out& out, char const* in) const { - XRPL_ASSERT( - in, "beast::detail::LexicalCast(char const*) : non-null input"); + XRPL_ASSERT(in, "beast::detail::LexicalCast(char const*) : non-null input"); return LexicalCast()(out, in); } }; @@ -215,5 +207,3 @@ lexicalCast(In in, Out defaultValue = Out()) } } // namespace beast - -#endif diff --git a/include/xrpl/beast/core/List.h b/include/xrpl/beast/core/List.h index 9ea7994ffc..75c981ea1b 100644 --- a/include/xrpl/beast/core/List.h +++ b/include/xrpl/beast/core/List.h @@ -1,5 +1,4 @@ -#ifndef BEAST_INTRUSIVE_LIST_H_INCLUDED -#define BEAST_INTRUSIVE_LIST_H_INCLUDED +#pragma once #include @@ -55,8 +54,7 @@ class ListIterator { public: using iterator_category = std::bidirectional_iterator_tag; - using value_type = - typename beast::detail::CopyConst::type; + using value_type = typename beast::detail::CopyConst::type; using difference_type = std::ptrdiff_t; using pointer = value_type*; using reference = value_type&; @@ -575,5 +573,3 @@ private: }; } // namespace beast - -#endif diff --git a/include/xrpl/beast/core/LockFreeStack.h b/include/xrpl/beast/core/LockFreeStack.h index 0d64667a76..bb32698dd8 100644 --- a/include/xrpl/beast/core/LockFreeStack.h +++ b/include/xrpl/beast/core/LockFreeStack.h @@ -1,5 +1,4 @@ -#ifndef BEAST_INTRUSIVE_LOCKFREESTACK_H_INCLUDED -#define BEAST_INTRUSIVE_LOCKFREESTACK_H_INCLUDED +#pragma once #include #include @@ -14,21 +13,16 @@ class LockFreeStackIterator { protected: using Node = typename Container::Node; - using NodePtr = - typename std::conditional::type; + using NodePtr = typename std::conditional::type; public: using iterator_category = std::forward_iterator_tag; using value_type = typename Container::value_type; using difference_type = typename Container::difference_type; - using pointer = typename std::conditional< - IsConst, - typename Container::const_pointer, - typename Container::pointer>::type; - using reference = typename std::conditional< - IsConst, - typename Container::const_reference, - typename Container::reference>::type; + using pointer = + typename std::conditional::type; + using reference = + typename std::conditional::type; LockFreeStackIterator() : m_node() { @@ -39,9 +33,7 @@ public: } template - explicit LockFreeStackIterator( - LockFreeStackIterator const& other) - : m_node(other.m_node) + explicit LockFreeStackIterator(LockFreeStackIterator const& other) : m_node(other.m_node) { } @@ -160,8 +152,7 @@ public: using size_type = std::size_t; using difference_type = std::ptrdiff_t; using iterator = LockFreeStackIterator, false>; - using const_iterator = - LockFreeStackIterator, true>; + using const_iterator = LockFreeStackIterator, true>; LockFreeStack() : m_end(nullptr), m_head(&m_end) { @@ -199,11 +190,7 @@ public: { first = (old_head == &m_end); node->m_next = old_head; - } while (!m_head.compare_exchange_strong( - old_head, - node, - std::memory_order_release, - std::memory_order_relaxed)); + } while (!m_head.compare_exchange_strong(old_head, node, std::memory_order_release, std::memory_order_relaxed)); return first; } @@ -226,11 +213,7 @@ public: if (node == &m_end) return nullptr; new_head = node->m_next.load(); - } while (!m_head.compare_exchange_strong( - node, - new_head, - std::memory_order_release, - std::memory_order_relaxed)); + } while (!m_head.compare_exchange_strong(node, new_head, std::memory_order_release, std::memory_order_relaxed)); return static_cast(node); } @@ -284,5 +267,3 @@ private: }; } // namespace beast - -#endif diff --git a/include/xrpl/beast/core/SemanticVersion.h b/include/xrpl/beast/core/SemanticVersion.h index fabda8290f..1d3525de25 100644 --- a/include/xrpl/beast/core/SemanticVersion.h +++ b/include/xrpl/beast/core/SemanticVersion.h @@ -1,5 +1,4 @@ -#ifndef BEAST_MODULE_CORE_DIAGNOSTIC_SEMANTICVERSION_H_INCLUDED -#define BEAST_MODULE_CORE_DIAGNOSTIC_SEMANTICVERSION_H_INCLUDED +#pragma once #include #include @@ -95,5 +94,3 @@ operator<(SemanticVersion const& lhs, SemanticVersion const& rhs) } } // namespace beast - -#endif diff --git a/include/xrpl/beast/hash/hash_append.h b/include/xrpl/beast/hash/hash_append.h index 28444a1280..e4d646e532 100644 --- a/include/xrpl/beast/hash/hash_append.h +++ b/include/xrpl/beast/hash/hash_append.h @@ -1,5 +1,4 @@ -#ifndef BEAST_HASH_HASH_APPEND_H_INCLUDED -#define BEAST_HASH_HASH_APPEND_H_INCLUDED +#pragma once #include #include @@ -27,8 +26,7 @@ template inline void reverse_bytes(T& t) { - unsigned char* bytes = static_cast( - std::memmove(std::addressof(t), std::addressof(t), sizeof(T))); + unsigned char* bytes = static_cast(std::memmove(std::addressof(t), std::addressof(t), sizeof(T))); for (unsigned i = 0; i < sizeof(T) / 2; ++i) std::swap(bytes[i], bytes[sizeof(T) - 1 - i]); } @@ -53,11 +51,7 @@ template inline void maybe_reverse_bytes(T& t, Hasher&) { - maybe_reverse_bytes( - t, - std::integral_constant< - bool, - Hasher::endian != boost::endian::order::native>{}); + maybe_reverse_bytes(t, std::integral_constant{}); } } // namespace detail @@ -71,10 +65,8 @@ maybe_reverse_bytes(T& t, Hasher&) template struct is_uniquely_represented - : public std::integral_constant< - bool, - std::is_integral::value || std::is_enum::value || - std::is_pointer::value> + : public std:: + integral_constant::value || std::is_enum::value || std::is_pointer::value> { explicit is_uniquely_represented() = default; }; @@ -92,8 +84,7 @@ struct is_uniquely_represented : public is_uniquely_represented }; template -struct is_uniquely_represented - : public is_uniquely_represented +struct is_uniquely_represented : public is_uniquely_represented { explicit is_uniquely_represented() = default; }; @@ -104,8 +95,7 @@ template struct is_uniquely_represented> : public std::integral_constant< bool, - is_uniquely_represented::value && - is_uniquely_represented::value && + is_uniquely_represented::value && is_uniquely_represented::value && sizeof(T) + sizeof(U) == sizeof(std::pair)> { explicit is_uniquely_represented() = default; @@ -117,8 +107,7 @@ template struct is_uniquely_represented> : public std::integral_constant< bool, - std::conjunction_v...> && - sizeof(std::tuple) == (sizeof(T) + ...)> + std::conjunction_v...> && sizeof(std::tuple) == (sizeof(T) + ...)> { explicit is_uniquely_represented() = default; }; @@ -135,10 +124,8 @@ struct is_uniquely_represented : public is_uniquely_represented template struct is_uniquely_represented> - : public std::integral_constant< - bool, - is_uniquely_represented::value && - sizeof(T) * N == sizeof(std::array)> + : public std:: + integral_constant::value && sizeof(T) * N == sizeof(std::array)> { explicit is_uniquely_represented() = default; }; @@ -158,12 +145,10 @@ struct is_uniquely_represented> */ /** @{ */ template -struct is_contiguously_hashable - : public std::integral_constant< - bool, - is_uniquely_represented::value && - (sizeof(T) == 1 || - HashAlgorithm::endian == boost::endian::order::native)> +struct is_contiguously_hashable : public std::integral_constant< + bool, + is_uniquely_represented::value && + (sizeof(T) == 1 || HashAlgorithm::endian == boost::endian::order::native)> { explicit is_contiguously_hashable() = default; }; @@ -173,8 +158,7 @@ struct is_contiguously_hashable : public std::integral_constant< bool, is_uniquely_represented::value && - (sizeof(T) == 1 || - HashAlgorithm::endian == boost::endian::order::native)> + (sizeof(T) == 1 || HashAlgorithm::endian == boost::endian::order::native)> { explicit is_contiguously_hashable() = default; }; @@ -219,8 +203,7 @@ hash_append(Hasher& h, T const& t) noexcept template inline std::enable_if_t< !is_contiguously_hashable::value && - (std::is_integral::value || std::is_pointer::value || - std::is_enum::value)> + (std::is_integral::value || std::is_pointer::value || std::is_enum::value)> hash_append(Hasher& h, T t) noexcept { detail::reverse_bytes(t); @@ -254,15 +237,11 @@ hash_append(Hasher& h, T (&a)[N]) noexcept; template std::enable_if_t::value> -hash_append( - Hasher& h, - std::basic_string const& s) noexcept; +hash_append(Hasher& h, std::basic_string const& s) noexcept; template std::enable_if_t::value> -hash_append( - Hasher& h, - std::basic_string const& s) noexcept; +hash_append(Hasher& h, std::basic_string const& s) noexcept; template std::enable_if_t, Hasher>::value> @@ -294,14 +273,10 @@ hash_append(Hasher& h, std::unordered_set const& s); template std::enable_if_t::value> -hash_append( - Hasher& h, - boost::container::flat_set const& v) noexcept; +hash_append(Hasher& h, boost::container::flat_set const& v) noexcept; template std::enable_if_t::value> -hash_append( - Hasher& h, - boost::container::flat_set const& v) noexcept; +hash_append(Hasher& h, boost::container::flat_set const& v) noexcept; template void hash_append(Hasher& h, T0 const& t0, T1 const& t1, T const&... t) noexcept; @@ -320,9 +295,7 @@ hash_append(Hasher& h, T (&a)[N]) noexcept template inline std::enable_if_t::value> -hash_append( - Hasher& h, - std::basic_string const& s) noexcept +hash_append(Hasher& h, std::basic_string const& s) noexcept { for (auto c : s) hash_append(h, c); @@ -331,9 +304,7 @@ hash_append( template inline std::enable_if_t::value> -hash_append( - Hasher& h, - std::basic_string const& s) noexcept +hash_append(Hasher& h, std::basic_string const& s) noexcept { h(s.data(), s.size() * sizeof(CharT)); hash_append(h, s.size()); @@ -342,8 +313,7 @@ hash_append( // pair template -inline std::enable_if_t< - !is_contiguously_hashable, Hasher>::value> +inline std::enable_if_t, Hasher>::value> hash_append(Hasher& h, std::pair const& p) noexcept { hash_append(h, p.first, p.second); @@ -380,18 +350,14 @@ hash_append(Hasher& h, std::array const& a) noexcept template std::enable_if_t::value> -hash_append( - Hasher& h, - boost::container::flat_set const& v) noexcept +hash_append(Hasher& h, boost::container::flat_set const& v) noexcept { for (auto const& t : v) hash_append(h, t); } template std::enable_if_t::value> -hash_append( - Hasher& h, - boost::container::flat_set const& v) noexcept +hash_append(Hasher& h, boost::container::flat_set const& v) noexcept { h(&(v.begin()), v.size() * sizeof(Key)); } @@ -414,10 +380,7 @@ hash_one(Hasher& h, T const& t) noexcept template inline void -tuple_hash( - Hasher& h, - std::tuple const& t, - std::index_sequence) noexcept +tuple_hash(Hasher& h, std::tuple const& t, std::index_sequence) noexcept { for_each_item(hash_one(h, std::get(t))...); } @@ -425,8 +388,7 @@ tuple_hash( } // namespace detail template -inline std::enable_if_t< - !is_contiguously_hashable, Hasher>::value> +inline std::enable_if_t, Hasher>::value> hash_append(Hasher& h, std::tuple const& t) noexcept { detail::tuple_hash(h, t, std::index_sequence_for{}); @@ -452,9 +414,7 @@ hash_append(Hasher& h, std::chrono::duration const& d) noexcept template inline void -hash_append( - Hasher& h, - std::chrono::time_point const& tp) noexcept +hash_append(Hasher& h, std::chrono::time_point const& tp) noexcept { hash_append(h, tp.time_since_epoch()); } @@ -479,5 +439,3 @@ hash_append(HashAlgorithm& h, std::error_code const& ec) } } // namespace beast - -#endif diff --git a/include/xrpl/beast/hash/uhash.h b/include/xrpl/beast/hash/uhash.h index c167412e3a..4f66f058a8 100644 --- a/include/xrpl/beast/hash/uhash.h +++ b/include/xrpl/beast/hash/uhash.h @@ -1,5 +1,4 @@ -#ifndef BEAST_HASH_UHASH_H_INCLUDED -#define BEAST_HASH_UHASH_H_INCLUDED +#pragma once #include #include @@ -25,5 +24,3 @@ struct uhash }; } // namespace beast - -#endif diff --git a/include/xrpl/beast/hash/xxhasher.h b/include/xrpl/beast/hash/xxhasher.h index 67169f85ec..473907ea89 100644 --- a/include/xrpl/beast/hash/xxhasher.h +++ b/include/xrpl/beast/hash/xxhasher.h @@ -1,5 +1,4 @@ -#ifndef BEAST_HASH_XXHASHER_H_INCLUDED -#define BEAST_HASH_XXHASHER_H_INCLUDED +#pragma once #include @@ -49,8 +48,7 @@ private: { std::memcpy(writeBuffer_.data(), data, len); writeBuffer_ = writeBuffer_.subspan(len); - readBuffer_ = std::span{ - std::begin(buffer_), buffer_.size() - writeBuffer_.size()}; + readBuffer_ = std::span{std::begin(buffer_), buffer_.size() - writeBuffer_.size()}; } } @@ -98,8 +96,7 @@ private: { if (seed_.has_value()) { - return XXH3_64bits_withSeed( - readBuffer_.data(), readBuffer_.size(), *seed_); + return XXH3_64bits_withSeed(readBuffer_.data(), readBuffer_.size(), *seed_); } else { @@ -128,17 +125,13 @@ public: } } - template < - class Seed, - std::enable_if_t::value>* = nullptr> + template ::value>* = nullptr> explicit xxhasher(Seed seed) : seed_(seed) { resetBuffers(); } - template < - class Seed, - std::enable_if_t::value>* = nullptr> + template ::value>* = nullptr> xxhasher(Seed seed, Seed) : seed_(seed) { resetBuffers(); @@ -158,5 +151,3 @@ public: }; } // namespace beast - -#endif diff --git a/include/xrpl/beast/insight/Collector.h b/include/xrpl/beast/insight/Collector.h index 045d9003a9..89aa8c1cb5 100644 --- a/include/xrpl/beast/insight/Collector.h +++ b/include/xrpl/beast/insight/Collector.h @@ -1,5 +1,4 @@ -#ifndef BEAST_INSIGHT_COLLECTOR_H_INCLUDED -#define BEAST_INSIGHT_COLLECTOR_H_INCLUDED +#pragma once #include #include @@ -120,5 +119,3 @@ public: } // namespace insight } // namespace beast - -#endif diff --git a/include/xrpl/beast/insight/Counter.h b/include/xrpl/beast/insight/Counter.h index e1b8c36545..f6722c4e03 100644 --- a/include/xrpl/beast/insight/Counter.h +++ b/include/xrpl/beast/insight/Counter.h @@ -1,5 +1,4 @@ -#ifndef BEAST_INSIGHT_COUNTER_H_INCLUDED -#define BEAST_INSIGHT_COUNTER_H_INCLUDED +#pragma once #include @@ -94,5 +93,3 @@ private: } // namespace insight } // namespace beast - -#endif diff --git a/include/xrpl/beast/insight/CounterImpl.h b/include/xrpl/beast/insight/CounterImpl.h index 409cfe07a7..199315dcb8 100644 --- a/include/xrpl/beast/insight/CounterImpl.h +++ b/include/xrpl/beast/insight/CounterImpl.h @@ -1,5 +1,4 @@ -#ifndef BEAST_INSIGHT_COUNTERIMPL_H_INCLUDED -#define BEAST_INSIGHT_COUNTERIMPL_H_INCLUDED +#pragma once #include #include @@ -21,5 +20,3 @@ public: } // namespace insight } // namespace beast - -#endif diff --git a/include/xrpl/beast/insight/Event.h b/include/xrpl/beast/insight/Event.h index c375c34f9c..bc0c0dd403 100644 --- a/include/xrpl/beast/insight/Event.h +++ b/include/xrpl/beast/insight/Event.h @@ -1,5 +1,4 @@ -#ifndef BEAST_INSIGHT_EVENT_H_INCLUDED -#define BEAST_INSIGHT_EVENT_H_INCLUDED +#pragma once #include @@ -61,5 +60,3 @@ private: } // namespace insight } // namespace beast - -#endif diff --git a/include/xrpl/beast/insight/EventImpl.h b/include/xrpl/beast/insight/EventImpl.h index cec378e71e..abd9741511 100644 --- a/include/xrpl/beast/insight/EventImpl.h +++ b/include/xrpl/beast/insight/EventImpl.h @@ -1,5 +1,4 @@ -#ifndef BEAST_INSIGHT_EVENTIMPL_H_INCLUDED -#define BEAST_INSIGHT_EVENTIMPL_H_INCLUDED +#pragma once #include #include @@ -21,5 +20,3 @@ public: } // namespace insight } // namespace beast - -#endif diff --git a/include/xrpl/beast/insight/Gauge.h b/include/xrpl/beast/insight/Gauge.h index c9c1b64cda..f2a88deda2 100644 --- a/include/xrpl/beast/insight/Gauge.h +++ b/include/xrpl/beast/insight/Gauge.h @@ -1,5 +1,4 @@ -#ifndef BEAST_INSIGHT_GAUGE_H_INCLUDED -#define BEAST_INSIGHT_GAUGE_H_INCLUDED +#pragma once #include @@ -124,5 +123,3 @@ private: } // namespace insight } // namespace beast - -#endif diff --git a/include/xrpl/beast/insight/GaugeImpl.h b/include/xrpl/beast/insight/GaugeImpl.h index c20d93744d..29afbe6a4d 100644 --- a/include/xrpl/beast/insight/GaugeImpl.h +++ b/include/xrpl/beast/insight/GaugeImpl.h @@ -1,5 +1,4 @@ -#ifndef BEAST_INSIGHT_GAUGEIMPL_H_INCLUDED -#define BEAST_INSIGHT_GAUGEIMPL_H_INCLUDED +#pragma once #include #include @@ -24,5 +23,3 @@ public: } // namespace insight } // namespace beast - -#endif diff --git a/include/xrpl/beast/insight/Group.h b/include/xrpl/beast/insight/Group.h index 8119b4004f..c85fd1bfb6 100644 --- a/include/xrpl/beast/insight/Group.h +++ b/include/xrpl/beast/insight/Group.h @@ -1,5 +1,4 @@ -#ifndef BEAST_INSIGHT_GROUP_H_INCLUDED -#define BEAST_INSIGHT_GROUP_H_INCLUDED +#pragma once #include @@ -22,5 +21,3 @@ public: } // namespace insight } // namespace beast - -#endif diff --git a/include/xrpl/beast/insight/Groups.h b/include/xrpl/beast/insight/Groups.h index 2fc996fcf8..8ac93454d3 100644 --- a/include/xrpl/beast/insight/Groups.h +++ b/include/xrpl/beast/insight/Groups.h @@ -1,5 +1,4 @@ -#ifndef BEAST_INSIGHT_GROUPS_H_INCLUDED -#define BEAST_INSIGHT_GROUPS_H_INCLUDED +#pragma once #include #include @@ -35,5 +34,3 @@ make_Groups(Collector::ptr const& collector); } // namespace insight } // namespace beast - -#endif diff --git a/include/xrpl/beast/insight/Hook.h b/include/xrpl/beast/insight/Hook.h index 1dc4cd0c74..ea511862d9 100644 --- a/include/xrpl/beast/insight/Hook.h +++ b/include/xrpl/beast/insight/Hook.h @@ -1,5 +1,4 @@ -#ifndef BEAST_INSIGHT_HOOK_H_INCLUDED -#define BEAST_INSIGHT_HOOK_H_INCLUDED +#pragma once #include @@ -40,5 +39,3 @@ private: } // namespace insight } // namespace beast - -#endif diff --git a/include/xrpl/beast/insight/HookImpl.h b/include/xrpl/beast/insight/HookImpl.h index dadbc6d106..18208b554a 100644 --- a/include/xrpl/beast/insight/HookImpl.h +++ b/include/xrpl/beast/insight/HookImpl.h @@ -1,5 +1,4 @@ -#ifndef BEAST_INSIGHT_HOOKIMPL_H_INCLUDED -#define BEAST_INSIGHT_HOOKIMPL_H_INCLUDED +#pragma once #include #include @@ -17,5 +16,3 @@ public: } // namespace insight } // namespace beast - -#endif diff --git a/include/xrpl/beast/insight/Insight.h b/include/xrpl/beast/insight/Insight.h index c298510291..bf3743cfd8 100644 --- a/include/xrpl/beast/insight/Insight.h +++ b/include/xrpl/beast/insight/Insight.h @@ -1,5 +1,4 @@ -#ifndef BEAST_INSIGHT_H_INCLUDED -#define BEAST_INSIGHT_H_INCLUDED +#pragma once #include #include @@ -14,5 +13,3 @@ #include #include #include - -#endif diff --git a/include/xrpl/beast/insight/Meter.h b/include/xrpl/beast/insight/Meter.h index 34aa4c59d4..193a1f1003 100644 --- a/include/xrpl/beast/insight/Meter.h +++ b/include/xrpl/beast/insight/Meter.h @@ -1,5 +1,4 @@ -#ifndef BEAST_INSIGHT_METER_H_INCLUDED -#define BEAST_INSIGHT_METER_H_INCLUDED +#pragma once #include @@ -79,5 +78,3 @@ private: } // namespace insight } // namespace beast - -#endif diff --git a/include/xrpl/beast/insight/MeterImpl.h b/include/xrpl/beast/insight/MeterImpl.h index c50dc07295..22efdbe647 100644 --- a/include/xrpl/beast/insight/MeterImpl.h +++ b/include/xrpl/beast/insight/MeterImpl.h @@ -1,5 +1,4 @@ -#ifndef BEAST_INSIGHT_METERIMPL_H_INCLUDED -#define BEAST_INSIGHT_METERIMPL_H_INCLUDED +#pragma once #include #include @@ -21,5 +20,3 @@ public: } // namespace insight } // namespace beast - -#endif diff --git a/include/xrpl/beast/insight/NullCollector.h b/include/xrpl/beast/insight/NullCollector.h index 6c4413007b..1d16a11e17 100644 --- a/include/xrpl/beast/insight/NullCollector.h +++ b/include/xrpl/beast/insight/NullCollector.h @@ -1,5 +1,4 @@ -#ifndef BEAST_INSIGHT_NULLCOLLECTOR_H_INCLUDED -#define BEAST_INSIGHT_NULLCOLLECTOR_H_INCLUDED +#pragma once #include @@ -18,5 +17,3 @@ public: } // namespace insight } // namespace beast - -#endif diff --git a/include/xrpl/beast/insight/StatsDCollector.h b/include/xrpl/beast/insight/StatsDCollector.h index 092b008709..ab09967483 100644 --- a/include/xrpl/beast/insight/StatsDCollector.h +++ b/include/xrpl/beast/insight/StatsDCollector.h @@ -1,5 +1,4 @@ -#ifndef BEAST_INSIGHT_STATSDCOLLECTOR_H_INCLUDED -#define BEAST_INSIGHT_STATSDCOLLECTOR_H_INCLUDED +#pragma once #include #include @@ -23,12 +22,8 @@ public: @param journal Destination for logging output. */ static std::shared_ptr - New(IP::Endpoint const& address, - std::string const& prefix, - Journal journal); + New(IP::Endpoint const& address, std::string const& prefix, Journal journal); }; } // namespace insight } // namespace beast - -#endif diff --git a/include/xrpl/beast/net/IPAddress.h b/include/xrpl/beast/net/IPAddress.h index c3c7ee3d56..2ac4c3bc43 100644 --- a/include/xrpl/beast/net/IPAddress.h +++ b/include/xrpl/beast/net/IPAddress.h @@ -1,5 +1,4 @@ -#ifndef BEAST_NET_IPADDRESS_H_INCLUDED -#define BEAST_NET_IPADDRESS_H_INCLUDED +#pragma once #include #include @@ -96,5 +95,3 @@ struct hash<::beast::IP::Address> } }; } // namespace boost - -#endif diff --git a/include/xrpl/beast/net/IPAddressConversion.h b/include/xrpl/beast/net/IPAddressConversion.h index e05ae8541f..2ebd0a6eef 100644 --- a/include/xrpl/beast/net/IPAddressConversion.h +++ b/include/xrpl/beast/net/IPAddressConversion.h @@ -1,5 +1,4 @@ -#ifndef BEAST_NET_IPADDRESSCONVERSION_H_INCLUDED -#define BEAST_NET_IPADDRESSCONVERSION_H_INCLUDED +#pragma once #include @@ -61,5 +60,3 @@ struct IPAddressConversion }; } // namespace beast - -#endif diff --git a/include/xrpl/beast/net/IPAddressV4.h b/include/xrpl/beast/net/IPAddressV4.h index c654db85c0..0d586716d8 100644 --- a/include/xrpl/beast/net/IPAddressV4.h +++ b/include/xrpl/beast/net/IPAddressV4.h @@ -1,5 +1,4 @@ -#ifndef BEAST_NET_IPADDRESSV4_H_INCLUDED -#define BEAST_NET_IPADDRESSV4_H_INCLUDED +#pragma once #include @@ -26,5 +25,3 @@ get_class(AddressV4 const& address); } // namespace IP } // namespace beast - -#endif diff --git a/include/xrpl/beast/net/IPAddressV6.h b/include/xrpl/beast/net/IPAddressV6.h index a4f9c20f16..2f9dedb748 100644 --- a/include/xrpl/beast/net/IPAddressV6.h +++ b/include/xrpl/beast/net/IPAddressV6.h @@ -1,5 +1,4 @@ -#ifndef BEAST_NET_IPADDRESSV6_H_INCLUDED -#define BEAST_NET_IPADDRESSV6_H_INCLUDED +#pragma once #include @@ -20,5 +19,3 @@ is_public(AddressV6 const& addr); } // namespace IP } // namespace beast - -#endif diff --git a/include/xrpl/beast/net/IPEndpoint.h b/include/xrpl/beast/net/IPEndpoint.h index 3d09e7f8e6..7a0394cbd1 100644 --- a/include/xrpl/beast/net/IPEndpoint.h +++ b/include/xrpl/beast/net/IPEndpoint.h @@ -1,5 +1,4 @@ -#ifndef BEAST_NET_IPENDPOINT_H_INCLUDED -#define BEAST_NET_IPENDPOINT_H_INCLUDED +#pragma once #include #include @@ -219,5 +218,3 @@ struct hash<::beast::IP::Endpoint> } }; } // namespace boost - -#endif diff --git a/include/xrpl/beast/rfc2616.h b/include/xrpl/beast/rfc2616.h index 145a22bad1..2ff770c011 100644 --- a/include/xrpl/beast/rfc2616.h +++ b/include/xrpl/beast/rfc2616.h @@ -1,5 +1,4 @@ -#ifndef BEAST_RFC2616_HPP -#define BEAST_RFC2616_HPP +#pragma once #include #include @@ -26,8 +25,7 @@ struct ci_equal_pred operator()(char c1, char c2) { // VFALCO TODO Use a table lookup here - return std::tolower(static_cast(c1)) == - std::tolower(static_cast(c2)); + return std::tolower(static_cast(c1)) == std::tolower(static_cast(c2)); } }; @@ -97,8 +95,7 @@ trim_right(String const& s) */ template < class FwdIt, - class Result = std::vector< - std::basic_string::value_type>>, + class Result = std::vector::value_type>>, class Char> Result split(FwdIt first, FwdIt last, Char delim) @@ -172,10 +169,7 @@ split(FwdIt first, FwdIt last, Char delim) return result; } -template < - class FwdIt, - class Result = std::vector< - std::basic_string::value_type>>> +template ::value_type>>> Result split_commas(FwdIt first, FwdIt last) { @@ -223,8 +217,7 @@ public: bool operator==(list_iterator const& other) const { - return other.it_ == it_ && other.end_ == end_ && - other.value_.size() == value_.size(); + return other.it_ == it_ && other.end_ == end_ && other.value_.size() == value_.size(); } bool @@ -288,14 +281,12 @@ list_iterator::increment() ++it_; if (it_ == end_) { - value_ = boost::string_ref( - &*start, std::distance(start, it_)); + value_ = boost::string_ref(&*start, std::distance(start, it_)); return; } if (*it_ == '"') { - value_ = boost::string_ref( - &*start, std::distance(start, it_)); + value_ = boost::string_ref(&*start, std::distance(start, it_)); ++it_; return; } @@ -321,8 +312,7 @@ list_iterator::increment() ++it_; if (it_ == end_ || *it_ == ',' || is_lws(*it_)) { - value_ = - boost::string_ref(&*start, std::distance(start, it_)); + value_ = boost::string_ref(&*start, std::distance(start, it_)); return; } } @@ -344,8 +334,7 @@ inline boost::iterator_range make_list(boost::string_ref const& field) { return boost::iterator_range{ - list_iterator{field.begin(), field.end()}, - list_iterator{field.end(), field.end()}}; + list_iterator{field.begin(), field.end()}, list_iterator{field.end(), field.end()}}; } /** Returns true if the specified token exists in the list. @@ -367,15 +356,9 @@ bool is_keep_alive(boost::beast::http::message const& m) { if (m.version() <= 10) - return boost::beast::http::token_list{ - m[boost::beast::http::field::connection]} - .exists("keep-alive"); - return !boost::beast::http::token_list{ - m[boost::beast::http::field::connection]} - .exists("close"); + return boost::beast::http::token_list{m[boost::beast::http::field::connection]}.exists("keep-alive"); + return !boost::beast::http::token_list{m[boost::beast::http::field::connection]}.exists("close"); } } // namespace rfc2616 } // namespace beast - -#endif diff --git a/include/xrpl/beast/test/yield_to.h b/include/xrpl/beast/test/yield_to.h index 037c33e470..b10530c0d3 100644 --- a/include/xrpl/beast/test/yield_to.h +++ b/include/xrpl/beast/test/yield_to.h @@ -2,8 +2,7 @@ // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // -#ifndef BEAST_TEST_YIELD_TO_HPP -#define BEAST_TEST_YIELD_TO_HPP +#pragma once #include #include @@ -31,9 +30,7 @@ protected: boost::asio::io_context ios_; private: - boost::optional> - work_; + boost::optional> work_; std::vector threads_; std::mutex m_; std::condition_variable cv_; @@ -43,8 +40,7 @@ public: /// The type of yield context passed to functions. using yield_context = boost::asio::yield_context; - explicit enable_yield_to(std::size_t concurrency = 1) - : work_(boost::asio::make_work_guard(ios_)) + explicit enable_yield_to(std::size_t concurrency = 1) : work_(boost::asio::make_work_guard(ios_)) { threads_.reserve(concurrency); while (concurrency--) @@ -130,5 +126,3 @@ enable_yield_to::spawn(F0&& f, FN&&... fn) } // namespace test } // namespace beast - -#endif diff --git a/include/xrpl/beast/type_name.h b/include/xrpl/beast/type_name.h index 1534af5eda..99b90d1757 100644 --- a/include/xrpl/beast/type_name.h +++ b/include/xrpl/beast/type_name.h @@ -1,5 +1,4 @@ -#ifndef BEAST_TYPE_NAME_H_INCLUDED -#define BEAST_TYPE_NAME_H_INCLUDED +#pragma once #include #include @@ -41,5 +40,3 @@ type_name() } } // namespace beast - -#endif diff --git a/include/xrpl/beast/unit_test.h b/include/xrpl/beast/unit_test.h index 721faef6f0..51ac96cacb 100644 --- a/include/xrpl/beast/unit_test.h +++ b/include/xrpl/beast/unit_test.h @@ -1,5 +1,4 @@ -#ifndef BEAST_UNIT_TEST_H_INCLUDED -#define BEAST_UNIT_TEST_H_INCLUDED +#pragma once #include #include @@ -19,5 +18,3 @@ //__LINE__);}while(false){} #define BEAST_EXPECT(cond) expect(cond, __FILE__ ":" BEAST_EXPECT_S2(__LINE__)) #endif - -#endif diff --git a/include/xrpl/beast/unit_test/amount.h b/include/xrpl/beast/unit_test/amount.h index 5082361fa6..aedced15a7 100644 --- a/include/xrpl/beast/unit_test/amount.h +++ b/include/xrpl/beast/unit_test/amount.h @@ -2,8 +2,7 @@ // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // -#ifndef BEAST_UNIT_TEST_AMOUNT_HPP -#define BEAST_UNIT_TEST_AMOUNT_HPP +#pragma once #include #include @@ -45,5 +44,3 @@ operator<<(std::ostream& s, amount const& t) } // namespace unit_test } // namespace beast - -#endif diff --git a/include/xrpl/beast/unit_test/detail/const_container.h b/include/xrpl/beast/unit_test/detail/const_container.h index c1e8c03a27..7c52e0e1ec 100644 --- a/include/xrpl/beast/unit_test/detail/const_container.h +++ b/include/xrpl/beast/unit_test/detail/const_container.h @@ -2,8 +2,7 @@ // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // -#ifndef BEAST_UNIT_TEST_DETAIL_CONST_CONTAINER_HPP -#define BEAST_UNIT_TEST_DETAIL_CONST_CONTAINER_HPP +#pragma once namespace beast { namespace unit_test { @@ -86,5 +85,3 @@ public: } // namespace detail } // namespace unit_test } // namespace beast - -#endif diff --git a/include/xrpl/beast/unit_test/global_suites.h b/include/xrpl/beast/unit_test/global_suites.h index 5bcba5fa68..68b4e2ced8 100644 --- a/include/xrpl/beast/unit_test/global_suites.h +++ b/include/xrpl/beast/unit_test/global_suites.h @@ -2,8 +2,7 @@ // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // -#ifndef BEAST_UNIT_TEST_GLOBAL_SUITES_HPP -#define BEAST_UNIT_TEST_GLOBAL_SUITES_HPP +#pragma once #include @@ -23,12 +22,7 @@ global_suites() template struct insert_suite { - insert_suite( - char const* name, - char const* module, - char const* library, - bool manual, - int priority) + insert_suite(char const* name, char const* module, char const* library, bool manual, int priority) { global_suites().insert(name, module, library, manual, priority); } @@ -45,5 +39,3 @@ global_suites() } // namespace unit_test } // namespace beast - -#endif diff --git a/include/xrpl/beast/unit_test/match.h b/include/xrpl/beast/unit_test/match.h index 0556aaab27..38816bb5c7 100644 --- a/include/xrpl/beast/unit_test/match.h +++ b/include/xrpl/beast/unit_test/match.h @@ -2,8 +2,7 @@ // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // -#ifndef BEAST_UNIT_TEST_MATCH_HPP -#define BEAST_UNIT_TEST_MATCH_HPP +#pragma once #include @@ -53,8 +52,7 @@ public: //------------------------------------------------------------------------------ template -selector::selector(mode_t mode, std::string const& pattern) - : mode_(mode), pat_(pattern) +selector::selector(mode_t mode, std::string const& pattern) : mode_(mode), pat_(pattern) { if (mode_ == automatch && pattern.empty()) mode_ = all; @@ -167,5 +165,3 @@ match_library(std::string const& name) } // namespace unit_test } // namespace beast - -#endif diff --git a/include/xrpl/beast/unit_test/recorder.h b/include/xrpl/beast/unit_test/recorder.h index 78b376f519..8f956fda88 100644 --- a/include/xrpl/beast/unit_test/recorder.h +++ b/include/xrpl/beast/unit_test/recorder.h @@ -2,8 +2,7 @@ // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // -#ifndef BEAST_UNIT_TEST_RECORDER_HPP -#define BEAST_UNIT_TEST_RECORDER_HPP +#pragma once #include #include @@ -76,5 +75,3 @@ private: } // namespace unit_test } // namespace beast - -#endif diff --git a/include/xrpl/beast/unit_test/reporter.h b/include/xrpl/beast/unit_test/reporter.h index 4ea662e30e..ee7168d039 100644 --- a/include/xrpl/beast/unit_test/reporter.h +++ b/include/xrpl/beast/unit_test/reporter.h @@ -2,8 +2,7 @@ // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // -#ifndef BEAST_UNIT_TEST_REPORTER_HPP -#define BEAST_UNIT_TEST_REPORTER_HPP +#pragma once #include #include @@ -140,10 +139,7 @@ reporter<_>::results::add(suite_results const& r) if (elapsed >= std::chrono::seconds{1}) { auto const iter = std::lower_bound( - top.begin(), - top.end(), - elapsed, - [](run_time const& t1, typename clock_type::duration const& t2) { + top.begin(), top.end(), elapsed, [](run_time const& t1, typename clock_type::duration const& t2) { return t1.second > t2; }); if (iter != top.end()) @@ -176,10 +172,8 @@ reporter<_>::~reporter() os_ << std::setw(8) << fmtdur(i.second) << " " << i.first << '\n'; } auto const elapsed = clock_type::now() - results_.start; - os_ << fmtdur(elapsed) << ", " << amount{results_.suites, "suite"} << ", " - << amount{results_.cases, "case"} << ", " - << amount{results_.total, "test"} << " total, " - << amount{results_.failed, "failure"} << std::endl; + os_ << fmtdur(elapsed) << ", " << amount{results_.suites, "suite"} << ", " << amount{results_.cases, "case"} << ", " + << amount{results_.total, "test"} << " total, " << amount{results_.failed, "failure"} << std::endl; } template @@ -214,9 +208,7 @@ void reporter<_>::on_case_begin(std::string const& name) { case_results_ = case_results(name); - os_ << suite_results_.name - << (case_results_.name.empty() ? "" : (" " + case_results_.name)) - << std::endl; + os_ << suite_results_.name << (case_results_.name.empty() ? "" : (" " + case_results_.name)) << std::endl; } template @@ -239,8 +231,7 @@ reporter<_>::on_fail(std::string const& reason) { ++case_results_.failed; ++case_results_.total; - os_ << "#" << case_results_.total << " failed" - << (reason.empty() ? "" : ": ") << reason << std::endl; + os_ << "#" << case_results_.total << " failed" << (reason.empty() ? "" : ": ") << reason << std::endl; } template @@ -256,5 +247,3 @@ using reporter = detail::reporter<>; } // namespace unit_test } // namespace beast - -#endif diff --git a/include/xrpl/beast/unit_test/results.h b/include/xrpl/beast/unit_test/results.h index 5cc0d3fc5c..cbd0a71057 100644 --- a/include/xrpl/beast/unit_test/results.h +++ b/include/xrpl/beast/unit_test/results.h @@ -2,8 +2,7 @@ // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // -#ifndef BEAST_UNIT_TEST_RESULTS_HPP -#define BEAST_UNIT_TEST_RESULTS_HPP +#pragma once #include @@ -24,8 +23,7 @@ public: { } - test(bool pass_, std::string const& reason_) - : pass(pass_), reason(reason_) + test(bool pass_, std::string const& reason_) : pass(pass_), reason(reason_) { } @@ -223,5 +221,3 @@ public: } // namespace unit_test } // namespace beast - -#endif diff --git a/include/xrpl/beast/unit_test/runner.h b/include/xrpl/beast/unit_test/runner.h index f91cc92c91..90d8a2f4b5 100644 --- a/include/xrpl/beast/unit_test/runner.h +++ b/include/xrpl/beast/unit_test/runner.h @@ -2,8 +2,7 @@ // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // -#ifndef BEAST_UNIT_TEST_RUNNER_H_INCLUDED -#define BEAST_UNIT_TEST_RUNNER_H_INCLUDED +#pragma once #include @@ -276,5 +275,3 @@ runner::log(std::string const& s) } // namespace unit_test } // namespace beast - -#endif diff --git a/include/xrpl/beast/unit_test/suite.h b/include/xrpl/beast/unit_test/suite.h index c80b336cfe..0e6b592a87 100644 --- a/include/xrpl/beast/unit_test/suite.h +++ b/include/xrpl/beast/unit_test/suite.h @@ -2,8 +2,7 @@ // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // -#ifndef BEAST_UNIT_TEST_SUITE_HPP -#define BEAST_UNIT_TEST_SUITE_HPP +#pragma once #include @@ -92,17 +91,13 @@ private: } }; - template < - class CharT, - class Traits = std::char_traits, - class Allocator = std::allocator> + template , class Allocator = std::allocator> class log_os : public std::basic_ostream { log_buf buf_; public: - explicit log_os(suite& self) - : std::basic_ostream(&buf_), buf_(self) + explicit log_os(suite& self) : std::basic_ostream(&buf_), buf_(self) { } }; @@ -241,11 +236,7 @@ public: template bool - expect( - Condition const& shouldBeTrue, - String const& reason, - char const* file, - int line); + expect(Condition const& shouldBeTrue, String const& reason, char const* file, int line); /** @} */ // @@ -349,8 +340,7 @@ public: } template - scoped_testcase(suite& self, std::stringstream& ss, T const& t) - : suite_(self), ss_(ss) + scoped_testcase(suite& self, std::stringstream& ss, T const& t) : suite_(self), ss_(ss) { ss_.clear(); ss_.str({}); @@ -423,11 +413,7 @@ suite::expect(Condition const& shouldBeTrue, String const& reason) template bool -suite::expect( - Condition const& shouldBeTrue, - String const& reason, - char const* file, - int line) +suite::expect(Condition const& shouldBeTrue, String const& reason, char const* file, int line) { if (shouldBeTrue) { @@ -576,8 +562,7 @@ suite::run(runner& r) If the condition is false, the file and line number are reported. */ -#define BEAST_EXPECTS(cond, reason) \ - ((cond) ? (pass(), true) : (fail((reason), __FILE__, __LINE__), false)) +#define BEAST_EXPECTS(cond, reason) ((cond) ? (pass(), true) : (fail((reason), __FILE__, __LINE__), false)) #endif } // namespace unit_test @@ -587,11 +572,9 @@ suite::run(runner& r) // detail: // This inserts the suite with the given manual flag -#define BEAST_DEFINE_TESTSUITE_INSERT( \ - Class, Module, Library, manual, priority) \ - static beast::unit_test::detail::insert_suite \ - Library##Module##Class##_test_instance( \ - #Class, #Module, #Library, manual, priority) +#define BEAST_DEFINE_TESTSUITE_INSERT(Class, Module, Library, manual, priority) \ + static beast::unit_test::detail::insert_suite Library##Module##Class##_test_instance( \ + #Class, #Module, #Library, manual, priority) //------------------------------------------------------------------------------ @@ -646,8 +629,7 @@ suite::run(runner& r) #else #include -#define BEAST_DEFINE_TESTSUITE(Class, Module, Library) \ - BEAST_DEFINE_TESTSUITE_INSERT(Class, Module, Library, false, 0) +#define BEAST_DEFINE_TESTSUITE(Class, Module, Library) BEAST_DEFINE_TESTSUITE_INSERT(Class, Module, Library, false, 0) #define BEAST_DEFINE_TESTSUITE_MANUAL(Class, Module, Library) \ BEAST_DEFINE_TESTSUITE_INSERT(Class, Module, Library, true, 0) #define BEAST_DEFINE_TESTSUITE_PRIO(Class, Module, Library, Priority) \ @@ -659,5 +641,3 @@ suite::run(runner& r) #endif //------------------------------------------------------------------------------ - -#endif diff --git a/include/xrpl/beast/unit_test/suite_info.h b/include/xrpl/beast/unit_test/suite_info.h index 078886a86e..019251b0c4 100644 --- a/include/xrpl/beast/unit_test/suite_info.h +++ b/include/xrpl/beast/unit_test/suite_info.h @@ -2,8 +2,7 @@ // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // -#ifndef BEAST_UNIT_TEST_SUITE_INFO_HPP -#define BEAST_UNIT_TEST_SUITE_INFO_HPP +#pragma once #include #include @@ -28,13 +27,7 @@ class suite_info run_type run_; public: - suite_info( - std::string name, - std::string module, - std::string library, - bool manual, - int priority, - run_type run) + suite_info(std::string name, std::string module, std::string library, bool manual, int priority, run_type run) : name_(std::move(name)) , module_(std::move(module)) , library_(std::move(library)) @@ -88,10 +81,8 @@ public: { // we want higher priority suites sorted first, thus the negation // of priority value here - return std::forward_as_tuple( - -lhs.priority_, lhs.library_, lhs.module_, lhs.name_) < - std::forward_as_tuple( - -rhs.priority_, rhs.library_, rhs.module_, rhs.name_); + return std::forward_as_tuple(-lhs.priority_, lhs.library_, lhs.module_, lhs.name_) < + std::forward_as_tuple(-rhs.priority_, rhs.library_, rhs.module_, rhs.name_); } }; @@ -100,23 +91,11 @@ public: /// Convenience for producing suite_info for a given test type. template suite_info -make_suite_info( - std::string name, - std::string module, - std::string library, - bool manual, - int priority) +make_suite_info(std::string name, std::string module, std::string library, bool manual, int priority) { return suite_info( - std::move(name), - std::move(module), - std::move(library), - manual, - priority, - [](runner& r) { Suite{}(r); }); + std::move(name), std::move(module), std::move(library), manual, priority, [](runner& r) { Suite{}(r); }); } } // namespace unit_test } // namespace beast - -#endif diff --git a/include/xrpl/beast/unit_test/suite_list.h b/include/xrpl/beast/unit_test/suite_list.h index be265e6145..4412883e31 100644 --- a/include/xrpl/beast/unit_test/suite_list.h +++ b/include/xrpl/beast/unit_test/suite_list.h @@ -2,8 +2,7 @@ // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // -#ifndef BEAST_UNIT_TEST_SUITE_LIST_HPP -#define BEAST_UNIT_TEST_SUITE_LIST_HPP +#pragma once #include #include @@ -33,24 +32,14 @@ public: */ template void - insert( - char const* name, - char const* module, - char const* library, - bool manual, - int priority); + insert(char const* name, char const* module, char const* library, bool manual, int priority); }; //------------------------------------------------------------------------------ template void -suite_list::insert( - char const* name, - char const* module, - char const* library, - bool manual, - int priority) +suite_list::insert(char const* name, char const* module, char const* library, bool manual, int priority) { #ifndef NDEBUG { @@ -65,11 +54,8 @@ suite_list::insert( BOOST_ASSERT(result.second); // Duplicate type } #endif - cont().emplace( - make_suite_info(name, module, library, manual, priority)); + cont().emplace(make_suite_info(name, module, library, manual, priority)); } } // namespace unit_test } // namespace beast - -#endif diff --git a/include/xrpl/beast/unit_test/thread.h b/include/xrpl/beast/unit_test/thread.h index 4b70c308d1..b49f8ed36e 100644 --- a/include/xrpl/beast/unit_test/thread.h +++ b/include/xrpl/beast/unit_test/thread.h @@ -2,8 +2,7 @@ // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // -#ifndef BEAST_UNIT_TEST_THREAD_HPP -#define BEAST_UNIT_TEST_THREAD_HPP +#pragma once #include @@ -45,8 +44,7 @@ public: template explicit thread(suite& s, F&& f, Args&&... args) : s_(&s) { - std::function b = - std::bind(std::forward(f), std::forward(args)...); + std::function b = std::bind(std::forward(f), std::forward(args)...); t_ = std::thread(&thread::run, this, std::move(b)); } @@ -112,5 +110,3 @@ private: } // namespace unit_test } // namespace beast - -#endif diff --git a/include/xrpl/beast/utility/Journal.h b/include/xrpl/beast/utility/Journal.h index a02a62fc45..dff88826ce 100644 --- a/include/xrpl/beast/utility/Journal.h +++ b/include/xrpl/beast/utility/Journal.h @@ -1,5 +1,4 @@ -#ifndef BEAST_UTILITY_JOURNAL_H_INCLUDED -#define BEAST_UTILITY_JOURNAL_H_INCLUDED +#pragma once #include @@ -130,8 +129,7 @@ public: class ScopedStream { public: - ScopedStream(ScopedStream const& other) - : ScopedStream(other.m_sink, other.m_level) + ScopedStream(ScopedStream const& other) : ScopedStream(other.m_sink, other.m_level) { } @@ -167,16 +165,12 @@ public: }; #ifndef __INTELLISENSE__ - static_assert( - std::is_default_constructible::value == false, - ""); + static_assert(std::is_default_constructible::value == false, ""); static_assert(std::is_copy_constructible::value == true, ""); static_assert(std::is_move_constructible::value == true, ""); static_assert(std::is_copy_assignable::value == false, ""); static_assert(std::is_move_assignable::value == false, ""); - static_assert( - std::is_nothrow_destructible::value == true, - ""); + static_assert(std::is_nothrow_destructible::value == true, ""); #endif //-------------------------------------------------------------------------- @@ -186,8 +180,7 @@ public: { public: /** Create a stream which produces no output. */ - explicit Stream() - : m_sink(getNullSink()), m_level(severities::kDisabled) + explicit Stream() : m_sink(getNullSink()), m_level(severities::kDisabled) { } @@ -197,9 +190,7 @@ public: */ Stream(Sink& sink, Severity level) : m_sink(sink), m_level(level) { - XRPL_ASSERT( - m_level < severities::kDisabled, - "beast::Journal::Stream::Stream : maximum level"); + XRPL_ASSERT(m_level < severities::kDisabled, "beast::Journal::Stream::Stream : maximum level"); } /** Construct or copy another Stream. */ @@ -430,8 +421,7 @@ class basic_logstream : public std::basic_ostream detail::logstream_buf buf_; public: - explicit basic_logstream(beast::Journal::Stream const& strm) - : std::basic_ostream(&buf_), buf_(strm) + explicit basic_logstream(beast::Journal::Stream const& strm) : std::basic_ostream(&buf_), buf_(strm) { } }; @@ -440,5 +430,3 @@ using logstream = basic_logstream; using logwstream = basic_logstream; } // namespace beast - -#endif diff --git a/include/xrpl/beast/utility/PropertyStream.h b/include/xrpl/beast/utility/PropertyStream.h index de1fc567f3..3d29138a12 100644 --- a/include/xrpl/beast/utility/PropertyStream.h +++ b/include/xrpl/beast/utility/PropertyStream.h @@ -1,5 +1,4 @@ -#ifndef BEAST_UTILITY_PROPERTYSTREAM_H_INCLUDED -#define BEAST_UTILITY_PROPERTYSTREAM_H_INCLUDED +#pragma once #include @@ -408,5 +407,3 @@ public: }; } // namespace beast - -#endif diff --git a/include/xrpl/beast/utility/WrappedSink.h b/include/xrpl/beast/utility/WrappedSink.h index eb2f103c17..bb8a1a6994 100644 --- a/include/xrpl/beast/utility/WrappedSink.h +++ b/include/xrpl/beast/utility/WrappedSink.h @@ -1,5 +1,4 @@ -#ifndef BEAST_UTILITY_WRAPPEDSINK_H_INCLUDED -#define BEAST_UTILITY_WRAPPEDSINK_H_INCLUDED +#pragma once #include @@ -18,16 +17,12 @@ private: std::string prefix_; public: - explicit WrappedSink( - beast::Journal::Sink& sink, - std::string const& prefix = "") + explicit WrappedSink(beast::Journal::Sink& sink, std::string const& prefix = "") : Sink(sink), sink_(sink), prefix_(prefix) { } - explicit WrappedSink( - beast::Journal const& journal, - std::string const& prefix = "") + explicit WrappedSink(beast::Journal const& journal, std::string const& prefix = "") : WrappedSink(journal.sink(), prefix) { } @@ -84,5 +79,3 @@ public: }; } // namespace beast - -#endif diff --git a/include/xrpl/beast/utility/Zero.h b/include/xrpl/beast/utility/Zero.h index fbafc59a81..00e91a1a47 100644 --- a/include/xrpl/beast/utility/Zero.h +++ b/include/xrpl/beast/utility/Zero.h @@ -1,7 +1,6 @@ // Copyright (c) 2014, Tom Ritchford -#ifndef BEAST_UTILITY_ZERO_H_INCLUDED -#define BEAST_UTILITY_ZERO_H_INCLUDED +#pragma once namespace beast { @@ -144,5 +143,3 @@ operator<=(Zero, T const& t) } } // namespace beast - -#endif diff --git a/include/xrpl/beast/utility/instrumentation.h b/include/xrpl/beast/utility/instrumentation.h index 3c364b64e6..0d0b2ce415 100644 --- a/include/xrpl/beast/utility/instrumentation.h +++ b/include/xrpl/beast/utility/instrumentation.h @@ -1,5 +1,4 @@ -#ifndef BEAST_UTILITY_INSTRUMENTATION_H_INCLUDED -#define BEAST_UTILITY_INSTRUMENTATION_H_INCLUDED +#pragma once #include @@ -20,8 +19,7 @@ #endif #define XRPL_ASSERT ALWAYS_OR_UNREACHABLE -#define XRPL_ASSERT_PARTS(cond, function, description, ...) \ - XRPL_ASSERT(cond, function " : " description) +#define XRPL_ASSERT_PARTS(cond, function, description, ...) XRPL_ASSERT(cond, function " : " description) // How to use the instrumentation macros: // @@ -52,5 +50,3 @@ // instrumentation macros - its name describes the condition which was _not_ // meant to happen, while name in other macros describes the condition that is // meant to happen (e.g. as in "assert that this happens"). - -#endif diff --git a/include/xrpl/beast/utility/maybe_const.h b/include/xrpl/beast/utility/maybe_const.h index bc5f4fe83a..4aac7f018e 100644 --- a/include/xrpl/beast/utility/maybe_const.h +++ b/include/xrpl/beast/utility/maybe_const.h @@ -1,5 +1,4 @@ -#ifndef BEAST_UTILITY_MAYBE_CONST_H_INCLUDED -#define BEAST_UTILITY_MAYBE_CONST_H_INCLUDED +#pragma once #include @@ -10,10 +9,8 @@ template struct maybe_const { explicit maybe_const() = default; - using type = typename std::conditional< - IsConst, - typename std::remove_const::type const, - typename std::remove_const::type>::type; + using type = typename std:: + conditional::type const, typename std::remove_const::type>::type; }; /** Alias for omitting `typename`. */ @@ -21,5 +18,3 @@ template using maybe_const_t = typename maybe_const::type; } // namespace beast - -#endif diff --git a/include/xrpl/beast/utility/rngfill.h b/include/xrpl/beast/utility/rngfill.h index 3fd0c12f0d..7c694aac4f 100644 --- a/include/xrpl/beast/utility/rngfill.h +++ b/include/xrpl/beast/utility/rngfill.h @@ -1,5 +1,4 @@ -#ifndef BEAST_RANDOM_RNGFILL_H_INCLUDED -#define BEAST_RANDOM_RNGFILL_H_INCLUDED +#pragma once #include @@ -36,10 +35,7 @@ rngfill(void* const buffer, std::size_t const bytes, Generator& g) } } -template < - class Generator, - std::size_t N, - class = std::enable_if_t> +template > void rngfill(std::array& a, Generator& g) { @@ -51,5 +47,3 @@ rngfill(std::array& a, Generator& g) } } // namespace beast - -#endif diff --git a/include/xrpl/beast/utility/temp_dir.h b/include/xrpl/beast/utility/temp_dir.h index 37f26b7fec..5aa7b28ac2 100644 --- a/include/xrpl/beast/utility/temp_dir.h +++ b/include/xrpl/beast/utility/temp_dir.h @@ -1,5 +1,4 @@ -#ifndef BEAST_UTILITY_TEMP_DIR_H_INCLUDED -#define BEAST_UTILITY_TEMP_DIR_H_INCLUDED +#pragma once #include @@ -62,5 +61,3 @@ public: }; } // namespace beast - -#endif diff --git a/include/xrpl/beast/xor_shift_engine.h b/include/xrpl/beast/xor_shift_engine.h index 7eab82ff43..d49cb08fc0 100644 --- a/include/xrpl/beast/xor_shift_engine.h +++ b/include/xrpl/beast/xor_shift_engine.h @@ -1,5 +1,4 @@ -#ifndef BEAST_RANDOM_XOR_SHIFT_ENGINE_H_INCLUDED -#define BEAST_RANDOM_XOR_SHIFT_ENGINE_H_INCLUDED +#pragma once #include #include @@ -95,5 +94,3 @@ xor_shift_engine<_>::murmurhash3(result_type x) -> result_type using xor_shift_engine = detail::xor_shift_engine<>; } // namespace beast - -#endif diff --git a/src/xrpld/conditions/Condition.h b/include/xrpl/conditions/Condition.h similarity index 80% rename from src/xrpld/conditions/Condition.h rename to include/xrpl/conditions/Condition.h index 52a6bcd9bb..6b306a3982 100644 --- a/src/xrpld/conditions/Condition.h +++ b/include/xrpl/conditions/Condition.h @@ -1,10 +1,8 @@ -#ifndef XRPL_CONDITIONS_CONDITION_H -#define XRPL_CONDITIONS_CONDITION_H - -#include +#pragma once #include #include +#include #include #include @@ -61,13 +59,11 @@ public: /** For compound conditions, set of conditions includes */ std::set subtypes; - Condition(Type t, std::uint32_t c, Slice fp) - : type(t), fingerprint(fp), cost(c) + Condition(Type t, std::uint32_t c, Slice fp) : type(t), fingerprint(fp), cost(c) { } - Condition(Type t, std::uint32_t c, Buffer&& fp) - : type(t), fingerprint(std::move(fp)), cost(c) + Condition(Type t, std::uint32_t c, Buffer&& fp) : type(t), fingerprint(std::move(fp)), cost(c) { } @@ -82,8 +78,8 @@ public: inline bool operator==(Condition const& lhs, Condition const& rhs) { - return lhs.type == rhs.type && lhs.cost == rhs.cost && - lhs.subtypes == rhs.subtypes && lhs.fingerprint == rhs.fingerprint; + return lhs.type == rhs.type && lhs.cost == rhs.cost && lhs.subtypes == rhs.subtypes && + lhs.fingerprint == rhs.fingerprint; } inline bool @@ -95,5 +91,3 @@ operator!=(Condition const& lhs, Condition const& rhs) } // namespace cryptoconditions } // namespace xrpl - -#endif diff --git a/src/xrpld/conditions/Fulfillment.h b/include/xrpl/conditions/Fulfillment.h similarity index 95% rename from src/xrpld/conditions/Fulfillment.h rename to include/xrpl/conditions/Fulfillment.h index 970aed121c..04d0b2aa1e 100644 --- a/src/xrpld/conditions/Fulfillment.h +++ b/include/xrpl/conditions/Fulfillment.h @@ -1,10 +1,8 @@ -#ifndef XRPL_CONDITIONS_FULFILLMENT_H -#define XRPL_CONDITIONS_FULFILLMENT_H - -#include +#pragma once #include #include +#include namespace xrpl { namespace cryptoconditions { @@ -78,8 +76,7 @@ inline bool operator==(Fulfillment const& lhs, Fulfillment const& rhs) { // FIXME: for compound conditions, need to also check subtypes - return lhs.type() == rhs.type() && lhs.cost() == rhs.cost() && - lhs.fingerprint() == rhs.fingerprint(); + return lhs.type() == rhs.type() && lhs.cost() == rhs.cost() && lhs.fingerprint() == rhs.fingerprint(); } inline bool @@ -123,5 +120,3 @@ validate(Fulfillment const& f, Condition const& c); } // namespace cryptoconditions } // namespace xrpl - -#endif diff --git a/src/xrpld/conditions/detail/PreimageSha256.h b/include/xrpl/conditions/detail/PreimageSha256.h similarity index 92% rename from src/xrpld/conditions/detail/PreimageSha256.h rename to include/xrpl/conditions/detail/PreimageSha256.h index f495885794..8726473c2d 100644 --- a/src/xrpld/conditions/detail/PreimageSha256.h +++ b/include/xrpl/conditions/detail/PreimageSha256.h @@ -1,12 +1,10 @@ -#ifndef XRPL_CONDITIONS_PREIMAGE_SHA256_H -#define XRPL_CONDITIONS_PREIMAGE_SHA256_H - -#include -#include -#include +#pragma once #include #include +#include +#include +#include #include #include @@ -131,5 +129,3 @@ public: } // namespace cryptoconditions } // namespace xrpl - -#endif diff --git a/src/xrpld/conditions/detail/error.h b/include/xrpl/conditions/detail/error.h similarity index 91% rename from src/xrpld/conditions/detail/error.h rename to include/xrpl/conditions/detail/error.h index 65584e974a..fdeed3d9ac 100644 --- a/src/xrpld/conditions/detail/error.h +++ b/include/xrpl/conditions/detail/error.h @@ -1,5 +1,4 @@ -#ifndef XRPL_CONDITIONS_ERROR_H -#define XRPL_CONDITIONS_ERROR_H +#pragma once #include @@ -43,5 +42,3 @@ struct is_error_code_enum }; } // namespace std - -#endif diff --git a/src/xrpld/conditions/detail/utils.h b/include/xrpl/conditions/detail/utils.h similarity index 97% rename from src/xrpld/conditions/detail/utils.h rename to include/xrpl/conditions/detail/utils.h index b07b7b29e0..17d93d43b5 100644 --- a/src/xrpld/conditions/detail/utils.h +++ b/include/xrpl/conditions/detail/utils.h @@ -1,10 +1,8 @@ -#ifndef XRPL_CONDITIONS_UTILS_H -#define XRPL_CONDITIONS_UTILS_H - -#include +#pragma once #include #include +#include #include @@ -209,5 +207,3 @@ parseInteger(Slice& s, std::size_t count, std::error_code& ec) } // namespace der } // namespace cryptoconditions } // namespace xrpl - -#endif diff --git a/include/xrpl/core/ClosureCounter.h b/include/xrpl/core/ClosureCounter.h index d2be76fa8c..6802a03f3d 100644 --- a/include/xrpl/core/ClosureCounter.h +++ b/include/xrpl/core/ClosureCounter.h @@ -1,5 +1,4 @@ -#ifndef XRPL_CORE_CLOSURE_COUNTER_H_INCLUDED -#define XRPL_CORE_CLOSURE_COUNTER_H_INCLUDED +#pragma once #include @@ -76,21 +75,18 @@ private: std::remove_reference_t closure_; static_assert( - std::is_same()...)), Ret_t>:: - value, + std::is_same()...)), Ret_t>::value, "Closure arguments don't match ClosureCounter Ret_t or Args_t"); public: Substitute() = delete; - Substitute(Substitute const& rhs) - : counter_(rhs.counter_), closure_(rhs.closure_) + Substitute(Substitute const& rhs) : counter_(rhs.counter_), closure_(rhs.closure_) { ++counter_; } - Substitute(Substitute&& rhs) noexcept( - std::is_nothrow_move_constructible::value) + Substitute(Substitute&& rhs) noexcept(std::is_nothrow_move_constructible::value) : counter_(rhs.counter_), closure_(std::move(rhs.closure_)) { ++counter_; @@ -150,13 +146,11 @@ public: waitForClosures_ = true; if (closureCount_ > 0) { - if (!allClosuresDoneCond_.wait_for( - lock, wait, [this] { return closureCount_ == 0; })) + if (!allClosuresDoneCond_.wait_for(lock, wait, [this] { return closureCount_ == 0; })) { if (auto stream = j.error()) stream << name << " waiting for ClosureCounter::join()."; - allClosuresDoneCond_.wait( - lock, [this] { return closureCount_ == 0; }); + allClosuresDoneCond_.wait(lock, [this] { return closureCount_ == 0; }); } } } @@ -203,5 +197,3 @@ public: }; } // namespace xrpl - -#endif // XRPL_CORE_CLOSURE_COUNTER_H_INCLUDED diff --git a/include/xrpl/core/Coro.ipp b/include/xrpl/core/Coro.ipp index 9f73d80647..2853adf0de 100644 --- a/include/xrpl/core/Coro.ipp +++ b/include/xrpl/core/Coro.ipp @@ -1,25 +1,17 @@ -#ifndef XRPL_CORE_COROINL_H_INCLUDED -#define XRPL_CORE_COROINL_H_INCLUDED +#pragma once #include namespace xrpl { template -JobQueue::Coro::Coro( - Coro_create_t, - JobQueue& jq, - JobType type, - std::string const& name, - F&& f) +JobQueue::Coro::Coro(Coro_create_t, JobQueue& jq, JobType type, std::string const& name, F&& f) : jq_(jq) , type_(type) , name_(name) , running_(false) , coro_( - [this, fn = std::forward(f)]( - boost::coroutines::asymmetric_coroutine::push_type& - do_yield) { + [this, fn = std::forward(f)](boost::coroutines::asymmetric_coroutine::push_type& do_yield) { yield_ = &do_yield; yield(); fn(shared_from_this()); @@ -57,8 +49,7 @@ JobQueue::Coro::post() } // sp keeps 'this' alive - if (jq_.addJob( - type_, name_, [this, sp = shared_from_this()]() { resume(); })) + if (jq_.addJob(type_, name_, [this, sp = shared_from_this()]() { resume(); })) { return true; } @@ -84,8 +75,7 @@ JobQueue::Coro::resume() auto saved = detail::getLocalValues().release(); detail::getLocalValues().reset(&lvs_); std::lock_guard lock(mutex_); - XRPL_ASSERT( - static_cast(coro_), "xrpl::JobQueue::Coro::resume : is runnable"); + XRPL_ASSERT(static_cast(coro_), "xrpl::JobQueue::Coro::resume : is runnable"); coro_(); detail::getLocalValues().release(); detail::getLocalValues().reset(saved); @@ -129,5 +119,3 @@ JobQueue::Coro::join() } } // namespace xrpl - -#endif diff --git a/src/xrpld/app/misc/HashRouter.h b/include/xrpl/core/HashRouter.h similarity index 89% rename from src/xrpld/app/misc/HashRouter.h rename to include/xrpl/core/HashRouter.h index 449097a387..dfc57081ee 100644 --- a/src/xrpld/app/misc/HashRouter.h +++ b/include/xrpl/core/HashRouter.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_MISC_HASHROUTER_H_INCLUDED -#define XRPL_APP_MISC_HASHROUTER_H_INCLUDED +#pragma once #include #include @@ -154,9 +153,7 @@ private: last relay timestamp and return true. */ bool - shouldRelay( - Stopwatch::time_point const& now, - std::chrono::seconds relayTime) + shouldRelay(Stopwatch::time_point const& now, std::chrono::seconds relayTime) { if (relayed_ && *relayed_ + relayTime > now) return false; @@ -183,8 +180,7 @@ private: }; public: - HashRouter(Setup const& setup, Stopwatch& clock) - : setup_(setup), suppressionMap_(clock) + HashRouter(Setup const& setup, Stopwatch& clock) : setup_(setup), suppressionMap_(clock) { } @@ -210,18 +206,11 @@ public: addSuppressionPeerWithStatus(uint256 const& key, PeerShortID peer); bool - addSuppressionPeer( - uint256 const& key, - PeerShortID peer, - HashRouterFlags& flags); + addSuppressionPeer(uint256 const& key, PeerShortID peer, HashRouterFlags& flags); // Add a peer suppression and return whether the entry should be processed bool - shouldProcess( - uint256 const& key, - PeerShortID peer, - HashRouterFlags& flags, - std::chrono::seconds tx_interval); + shouldProcess(uint256 const& key, PeerShortID peer, HashRouterFlags& flags, std::chrono::seconds tx_interval); /** Set the flags on a hash. @@ -259,17 +248,7 @@ private: Setup const setup_; // Stores all suppressed hashes and their expiration time - beast::aged_unordered_map< - uint256, - Entry, - Stopwatch::clock_type, - hardened_hash> - suppressionMap_; + beast::aged_unordered_map> suppressionMap_; }; -HashRouter::Setup -setup_HashRouter(Config const&); - } // namespace xrpl - -#endif diff --git a/include/xrpl/core/Job.h b/include/xrpl/core/Job.h index cb597b3860..61651fd673 100644 --- a/include/xrpl/core/Job.h +++ b/include/xrpl/core/Job.h @@ -1,5 +1,4 @@ -#ifndef XRPL_CORE_JOB_H_INCLUDED -#define XRPL_CORE_JOB_H_INCLUDED +#pragma once #include #include @@ -93,11 +92,7 @@ public: Job(JobType type, std::uint64_t index); // VFALCO TODO try to remove the dependency on LoadMonitor. - Job(JobType type, - std::string const& name, - std::uint64_t index, - LoadMonitor& lm, - std::function const& job); + Job(JobType type, std::string const& name, std::uint64_t index, LoadMonitor& lm, std::function const& job); JobType getType() const; @@ -132,5 +127,3 @@ private: using JobCounter = ClosureCounter; } // namespace xrpl - -#endif diff --git a/include/xrpl/core/JobQueue.h b/include/xrpl/core/JobQueue.h index 2a22b7f5c9..b410e200e1 100644 --- a/include/xrpl/core/JobQueue.h +++ b/include/xrpl/core/JobQueue.h @@ -1,5 +1,4 @@ -#ifndef XRPL_CORE_JOBQUEUE_H_INCLUDED -#define XRPL_CORE_JOBQUEUE_H_INCLUDED +#pragma once #include #include @@ -141,14 +140,11 @@ public: */ template < typename JobHandler, - typename = std::enable_if_t()()), - void>::value>> + typename = std::enable_if_t()()), void>::value>> bool addJob(JobType type, std::string const& name, JobHandler&& jobHandler) { - if (auto optionalCountedJob = - jobCounter_.wrap(std::forward(jobHandler))) + if (auto optionalCountedJob = jobCounter_.wrap(std::forward(jobHandler))) { return addRefCountedJob(type, name, std::move(*optionalCountedJob)); } @@ -264,10 +260,7 @@ private: // // return true if func added to queue. bool - addRefCountedJob( - JobType type, - std::string const& name, - JobFunction const& func); + addRefCountedJob(JobType type, std::string const& name, JobFunction const& func); // Returns the next Job we should run now. // @@ -396,8 +389,7 @@ JobQueue::postCoro(JobType t, std::string const& name, F&& f) Last param is the function the coroutine runs. Signature of void(std::shared_ptr). */ - auto coro = std::make_shared( - Coro_create_t{}, *this, t, name, std::forward(f)); + auto coro = std::make_shared(Coro_create_t{}, *this, t, name, std::forward(f)); if (!coro->post()) { // The Coro was not successfully posted. Disable it so it's destructor @@ -409,5 +401,3 @@ JobQueue::postCoro(JobType t, std::string const& name, F&& f) } } // namespace xrpl - -#endif diff --git a/include/xrpl/core/JobTypeData.h b/include/xrpl/core/JobTypeData.h index 377309aa3c..cdcb19c316 100644 --- a/include/xrpl/core/JobTypeData.h +++ b/include/xrpl/core/JobTypeData.h @@ -1,5 +1,4 @@ -#ifndef XRPL_CORE_JOBTYPEDATA_H_INCLUDED -#define XRPL_CORE_JOBTYPEDATA_H_INCLUDED +#pragma once #include #include @@ -32,19 +31,10 @@ public: beast::insight::Event dequeue; beast::insight::Event execute; - JobTypeData( - JobTypeInfo const& info_, - beast::insight::Collector::ptr const& collector, - Logs& logs) noexcept - : m_load(logs.journal("LoadMonitor")) - , m_collector(collector) - , info(info_) - , waiting(0) - , running(0) - , deferred(0) + JobTypeData(JobTypeInfo const& info_, beast::insight::Collector::ptr const& collector, Logs& logs) noexcept + : m_load(logs.journal("LoadMonitor")), m_collector(collector), info(info_), waiting(0), running(0), deferred(0) { - m_load.setTargetLatency( - info.getAverageLatency(), info.getPeakLatency()); + m_load.setTargetLatency(info.getAverageLatency(), info.getPeakLatency()); if (!info.special()) { @@ -84,5 +74,3 @@ public: }; } // namespace xrpl - -#endif diff --git a/include/xrpl/core/JobTypeInfo.h b/include/xrpl/core/JobTypeInfo.h index a726fb276b..d4daa1ec68 100644 --- a/include/xrpl/core/JobTypeInfo.h +++ b/include/xrpl/core/JobTypeInfo.h @@ -1,5 +1,4 @@ -#ifndef XRPL_CORE_JOBTYPEINFO_H_INCLUDED -#define XRPL_CORE_JOBTYPEINFO_H_INCLUDED +#pragma once #include @@ -33,11 +32,7 @@ public: int limit, std::chrono::milliseconds avgLatency, std::chrono::milliseconds peakLatency) - : m_type(type) - , m_name(std::move(name)) - , m_limit(limit) - , m_avgLatency(avgLatency) - , m_peakLatency(peakLatency) + : m_type(type), m_name(std::move(name)), m_limit(limit), m_avgLatency(avgLatency), m_peakLatency(peakLatency) { } @@ -79,5 +74,3 @@ public: }; } // namespace xrpl - -#endif diff --git a/include/xrpl/core/JobTypes.h b/include/xrpl/core/JobTypes.h index f7952ca9a2..88f98aad66 100644 --- a/include/xrpl/core/JobTypes.h +++ b/include/xrpl/core/JobTypes.h @@ -1,5 +1,4 @@ -#ifndef XRPL_CORE_JOBTYPES_H_INCLUDED -#define XRPL_CORE_JOBTYPES_H_INCLUDED +#pragma once #include #include @@ -16,13 +15,7 @@ public: using const_iterator = Map::const_iterator; private: - JobTypes() - : m_unknown( - jtINVALID, - "invalid", - 0, - std::chrono::milliseconds{0}, - std::chrono::milliseconds{0}) + JobTypes() : m_unknown(jtINVALID, "invalid", 0, std::chrono::milliseconds{0}, std::chrono::milliseconds{0}) { using namespace std::chrono_literals; int maxLimit = std::numeric_limits::max(); @@ -33,22 +26,17 @@ private: int limit, std::chrono::milliseconds avgLatency, std::chrono::milliseconds peakLatency) { - XRPL_ASSERT( - m_map.find(jt) == m_map.end(), - "xrpl::JobTypes::JobTypes::add : unique job type input"); + XRPL_ASSERT(m_map.find(jt) == m_map.end(), "xrpl::JobTypes::JobTypes::add : unique job type input"); [[maybe_unused]] auto const inserted = m_map .emplace( std::piecewise_construct, std::forward_as_tuple(jt), - std::forward_as_tuple( - jt, name, limit, avgLatency, peakLatency)) + std::forward_as_tuple(jt, name, limit, avgLatency, peakLatency)) .second; - XRPL_ASSERT( - inserted == true, - "xrpl::JobTypes::JobTypes::add : input is inserted"); + XRPL_ASSERT(inserted == true, "xrpl::JobTypes::JobTypes::add : input is inserted"); }; // clang-format off @@ -171,5 +159,3 @@ public: }; } // namespace xrpl - -#endif diff --git a/include/xrpl/core/LoadEvent.h b/include/xrpl/core/LoadEvent.h index 8422fe883e..f94e1020bf 100644 --- a/include/xrpl/core/LoadEvent.h +++ b/include/xrpl/core/LoadEvent.h @@ -1,5 +1,4 @@ -#ifndef XRPL_CORE_LOADEVENT_H_INCLUDED -#define XRPL_CORE_LOADEVENT_H_INCLUDED +#pragma once #include #include @@ -66,5 +65,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/include/xrpl/core/LoadMonitor.h b/include/xrpl/core/LoadMonitor.h index 54cd607d5b..71fbf75d68 100644 --- a/include/xrpl/core/LoadMonitor.h +++ b/include/xrpl/core/LoadMonitor.h @@ -1,5 +1,4 @@ -#ifndef XRPL_CORE_LOADMONITOR_H_INCLUDED -#define XRPL_CORE_LOADMONITOR_H_INCLUDED +#pragma once #include #include @@ -27,9 +26,7 @@ public: addSamples(int count, std::chrono::milliseconds latency); void - setTargetLatency( - std::chrono::milliseconds avg, - std::chrono::milliseconds pk); + setTargetLatency(std::chrono::milliseconds avg, std::chrono::milliseconds pk); bool isOverTarget(std::chrono::milliseconds avg, std::chrono::milliseconds peak); @@ -68,5 +65,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/src/xrpld/overlay/PeerReservationTable.h b/include/xrpl/core/PeerReservationTable.h similarity index 90% rename from src/xrpld/overlay/PeerReservationTable.h rename to include/xrpl/core/PeerReservationTable.h index 9ddf79aca9..8f187bf324 100644 --- a/src/xrpld/overlay/PeerReservationTable.h +++ b/include/xrpl/core/PeerReservationTable.h @@ -1,5 +1,4 @@ -#ifndef XRPL_OVERLAY_PEER_RESERVATION_TABLE_H_INCLUDED -#define XRPL_OVERLAY_PEER_RESERVATION_TABLE_H_INCLUDED +#pragma once #include #include @@ -56,8 +55,7 @@ struct KeyEqual final class PeerReservationTable final { public: - explicit PeerReservationTable( - beast::Journal journal = beast::Journal(beast::Journal::getNullSink())) + explicit PeerReservationTable(beast::Journal journal = beast::Journal(beast::Journal::getNullSink())) : journal_(journal) { } @@ -98,5 +96,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/include/xrpl/core/PerfLog.h b/include/xrpl/core/PerfLog.h index f8ca779963..eebd41ae09 100644 --- a/include/xrpl/core/PerfLog.h +++ b/include/xrpl/core/PerfLog.h @@ -1,5 +1,4 @@ -#ifndef XRPL_CORE_PERFLOG_H -#define XRPL_CORE_PERFLOG_H +#pragma once #include #include @@ -105,11 +104,7 @@ public: * @param instance JobQueue worker thread instance */ virtual void - jobStart( - JobType const type, - microseconds dur, - steady_time_point startTime, - int instance) = 0; + jobStart(JobType const type, microseconds dur, steady_time_point startTime, int instance) = 0; /** * Log job finishing @@ -156,11 +151,7 @@ PerfLog::Setup setup_PerfLog(Section const& section, boost::filesystem::path const& configDir); std::unique_ptr -make_PerfLog( - PerfLog::Setup const& setup, - Application& app, - beast::Journal journal, - std::function&& signalStop); +make_PerfLog(PerfLog::Setup const& setup, Application& app, beast::Journal journal, std::function&& signalStop); template auto @@ -175,12 +166,10 @@ measureDurationAndLog( auto result = func(); auto end_time = std::chrono::high_resolution_clock::now(); - auto duration = std::chrono::duration_cast( - end_time - start_time); + auto duration = std::chrono::duration_cast(end_time - start_time); if (duration > maxDelay) { - JLOG(journal.warn()) - << actionDescription << " took " << duration.count() << " ms"; + JLOG(journal.warn()) << actionDescription << " took " << duration.count() << " ms"; } return result; @@ -188,5 +177,3 @@ measureDurationAndLog( } // namespace perf } // namespace xrpl - -#endif // XRPL_CORE_PERFLOG_H diff --git a/include/xrpl/core/ServiceRegistry.h b/include/xrpl/core/ServiceRegistry.h new file mode 100644 index 0000000000..fabf61f9e4 --- /dev/null +++ b/include/xrpl/core/ServiceRegistry.h @@ -0,0 +1,230 @@ +#pragma once + +#include +#include +#include +#include + +#include + +namespace xrpl { + +// Forward declarations +namespace NodeStore { +class Database; +} +namespace Resource { +class Manager; +} +namespace perf { +class PerfLog; +} + +// This is temporary until we migrate all code to use ServiceRegistry. +class Application; + +// Forward declarations +class AcceptedLedger; +class AmendmentTable; +class Cluster; +class CollectorManager; +class DatabaseCon; +class Family; +class HashRouter; +class InboundLedgers; +class InboundTransactions; +class JobQueue; +class LedgerCleaner; +class LedgerMaster; +class LedgerReplayer; +class LoadFeeTrack; +class LoadManager; +class ManifestCache; +class NetworkOPs; +class OpenLedger; +class OrderBookDB; +class Overlay; +class PathRequests; +class PeerReservationTable; +class PendingSaves; +class RelationalDatabase; +class ServerHandler; +class SHAMapStore; +class TimeKeeper; +class TransactionMaster; +class TxQ; +class ValidatorList; +class ValidatorSite; + +template +class Validations; +class RCLValidationsAdaptor; +using RCLValidations = Validations; + +using NodeCache = TaggedCache; + +/** Service registry for dependency injection. + + This abstract interface provides access to various services and components + used throughout the application. It separates the service locator pattern + from the Application lifecycle management. + + Components that need access to services can hold a reference to + ServiceRegistry rather than Application when they only need service + access and not lifecycle management. + +*/ +class ServiceRegistry +{ +public: + ServiceRegistry() = default; + virtual ~ServiceRegistry() = default; + + // Core infrastructure services + virtual CollectorManager& + getCollectorManager() = 0; + + virtual Family& + getNodeFamily() = 0; + + virtual TimeKeeper& + timeKeeper() = 0; + + virtual JobQueue& + getJobQueue() = 0; + + virtual NodeCache& + getTempNodeCache() = 0; + + virtual CachedSLEs& + cachedSLEs() = 0; + + // Protocol and validation services + virtual AmendmentTable& + getAmendmentTable() = 0; + + virtual HashRouter& + getHashRouter() = 0; + + virtual LoadFeeTrack& + getFeeTrack() = 0; + + virtual LoadManager& + getLoadManager() = 0; + + virtual RCLValidations& + getValidations() = 0; + + virtual ValidatorList& + validators() = 0; + + virtual ValidatorSite& + validatorSites() = 0; + + virtual ManifestCache& + validatorManifests() = 0; + + virtual ManifestCache& + publisherManifests() = 0; + + // Network services + virtual Overlay& + overlay() = 0; + + virtual Cluster& + cluster() = 0; + + virtual PeerReservationTable& + peerReservations() = 0; + + virtual Resource::Manager& + getResourceManager() = 0; + + // Storage services + virtual NodeStore::Database& + getNodeStore() = 0; + + virtual SHAMapStore& + getSHAMapStore() = 0; + + virtual RelationalDatabase& + getRelationalDatabase() = 0; + + // Ledger services + virtual InboundLedgers& + getInboundLedgers() = 0; + + virtual InboundTransactions& + getInboundTransactions() = 0; + + virtual TaggedCache& + getAcceptedLedgerCache() = 0; + + virtual LedgerMaster& + getLedgerMaster() = 0; + + virtual LedgerCleaner& + getLedgerCleaner() = 0; + + virtual LedgerReplayer& + getLedgerReplayer() = 0; + + virtual PendingSaves& + pendingSaves() = 0; + + virtual OpenLedger& + openLedger() = 0; + + virtual OpenLedger const& + openLedger() const = 0; + + // Transaction and operation services + virtual NetworkOPs& + getOPs() = 0; + + virtual OrderBookDB& + getOrderBookDB() = 0; + + virtual TransactionMaster& + getMasterTransaction() = 0; + + virtual TxQ& + getTxQ() = 0; + + virtual PathRequests& + getPathRequests() = 0; + + // Server services + virtual ServerHandler& + getServerHandler() = 0; + + virtual perf::PerfLog& + getPerfLog() = 0; + + // Configuration and state + virtual bool + isStopping() const = 0; + + virtual beast::Journal + journal(std::string const& name) = 0; + + virtual boost::asio::io_context& + getIOContext() = 0; + + virtual Logs& + logs() = 0; + + virtual std::optional const& + trapTxID() const = 0; + + /** Retrieve the "wallet database" */ + virtual DatabaseCon& + getWalletDB() = 0; + + // Temporary: Get the underlying Application for functions that haven't + // been migrated yet. This should be removed once all code is migrated. + virtual Application& + app() = 0; +}; + +} // namespace xrpl diff --git a/include/xrpl/core/StartUpType.h b/include/xrpl/core/StartUpType.h new file mode 100644 index 0000000000..74a1898806 --- /dev/null +++ b/include/xrpl/core/StartUpType.h @@ -0,0 +1,16 @@ +#pragma once + +#include +#include + +namespace xrpl { + +enum class StartUpType { FRESH, NORMAL, LOAD, LOAD_FILE, REPLAY, NETWORK }; + +inline std::ostream& +operator<<(std::ostream& os, StartUpType const& type) +{ + return os << static_cast>(type); +} + +} // namespace xrpl diff --git a/include/xrpl/core/detail/Workers.h b/include/xrpl/core/detail/Workers.h index 3a77f9e769..c5df622fa1 100644 --- a/include/xrpl/core/detail/Workers.h +++ b/include/xrpl/core/detail/Workers.h @@ -1,5 +1,4 @@ -#ifndef XRPL_CORE_WORKERS_H_INCLUDED -#define XRPL_CORE_WORKERS_H_INCLUDED +#pragma once #include #include @@ -95,8 +94,7 @@ public: Callback& callback, perf::PerfLog* perfLog, std::string const& threadNames = "Worker", - int numberOfThreads = - static_cast(std::thread::hardware_concurrency())); + int numberOfThreads = static_cast(std::thread::hardware_concurrency())); ~Workers(); @@ -162,14 +160,10 @@ private: Idle: Active, but blocked on waiting for a task. Paused: Blocked waiting to exit or become active. */ - class Worker : public beast::LockFreeStack::Node, - public beast::LockFreeStack::Node + class Worker : public beast::LockFreeStack::Node, public beast::LockFreeStack::Node { public: - Worker( - Workers& workers, - std::string const& threadName, - int const instance); + Worker(Workers& workers, std::string const& threadName, int const instance); ~Worker(); @@ -203,17 +197,13 @@ private: std::condition_variable m_cv; // signaled when all threads paused std::mutex m_mut; bool m_allPaused; - semaphore m_semaphore; // each pending task is 1 resource - int m_numberOfThreads; // how many we want active now - std::atomic m_activeCount; // to know when all are paused - std::atomic m_pauseCount; // how many threads need to pause now - std::atomic - m_runningTaskCount; // how many calls to processTask() active - beast::LockFreeStack m_everyone; // holds all created workers - beast::LockFreeStack - m_paused; // holds just paused workers + semaphore m_semaphore; // each pending task is 1 resource + int m_numberOfThreads; // how many we want active now + std::atomic m_activeCount; // to know when all are paused + std::atomic m_pauseCount; // how many threads need to pause now + std::atomic m_runningTaskCount; // how many calls to processTask() active + beast::LockFreeStack m_everyone; // holds all created workers + beast::LockFreeStack m_paused; // holds just paused workers }; } // namespace xrpl - -#endif diff --git a/include/xrpl/core/detail/semaphore.h b/include/xrpl/core/detail/semaphore.h index 4249b3b860..fad3bf5e29 100644 --- a/include/xrpl/core/detail/semaphore.h +++ b/include/xrpl/core/detail/semaphore.h @@ -26,8 +26,7 @@ * version is updated. */ -#ifndef XRPL_CORE_SEMAPHORE_H_INCLUDED -#define XRPL_CORE_SEMAPHORE_H_INCLUDED +#pragma once #include #include @@ -88,5 +87,3 @@ public: using semaphore = basic_semaphore; } // namespace xrpl - -#endif diff --git a/include/xrpl/crypto/RFC1751.h b/include/xrpl/crypto/RFC1751.h index a413c2ac8a..64b3e08813 100644 --- a/include/xrpl/crypto/RFC1751.h +++ b/include/xrpl/crypto/RFC1751.h @@ -1,5 +1,4 @@ -#ifndef XRPL_CRYPTO_RFC1751_H_INCLUDED -#define XRPL_CRYPTO_RFC1751_H_INCLUDED +#pragma once #include #include @@ -43,5 +42,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/include/xrpl/crypto/csprng.h b/include/xrpl/crypto/csprng.h index dc89da4f61..e5135c96d7 100644 --- a/include/xrpl/crypto/csprng.h +++ b/include/xrpl/crypto/csprng.h @@ -1,5 +1,4 @@ -#ifndef XRPL_CRYPTO_RANDOM_H_INCLUDED -#define XRPL_CRYPTO_RANDOM_H_INCLUDED +#pragma once #include @@ -71,5 +70,3 @@ csprng_engine& crypto_prng(); } // namespace xrpl - -#endif diff --git a/include/xrpl/crypto/secure_erase.h b/include/xrpl/crypto/secure_erase.h index 3ecde0c7fa..2815a8531a 100644 --- a/include/xrpl/crypto/secure_erase.h +++ b/include/xrpl/crypto/secure_erase.h @@ -1,5 +1,4 @@ -#ifndef XRPL_CRYPTO_SECURE_ERASE_H_INCLUDED -#define XRPL_CRYPTO_SECURE_ERASE_H_INCLUDED +#pragma once #include @@ -23,5 +22,3 @@ void secure_erase(void* dest, std::size_t bytes); } // namespace xrpl - -#endif diff --git a/include/xrpl/json/JsonPropertyStream.h b/include/xrpl/json/JsonPropertyStream.h index 54cfcbfa04..510ed72950 100644 --- a/include/xrpl/json/JsonPropertyStream.h +++ b/include/xrpl/json/JsonPropertyStream.h @@ -1,5 +1,4 @@ -#ifndef XRPL_JSON_JSONPROPERTYSTREAM_H_INCLUDED -#define XRPL_JSON_JSONPROPERTYSTREAM_H_INCLUDED +#pragma once #include #include @@ -67,5 +66,3 @@ protected: }; } // namespace xrpl - -#endif diff --git a/include/xrpl/json/Output.h b/include/xrpl/json/Output.h index cdfa674014..b0ba3fa6d4 100644 --- a/include/xrpl/json/Output.h +++ b/include/xrpl/json/Output.h @@ -1,5 +1,4 @@ -#ifndef XRPL_JSON_OUTPUT_H_INCLUDED -#define XRPL_JSON_OUTPUT_H_INCLUDED +#pragma once #include @@ -15,9 +14,7 @@ using Output = std::function; inline Output stringOutput(std::string& s) { - return [&](boost::beast::string_view const& b) { - s.append(b.data(), b.size()); - }; + return [&](boost::beast::string_view const& b) { s.append(b.data(), b.size()); }; } /** Writes a minimal representation of a Json value to an Output in O(n) time. @@ -37,5 +34,3 @@ std::string jsonAsString(Json::Value const&); } // namespace Json - -#endif diff --git a/include/xrpl/json/Writer.h b/include/xrpl/json/Writer.h index ab52427a5b..e348e57825 100644 --- a/include/xrpl/json/Writer.h +++ b/include/xrpl/json/Writer.h @@ -1,5 +1,4 @@ -#ifndef XRPL_JSON_WRITER_H_INCLUDED -#define XRPL_JSON_WRITER_H_INCLUDED +#pragma once #include #include @@ -238,5 +237,3 @@ check(bool condition, std::string const& message) } } // namespace Json - -#endif diff --git a/include/xrpl/json/detail/json_assert.h b/include/xrpl/json/detail/json_assert.h index 3092b65452..e9a66ccef1 100644 --- a/include/xrpl/json/detail/json_assert.h +++ b/include/xrpl/json/detail/json_assert.h @@ -1,5 +1,4 @@ -#ifndef XRPL_JSON_JSON_ASSERT_H_INCLUDED -#define XRPL_JSON_JSON_ASSERT_H_INCLUDED +#pragma once #include #include @@ -7,5 +6,3 @@ #define JSON_ASSERT_MESSAGE(condition, message) \ if (!(condition)) \ xrpl::Throw(message); - -#endif diff --git a/include/xrpl/json/json_errors.h b/include/xrpl/json/json_errors.h index a63637b116..5cbf3bd2a5 100644 --- a/include/xrpl/json/json_errors.h +++ b/include/xrpl/json/json_errors.h @@ -1,5 +1,4 @@ -#ifndef XRPL_JSON_JSON_ERRORS_H_INCLUDED -#define XRPL_JSON_JSON_ERRORS_H_INCLUDED +#pragma once #include @@ -11,5 +10,3 @@ struct error : std::runtime_error }; } // namespace Json - -#endif // JSON_FORWARDS_H_INCLUDED diff --git a/include/xrpl/json/json_forwards.h b/include/xrpl/json/json_forwards.h index 7a6c444660..612648a5f4 100644 --- a/include/xrpl/json/json_forwards.h +++ b/include/xrpl/json/json_forwards.h @@ -1,5 +1,4 @@ -#ifndef XRPL_JSON_JSON_FORWARDS_H_INCLUDED -#define XRPL_JSON_JSON_FORWARDS_H_INCLUDED +#pragma once namespace Json { @@ -13,5 +12,3 @@ class ValueIterator; class ValueConstIterator; } // namespace Json - -#endif // JSON_FORWARDS_H_INCLUDED diff --git a/include/xrpl/json/json_reader.h b/include/xrpl/json/json_reader.h index 2a8ec5a3fe..3a1bc38929 100644 --- a/include/xrpl/json/json_reader.h +++ b/include/xrpl/json/json_reader.h @@ -1,5 +1,4 @@ -#ifndef XRPL_JSON_JSON_READER_H_INCLUDED -#define XRPL_JSON_JSON_READER_H_INCLUDED +#pragma once #include #include @@ -144,26 +143,15 @@ private: bool decodeDouble(Token& token); bool - decodeUnicodeCodePoint( - Token& token, - Location& current, - Location end, - unsigned int& unicode); + decodeUnicodeCodePoint(Token& token, Location& current, Location end, unsigned int& unicode); bool - decodeUnicodeEscapeSequence( - Token& token, - Location& current, - Location end, - unsigned int& unicode); + decodeUnicodeEscapeSequence(Token& token, Location& current, Location end, unsigned int& unicode); bool addError(std::string const& message, Token& token, Location extra = 0); bool recoverFromError(TokenType skipUntilToken); bool - addErrorAndRecover( - std::string const& message, - Token& token, - TokenType skipUntilToken); + addErrorAndRecover(std::string const& message, Token& token, TokenType skipUntilToken); void skipUntilSpace(); Value& @@ -228,5 +216,3 @@ std::istream& operator>>(std::istream&, Value&); } // namespace Json - -#endif // XRPL_JSON_JSON_READER_H_INCLUDED diff --git a/include/xrpl/json/json_value.h b/include/xrpl/json/json_value.h index 979e7fd788..5895c94065 100644 --- a/include/xrpl/json/json_value.h +++ b/include/xrpl/json/json_value.h @@ -1,5 +1,4 @@ -#ifndef XRPL_JSON_JSON_VALUE_H_INCLUDED -#define XRPL_JSON_JSON_VALUE_H_INCLUDED +#pragma once #include #include @@ -148,11 +147,7 @@ private: class CZString { public: - enum DuplicationPolicy { - noDuplication = 0, - duplicate, - duplicateOnCopy - }; + enum DuplicationPolicy { noDuplication = 0, duplicate, duplicateOnCopy }; CZString(int index); CZString(char const* cstr, DuplicationPolicy allocate); CZString(CZString const& other); @@ -681,5 +676,3 @@ public: }; } // namespace Json - -#endif // XRPL_JSON_JSON_VALUE_H_INCLUDED diff --git a/include/xrpl/json/json_writer.h b/include/xrpl/json/json_writer.h index 08e7b619b2..9455d4abd9 100644 --- a/include/xrpl/json/json_writer.h +++ b/include/xrpl/json/json_writer.h @@ -1,5 +1,4 @@ -#ifndef XRPL_JSON_JSON_WRITER_H_INCLUDED -#define XRPL_JSON_JSON_WRITER_H_INCLUDED +#pragma once #include #include @@ -316,14 +315,9 @@ public: operator<<(std::ostream& o, Compact const& cJv) { detail::write_value( - [&o](void const* data, std::size_t n) { - o.write(static_cast(data), n); - }, - cJv.jv_); + [&o](void const* data, std::size_t n) { o.write(static_cast(data), n); }, cJv.jv_); return o; } }; } // namespace Json - -#endif // JSON_WRITER_H_INCLUDED diff --git a/include/xrpl/json/to_string.h b/include/xrpl/json/to_string.h index a930c29231..fb379f5759 100644 --- a/include/xrpl/json/to_string.h +++ b/include/xrpl/json/to_string.h @@ -1,5 +1,4 @@ -#ifndef XRPL_JSON_TO_STRING_H_INCLUDED -#define XRPL_JSON_TO_STRING_H_INCLUDED +#pragma once #include #include @@ -21,5 +20,3 @@ std::ostream& operator<<(std::ostream&, Value const& root); } // namespace Json - -#endif // JSON_TO_STRING_H_INCLUDED diff --git a/src/xrpld/app/ledger/AcceptedLedgerTx.h b/include/xrpl/ledger/AcceptedLedgerTx.h similarity index 90% rename from src/xrpld/app/ledger/AcceptedLedgerTx.h rename to include/xrpl/ledger/AcceptedLedgerTx.h index efea5b9162..d07016b860 100644 --- a/src/xrpld/app/ledger/AcceptedLedgerTx.h +++ b/include/xrpl/ledger/AcceptedLedgerTx.h @@ -1,16 +1,15 @@ -#ifndef XRPL_APP_LEDGER_ACCEPTEDLEDGERTX_H_INCLUDED -#define XRPL_APP_LEDGER_ACCEPTEDLEDGERTX_H_INCLUDED - -#include +#pragma once +#include +#include #include +#include +#include #include namespace xrpl { -class Logs; - /** A transaction that is in a closed ledger. @@ -86,5 +85,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/include/xrpl/ledger/ApplyView.h b/include/xrpl/ledger/ApplyView.h index 393af2a7fd..2de5f79452 100644 --- a/include/xrpl/ledger/ApplyView.h +++ b/include/xrpl/ledger/ApplyView.h @@ -1,5 +1,4 @@ -#ifndef XRPL_LEDGER_APPLYVIEW_H_INCLUDED -#define XRPL_LEDGER_APPLYVIEW_H_INCLUDED +#pragma once #include #include @@ -34,23 +33,17 @@ constexpr ApplyFlags operator|(ApplyFlags const& lhs, ApplyFlags const& rhs) { return safe_cast( - safe_cast>(lhs) | - safe_cast>(rhs)); + safe_cast>(lhs) | safe_cast>(rhs)); } -static_assert( - (tapFAIL_HARD | tapRETRY) == safe_cast(0x30u), - "ApplyFlags operator |"); -static_assert( - (tapRETRY | tapFAIL_HARD) == safe_cast(0x30u), - "ApplyFlags operator |"); +static_assert((tapFAIL_HARD | tapRETRY) == safe_cast(0x30u), "ApplyFlags operator |"); +static_assert((tapRETRY | tapFAIL_HARD) == safe_cast(0x30u), "ApplyFlags operator |"); constexpr ApplyFlags operator&(ApplyFlags const& lhs, ApplyFlags const& rhs) { return safe_cast( - safe_cast>(lhs) & - safe_cast>(rhs)); + safe_cast>(lhs) & safe_cast>(rhs)); } static_assert((tapFAIL_HARD & tapRETRY) == tapNONE, "ApplyFlags operator &"); @@ -59,13 +52,10 @@ static_assert((tapRETRY & tapFAIL_HARD) == tapNONE, "ApplyFlags operator &"); constexpr ApplyFlags operator~(ApplyFlags const& flags) { - return safe_cast( - ~safe_cast>(flags)); + return safe_cast(~safe_cast>(flags)); } -static_assert( - ~tapRETRY == safe_cast(0xFFFFFFDFu), - "ApplyFlags operator ~"); +static_assert(~tapRETRY == safe_cast(0xFFFFFFDFu), "ApplyFlags operator ~"); inline ApplyFlags operator|=(ApplyFlags& lhs, ApplyFlags const& rhs) @@ -221,21 +211,14 @@ public: // Called when a credit is made to an account // This is required to support PaymentSandbox virtual void - creditHook( - AccountID const& from, - AccountID const& to, - STAmount const& amount, - STAmount const& preCreditBalance) + creditHook(AccountID const& from, AccountID const& to, STAmount const& amount, STAmount const& preCreditBalance) { } // Called when the owner count changes // This is required to support PaymentSandbox virtual void - adjustOwnerCountHook( - AccountID const& account, - std::uint32_t cur, - std::uint32_t next) + adjustOwnerCountHook(AccountID const& account, std::uint32_t cur, std::uint32_t next) { } @@ -332,18 +315,10 @@ public: */ /** @{ */ bool - dirRemove( - Keylet const& directory, - std::uint64_t page, - uint256 const& key, - bool keepRoot); + dirRemove(Keylet const& directory, std::uint64_t page, uint256 const& key, bool keepRoot); bool - dirRemove( - Keylet const& directory, - std::uint64_t page, - Keylet const& key, - bool keepRoot) + dirRemove(Keylet const& directory, std::uint64_t page, Keylet const& key, bool keepRoot) { return dirRemove(directory, page, key.key, keepRoot); } @@ -351,9 +326,7 @@ public: /** Remove the specified directory, invoking the callback for every node. */ bool - dirDelete( - Keylet const& directory, - std::function const&); + dirDelete(Keylet const& directory, std::function const&); /** Remove the specified directory, if it is empty. @@ -408,5 +381,3 @@ insertPage( } // namespace directory } // namespace xrpl - -#endif diff --git a/include/xrpl/ledger/ApplyViewImpl.h b/include/xrpl/ledger/ApplyViewImpl.h index 0c11726135..f6c83462f2 100644 --- a/include/xrpl/ledger/ApplyViewImpl.h +++ b/include/xrpl/ledger/ApplyViewImpl.h @@ -1,5 +1,4 @@ -#ifndef XRPL_LEDGER_APPLYVIEWIMPL_H_INCLUDED -#define XRPL_LEDGER_APPLYVIEWIMPL_H_INCLUDED +#pragma once #include #include @@ -34,13 +33,7 @@ public: destructor. */ std::optional - apply( - OpenView& to, - STTx const& tx, - TER ter, - std::optional parentBatchId, - bool isDryRun, - beast::Journal j); + apply(OpenView& to, STTx const& tx, TER ter, std::optional parentBatchId, bool isDryRun, beast::Journal j); /** Set the amount of currency delivered. @@ -76,5 +69,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/include/xrpl/ledger/BookDirs.h b/include/xrpl/ledger/BookDirs.h index daa1ef172a..eb1cbcbfa7 100644 --- a/include/xrpl/ledger/BookDirs.h +++ b/include/xrpl/ledger/BookDirs.h @@ -1,5 +1,4 @@ -#ifndef XRPL_LEDGER_BOOK_DIRS_H_INCLUDED -#define XRPL_LEDGER_BOOK_DIRS_H_INCLUDED +#pragma once #include #include @@ -68,10 +67,7 @@ public: private: friend class BookDirs; - const_iterator( - ReadView const& view, - uint256 const& root, - uint256 const& dir_key) + const_iterator(ReadView const& view, uint256 const& root, uint256 const& dir_key) : view_(&view), root_(root), key_(dir_key), cur_key_(dir_key) { } @@ -90,5 +86,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/src/xrpld/app/ledger/BookListeners.h b/include/xrpl/ledger/BookListeners.h similarity index 89% rename from src/xrpld/app/ledger/BookListeners.h rename to include/xrpl/ledger/BookListeners.h index 784172974e..3ed267448b 100644 --- a/src/xrpld/app/ledger/BookListeners.h +++ b/include/xrpl/ledger/BookListeners.h @@ -1,9 +1,7 @@ -#ifndef XRPL_APP_LEDGER_BOOKLISTENERS_H_INCLUDED -#define XRPL_APP_LEDGER_BOOKLISTENERS_H_INCLUDED - -#include +#pragma once #include +#include #include #include @@ -51,5 +49,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/include/xrpl/ledger/CachedSLEs.h b/include/xrpl/ledger/CachedSLEs.h index b478b78b7d..2909501b1d 100644 --- a/include/xrpl/ledger/CachedSLEs.h +++ b/include/xrpl/ledger/CachedSLEs.h @@ -1,5 +1,4 @@ -#ifndef XRPL_LEDGER_CACHEDSLES_H_INCLUDED -#define XRPL_LEDGER_CACHEDSLES_H_INCLUDED +#pragma once #include #include @@ -8,5 +7,3 @@ namespace xrpl { using CachedSLEs = TaggedCache; } - -#endif // XRPL_LEDGER_CACHEDSLES_H_INCLUDED diff --git a/include/xrpl/ledger/CachedView.h b/include/xrpl/ledger/CachedView.h index c1d66ecfc9..7cab1dc1b3 100644 --- a/include/xrpl/ledger/CachedView.h +++ b/include/xrpl/ledger/CachedView.h @@ -1,5 +1,4 @@ -#ifndef XRPL_LEDGER_CACHEDVIEW_H_INCLUDED -#define XRPL_LEDGER_CACHEDVIEW_H_INCLUDED +#pragma once #include #include @@ -26,8 +25,7 @@ public: CachedViewImpl& operator=(CachedViewImpl const&) = delete; - CachedViewImpl(DigestAwareReadView const* base, CachedSLEs& cache) - : base_(*base), cache_(cache) + CachedViewImpl(DigestAwareReadView const* base, CachedSLEs& cache) : base_(*base), cache_(cache) { } @@ -66,9 +64,7 @@ public: } std::optional - succ( - key_type const& key, - std::optional const& last = std::nullopt) const override + succ(key_type const& key, std::optional const& last = std::nullopt) const override { return base_.succ(key, last); } @@ -165,5 +161,3 @@ public: }; } // namespace xrpl - -#endif diff --git a/include/xrpl/ledger/CredentialHelpers.h b/include/xrpl/ledger/CredentialHelpers.h index b90aa44c0d..3744ff47eb 100644 --- a/include/xrpl/ledger/CredentialHelpers.h +++ b/include/xrpl/ledger/CredentialHelpers.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_MISC_CREDENTIALHELPERS_H_INCLUDED -#define XRPL_APP_MISC_CREDENTIALHELPERS_H_INCLUDED +#pragma once #include #include @@ -20,9 +19,7 @@ namespace credentials { // Check if credential sfExpiration field has passed ledger's parentCloseTime bool -checkExpired( - std::shared_ptr const& sleCredential, - NetClock::time_point const& closed); +checkExpired(std::shared_ptr const& sleCredential, NetClock::time_point const& closed); // Return true if any expired credential was found in arr (and deleted) bool @@ -30,10 +27,7 @@ removeExpired(ApplyView& view, STVector256 const& arr, beast::Journal const j); // Actually remove a credentials object from the ledger TER -deleteSLE( - ApplyView& view, - std::shared_ptr const& sleCredential, - beast::Journal j); +deleteSLE(ApplyView& view, std::shared_ptr const& sleCredential, beast::Journal j); // Amendment and parameters checks for sfCredentialIDs field NotTEC @@ -44,11 +38,7 @@ checkFields(STTx const& tx, beast::Journal j); // If you call it in preclaim, you also must call verifyDepositPreauth in // doApply TER -valid( - STTx const& tx, - ReadView const& view, - AccountID const& src, - beast::Journal j); +valid(STTx const& tx, ReadView const& view, AccountID const& src, beast::Journal j); // Check if subject has any credential maching the given domain. If you call it // in preclaim and it returns tecEXPIRED, you should call verifyValidDomain in @@ -59,10 +49,7 @@ validDomain(ReadView const& view, uint256 domainID, AccountID const& subject); // This function is only called when we about to return tecNO_PERMISSION // because all the checks for the DepositPreauth authorization failed. TER -authorizedDepositPreauth( - ApplyView const& view, - STVector256 const& ctx, - AccountID const& dst); +authorizedDepositPreauth(ApplyView const& view, STVector256 const& ctx, AccountID const& dst); // Sort credentials array, return empty set if there are duplicates std::set> @@ -78,11 +65,7 @@ checkArray(STArray const& credentials, unsigned maxSize, beast::Journal j); // Check expired credentials and for credentials maching DomainID of the ledger // object TER -verifyValidDomain( - ApplyView& view, - AccountID const& account, - uint256 domainID, - beast::Journal j); +verifyValidDomain(ApplyView& view, AccountID const& account, uint256 domainID, beast::Journal j); // Check expired credentials and for existing DepositPreauth ledger object TER @@ -95,5 +78,3 @@ verifyDepositPreauth( beast::Journal j); } // namespace xrpl - -#endif diff --git a/include/xrpl/ledger/Credit.h b/include/xrpl/ledger/Credit.h index 09b65b3dde..58ec23a86a 100644 --- a/include/xrpl/ledger/Credit.h +++ b/include/xrpl/ledger/Credit.h @@ -1,5 +1,4 @@ -#ifndef XRPL_LEDGER_CREDIT_H_INCLUDED -#define XRPL_LEDGER_CREDIT_H_INCLUDED +#pragma once #include #include @@ -16,18 +15,10 @@ namespace xrpl { */ /** @{ */ STAmount -creditLimit( - ReadView const& view, - AccountID const& account, - AccountID const& issuer, - Currency const& currency); +creditLimit(ReadView const& view, AccountID const& account, AccountID const& issuer, Currency const& currency); IOUAmount -creditLimit2( - ReadView const& v, - AccountID const& acc, - AccountID const& iss, - Currency const& cur); +creditLimit2(ReadView const& v, AccountID const& acc, AccountID const& iss, Currency const& cur); /** @} */ /** Returns the amount of IOUs issued by issuer that are held by an account @@ -38,13 +29,7 @@ creditLimit2( */ /** @{ */ STAmount -creditBalance( - ReadView const& view, - AccountID const& account, - AccountID const& issuer, - Currency const& currency); +creditBalance(ReadView const& view, AccountID const& account, AccountID const& issuer, Currency const& currency); /** @} */ } // namespace xrpl - -#endif diff --git a/include/xrpl/ledger/Dir.h b/include/xrpl/ledger/Dir.h index 4b7327a015..0c2f1e3765 100644 --- a/include/xrpl/ledger/Dir.h +++ b/include/xrpl/ledger/Dir.h @@ -1,5 +1,4 @@ -#ifndef XRPL_LEDGER_DIR_H_INCLUDED -#define XRPL_LEDGER_DIR_H_INCLUDED +#pragma once #include #include @@ -109,5 +108,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/include/xrpl/ledger/OpenView.h b/include/xrpl/ledger/OpenView.h index bd90dbef18..42f62d5bca 100644 --- a/include/xrpl/ledger/OpenView.h +++ b/include/xrpl/ledger/OpenView.h @@ -1,5 +1,4 @@ -#ifndef XRPL_LEDGER_OPENVIEW_H_INCLUDED -#define XRPL_LEDGER_OPENVIEW_H_INCLUDED +#pragma once #include #include @@ -58,9 +57,7 @@ private: std::shared_ptr meta; // Constructor needed for emplacement in std::map - txData( - std::shared_ptr const& txn_, - std::shared_ptr const& meta_) + txData(std::shared_ptr const& txn_, std::shared_ptr const& meta_) : txn(txn_), meta(meta_) { } @@ -73,13 +70,11 @@ private: key_type, txData, std::less, - boost::container::pmr::polymorphic_allocator< - std::pair>>; + boost::container::pmr::polymorphic_allocator>>; // monotonic_resource_ must outlive `items_`. Make a pointer so it may be // easily moved. - std::unique_ptr - monotonic_resource_; + std::unique_ptr monotonic_resource_; txs_map txs_; Rules rules_; LedgerHeader header_; @@ -135,16 +130,9 @@ public: The tx list starts empty and will contain all newly inserted tx. */ - OpenView( - open_ledger_t, - ReadView const* base, - Rules const& rules, - std::shared_ptr hold = nullptr); + OpenView(open_ledger_t, ReadView const* base, Rules const& rules, std::shared_ptr hold = nullptr); - OpenView( - open_ledger_t, - Rules const& rules, - std::shared_ptr const& base) + OpenView(open_ledger_t, Rules const& rules, std::shared_ptr const& base) : OpenView(open_ledger, &*base, rules, base) { } @@ -201,9 +189,7 @@ public: exists(Keylet const& k) const override; std::optional - succ( - key_type const& key, - std::optional const& last = std::nullopt) const override; + succ(key_type const& key, std::optional const& last = std::nullopt) const override; std::shared_ptr read(Keylet const& k) const override; @@ -253,5 +239,3 @@ public: }; } // namespace xrpl - -#endif diff --git a/include/xrpl/ledger/OrderBookDB.h b/include/xrpl/ledger/OrderBookDB.h new file mode 100644 index 0000000000..3d689607bf --- /dev/null +++ b/include/xrpl/ledger/OrderBookDB.h @@ -0,0 +1,93 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace xrpl { + +/** Tracks order books in the ledger. + + This interface provides access to order book information, including: + - Which order books exist in the ledger + - Querying order books by issue + - Managing order book subscriptions + + The order book database is updated as ledgers are accepted and provides + efficient lookup of order book information for pathfinding and client + subscriptions. +*/ +class OrderBookDB +{ +public: + virtual ~OrderBookDB() = default; + + /** Initialize or update the order book database with a new ledger. + + This method should be called when a new ledger is accepted to update + the order book database with the current state of all order books. + + @param ledger The ledger to scan for order books + */ + virtual void + setup(std::shared_ptr const& ledger) = 0; + + /** Add an order book to track. + + @param book The order book to add + */ + virtual void + addOrderBook(Book const& book) = 0; + + /** Get all order books that want a specific issue. + + Returns a list of all order books where the taker pays the specified + issue. This is useful for pathfinding to find all possible next hops + from a given currency. + + @param issue The issue to search for + @param domain Optional domain restriction for the order book + @return Vector of books that want this issue + */ + virtual std::vector + getBooksByTakerPays(Issue const& issue, std::optional const& domain = std::nullopt) = 0; + + /** Get the count of order books that want a specific issue. + + @param issue The issue to search for + @param domain Optional domain restriction for the order book + @return Number of books that want this issue + */ + virtual int + getBookSize(Issue const& issue, std::optional const& domain = std::nullopt) = 0; + + /** Check if an order book to XRP exists for the given issue. + + @param issue The issue to check + @param domain Optional domain restriction for the order book + @return true if a book from this issue to XRP exists + */ + virtual bool + isBookToXRP(Issue const& issue, std::optional domain = std::nullopt) = 0; + + virtual void + processTxn( + std::shared_ptr const& ledger, + AcceptedLedgerTx const& alTx, + MultiApiJson const& jvObj) = 0; + + virtual BookListeners::pointer + getBookListeners(Book const&) = 0; + virtual BookListeners::pointer + makeBookListeners(Book const&) = 0; +}; + +} // namespace xrpl diff --git a/include/xrpl/ledger/PaymentSandbox.h b/include/xrpl/ledger/PaymentSandbox.h index e1d197380d..fe62d753ec 100644 --- a/include/xrpl/ledger/PaymentSandbox.h +++ b/include/xrpl/ledger/PaymentSandbox.h @@ -1,5 +1,4 @@ -#ifndef XRPL_LEDGER_PAYMENTSANDBOX_H_INCLUDED -#define XRPL_LEDGER_PAYMENTSANDBOX_H_INCLUDED +#pragma once #include #include @@ -19,8 +18,7 @@ class DeferredCredits public: struct Adjustment { - Adjustment(STAmount const& d, STAmount const& c, STAmount const& b) - : debits(d), credits(c), origBalance(b) + Adjustment(STAmount const& d, STAmount const& c, STAmount const& b) : debits(d), credits(c), origBalance(b) { } STAmount debits; @@ -31,10 +29,7 @@ public: // Get the adjustments for the balance between main and other. // Returns the debits, credits and the original balance std::optional - adjustments( - AccountID const& main, - AccountID const& other, - Currency const& currency) const; + adjustments(AccountID const& main, AccountID const& other, Currency const& currency) const; void credit( @@ -102,8 +97,7 @@ public: PaymentSandbox(PaymentSandbox&&) = default; - PaymentSandbox(ReadView const* base, ApplyFlags flags) - : ApplyViewBase(base, flags) + PaymentSandbox(ReadView const* base, ApplyFlags flags) : ApplyViewBase(base, flags) { } @@ -125,39 +119,27 @@ public: // or a PaymentSandbox-derived class, we MUST go through // one of these constructors or invariants will be broken. /** @{ */ - explicit PaymentSandbox(PaymentSandbox const* base) - : ApplyViewBase(base, base->flags()), ps_(base) + explicit PaymentSandbox(PaymentSandbox const* base) : ApplyViewBase(base, base->flags()), ps_(base) { } - explicit PaymentSandbox(PaymentSandbox* base) - : ApplyViewBase(base, base->flags()), ps_(base) + explicit PaymentSandbox(PaymentSandbox* base) : ApplyViewBase(base, base->flags()), ps_(base) { } /** @} */ STAmount - balanceHook( - AccountID const& account, - AccountID const& issuer, - STAmount const& amount) const override; + balanceHook(AccountID const& account, AccountID const& issuer, STAmount const& amount) const override; void - creditHook( - AccountID const& from, - AccountID const& to, - STAmount const& amount, - STAmount const& preCreditBalance) override; + creditHook(AccountID const& from, AccountID const& to, STAmount const& amount, STAmount const& preCreditBalance) + override; void - adjustOwnerCountHook( - AccountID const& account, - std::uint32_t cur, - std::uint32_t next) override; + adjustOwnerCountHook(AccountID const& account, std::uint32_t cur, std::uint32_t next) override; std::uint32_t - ownerCountHook(AccountID const& account, std::uint32_t count) - const override; + ownerCountHook(AccountID const& account, std::uint32_t count) const override; /** Apply changes to base view. @@ -189,5 +171,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/include/xrpl/ledger/RawView.h b/include/xrpl/ledger/RawView.h index c0e81fb833..cfcf807e13 100644 --- a/include/xrpl/ledger/RawView.h +++ b/include/xrpl/ledger/RawView.h @@ -1,5 +1,4 @@ -#ifndef XRPL_LEDGER_RAWVIEW_H_INCLUDED -#define XRPL_LEDGER_RAWVIEW_H_INCLUDED +#pragma once #include #include @@ -88,5 +87,3 @@ public: }; } // namespace xrpl - -#endif diff --git a/include/xrpl/ledger/ReadView.h b/include/xrpl/ledger/ReadView.h index d2b6796ec9..faec10993a 100644 --- a/include/xrpl/ledger/ReadView.h +++ b/include/xrpl/ledger/ReadView.h @@ -1,5 +1,4 @@ -#ifndef XRPL_LEDGER_READVIEW_H_INCLUDED -#define XRPL_LEDGER_READVIEW_H_INCLUDED +#pragma once #include #include @@ -31,8 +30,7 @@ namespace xrpl { class ReadView { public: - using tx_type = - std::pair, std::shared_ptr>; + using tx_type = std::pair, std::shared_ptr>; using key_type = uint256; @@ -130,9 +128,7 @@ public: interval (key, last). */ virtual std::optional - succ( - key_type const& key, - std::optional const& last = std::nullopt) const = 0; + succ(key_type const& key, std::optional const& last = std::nullopt) const = 0; /** Return the state item associated with a key. @@ -156,10 +152,7 @@ public: // balances so newly acquired assets are not counted toward the balance. // This is required to support PaymentSandbox. virtual STAmount - balanceHook( - AccountID const& account, - AccountID const& issuer, - STAmount const& amount) const + balanceHook(AccountID const& account, AccountID const& issuer, STAmount const& amount) const { return amount; } @@ -254,12 +247,8 @@ Rules makeRulesGivenLedger(DigestAwareReadView const& ledger, Rules const& current); Rules -makeRulesGivenLedger( - DigestAwareReadView const& ledger, - std::unordered_set> const& presets); +makeRulesGivenLedger(DigestAwareReadView const& ledger, std::unordered_set> const& presets); } // namespace xrpl #include - -#endif diff --git a/include/xrpl/ledger/Sandbox.h b/include/xrpl/ledger/Sandbox.h index 1e4a816529..dc80df5ba2 100644 --- a/include/xrpl/ledger/Sandbox.h +++ b/include/xrpl/ledger/Sandbox.h @@ -1,5 +1,4 @@ -#ifndef XRPL_LEDGER_SANDBOX_H_INCLUDED -#define XRPL_LEDGER_SANDBOX_H_INCLUDED +#pragma once #include #include @@ -40,5 +39,3 @@ public: }; } // namespace xrpl - -#endif diff --git a/include/xrpl/ledger/View.h b/include/xrpl/ledger/View.h index 707a08b890..fa16e16006 100644 --- a/include/xrpl/ledger/View.h +++ b/include/xrpl/ledger/View.h @@ -1,5 +1,4 @@ -#ifndef XRPL_LEDGER_VIEW_H_INCLUDED -#define XRPL_LEDGER_VIEW_H_INCLUDED +#pragma once #include #include @@ -75,70 +74,37 @@ isGlobalFrozen(ReadView const& view, Asset const& asset); // Note, depth parameter is used to limit the recursion depth [[nodiscard]] bool -isVaultPseudoAccountFrozen( - ReadView const& view, - AccountID const& account, - MPTIssue const& mptShare, - int depth); +isVaultPseudoAccountFrozen(ReadView const& view, AccountID const& account, MPTIssue const& mptShare, int depth); [[nodiscard]] bool -isIndividualFrozen( - ReadView const& view, - AccountID const& account, - Currency const& currency, - AccountID const& issuer); +isIndividualFrozen(ReadView const& view, AccountID const& account, Currency const& currency, AccountID const& issuer); [[nodiscard]] inline bool -isIndividualFrozen( - ReadView const& view, - AccountID const& account, - Issue const& issue) +isIndividualFrozen(ReadView const& view, AccountID const& account, Issue const& issue) { return isIndividualFrozen(view, account, issue.currency, issue.account); } [[nodiscard]] bool -isIndividualFrozen( - ReadView const& view, - AccountID const& account, - MPTIssue const& mptIssue); +isIndividualFrozen(ReadView const& view, AccountID const& account, MPTIssue const& mptIssue); [[nodiscard]] inline bool -isIndividualFrozen( - ReadView const& view, - AccountID const& account, - Asset const& asset) +isIndividualFrozen(ReadView const& view, AccountID const& account, Asset const& asset) { - return std::visit( - [&](auto const& issue) { - return isIndividualFrozen(view, account, issue); - }, - asset.value()); + return std::visit([&](auto const& issue) { return isIndividualFrozen(view, account, issue); }, asset.value()); } [[nodiscard]] bool -isFrozen( - ReadView const& view, - AccountID const& account, - Currency const& currency, - AccountID const& issuer); +isFrozen(ReadView const& view, AccountID const& account, Currency const& currency, AccountID const& issuer); [[nodiscard]] inline bool -isFrozen( - ReadView const& view, - AccountID const& account, - Issue const& issue, - int = 0 /*ignored*/) +isFrozen(ReadView const& view, AccountID const& account, Issue const& issue, int = 0 /*ignored*/) { return isFrozen(view, account, issue.currency, issue.account); } [[nodiscard]] bool -isFrozen( - ReadView const& view, - AccountID const& account, - MPTIssue const& mptIssue, - int depth = 0); +isFrozen(ReadView const& view, AccountID const& account, MPTIssue const& mptIssue, int depth = 0); /** * isFrozen check is recursive for MPT shares in a vault, descending to @@ -146,17 +112,9 @@ isFrozen( * purely defensive, as we currently do not allow such vaults to be created. */ [[nodiscard]] inline bool -isFrozen( - ReadView const& view, - AccountID const& account, - Asset const& asset, - int depth = 0) +isFrozen(ReadView const& view, AccountID const& account, Asset const& asset, int depth = 0) { - return std::visit( - [&](auto const& issue) { - return isFrozen(view, account, issue, depth); - }, - asset.value()); + return std::visit([&](auto const& issue) { return isFrozen(view, account, issue, depth); }, asset.value()); } [[nodiscard]] inline TER @@ -166,10 +124,7 @@ checkFrozen(ReadView const& view, AccountID const& account, Issue const& issue) } [[nodiscard]] inline TER -checkFrozen( - ReadView const& view, - AccountID const& account, - MPTIssue const& mptIssue) +checkFrozen(ReadView const& view, AccountID const& account, MPTIssue const& mptIssue) { return isFrozen(view, account, mptIssue) ? (TER)tecLOCKED : (TER)tesSUCCESS; } @@ -177,9 +132,7 @@ checkFrozen( [[nodiscard]] inline TER checkFrozen(ReadView const& view, AccountID const& account, Asset const& asset) { - return std::visit( - [&](auto const& issue) { return checkFrozen(view, account, issue); }, - asset.value()); + return std::visit([&](auto const& issue) { return checkFrozen(view, account, issue); }, asset.value()); } [[nodiscard]] bool @@ -190,10 +143,7 @@ isAnyFrozen( int depth = 0); [[nodiscard]] inline bool -isAnyFrozen( - ReadView const& view, - std::initializer_list const& accounts, - Issue const& issue) +isAnyFrozen(ReadView const& view, std::initializer_list const& accounts, Issue const& issue) { for (auto const& account : accounts) { @@ -204,11 +154,7 @@ isAnyFrozen( } [[nodiscard]] inline bool -isAnyFrozen( - ReadView const& view, - std::initializer_list const& accounts, - Asset const& asset, - int depth = 0) +isAnyFrozen(ReadView const& view, std::initializer_list const& accounts, Asset const& asset, int depth = 0) { return std::visit( [&](TIss const& issue) { @@ -221,28 +167,16 @@ isAnyFrozen( } [[nodiscard]] bool -isDeepFrozen( - ReadView const& view, - AccountID const& account, - Currency const& currency, - AccountID const& issuer); +isDeepFrozen(ReadView const& view, AccountID const& account, Currency const& currency, AccountID const& issuer); [[nodiscard]] inline bool -isDeepFrozen( - ReadView const& view, - AccountID const& account, - Issue const& issue, - int = 0 /*ignored*/) +isDeepFrozen(ReadView const& view, AccountID const& account, Issue const& issue, int = 0 /*ignored*/) { return isDeepFrozen(view, account, issue.currency, issue.account); } [[nodiscard]] inline bool -isDeepFrozen( - ReadView const& view, - AccountID const& account, - MPTIssue const& mptIssue, - int depth = 0) +isDeepFrozen(ReadView const& view, AccountID const& account, MPTIssue const& mptIssue, int depth = 0) { // Unlike IOUs, frozen / locked MPTs are not allowed to send or receive // funds, so checking "deep frozen" is the same as checking "frozen". @@ -255,58 +189,31 @@ isDeepFrozen( * purely defensive, as we currently do not allow such vaults to be created. */ [[nodiscard]] inline bool -isDeepFrozen( - ReadView const& view, - AccountID const& account, - Asset const& asset, - int depth = 0) +isDeepFrozen(ReadView const& view, AccountID const& account, Asset const& asset, int depth = 0) { - return std::visit( - [&](auto const& issue) { - return isDeepFrozen(view, account, issue, depth); - }, - asset.value()); + return std::visit([&](auto const& issue) { return isDeepFrozen(view, account, issue, depth); }, asset.value()); } [[nodiscard]] inline TER -checkDeepFrozen( - ReadView const& view, - AccountID const& account, - Issue const& issue) +checkDeepFrozen(ReadView const& view, AccountID const& account, Issue const& issue) { - return isDeepFrozen(view, account, issue) ? (TER)tecFROZEN - : (TER)tesSUCCESS; + return isDeepFrozen(view, account, issue) ? (TER)tecFROZEN : (TER)tesSUCCESS; } [[nodiscard]] inline TER -checkDeepFrozen( - ReadView const& view, - AccountID const& account, - MPTIssue const& mptIssue) +checkDeepFrozen(ReadView const& view, AccountID const& account, MPTIssue const& mptIssue) { - return isDeepFrozen(view, account, mptIssue) ? (TER)tecLOCKED - : (TER)tesSUCCESS; + return isDeepFrozen(view, account, mptIssue) ? (TER)tecLOCKED : (TER)tesSUCCESS; } [[nodiscard]] inline TER -checkDeepFrozen( - ReadView const& view, - AccountID const& account, - Asset const& asset) +checkDeepFrozen(ReadView const& view, AccountID const& account, Asset const& asset) { - return std::visit( - [&](auto const& issue) { - return checkDeepFrozen(view, account, issue); - }, - asset.value()); + return std::visit([&](auto const& issue) { return checkDeepFrozen(view, account, issue); }, asset.value()); } [[nodiscard]] bool -isLPTokenFrozen( - ReadView const& view, - AccountID const& account, - Issue const& asset, - Issue const& asset2); +isLPTokenFrozen(ReadView const& view, AccountID const& account, Issue const& asset, Issue const& asset2); // Returns the amount an account can spend. // @@ -380,18 +287,11 @@ accountFunds( // // @param ownerCountAdj positive to add to count, negative to reduce count. [[nodiscard]] XRPAmount -xrpLiquid( - ReadView const& view, - AccountID const& id, - std::int32_t ownerCountAdj, - beast::Journal j); +xrpLiquid(ReadView const& view, AccountID const& id, std::int32_t ownerCountAdj, beast::Journal j); /** Iterate all items in the given directory. */ void -forEachItem( - ReadView const& view, - Keylet const& root, - std::function const&)> const& f); +forEachItem(ReadView const& view, Keylet const& root, std::function const&)> const& f); /** Iterate all items after an item in the given directory. @param after The key of the item to start after @@ -410,10 +310,7 @@ forEachItemAfter( /** Iterate all items in an account's owner directory. */ inline void -forEachItem( - ReadView const& view, - AccountID const& id, - std::function const&)> const& f) +forEachItem(ReadView const& view, AccountID const& id, std::function const&)> const& f) { return forEachItem(view, keylet::ownerDir(id), f); } @@ -510,11 +407,7 @@ getCandidateLedger(LedgerIndex requested) use the second form if you have not acquired the valid ledger yet */ [[nodiscard]] bool -areCompatible( - ReadView const& validLedger, - ReadView const& testLedger, - beast::Journal::Stream& s, - char const* reason); +areCompatible(ReadView const& validLedger, ReadView const& testLedger, beast::Journal::Stream& s, char const* reason); [[nodiscard]] bool areCompatible( @@ -532,11 +425,7 @@ areCompatible( /** Adjust the owner count up or down. */ void -adjustOwnerCount( - ApplyView& view, - std::shared_ptr const& sle, - std::int32_t amount, - beast::Journal j); +adjustOwnerCount(ApplyView& view, std::shared_ptr const& sle, std::int32_t amount, beast::Journal j); /** @{ */ /** Returns the first entry in the directory, advancing the index @@ -562,12 +451,7 @@ cdirFirst( uint256& entry); bool -dirFirst( - ApplyView& view, - uint256 const& root, - std::shared_ptr& page, - unsigned int& index, - uint256& entry); +dirFirst(ApplyView& view, uint256 const& root, std::shared_ptr& page, unsigned int& index, uint256& entry); /** @} */ /** @{ */ @@ -594,23 +478,14 @@ cdirNext( uint256& entry); bool -dirNext( - ApplyView& view, - uint256 const& root, - std::shared_ptr& page, - unsigned int& index, - uint256& entry); +dirNext(ApplyView& view, uint256 const& root, std::shared_ptr& page, unsigned int& index, uint256& entry); /** @} */ [[nodiscard]] std::function describeOwnerDir(AccountID const& account); [[nodiscard]] TER -dirLink( - ApplyView& view, - AccountID const& owner, - std::shared_ptr& object, - SF_UINT64 const& node = sfOwnerNode); +dirLink(ApplyView& view, AccountID const& owner, std::shared_ptr& object, SF_UINT64 const& node = sfOwnerNode); AccountID pseudoAccountAddress(ReadView const& view, uint256 const& pseudoOwnerKey); @@ -624,10 +499,7 @@ pseudoAccountAddress(ReadView const& view, uint256 const& pseudoOwnerKey); * field. The amendment check is **not** performed in createPseudoAccount. */ [[nodiscard]] Expected, TER> -createPseudoAccount( - ApplyView& view, - uint256 const& pseudoOwnerKey, - SField const& ownerField); +createPseudoAccount(ApplyView& view, uint256 const& pseudoOwnerKey, SField const& ownerField); // Returns true if and only if sleAcct is a pseudo-account or specific // pseudo-accounts in pseudoFieldFilter. @@ -637,9 +509,7 @@ createPseudoAccount( // * NOT a ltACCOUNT_ROOT OR // * null pointer [[nodiscard]] bool -isPseudoAccount( - std::shared_ptr sleAcct, - std::set const& pseudoFieldFilter = {}); +isPseudoAccount(std::shared_ptr sleAcct, std::set const& pseudoFieldFilter = {}); // Returns the list of fields that define an ACCOUNT_ROOT as a pseudo-account if // set @@ -653,13 +523,9 @@ isPseudoAccount( getPseudoAccountFields(); [[nodiscard]] inline bool -isPseudoAccount( - ReadView const& view, - AccountID const& accountId, - std::set const& pseudoFieldFilter = {}) +isPseudoAccount(ReadView const& view, AccountID const& accountId, std::set const& pseudoFieldFilter = {}) { - return isPseudoAccount( - view.read(keylet::account(accountId)), pseudoFieldFilter); + return isPseudoAccount(view.read(keylet::account(accountId)), pseudoFieldFilter); } [[nodiscard]] TER @@ -774,8 +640,7 @@ addEmptyHolding( { return std::visit( [&](TIss const& issue) -> TER { - return addEmptyHolding( - view, accountID, priorBalance, issue, journal); + return addEmptyHolding(view, accountID, priorBalance, issue, journal); }, asset.value()); } @@ -818,25 +683,13 @@ trustCreate( beast::Journal j); [[nodiscard]] TER -removeEmptyHolding( - ApplyView& view, - AccountID const& accountID, - Issue const& issue, - beast::Journal journal); +removeEmptyHolding(ApplyView& view, AccountID const& accountID, Issue const& issue, beast::Journal journal); [[nodiscard]] TER -removeEmptyHolding( - ApplyView& view, - AccountID const& accountID, - MPTIssue const& mptIssue, - beast::Journal journal); +removeEmptyHolding(ApplyView& view, AccountID const& accountID, MPTIssue const& mptIssue, beast::Journal journal); [[nodiscard]] inline TER -removeEmptyHolding( - ApplyView& view, - AccountID const& accountID, - Asset const& asset, - beast::Journal journal) +removeEmptyHolding(ApplyView& view, AccountID const& accountID, Asset const& asset, beast::Journal journal) { return std::visit( [&](TIss const& issue) -> TER { @@ -888,11 +741,7 @@ rippleCredit( beast::Journal j); TER -rippleLockEscrowMPT( - ApplyView& view, - AccountID const& uGrantorID, - STAmount const& saAmount, - beast::Journal j); +rippleLockEscrowMPT(ApplyView& view, AccountID const& uGrantorID, STAmount const& saAmount, beast::Journal j); TER rippleUnlockEscrowMPT( @@ -932,28 +781,13 @@ accountSendMulti( WaiveTransferFee waiveFee = WaiveTransferFee::No); [[nodiscard]] TER -issueIOU( - ApplyView& view, - AccountID const& account, - STAmount const& amount, - Issue const& issue, - beast::Journal j); +issueIOU(ApplyView& view, AccountID const& account, STAmount const& amount, Issue const& issue, beast::Journal j); [[nodiscard]] TER -redeemIOU( - ApplyView& view, - AccountID const& account, - STAmount const& amount, - Issue const& issue, - beast::Journal j); +redeemIOU(ApplyView& view, AccountID const& account, STAmount const& amount, Issue const& issue, beast::Journal j); [[nodiscard]] TER -transferXRP( - ApplyView& view, - AccountID const& from, - AccountID const& to, - STAmount const& amount, - beast::Journal j); +transferXRP(ApplyView& view, AccountID const& from, AccountID const& to, STAmount const& amount, beast::Journal j); /* Check if MPToken (for MPT) or trust line (for IOU) exists: * - StrongAuth - before checking if authorization is required @@ -984,11 +818,7 @@ enum class AuthType { StrongAuth, WeakAuth, Legacy }; * The default "Legacy" auth type is equivalent to WeakAuth. */ [[nodiscard]] TER -requireAuth( - ReadView const& view, - Issue const& issue, - AccountID const& account, - AuthType authType = AuthType::Legacy); +requireAuth(ReadView const& view, Issue const& issue, AccountID const& account, AuthType authType = AuthType::Legacy); /** Check if the account lacks required authorization. * @@ -1028,9 +858,7 @@ requireAuth( AuthType authType = AuthType::Legacy) { return std::visit( - [&](TIss const& issue_) { - return requireAuth(view, issue_, account, authType); - }, + [&](TIss const& issue_) { return requireAuth(view, issue_, account, authType); }, asset.value()); } @@ -1070,18 +898,10 @@ enforceMPTokenAuthorization( * and tesSUCCESS otherwise. */ [[nodiscard]] TER -canTransfer( - ReadView const& view, - MPTIssue const& mptIssue, - AccountID const& from, - AccountID const& to); +canTransfer(ReadView const& view, MPTIssue const& mptIssue, AccountID const& from, AccountID const& to); [[nodiscard]] TER -canTransfer( - ReadView const& view, - Issue const& issue, - AccountID const& from, - AccountID const& to); +canTransfer(ReadView const& view, Issue const& issue, AccountID const& from, AccountID const& to); [[nodiscard]] TER inline canTransfer( ReadView const& view, @@ -1090,9 +910,7 @@ canTransfer( AccountID const& to) { return std::visit( - [&](TIss const& issue) -> TER { - return canTransfer(view, issue, from, to); - }, + [&](TIss const& issue) -> TER { return canTransfer(view, issue, from, to); }, asset.value()); } @@ -1100,10 +918,7 @@ canTransfer( * (if should not be skipped) and if the entry should be skipped. The status * is always tesSUCCESS if the entry should be skipped. */ -using EntryDeleter = std::function( - LedgerEntryType, - uint256 const&, - std::shared_ptr&)>; +using EntryDeleter = std::function(LedgerEntryType, uint256 const&, std::shared_ptr&)>; /** Cleanup owner directory entries on account delete. * Used for a regular and AMM accounts deletion. The caller * has to provide the deleter function, which handles details of @@ -1180,5 +995,3 @@ bool after(NetClock::time_point now, std::uint32_t mark); } // namespace xrpl - -#endif diff --git a/include/xrpl/ledger/detail/ApplyStateTable.h b/include/xrpl/ledger/detail/ApplyStateTable.h index f5ec0c9f51..07af5247f6 100644 --- a/include/xrpl/ledger/detail/ApplyStateTable.h +++ b/include/xrpl/ledger/detail/ApplyStateTable.h @@ -1,5 +1,4 @@ -#ifndef XRPL_LEDGER_APPLYSTATETABLE_H_INCLUDED -#define XRPL_LEDGER_APPLYSTATETABLE_H_INCLUDED +#pragma once #include #include @@ -60,10 +59,7 @@ public: exists(ReadView const& base, Keylet const& k) const; std::optional - succ( - ReadView const& base, - key_type const& key, - std::optional const& last) const; + succ(ReadView const& base, key_type const& key, std::optional const& last) const; std::shared_ptr read(ReadView const& base, Keylet const& k) const; @@ -115,19 +111,10 @@ private: threadItem(TxMeta& meta, std::shared_ptr const& to); std::shared_ptr - getForMod( - ReadView const& base, - key_type const& key, - Mods& mods, - beast::Journal j); + getForMod(ReadView const& base, key_type const& key, Mods& mods, beast::Journal j); void - threadTx( - ReadView const& base, - TxMeta& meta, - AccountID const& to, - Mods& mods, - beast::Journal j); + threadTx(ReadView const& base, TxMeta& meta, AccountID const& to, Mods& mods, beast::Journal j); void threadOwners( @@ -140,5 +127,3 @@ private: } // namespace detail } // namespace xrpl - -#endif diff --git a/include/xrpl/ledger/detail/ApplyViewBase.h b/include/xrpl/ledger/detail/ApplyViewBase.h index 9992d73ad1..b3ec3c0fea 100644 --- a/include/xrpl/ledger/detail/ApplyViewBase.h +++ b/include/xrpl/ledger/detail/ApplyViewBase.h @@ -1,5 +1,4 @@ -#ifndef XRPL_LEDGER_APPLYVIEWBASE_H_INCLUDED -#define XRPL_LEDGER_APPLYVIEWBASE_H_INCLUDED +#pragma once #include #include @@ -40,9 +39,7 @@ public: exists(Keylet const& k) const override; std::optional - succ( - key_type const& key, - std::optional const& last = std::nullopt) const override; + succ(key_type const& key, std::optional const& last = std::nullopt) const override; std::shared_ptr read(Keylet const& k) const override; @@ -107,5 +104,3 @@ protected: } // namespace detail } // namespace xrpl - -#endif diff --git a/include/xrpl/ledger/detail/RawStateTable.h b/include/xrpl/ledger/detail/RawStateTable.h index 19d2882a63..e09f2f0e44 100644 --- a/include/xrpl/ledger/detail/RawStateTable.h +++ b/include/xrpl/ledger/detail/RawStateTable.h @@ -1,5 +1,4 @@ -#ifndef XRPL_LEDGER_RAWSTATETABLE_H_INCLUDED -#define XRPL_LEDGER_RAWSTATETABLE_H_INCLUDED +#pragma once #include #include @@ -24,15 +23,11 @@ public: static constexpr size_t initialBufferSize = kilobytes(256); RawStateTable() - : monotonic_resource_{std::make_unique< - boost::container::pmr::monotonic_buffer_resource>( - initialBufferSize)} + : monotonic_resource_{std::make_unique(initialBufferSize)} , items_{monotonic_resource_.get()} {}; RawStateTable(RawStateTable const& rhs) - : monotonic_resource_{std::make_unique< - boost::container::pmr::monotonic_buffer_resource>( - initialBufferSize)} + : monotonic_resource_{std::make_unique(initialBufferSize)} , items_{rhs.items_, monotonic_resource_.get()} , dropsDestroyed_{rhs.dropsDestroyed_} {}; @@ -50,10 +45,7 @@ public: exists(ReadView const& base, Keylet const& k) const; std::optional - succ( - ReadView const& base, - key_type const& key, - std::optional const& last) const; + succ(ReadView const& base, key_type const& key, std::optional const& last) const; void erase(std::shared_ptr const& sle); @@ -94,8 +86,7 @@ private: std::shared_ptr sle; // Constructor needed for emplacement in std::map - sleAction(Action action_, std::shared_ptr const& sle_) - : action(action_), sle(sle_) + sleAction(Action action_, std::shared_ptr const& sle_) : action(action_), sle(sle_) { } }; @@ -106,12 +97,10 @@ private: key_type, sleAction, std::less, - boost::container::pmr::polymorphic_allocator< - std::pair>>; + boost::container::pmr::polymorphic_allocator>>; // monotonic_resource_ must outlive `items_`. Make a pointer so it may be // easily moved. - std::unique_ptr - monotonic_resource_; + std::unique_ptr monotonic_resource_; items_t items_; XRPAmount dropsDestroyed_{0}; @@ -119,5 +108,3 @@ private: } // namespace detail } // namespace xrpl - -#endif diff --git a/include/xrpl/ledger/detail/ReadViewFwdRange.h b/include/xrpl/ledger/detail/ReadViewFwdRange.h index 557bba4987..bf40b04a6a 100644 --- a/include/xrpl/ledger/detail/ReadViewFwdRange.h +++ b/include/xrpl/ledger/detail/ReadViewFwdRange.h @@ -1,5 +1,4 @@ -#ifndef XRPL_LEDGER_READVIEWFWDRANGE_H_INCLUDED -#define XRPL_LEDGER_READVIEWFWDRANGE_H_INCLUDED +#pragma once #include #include @@ -73,9 +72,7 @@ public: iterator(iterator&& other) noexcept; // Used by the implementation - explicit iterator( - ReadView const* view, - std::unique_ptr impl); + explicit iterator(ReadView const* view, std::unique_ptr impl); iterator& operator=(iterator const& other); @@ -131,5 +128,3 @@ protected: } // namespace detail } // namespace xrpl - -#endif diff --git a/include/xrpl/ledger/detail/ReadViewFwdRange.ipp b/include/xrpl/ledger/detail/ReadViewFwdRange.ipp index e86246133a..212be52432 100644 --- a/include/xrpl/ledger/detail/ReadViewFwdRange.ipp +++ b/include/xrpl/ledger/detail/ReadViewFwdRange.ipp @@ -1,37 +1,29 @@ -#ifndef XRPL_LEDGER_READVIEWFWDRANGEINL_H_INCLUDED -#define XRPL_LEDGER_READVIEWFWDRANGEINL_H_INCLUDED +#pragma once namespace xrpl { namespace detail { template ReadViewFwdRange::iterator::iterator(iterator const& other) - : view_(other.view_) - , impl_(other.impl_ ? other.impl_->copy() : nullptr) - , cache_(other.cache_) + : view_(other.view_), impl_(other.impl_ ? other.impl_->copy() : nullptr), cache_(other.cache_) { } template ReadViewFwdRange::iterator::iterator(iterator&& other) noexcept - : view_(other.view_) - , impl_(std::move(other.impl_)) - , cache_(std::move(other.cache_)) + : view_(other.view_), impl_(std::move(other.impl_)), cache_(std::move(other.cache_)) { } template -ReadViewFwdRange::iterator::iterator( - ReadView const* view, - std::unique_ptr impl) +ReadViewFwdRange::iterator::iterator(ReadView const* view, std::unique_ptr impl) : view_(view), impl_(std::move(impl)) { } template auto -ReadViewFwdRange::iterator::operator=(iterator const& other) - -> iterator& +ReadViewFwdRange::iterator::operator=(iterator const& other) -> iterator& { if (this != &other) { @@ -44,8 +36,7 @@ ReadViewFwdRange::iterator::operator=(iterator const& other) template auto -ReadViewFwdRange::iterator::operator=(iterator&& other) noexcept - -> iterator& +ReadViewFwdRange::iterator::operator=(iterator&& other) noexcept -> iterator& { if (this != &other) { @@ -116,5 +107,3 @@ ReadViewFwdRange::iterator::operator++(int) -> iterator } // namespace detail } // namespace xrpl - -#endif diff --git a/include/xrpl/net/AutoSocket.h b/include/xrpl/net/AutoSocket.h index 2fcba5780c..85a3adb456 100644 --- a/include/xrpl/net/AutoSocket.h +++ b/include/xrpl/net/AutoSocket.h @@ -1,5 +1,4 @@ -#ifndef XRPL_WEBSOCKET_AUTOSOCKET_AUTOSOCKET_H_INCLUDED -#define XRPL_WEBSOCKET_AUTOSOCKET_AUTOSOCKET_H_INCLUDED +#pragma once #include #include @@ -27,20 +26,13 @@ public: using callback = std::function; public: - AutoSocket( - boost::asio::io_context& s, - boost::asio::ssl::context& c, - bool secureOnly, - bool plainOnly) - : mSecure(secureOnly) - , mBuffer((plainOnly || secureOnly) ? 0 : 4) - , j_{beast::Journal::getNullSink()} + AutoSocket(boost::asio::io_context& s, boost::asio::ssl::context& c, bool secureOnly, bool plainOnly) + : mSecure(secureOnly), mBuffer((plainOnly || secureOnly) ? 0 : 4), j_{beast::Journal::getNullSink()} { mSocket = std::make_unique(s, c); } - AutoSocket(boost::asio::io_context& s, boost::asio::ssl::context& c) - : AutoSocket(s, c, false, false) + AutoSocket(boost::asio::io_context& s, boost::asio::ssl::context& c) : AutoSocket(s, c, false, false) { } @@ -105,9 +97,7 @@ public: { // must be plain mSecure = false; - post( - mSocket->get_executor(), - boost::beast::bind_handler(cbFunc, error_code())); + post(mSocket->get_executor(), boost::beast::bind_handler(cbFunc, error_code())); } else { @@ -115,12 +105,7 @@ public: mSocket->next_layer().async_receive( boost::asio::buffer(mBuffer), boost::asio::socket_base::message_peek, - std::bind( - &AutoSocket::handle_autodetect, - this, - cbFunc, - std::placeholders::_1, - std::placeholders::_2)); + std::bind(&AutoSocket::handle_autodetect, this, cbFunc, std::placeholders::_1, std::placeholders::_2)); } } @@ -141,9 +126,7 @@ public: { ec = e.code(); } - post( - mSocket->get_executor(), - boost::beast::bind_handler(handler, ec)); + post(mSocket->get_executor(), boost::beast::bind_handler(handler, ec)); } } @@ -162,39 +145,29 @@ public: async_read_until(Seq const& buffers, Condition condition, Handler handler) { if (isSecure()) - boost::asio::async_read_until( - *mSocket, buffers, condition, handler); + boost::asio::async_read_until(*mSocket, buffers, condition, handler); else - boost::asio::async_read_until( - PlainSocket(), buffers, condition, handler); + boost::asio::async_read_until(PlainSocket(), buffers, condition, handler); } template void - async_read_until( - boost::asio::basic_streambuf& buffers, - std::string const& delim, - Handler handler) + async_read_until(boost::asio::basic_streambuf& buffers, std::string const& delim, Handler handler) { if (isSecure()) boost::asio::async_read_until(*mSocket, buffers, delim, handler); else - boost::asio::async_read_until( - PlainSocket(), buffers, delim, handler); + boost::asio::async_read_until(PlainSocket(), buffers, delim, handler); } template void - async_read_until( - boost::asio::basic_streambuf& buffers, - MatchCondition cond, - Handler handler) + async_read_until(boost::asio::basic_streambuf& buffers, MatchCondition cond, Handler handler) { if (isSecure()) boost::asio::async_read_until(*mSocket, buffers, cond, handler); else - boost::asio::async_read_until( - PlainSocket(), buffers, cond, handler); + boost::asio::async_read_until(PlainSocket(), buffers, cond, handler); } template @@ -209,9 +182,7 @@ public: template void - async_write( - boost::asio::basic_streambuf& buffers, - Handler handler) + async_write(boost::asio::basic_streambuf& buffers, Handler handler) { if (isSecure()) boost::asio::async_write(*mSocket, buffers, handler); @@ -231,10 +202,7 @@ public: template void - async_read( - boost::asio::basic_streambuf& buffers, - Condition cond, - Handler handler) + async_read(boost::asio::basic_streambuf& buffers, Condition cond, Handler handler) { if (isSecure()) boost::asio::async_read(*mSocket, buffers, cond, handler); @@ -264,10 +232,7 @@ public: protected: void - handle_autodetect( - callback cbFunc, - error_code const& ec, - size_t bytesTransferred) + handle_autodetect(callback cbFunc, error_code const& ec, size_t bytesTransferred) { using namespace xrpl; @@ -278,12 +243,9 @@ protected: } else if ( (mBuffer[0] < 127) && (mBuffer[0] > 31) && - ((bytesTransferred < 2) || - ((mBuffer[1] < 127) && (mBuffer[1] > 31))) && - ((bytesTransferred < 3) || - ((mBuffer[2] < 127) && (mBuffer[2] > 31))) && - ((bytesTransferred < 4) || - ((mBuffer[3] < 127) && (mBuffer[3] > 31)))) + ((bytesTransferred < 2) || ((mBuffer[1] < 127) && (mBuffer[1] > 31))) && + ((bytesTransferred < 3) || ((mBuffer[2] < 127) && (mBuffer[2] > 31))) && + ((bytesTransferred < 4) || ((mBuffer[3] < 127) && (mBuffer[3] > 31)))) { // not ssl JLOG(j_.trace()) << "non-SSL"; @@ -305,5 +267,3 @@ private: std::vector mBuffer; beast::Journal j_; }; - -#endif diff --git a/include/xrpl/net/HTTPClient.h b/include/xrpl/net/HTTPClient.h index 6e4d4ce685..289ce8f6e3 100644 --- a/include/xrpl/net/HTTPClient.h +++ b/include/xrpl/net/HTTPClient.h @@ -1,5 +1,4 @@ -#ifndef XRPL_NET_HTTPCLIENT_H_INCLUDED -#define XRPL_NET_HTTPCLIENT_H_INCLUDED +#pragma once #include #include @@ -38,10 +37,8 @@ public: std::string const& strPath, std::size_t responseMax, // if no Content-Length header std::chrono::seconds timeout, - std::function complete, + std::function + complete, beast::Journal& j); static void @@ -52,10 +49,8 @@ public: std::string const& strPath, std::size_t responseMax, // if no Content-Length header std::chrono::seconds timeout, - std::function complete, + std::function + complete, beast::Journal& j); static void @@ -64,17 +59,12 @@ public: boost::asio::io_context& io_context, std::string strSite, unsigned short const port, - std::function< - void(boost::asio::streambuf& sb, std::string const& strHost)> build, + std::function build, std::size_t responseMax, // if no Content-Length header std::chrono::seconds timeout, - std::function complete, + std::function + complete, beast::Journal& j); }; } // namespace xrpl - -#endif diff --git a/include/xrpl/net/HTTPClientSSLContext.h b/include/xrpl/net/HTTPClientSSLContext.h index b8dfbd3e09..1033b9a22b 100644 --- a/include/xrpl/net/HTTPClientSSLContext.h +++ b/include/xrpl/net/HTTPClientSSLContext.h @@ -1,5 +1,4 @@ -#ifndef XRPL_NET_HTTPCLIENTSSLCONTEXT_H_INCLUDED -#define XRPL_NET_HTTPCLIENTSSLCONTEXT_H_INCLUDED +#pragma once #include #include @@ -21,8 +20,7 @@ public: std::string const& sslVerifyFile, bool sslVerify, beast::Journal j, - boost::asio::ssl::context_base::method method = - boost::asio::ssl::context::sslv23) + boost::asio::ssl::context_base::method method = boost::asio::ssl::context::sslv23) : ssl_context_{method}, j_(j), verify_{sslVerify} { boost::system::error_code ec; @@ -32,9 +30,8 @@ public: registerSSLCerts(ssl_context_, ec, j_); if (ec && sslVerifyDir.empty()) - Throw(boost::str( - boost::format("Failed to set_default_verify_paths: %s") % - ec.message())); + Throw( + boost::str(boost::format("Failed to set_default_verify_paths: %s") % ec.message())); } else { @@ -46,9 +43,7 @@ public: ssl_context_.add_verify_path(sslVerifyDir, ec); if (ec) - Throw(boost::str( - boost::format("Failed to add verify path: %s") % - ec.message())); + Throw(boost::str(boost::format("Failed to add verify path: %s") % ec.message())); } } @@ -79,23 +74,15 @@ public: template < class T, class = std::enable_if_t< - std::is_same< - T, - boost::asio::ssl::stream>:: - value || - std::is_same< - T, - boost::asio::ssl::stream>:: - value>> + std::is_same>::value || + std::is_same>::value>> boost::system::error_code preConnectVerify(T& strm, std::string const& host) { boost::system::error_code ec; if (!SSL_set_tlsext_host_name(strm.native_handle(), host.c_str())) { - ec.assign( - static_cast(::ERR_get_error()), - boost::asio::error::get_ssl_category()); + ec.assign(static_cast(::ERR_get_error()), boost::asio::error::get_ssl_category()); } else if (!sslVerify()) { @@ -107,14 +94,8 @@ public: template < class T, class = std::enable_if_t< - std::is_same< - T, - boost::asio::ssl::stream>:: - value || - std::is_same< - T, - boost::asio::ssl::stream>:: - value>> + std::is_same>::value || + std::is_same>::value>> /** * @brief invoked after connect/async_connect but before sending data * on an ssl stream - to setup name verification. @@ -133,13 +114,7 @@ public: if (!ec) { strm.set_verify_callback( - std::bind( - &rfc6125_verify, - host, - std::placeholders::_1, - std::placeholders::_2, - j_), - ec); + std::bind(&rfc6125_verify, host, std::placeholders::_1, std::placeholders::_2, j_), ec); } } @@ -156,17 +131,12 @@ public: * @param j journal for logging */ static bool - rfc6125_verify( - std::string const& domain, - bool preverified, - boost::asio::ssl::verify_context& ctx, - beast::Journal j) + rfc6125_verify(std::string const& domain, bool preverified, boost::asio::ssl::verify_context& ctx, beast::Journal j) { if (boost::asio::ssl::host_name_verification(domain)(preverified, ctx)) return true; - JLOG(j.warn()) << "Outbound SSL connection to " << domain - << " fails certificate verification"; + JLOG(j.warn()) << "Outbound SSL connection to " << domain << " fails certificate verification"; return false; } @@ -177,5 +147,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/include/xrpl/net/RegisterSSLCerts.h b/include/xrpl/net/RegisterSSLCerts.h index f9b865c3aa..e313b1cb06 100644 --- a/include/xrpl/net/RegisterSSLCerts.h +++ b/include/xrpl/net/RegisterSSLCerts.h @@ -1,5 +1,4 @@ -#ifndef XRPL_NET_REGISTER_SSL_CERTS_H_INCLUDED -#define XRPL_NET_REGISTER_SSL_CERTS_H_INCLUDED +#pragma once #include @@ -14,11 +13,6 @@ namespace xrpl { store accessible via CryptoAPI. */ void -registerSSLCerts( - boost::asio::ssl::context&, - boost::system::error_code&, - beast::Journal j); +registerSSLCerts(boost::asio::ssl::context&, boost::system::error_code&, beast::Journal j); } // namespace xrpl - -#endif diff --git a/include/xrpl/nodestore/Backend.h b/include/xrpl/nodestore/Backend.h index 0ea8835f61..6af292d5b3 100644 --- a/include/xrpl/nodestore/Backend.h +++ b/include/xrpl/nodestore/Backend.h @@ -1,5 +1,4 @@ -#ifndef XRPL_NODESTORE_BACKEND_H_INCLUDED -#define XRPL_NODESTORE_BACKEND_H_INCLUDED +#pragma once #include @@ -64,9 +63,7 @@ public: virtual void open(bool createIfMissing, uint64_t appType, uint64_t uid, uint64_t salt) { - Throw( - "Deterministic appType/uid/salt not supported by backend " + - getName()); + Throw("Deterministic appType/uid/salt not supported by backend " + getName()); } /** Close the backend. @@ -144,5 +141,3 @@ public: } // namespace NodeStore } // namespace xrpl - -#endif diff --git a/include/xrpl/nodestore/Database.h b/include/xrpl/nodestore/Database.h index 474f873876..d1f5b1bda2 100644 --- a/include/xrpl/nodestore/Database.h +++ b/include/xrpl/nodestore/Database.h @@ -1,5 +1,4 @@ -#ifndef XRPL_NODESTORE_DATABASE_H_INCLUDED -#define XRPL_NODESTORE_DATABASE_H_INCLUDED +#pragma once #include #include @@ -40,11 +39,7 @@ public: @param config The configuration settings @param journal Destination for logging output. */ - Database( - Scheduler& scheduler, - int readThreads, - Section const& config, - beast::Journal j); + Database(Scheduler& scheduler, int readThreads, Section const& config, beast::Journal j); /** Destroy the node store. All pending operations are completed, pending writes flushed, @@ -82,11 +77,7 @@ public: @return `true` if the object was stored? */ virtual void - store( - NodeObjectType type, - Blob&& data, - uint256 const& hash, - std::uint32_t ledgerSeq) = 0; + store(NodeObjectType type, Blob&& data, uint256 const& hash, std::uint32_t ledgerSeq) = 0; /* Check if two ledgers are in the same database @@ -142,10 +133,6 @@ public: std::uint32_t ledgerSeq, std::function const&)>&& callback); - /** Remove expired entries from the positive and negative caches. */ - virtual void - sweep() = 0; - /** Gather statistics pertaining to read and write activities. * * @param obj Json object reference into which to place counters. @@ -228,9 +215,7 @@ protected: void storeStats(std::uint64_t count, std::uint64_t sz) { - XRPL_ASSERT( - count <= sz, - "xrpl::NodeStore::Database::storeStats : valid inputs"); + XRPL_ASSERT(count <= sz, "xrpl::NodeStore::Database::storeStats : valid inputs"); storeCount_ += count; storeSz_ += sz; } @@ -258,11 +243,7 @@ private: std::condition_variable readCondVar_; // reads to do - std::map< - uint256, - std::vector const&)>>>> + std::map const&)>>>> read_; std::atomic readStopping_ = false; @@ -270,11 +251,7 @@ private: std::atomic runningThreads_ = 0; virtual std::shared_ptr - fetchNodeObject( - uint256 const& hash, - std::uint32_t ledgerSeq, - FetchReport& fetchReport, - bool duplicate) = 0; + fetchNodeObject(uint256 const& hash, std::uint32_t ledgerSeq, FetchReport& fetchReport, bool duplicate) = 0; /** Visit every object in the database This is usually called during import. @@ -292,5 +269,3 @@ private: } // namespace NodeStore } // namespace xrpl - -#endif diff --git a/include/xrpl/nodestore/DatabaseRotating.h b/include/xrpl/nodestore/DatabaseRotating.h index 85202e7a84..e20b49805c 100644 --- a/include/xrpl/nodestore/DatabaseRotating.h +++ b/include/xrpl/nodestore/DatabaseRotating.h @@ -1,5 +1,4 @@ -#ifndef XRPL_NODESTORE_DATABASEROTATING_H_INCLUDED -#define XRPL_NODESTORE_DATABASEROTATING_H_INCLUDED +#pragma once #include @@ -14,11 +13,7 @@ namespace NodeStore { class DatabaseRotating : public Database { public: - DatabaseRotating( - Scheduler& scheduler, - int readThreads, - Section const& config, - beast::Journal journal) + DatabaseRotating(Scheduler& scheduler, int readThreads, Section const& config, beast::Journal journal) : Database(scheduler, readThreads, config, journal) { } @@ -33,12 +28,8 @@ public: virtual void rotate( std::unique_ptr&& newBackend, - std::function const& f) = 0; + std::function const& f) = 0; }; } // namespace NodeStore } // namespace xrpl - -#endif diff --git a/include/xrpl/nodestore/DummyScheduler.h b/include/xrpl/nodestore/DummyScheduler.h index b31613480f..9fce4a6100 100644 --- a/include/xrpl/nodestore/DummyScheduler.h +++ b/include/xrpl/nodestore/DummyScheduler.h @@ -1,5 +1,4 @@ -#ifndef XRPL_NODESTORE_DUMMYSCHEDULER_H_INCLUDED -#define XRPL_NODESTORE_DUMMYSCHEDULER_H_INCLUDED +#pragma once #include @@ -22,5 +21,3 @@ public: } // namespace NodeStore } // namespace xrpl - -#endif diff --git a/include/xrpl/nodestore/Factory.h b/include/xrpl/nodestore/Factory.h index d6d33c4b64..e01bdfabf2 100644 --- a/include/xrpl/nodestore/Factory.h +++ b/include/xrpl/nodestore/Factory.h @@ -1,5 +1,4 @@ -#ifndef XRPL_NODESTORE_FACTORY_H_INCLUDED -#define XRPL_NODESTORE_FACTORY_H_INCLUDED +#pragma once #include #include @@ -62,5 +61,3 @@ public: } // namespace NodeStore } // namespace xrpl - -#endif diff --git a/include/xrpl/nodestore/Manager.h b/include/xrpl/nodestore/Manager.h index 72edf2b47e..9553407881 100644 --- a/include/xrpl/nodestore/Manager.h +++ b/include/xrpl/nodestore/Manager.h @@ -1,5 +1,4 @@ -#ifndef XRPL_NODESTORE_MANAGER_H_INCLUDED -#define XRPL_NODESTORE_MANAGER_H_INCLUDED +#pragma once #include #include @@ -39,11 +38,7 @@ public: /** Create a backend. */ virtual std::unique_ptr - make_Backend( - Section const& parameters, - std::size_t burstSize, - Scheduler& scheduler, - beast::Journal journal) = 0; + make_Backend(Section const& parameters, std::size_t burstSize, Scheduler& scheduler, beast::Journal journal) = 0; /** Construct a NodeStore database. @@ -84,5 +79,3 @@ public: } // namespace NodeStore } // namespace xrpl - -#endif diff --git a/include/xrpl/nodestore/NodeObject.h b/include/xrpl/nodestore/NodeObject.h index 6a69245fd2..2274fc8c38 100644 --- a/include/xrpl/nodestore/NodeObject.h +++ b/include/xrpl/nodestore/NodeObject.h @@ -1,5 +1,4 @@ -#ifndef XRPL_NODESTORE_NODEOBJECT_H_INCLUDED -#define XRPL_NODESTORE_NODEOBJECT_H_INCLUDED +#pragma once #include #include @@ -43,11 +42,7 @@ private: public: // This constructor is private, use createObject instead. - NodeObject( - NodeObjectType type, - Blob&& data, - uint256 const& hash, - PrivateAccess); + NodeObject(NodeObjectType type, Blob&& data, uint256 const& hash, PrivateAccess); /** Create an object from fields. @@ -82,5 +77,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/include/xrpl/nodestore/Scheduler.h b/include/xrpl/nodestore/Scheduler.h index 0835e08fa2..6e01533930 100644 --- a/include/xrpl/nodestore/Scheduler.h +++ b/include/xrpl/nodestore/Scheduler.h @@ -1,5 +1,4 @@ -#ifndef XRPL_NODESTORE_SCHEDULER_H_INCLUDED -#define XRPL_NODESTORE_SCHEDULER_H_INCLUDED +#pragma once #include @@ -67,5 +66,3 @@ public: } // namespace NodeStore } // namespace xrpl - -#endif diff --git a/include/xrpl/nodestore/Task.h b/include/xrpl/nodestore/Task.h index bd21e61975..4bfc88bd13 100644 --- a/include/xrpl/nodestore/Task.h +++ b/include/xrpl/nodestore/Task.h @@ -1,5 +1,4 @@ -#ifndef XRPL_NODESTORE_TASK_H_INCLUDED -#define XRPL_NODESTORE_TASK_H_INCLUDED +#pragma once namespace xrpl { namespace NodeStore { @@ -18,5 +17,3 @@ struct Task } // namespace NodeStore } // namespace xrpl - -#endif diff --git a/include/xrpl/nodestore/Types.h b/include/xrpl/nodestore/Types.h index 6763196860..5adbc40f70 100644 --- a/include/xrpl/nodestore/Types.h +++ b/include/xrpl/nodestore/Types.h @@ -1,5 +1,4 @@ -#ifndef XRPL_NODESTORE_TYPES_H_INCLUDED -#define XRPL_NODESTORE_TYPES_H_INCLUDED +#pragma once #include @@ -38,5 +37,3 @@ using Batch = std::vector>; } // namespace NodeStore } // namespace xrpl - -#endif diff --git a/include/xrpl/nodestore/detail/BatchWriter.h b/include/xrpl/nodestore/detail/BatchWriter.h index f1faf0a612..1820435133 100644 --- a/include/xrpl/nodestore/detail/BatchWriter.h +++ b/include/xrpl/nodestore/detail/BatchWriter.h @@ -1,5 +1,4 @@ -#ifndef XRPL_NODESTORE_BATCHWRITER_H_INCLUDED -#define XRPL_NODESTORE_BATCHWRITER_H_INCLUDED +#pragma once #include #include @@ -79,5 +78,3 @@ private: } // namespace NodeStore } // namespace xrpl - -#endif diff --git a/include/xrpl/nodestore/detail/DatabaseNodeImp.h b/include/xrpl/nodestore/detail/DatabaseNodeImp.h index bf222129cc..94859c4d22 100644 --- a/include/xrpl/nodestore/detail/DatabaseNodeImp.h +++ b/include/xrpl/nodestore/detail/DatabaseNodeImp.h @@ -1,5 +1,4 @@ -#ifndef XRPL_NODESTORE_DATABASENODEIMP_H_INCLUDED -#define XRPL_NODESTORE_DATABASENODEIMP_H_INCLUDED +#pragma once #include #include @@ -22,41 +21,8 @@ public: std::shared_ptr backend, Section const& config, beast::Journal j) - : Database(scheduler, readThreads, config, j) - , backend_(std::move(backend)) + : Database(scheduler, readThreads, config, j), backend_(std::move(backend)) { - std::optional cacheSize, cacheAge; - - if (config.exists("cache_size")) - { - cacheSize = get(config, "cache_size"); - if (cacheSize.value() < 0) - { - Throw( - "Specified negative value for cache_size"); - } - } - - if (config.exists("cache_age")) - { - cacheAge = get(config, "cache_age"); - if (cacheAge.value() < 0) - { - Throw( - "Specified negative value for cache_age"); - } - } - - if (cacheSize != 0 || cacheAge != 0) - { - cache_ = std::make_shared>( - "DatabaseNodeImp", - cacheSize.value_or(0), - std::chrono::minutes(cacheAge.value_or(0)), - stopwatch(), - j); - } - XRPL_ASSERT( backend_, "xrpl::NodeStore::DatabaseNodeImp::DatabaseNodeImp : non-null " @@ -87,8 +53,7 @@ public: } void - store(NodeObjectType type, Blob&& data, uint256 const& hash, std::uint32_t) - override; + store(NodeObjectType type, Blob&& data, uint256 const& hash, std::uint32_t) override; bool isSameDB(std::uint32_t, std::uint32_t) override @@ -110,25 +75,14 @@ public: asyncFetch( uint256 const& hash, std::uint32_t ledgerSeq, - std::function const&)>&& callback) - override; - - void - sweep() override; + std::function const&)>&& callback) override; private: - // Cache for database objects. This cache is not always initialized. Check - // for null before using. - std::shared_ptr> cache_; // Persistent key/value storage std::shared_ptr backend_; std::shared_ptr - fetchNodeObject( - uint256 const& hash, - std::uint32_t, - FetchReport& fetchReport, - bool duplicate) override; + fetchNodeObject(uint256 const& hash, std::uint32_t, FetchReport& fetchReport, bool duplicate) override; void for_each(std::function)> f) override @@ -139,5 +93,3 @@ private: } // namespace NodeStore } // namespace xrpl - -#endif diff --git a/include/xrpl/nodestore/detail/DatabaseRotatingImp.h b/include/xrpl/nodestore/detail/DatabaseRotatingImp.h index 63d628a30a..1a378c54c7 100644 --- a/include/xrpl/nodestore/detail/DatabaseRotatingImp.h +++ b/include/xrpl/nodestore/detail/DatabaseRotatingImp.h @@ -1,5 +1,4 @@ -#ifndef XRPL_NODESTORE_DATABASEROTATINGIMP_H_INCLUDED -#define XRPL_NODESTORE_DATABASEROTATINGIMP_H_INCLUDED +#pragma once #include @@ -32,9 +31,7 @@ public: void rotate( std::unique_ptr&& newBackend, - std::function const& f) override; + std::function const& f) override; std::string getName() const override; @@ -53,26 +50,18 @@ public: } void - store(NodeObjectType type, Blob&& data, uint256 const& hash, std::uint32_t) - override; + store(NodeObjectType type, Blob&& data, uint256 const& hash, std::uint32_t) override; void sync() override; - void - sweep() override; - private: std::shared_ptr writableBackend_; std::shared_ptr archiveBackend_; mutable std::mutex mutex_; std::shared_ptr - fetchNodeObject( - uint256 const& hash, - std::uint32_t, - FetchReport& fetchReport, - bool duplicate) override; + fetchNodeObject(uint256 const& hash, std::uint32_t, FetchReport& fetchReport, bool duplicate) override; void for_each(std::function)> f) override; @@ -80,5 +69,3 @@ private: } // namespace NodeStore } // namespace xrpl - -#endif diff --git a/include/xrpl/nodestore/detail/DecodedBlob.h b/include/xrpl/nodestore/detail/DecodedBlob.h index 0eaa169269..dc6704a08d 100644 --- a/include/xrpl/nodestore/detail/DecodedBlob.h +++ b/include/xrpl/nodestore/detail/DecodedBlob.h @@ -1,5 +1,4 @@ -#ifndef XRPL_NODESTORE_DECODEDBLOB_H_INCLUDED -#define XRPL_NODESTORE_DECODEDBLOB_H_INCLUDED +#pragma once #include @@ -44,5 +43,3 @@ private: } // namespace NodeStore } // namespace xrpl - -#endif diff --git a/include/xrpl/nodestore/detail/EncodedBlob.h b/include/xrpl/nodestore/detail/EncodedBlob.h index 2cd35a7b6f..78e7153f73 100644 --- a/include/xrpl/nodestore/detail/EncodedBlob.h +++ b/include/xrpl/nodestore/detail/EncodedBlob.h @@ -1,5 +1,4 @@ -#ifndef XRPL_NODESTORE_ENCODEDBLOB_H_INCLUDED -#define XRPL_NODESTORE_ENCODEDBLOB_H_INCLUDED +#pragma once #include #include @@ -44,10 +43,7 @@ class EncodedBlob 1024 more bytes. The precise size is calculated automatically at compile time so as to avoid wasting space on padding bytes. */ - std::array< - std::uint8_t, - boost::alignment::align_up(9 + 1024, alignof(std::uint32_t))> - payload_; + std::array payload_; /** The size of the serialized data. */ std::uint32_t size_; @@ -62,19 +58,14 @@ class EncodedBlob public: explicit EncodedBlob(std::shared_ptr const& obj) : size_([&obj]() { - XRPL_ASSERT( - obj, - "xrpl::NodeStore::EncodedBlob::EncodedBlob : non-null input"); + XRPL_ASSERT(obj, "xrpl::NodeStore::EncodedBlob::EncodedBlob : non-null input"); if (!obj) - throw std::runtime_error( - "EncodedBlob: unseated std::shared_ptr used."); + throw std::runtime_error("EncodedBlob: unseated std::shared_ptr used."); return obj->getData().size() + 9; }()) - , ptr_( - (size_ <= payload_.size()) ? payload_.data() - : new std::uint8_t[size_]) + , ptr_((size_ <= payload_.size()) ? payload_.data() : new std::uint8_t[size_]) { std::fill_n(ptr_, 8, std::uint8_t{0}); ptr_[8] = static_cast(obj->getType()); @@ -115,5 +106,3 @@ public: } // namespace NodeStore } // namespace xrpl - -#endif diff --git a/include/xrpl/nodestore/detail/ManagerImp.h b/include/xrpl/nodestore/detail/ManagerImp.h index fd3de8a7ca..f46a7d56d0 100644 --- a/include/xrpl/nodestore/detail/ManagerImp.h +++ b/include/xrpl/nodestore/detail/ManagerImp.h @@ -1,5 +1,4 @@ -#ifndef XRPL_NODESTORE_MANAGERIMP_H_INCLUDED -#define XRPL_NODESTORE_MANAGERIMP_H_INCLUDED +#pragma once #include @@ -34,11 +33,8 @@ public: erase(Factory& factory) override; std::unique_ptr - make_Backend( - Section const& parameters, - std::size_t burstSize, - Scheduler& scheduler, - beast::Journal journal) override; + make_Backend(Section const& parameters, std::size_t burstSize, Scheduler& scheduler, beast::Journal journal) + override; std::unique_ptr make_Database( @@ -51,5 +47,3 @@ public: } // namespace NodeStore } // namespace xrpl - -#endif diff --git a/include/xrpl/nodestore/detail/codec.h b/include/xrpl/nodestore/detail/codec.h index e02d3963bd..1d08beff59 100644 --- a/include/xrpl/nodestore/detail/codec.h +++ b/include/xrpl/nodestore/detail/codec.h @@ -1,5 +1,4 @@ -#ifndef XRPL_NODESTORE_CODEC_H_INCLUDED -#define XRPL_NODESTORE_CODEC_H_INCLUDED +#pragma once // Disable lz4 deprecation warning due to incompatibility with clang attributes #define LZ4_DISABLE_DEPRECATE_WARNINGS @@ -30,8 +29,7 @@ lz4_decompress(void const* in, std::size_t in_size, BufferFactory&& bf) std::size_t outSize = 0; - auto const n = read_varint( - reinterpret_cast(in), in_size, outSize); + auto const n = read_varint(reinterpret_cast(in), in_size, outSize); if (n == 0 || n >= in_size) Throw("lz4_decompress: invalid blob"); @@ -64,11 +62,8 @@ lz4_compress(void const* in, std::size_t in_size, BufferFactory&& bf) std::uint8_t* out = reinterpret_cast(bf(n + out_max)); result.first = out; std::memcpy(out, vi.data(), n); - auto const out_size = LZ4_compress_default( - reinterpret_cast(in), - reinterpret_cast(out + n), - in_size, - out_max); + auto const out_size = + LZ4_compress_default(reinterpret_cast(in), reinterpret_cast(out + n), in_size, out_max); if (out_size == 0) Throw("lz4 compress"); result.second = n + out_size; @@ -119,9 +114,8 @@ nodeobject_decompress(void const* in, std::size_t in_size, BufferFactory&& bf) auto const hs = field::size; // Mask if (in_size < hs + 32) Throw( - "nodeobject codec v1: short inner node size: " + - std::string("in_size = ") + std::to_string(in_size) + - " hs = " + std::to_string(hs)); + "nodeobject codec v1: short inner node size: " + std::string("in_size = ") + + std::to_string(in_size) + " hs = " + std::to_string(hs)); istream is(p, in_size); std::uint16_t mask; read(is, mask); // Mask @@ -133,11 +127,9 @@ nodeobject_decompress(void const* in, std::size_t in_size, BufferFactory&& bf) write(os, 0); write(os, 0); write(os, hotUNKNOWN); - write( - os, static_cast(HashPrefix::innerNode)); + write(os, static_cast(HashPrefix::innerNode)); if (mask == 0) - Throw( - "nodeobject codec v1: empty inner node"); + Throw("nodeobject codec v1: empty inner node"); std::uint16_t bit = 0x8000; for (int i = 16; i--; bit >>= 1) { @@ -145,10 +137,8 @@ nodeobject_decompress(void const* in, std::size_t in_size, BufferFactory&& bf) { if (in_size < 32) Throw( - "nodeobject codec v1: short inner node subsize: " + - std::string("in_size = ") + - std::to_string(in_size) + - " i = " + std::to_string(i)); + "nodeobject codec v1: short inner node subsize: " + std::string("in_size = ") + + std::to_string(in_size) + " i = " + std::to_string(i)); std::memcpy(os.data(32), is(32), 32); in_size -= 32; } @@ -158,17 +148,14 @@ nodeobject_decompress(void const* in, std::size_t in_size, BufferFactory&& bf) } } if (in_size > 0) - Throw( - "nodeobject codec v1: long inner node, in_size = " + - std::to_string(in_size)); + Throw("nodeobject codec v1: long inner node, in_size = " + std::to_string(in_size)); break; } case 3: // full v1 inner node { if (in_size != 16 * 32) // hashes Throw( - "nodeobject codec v1: short full inner node, in_size = " + - std::to_string(in_size)); + "nodeobject codec v1: short full inner node, in_size = " + std::to_string(in_size)); istream is(p, in_size); result.second = 525; void* const out = bf(result.second); @@ -177,14 +164,12 @@ nodeobject_decompress(void const* in, std::size_t in_size, BufferFactory&& bf) write(os, 0); write(os, 0); write(os, hotUNKNOWN); - write( - os, static_cast(HashPrefix::innerNode)); + write(os, static_cast(HashPrefix::innerNode)); write(os, is(512), 512); break; } default: - Throw( - "nodeobject codec: bad type=" + std::to_string(type)); + Throw("nodeobject codec: bad type=" + std::to_string(type)); }; return result; } @@ -238,8 +223,7 @@ nodeobject_compress(void const* in, std::size_t in_size, BufferFactory&& bf) auto const vs = size_varint(type); result.second = vs + field::size + // mask n * 32; // hashes - std::uint8_t* out = - reinterpret_cast(bf(result.second)); + std::uint8_t* out = reinterpret_cast(bf(result.second)); result.first = out; ostream os(out, result.second); write(os, type); @@ -251,8 +235,7 @@ nodeobject_compress(void const* in, std::size_t in_size, BufferFactory&& bf) auto const type = 3U; auto const vs = size_varint(type); result.second = vs + n * 32; // hashes - std::uint8_t* out = - reinterpret_cast(bf(result.second)); + std::uint8_t* out = reinterpret_cast(bf(result.second)); result.first = out; ostream os(out, result.second); write(os, type); @@ -272,19 +255,17 @@ nodeobject_compress(void const* in, std::size_t in_size, BufferFactory&& bf) case 1: // lz4 { std::uint8_t* p; - auto const lzr = NodeStore::lz4_compress( - in, in_size, [&p, &vn, &bf](std::size_t n) { - p = reinterpret_cast(bf(vn + n)); - return p + vn; - }); + auto const lzr = NodeStore::lz4_compress(in, in_size, [&p, &vn, &bf](std::size_t n) { + p = reinterpret_cast(bf(vn + n)); + return p + vn; + }); std::memcpy(p, vi.data(), vn); result.first = p; result.second = vn + lzr.second; break; } default: - Throw( - "nodeobject codec: unknown=" + std::to_string(codecType)); + Throw("nodeobject codec: unknown=" + std::to_string(codecType)); }; return result; } @@ -323,5 +304,3 @@ filter_inner(void* in, std::size_t in_size) } // namespace NodeStore } // namespace xrpl - -#endif diff --git a/include/xrpl/nodestore/detail/varint.h b/include/xrpl/nodestore/detail/varint.h index 7cf9fbaf4b..98f8d8ff08 100644 --- a/include/xrpl/nodestore/detail/varint.h +++ b/include/xrpl/nodestore/detail/varint.h @@ -1,5 +1,4 @@ -#ifndef BEAST_NUDB_VARINT_H_INCLUDED -#define BEAST_NUDB_VARINT_H_INCLUDED +#pragma once #include @@ -119,5 +118,3 @@ write(nudb::detail::ostream& os, std::size_t t) } // namespace NodeStore } // namespace xrpl - -#endif diff --git a/include/xrpl/proto/xrpl.proto b/include/xrpl/proto/xrpl.proto index 613ef70a1f..0af7deb35d 100644 --- a/include/xrpl/proto/xrpl.proto +++ b/include/xrpl/proto/xrpl.proto @@ -86,9 +86,9 @@ message TMPublicKey { // you must first combine coins from one address to another. enum TransactionStatus { - tsNEW = 1; // origin node did/could not validate - tsCURRENT = 2; // scheduled to go in this ledger - tsCOMMITED = 3; // in a closed ledger + tsNEW = 1; // origin node did/could not validate + tsCURRENT = 2; // scheduled to go in this ledger + tsCOMMITTED = 3; // in a closed ledger tsREJECT_CONFLICT = 4; tsREJECT_INVALID = 5; tsREJECT_FUNDS = 6; diff --git a/include/xrpl/protocol/AMMCore.h b/include/xrpl/protocol/AMMCore.h index e259089367..a2c531f361 100644 --- a/include/xrpl/protocol/AMMCore.h +++ b/include/xrpl/protocol/AMMCore.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_AMMCORE_H_INCLUDED -#define XRPL_PROTOCOL_AMMCORE_H_INCLUDED +#pragma once #include #include @@ -18,8 +17,7 @@ std::uint16_t constexpr AUCTION_SLOT_MAX_AUTH_ACCOUNTS = 4; std::uint32_t constexpr AUCTION_SLOT_FEE_SCALE_FACTOR = 100000; std::uint32_t constexpr AUCTION_SLOT_DISCOUNTED_FEE_FRACTION = 10; std::uint32_t constexpr AUCTION_SLOT_MIN_FEE_FRACTION = 25; -std::uint32_t constexpr AUCTION_SLOT_INTERVAL_DURATION = - TOTAL_TIME_SLOT_SECS / AUCTION_SLOT_TIME_INTERVALS; +std::uint32_t constexpr AUCTION_SLOT_INTERVAL_DURATION = TOTAL_TIME_SLOT_SECS / AUCTION_SLOT_TIME_INTERVALS; // Votes std::uint16_t constexpr VOTE_MAX_SLOTS = 8; @@ -37,10 +35,7 @@ ammLPTCurrency(Currency const& cur1, Currency const& cur2); /** Calculate LPT Issue from AMM asset pair. */ Issue -ammLPTIssue( - Currency const& cur1, - Currency const& cur2, - AccountID const& ammAccountID); +ammLPTIssue(Currency const& cur1, Currency const& cur2, AccountID const& ammAccountID); /** Validate the amount. * If validZero is false and amount is beast::zero then invalid amount. @@ -54,9 +49,7 @@ invalidAMMAmount( bool validZero = false); NotTEC -invalidAMMAsset( - Issue const& issue, - std::optional> const& pair = std::nullopt); +invalidAMMAsset(Issue const& issue, std::optional> const& pair = std::nullopt); NotTEC invalidAMMAssetPair( @@ -103,5 +96,3 @@ feeMultHalf(std::uint16_t tfee) } } // namespace xrpl - -#endif // XRPL_PROTOCOL_AMMCORE_H_INCLUDED diff --git a/include/xrpl/protocol/AccountID.h b/include/xrpl/protocol/AccountID.h index d61938e2a7..bc57058d9e 100644 --- a/include/xrpl/protocol/AccountID.h +++ b/include/xrpl/protocol/AccountID.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_ACCOUNTID_H_INCLUDED -#define XRPL_PROTOCOL_ACCOUNTID_H_INCLUDED +#pragma once #include // VFALCO Uncomment when the header issues are resolved @@ -133,5 +132,3 @@ struct hash : xrpl::AccountID::hasher }; } // namespace std - -#endif diff --git a/include/xrpl/protocol/AmountConversions.h b/include/xrpl/protocol/AmountConversions.h index 2cdccecabb..0807e96c49 100644 --- a/include/xrpl/protocol/AmountConversions.h +++ b/include/xrpl/protocol/AmountConversions.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_AMOUNTCONVERSION_H_INCLUDED -#define XRPL_PROTOCOL_AMOUNTCONVERSION_H_INCLUDED +#pragma once #include #include @@ -34,8 +33,7 @@ toSTAmount(XRPAmount const& xrp) inline STAmount toSTAmount(XRPAmount const& xrp, Issue const& iss) { - XRPL_ASSERT( - isXRP(iss.account) && isXRP(iss.currency), "xrpl::toSTAmount : is XRP"); + XRPL_ASSERT(isXRP(iss.account) && isXRP(iss.currency), "xrpl::toSTAmount : is XRP"); return toSTAmount(xrp); } @@ -55,11 +53,9 @@ inline IOUAmount toAmount(STAmount const& amt) { XRPL_ASSERT( - amt.mantissa() < std::numeric_limits::max(), - "xrpl::toAmount : maximum mantissa"); + amt.mantissa() < std::numeric_limits::max(), "xrpl::toAmount : maximum mantissa"); bool const isNeg = amt.negative(); - std::int64_t const sMant = - isNeg ? -std::int64_t(amt.mantissa()) : amt.mantissa(); + std::int64_t const sMant = isNeg ? -std::int64_t(amt.mantissa()) : amt.mantissa(); XRPL_ASSERT(!isXRP(amt), "xrpl::toAmount : is not XRP"); return IOUAmount(sMant, amt.exponent()); @@ -70,11 +66,9 @@ inline XRPAmount toAmount(STAmount const& amt) { XRPL_ASSERT( - amt.mantissa() < std::numeric_limits::max(), - "xrpl::toAmount : maximum mantissa"); + amt.mantissa() < std::numeric_limits::max(), "xrpl::toAmount : maximum mantissa"); bool const isNeg = amt.negative(); - std::int64_t const sMant = - isNeg ? -std::int64_t(amt.mantissa()) : amt.mantissa(); + std::int64_t const sMant = isNeg ? -std::int64_t(amt.mantissa()) : amt.mantissa(); XRPL_ASSERT(isXRP(amt), "xrpl::toAmount : is XRP"); return XRPAmount(sMant); @@ -104,10 +98,7 @@ toAmount(XRPAmount const& amt) template T -toAmount( - Issue const& issue, - Number const& n, - Number::rounding_mode mode = Number::getround()) +toAmount(Issue const& issue, Number const& n, Number::rounding_mode mode = Number::getround()) { saveNumberRoundMode rm(Number::getround()); if (isXRP(issue)) @@ -141,8 +132,7 @@ toMaxAmount(Issue const& issue) else if constexpr (std::is_same_v) { if (isXRP(issue)) - return STAmount( - issue, static_cast(STAmount::cMaxNativeN)); + return STAmount(issue, static_cast(STAmount::cMaxNativeN)); return STAmount(issue, STAmount::cMaxValue, STAmount::cMaxOffset); } else @@ -153,10 +143,7 @@ toMaxAmount(Issue const& issue) } inline STAmount -toSTAmount( - Issue const& issue, - Number const& n, - Number::rounding_mode mode = Number::getround()) +toSTAmount(Issue const& issue, Number const& n, Number::rounding_mode mode = Number::getround()) { return toAmount(issue, n, mode); } @@ -196,5 +183,3 @@ get(STAmount const& a) } } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/ApiVersion.h b/include/xrpl/protocol/ApiVersion.h index d1a84e76b0..756a41d25e 100644 --- a/include/xrpl/protocol/ApiVersion.h +++ b/include/xrpl/protocol/ApiVersion.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_APIVERSION_H_INCLUDED -#define XRPL_PROTOCOL_APIVERSION_H_INCLUDED +#pragma once #include #include @@ -42,18 +41,15 @@ constexpr static auto apiInvalidVersion = apiVersion<0>; constexpr static auto apiMinimumSupportedVersion = apiVersion<1>; constexpr static auto apiMaximumSupportedVersion = apiVersion<2>; constexpr static auto apiVersionIfUnspecified = apiVersion<1>; -constexpr static auto apiCommandLineVersion = - apiVersion<1>; // TODO Bump to 2 later +constexpr static auto apiCommandLineVersion = apiVersion<1>; // TODO Bump to 2 later constexpr static auto apiBetaVersion = apiVersion<3>; constexpr static auto apiMaximumValidVersion = apiBetaVersion; static_assert(apiInvalidVersion < apiMinimumSupportedVersion); static_assert( - apiVersionIfUnspecified >= apiMinimumSupportedVersion && - apiVersionIfUnspecified <= apiMaximumSupportedVersion); + apiVersionIfUnspecified >= apiMinimumSupportedVersion && apiVersionIfUnspecified <= apiMaximumSupportedVersion); static_assert( - apiCommandLineVersion >= apiMinimumSupportedVersion && - apiCommandLineVersion <= apiMaximumSupportedVersion); + apiCommandLineVersion >= apiMinimumSupportedVersion && apiCommandLineVersion <= apiMaximumSupportedVersion); static_assert(apiMaximumSupportedVersion >= apiMinimumSupportedVersion); static_assert(apiBetaVersion >= apiMaximumSupportedVersion); static_assert(apiMaximumValidVersion >= apiMaximumSupportedVersion); @@ -61,9 +57,7 @@ static_assert(apiMaximumValidVersion >= apiMaximumSupportedVersion); inline void setVersion(Json::Value& parent, unsigned int apiVersion, bool betaEnabled) { - XRPL_ASSERT( - apiVersion != apiInvalidVersion, - "xrpl::RPC::setVersion : input is valid"); + XRPL_ASSERT(apiVersion != apiInvalidVersion, "xrpl::RPC::setVersion : input is valid"); auto& retObj = parent[jss::version] = Json::objectValue; @@ -81,8 +75,7 @@ setVersion(Json::Value& parent, unsigned int apiVersion, bool betaEnabled) else { retObj[jss::first] = apiMinimumSupportedVersion.value; - retObj[jss::last] = - betaEnabled ? apiBetaVersion : apiMaximumSupportedVersion; + retObj[jss::last] = betaEnabled ? apiBetaVersion : apiMaximumSupportedVersion; } } @@ -104,8 +97,7 @@ inline unsigned int getAPIVersionNumber(Json::Value const& jv, bool betaEnabled) { static Json::Value const minVersion(RPC::apiMinimumSupportedVersion); - Json::Value const maxVersion( - betaEnabled ? RPC::apiBetaVersion : RPC::apiMaximumSupportedVersion); + Json::Value const maxVersion(betaEnabled ? RPC::apiBetaVersion : RPC::apiMaximumSupportedVersion); if (jv.isObject()) { @@ -117,8 +109,7 @@ getAPIVersionNumber(Json::Value const& jv, bool betaEnabled) return RPC::apiInvalidVersion; } auto const specifiedVersionInt = specifiedVersion.asInt(); - if (specifiedVersionInt < minVersion || - specifiedVersionInt > maxVersion) + if (specifiedVersionInt < minVersion || specifiedVersionInt > maxVersion) { return RPC::apiInvalidVersion; } @@ -138,18 +129,13 @@ forApiVersions(Fn const& fn, Args&&... args) (maxVer >= minVer) && // (minVer >= RPC::apiMinimumSupportedVersion) && // (RPC::apiMaximumValidVersion >= maxVer) && requires { - fn(std::integral_constant{}, - std::forward(args)...); - fn(std::integral_constant{}, - std::forward(args)...); + fn(std::integral_constant{}, std::forward(args)...); + fn(std::integral_constant{}, std::forward(args)...); } { constexpr auto size = maxVer + 1 - minVer; [&](std::index_sequence) { - (((void)fn( - std::integral_constant{}, - std::forward(args)...)), - ...); + (((void)fn(std::integral_constant{}, std::forward(args)...)), ...); }(std::make_index_sequence{}); } @@ -157,16 +143,10 @@ template void forAllApiVersions(Fn const& fn, Args&&... args) requires requires { - forApiVersions< - RPC::apiMinimumSupportedVersion, - RPC::apiMaximumValidVersion>(fn, std::forward(args)...); + forApiVersions(fn, std::forward(args)...); } { - forApiVersions< - RPC::apiMinimumSupportedVersion, - RPC::apiMaximumValidVersion>(fn, std::forward(args)...); + forApiVersions(fn, std::forward(args)...); } } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/Asset.h b/include/xrpl/protocol/Asset.h index b72c20d82c..d48bc94b50 100644 --- a/include/xrpl/protocol/Asset.h +++ b/include/xrpl/protocol/Asset.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_ASSET_H_INCLUDED -#define XRPL_PROTOCOL_ASSET_H_INCLUDED +#pragma once #include #include @@ -12,12 +11,10 @@ class Asset; class STAmount; template -concept ValidIssueType = - std::is_same_v || std::is_same_v; +concept ValidIssueType = std::is_same_v || std::is_same_v; template -concept AssetType = - std::is_convertible_v || std::is_convertible_v || +concept AssetType = std::is_convertible_v || std::is_convertible_v || std::is_convertible_v || std::is_convertible_v; /* Asset is an abstraction of three different issue types: XRP, IOU, MPT. @@ -163,8 +160,7 @@ constexpr bool operator==(Asset const& lhs, Asset const& rhs) { return std::visit( - [&]( - TLhs const& issLhs, TRhs const& issRhs) { + [&](TLhs const& issLhs, TRhs const& issRhs) { if constexpr (std::is_same_v) return issLhs == issRhs; else @@ -178,12 +174,10 @@ constexpr std::weak_ordering operator<=>(Asset const& lhs, Asset const& rhs) { return std::visit( - []( - TLhs const& lhs_, TRhs const& rhs_) { + [](TLhs const& lhs_, TRhs const& rhs_) { if constexpr (std::is_same_v) return std::weak_ordering(lhs_ <=> rhs_); - else if constexpr ( - std::is_same_v && std::is_same_v) + else if constexpr (std::is_same_v && std::is_same_v) return std::weak_ordering::greater; else return std::weak_ordering::less; @@ -202,14 +196,10 @@ constexpr bool equalTokens(Asset const& lhs, Asset const& rhs) { return std::visit( - [&]( - TLhs const& issLhs, TRhs const& issRhs) { - if constexpr ( - std::is_same_v && std::is_same_v) + [&](TLhs const& issLhs, TRhs const& issRhs) { + if constexpr (std::is_same_v && std::is_same_v) return issLhs.currency == issRhs.currency; - else if constexpr ( - std::is_same_v && - std::is_same_v) + else if constexpr (std::is_same_v && std::is_same_v) return issLhs.getMptID() == issRhs.getMptID(); else return false; @@ -234,5 +224,3 @@ Asset assetFromJson(Json::Value const& jv); } // namespace xrpl - -#endif // XRPL_PROTOCOL_ASSET_H_INCLUDED diff --git a/include/xrpl/protocol/Batch.h b/include/xrpl/protocol/Batch.h index 1404c8069f..91fb8e5a9d 100644 --- a/include/xrpl/protocol/Batch.h +++ b/include/xrpl/protocol/Batch.h @@ -5,10 +5,7 @@ namespace xrpl { inline void -serializeBatch( - Serializer& msg, - std::uint32_t const& flags, - std::vector const& txids) +serializeBatch(Serializer& msg, std::uint32_t const& flags, std::vector const& txids) { msg.add32(HashPrefix::batch); msg.add32(flags); diff --git a/include/xrpl/protocol/Book.h b/include/xrpl/protocol/Book.h index ddd315de30..83965cf701 100644 --- a/include/xrpl/protocol/Book.h +++ b/include/xrpl/protocol/Book.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_BOOK_H_INCLUDED -#define XRPL_PROTOCOL_BOOK_H_INCLUDED +#pragma once #include #include @@ -24,10 +23,7 @@ public: { } - Book( - Issue const& in_, - Issue const& out_, - std::optional const& domain_) + Book(Issue const& in_, Issue const& out_, std::optional const& domain_) : in(in_), out(out_), domain(domain_) { } @@ -60,8 +56,7 @@ reversed(Book const& book); [[nodiscard]] inline constexpr bool operator==(Book const& lhs, Book const& rhs) { - return (lhs.in == rhs.in) && (lhs.out == rhs.out) && - (lhs.domain == rhs.domain); + return (lhs.in == rhs.in) && (lhs.out == rhs.out) && (lhs.domain == rhs.domain); } /** @} */ @@ -94,15 +89,12 @@ operator<=>(Book const& lhs, Book const& rhs) namespace std { template <> -struct hash - : private boost::base_from_member, 0>, - private boost::base_from_member, 1> +struct hash : private boost::base_from_member, 0>, + private boost::base_from_member, 1> { private: - using currency_hash_type = - boost::base_from_member, 0>; - using issuer_hash_type = - boost::base_from_member, 1>; + using currency_hash_type = boost::base_from_member, 0>; + using issuer_hash_type = boost::base_from_member, 1>; public: hash() = default; @@ -115,8 +107,7 @@ public: { value_type result(currency_hash_type::member(value.currency)); if (!isXRP(value.currency)) - boost::hash_combine( - result, issuer_hash_type::member(value.account)); + boost::hash_combine(result, issuer_hash_type::member(value.account)); return result; } }; @@ -179,5 +170,3 @@ struct hash : std::hash }; } // namespace boost - -#endif diff --git a/include/xrpl/protocol/BuildInfo.h b/include/xrpl/protocol/BuildInfo.h index 0b75f8b0a1..3c42a4323f 100644 --- a/include/xrpl/protocol/BuildInfo.h +++ b/include/xrpl/protocol/BuildInfo.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_BUILDINFO_H_INCLUDED -#define XRPL_PROTOCOL_BUILDINFO_H_INCLUDED +#pragma once #include #include @@ -80,5 +79,3 @@ isNewerVersion(std::uint64_t version); } // namespace BuildInfo } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/ErrorCodes.h b/include/xrpl/protocol/ErrorCodes.h index 3a2645347a..08c034e38f 100644 --- a/include/xrpl/protocol/ErrorCodes.h +++ b/include/xrpl/protocol/ErrorCodes.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_ERRORCODES_H_INCLUDED -#define XRPL_PROTOCOL_ERRORCODES_H_INCLUDED +#pragma once #include #include @@ -142,8 +141,7 @@ enum error_code_i { rpcENTRY_NOT_FOUND = 98, rpcUNEXPECTED_LEDGER_TYPE = 99, - rpcLAST = - rpcUNEXPECTED_LEDGER_TYPE // rpcLAST should always equal the last code. + rpcLAST = rpcUNEXPECTED_LEDGER_TYPE // rpcLAST should always equal the last code. }; /** Codes returned in the `warnings` array of certain RPC commands. @@ -169,31 +167,17 @@ namespace RPC { struct ErrorInfo { // Default ctor needed to produce an empty std::array during constexpr eval. - constexpr ErrorInfo() - : code(rpcUNKNOWN) - , token("unknown") - , message("An unknown error code.") - , http_status(200) + constexpr ErrorInfo() : code(rpcUNKNOWN), token("unknown"), message("An unknown error code."), http_status(200) { } - constexpr ErrorInfo( - error_code_i code_, - char const* token_, - char const* message_) + constexpr ErrorInfo(error_code_i code_, char const* token_, char const* message_) : code(code_), token(token_), message(message_), http_status(200) { } - constexpr ErrorInfo( - error_code_i code_, - char const* token_, - char const* message_, - int http_status_) - : code(code_) - , token(token_) - , message(message_) - , http_status(http_status_) + constexpr ErrorInfo(error_code_i code_, char const* token_, char const* message_, int http_status_) + : code(code_), token(token_), message(message_), http_status(http_status_) { } @@ -339,5 +323,3 @@ std::string rpcErrorString(Json::Value const& jv); } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/Feature.h b/include/xrpl/protocol/Feature.h index 317bde3ee6..6d674fbef2 100644 --- a/include/xrpl/protocol/Feature.h +++ b/include/xrpl/protocol/Feature.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_FEATURE_H_INCLUDED -#define XRPL_PROTOCOL_FEATURE_H_INCLUDED +#pragma once #include @@ -175,9 +174,7 @@ public: explicit FeatureBitset(base const& b) : base(b) { - XRPL_ASSERT( - b.count() == count(), - "xrpl::FeatureBitset::FeatureBitset(base) : count match"); + XRPL_ASSERT(b.count() == count(), "xrpl::FeatureBitset::FeatureBitset(base) : count match"); } template @@ -257,8 +254,7 @@ public: friend FeatureBitset operator&(FeatureBitset const& lhs, FeatureBitset const& rhs) { - return FeatureBitset{ - static_cast(lhs) & static_cast(rhs)}; + return FeatureBitset{static_cast(lhs) & static_cast(rhs)}; } friend FeatureBitset @@ -276,8 +272,7 @@ public: friend FeatureBitset operator|(FeatureBitset const& lhs, FeatureBitset const& rhs) { - return FeatureBitset{ - static_cast(lhs) | static_cast(rhs)}; + return FeatureBitset{static_cast(lhs) | static_cast(rhs)}; } friend FeatureBitset @@ -295,8 +290,7 @@ public: friend FeatureBitset operator^(FeatureBitset const& lhs, FeatureBitset const& rhs) { - return FeatureBitset{ - static_cast(lhs) ^ static_cast(rhs)}; + return FeatureBitset{static_cast(lhs) ^ static_cast(rhs)}; } friend FeatureBitset @@ -366,5 +360,3 @@ foreachFeature(FeatureBitset bs, F&& f) #pragma pop_macro("XRPL_FEATURE") } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/Fees.h b/include/xrpl/protocol/Fees.h index 8c7cb51777..84c8ffe81f 100644 --- a/include/xrpl/protocol/Fees.h +++ b/include/xrpl/protocol/Fees.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_FEES_H_INCLUDED -#define XRPL_PROTOCOL_FEES_H_INCLUDED +#pragma once #include @@ -34,5 +33,3 @@ struct Fees }; } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/HashPrefix.h b/include/xrpl/protocol/HashPrefix.h index 39e03bf94f..305b4bfd49 100644 --- a/include/xrpl/protocol/HashPrefix.h +++ b/include/xrpl/protocol/HashPrefix.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_HASHPREFIX_H_INCLUDED -#define XRPL_PROTOCOL_HASHPREFIX_H_INCLUDED +#pragma once #include @@ -12,8 +11,7 @@ namespace detail { constexpr std::uint32_t make_hash_prefix(char a, char b, char c) { - return (static_cast(a) << 24) + - (static_cast(b) << 16) + + return (static_cast(a) << 24) + (static_cast(b) << 16) + (static_cast(c) << 8); } @@ -80,5 +78,3 @@ hash_append(Hasher& h, HashPrefix const& hp) noexcept } } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/IOUAmount.h b/include/xrpl/protocol/IOUAmount.h index 405de18e29..52c2272da0 100644 --- a/include/xrpl/protocol/IOUAmount.h +++ b/include/xrpl/protocol/IOUAmount.h @@ -1,5 +1,4 @@ -#ifndef XRPL_BASICS_IOUAMOUNT_H_INCLUDED -#define XRPL_BASICS_IOUAMOUNT_H_INCLUDED +#pragma once #include #include @@ -22,8 +21,7 @@ namespace xrpl { if the amount exceeds the largest representable amount, but underflows will silently truncate to zero. */ -class IOUAmount : private boost::totally_ordered, - private boost::additive +class IOUAmount : private boost::totally_ordered, private boost::additive { private: using mantissa_type = std::int64_t; @@ -97,8 +95,7 @@ inline IOUAmount::IOUAmount(beast::Zero) *this = beast::zero; } -inline IOUAmount::IOUAmount(mantissa_type mantissa, exponent_type exponent) - : mantissa_(mantissa), exponent_(exponent) +inline IOUAmount::IOUAmount(mantissa_type mantissa, exponent_type exponent) : mantissa_(mantissa), exponent_(exponent) { normalize(); } @@ -175,11 +172,7 @@ to_string(IOUAmount const& amount); dividing by den. */ IOUAmount -mulRatio( - IOUAmount const& amt, - std::uint32_t num, - std::uint32_t den, - bool roundUp); +mulRatio(IOUAmount const& amt, std::uint32_t num, std::uint32_t den, bool roundUp); // Since many uses of the number class do not have access to a ledger, // getSTNumberSwitchover needs to be globally accessible. @@ -214,5 +207,3 @@ public: }; } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/Indexes.h b/include/xrpl/protocol/Indexes.h index 777c3b8aa9..f1e0b1655a 100644 --- a/include/xrpl/protocol/Indexes.h +++ b/include/xrpl/protocol/Indexes.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_INDEXES_H_INCLUDED -#define XRPL_PROTOCOL_INDEXES_H_INCLUDED +#pragma once #include #include @@ -94,10 +93,7 @@ static book_t const book{}; */ /** @{ */ Keylet -line( - AccountID const& id0, - AccountID const& id1, - Currency const& currency) noexcept; +line(AccountID const& id0, AccountID const& id1, Currency const& currency) noexcept; inline Keylet line(AccountID const& id, Issue const& issue) noexcept @@ -173,9 +169,7 @@ Keylet depositPreauth(AccountID const& owner, AccountID const& preauthorized) noexcept; Keylet -depositPreauth( - AccountID const& owner, - std::set> const& authCreds) noexcept; +depositPreauth(AccountID const& owner, std::set> const& authCreds) noexcept; inline Keylet depositPreauth(uint256 const& key) noexcept @@ -202,8 +196,7 @@ page(uint256 const& root, std::uint64_t index = 0) noexcept; inline Keylet page(Keylet const& root, std::uint64_t index = 0) noexcept { - XRPL_ASSERT( - root.type == ltDIR_NODE, "xrpl::keylet::page : valid root type"); + XRPL_ASSERT(root.type == ltDIR_NODE, "xrpl::keylet::page : valid root type"); return page(root.key, index); } /** @} */ @@ -283,10 +276,7 @@ Keylet oracle(AccountID const& account, std::uint32_t const& documentID) noexcept; Keylet -credential( - AccountID const& subject, - AccountID const& issuer, - Slice const& credType) noexcept; +credential(AccountID const& subject, AccountID const& issuer, Slice const& credType) noexcept; inline Keylet credential(uint256 const& key) noexcept @@ -394,5 +384,3 @@ MPTID makeMptID(std::uint32_t sequence, AccountID const& account); } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/InnerObjectFormats.h b/include/xrpl/protocol/InnerObjectFormats.h index 6d656d0065..a00e6e120b 100644 --- a/include/xrpl/protocol/InnerObjectFormats.h +++ b/include/xrpl/protocol/InnerObjectFormats.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_INNER_OBJECT_FORMATS_H_INCLUDED -#define XRPL_PROTOCOL_INNER_OBJECT_FORMATS_H_INCLUDED +#pragma once #include @@ -24,5 +23,3 @@ public: }; } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/Issue.h b/include/xrpl/protocol/Issue.h index a76b7a8316..c8e598a540 100644 --- a/include/xrpl/protocol/Issue.h +++ b/include/xrpl/protocol/Issue.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_ISSUE_H_INCLUDED -#define XRPL_PROTOCOL_ISSUE_H_INCLUDED +#pragma once #include #include @@ -72,8 +71,7 @@ hash_append(Hasher& h, Issue const& r) [[nodiscard]] inline constexpr bool operator==(Issue const& lhs, Issue const& rhs) { - return (lhs.currency == rhs.currency) && - (isXRP(lhs.currency) || lhs.account == rhs.account); + return (lhs.currency == rhs.currency) && (isXRP(lhs.currency) || lhs.account == rhs.account); } /** @} */ @@ -117,5 +115,3 @@ isXRP(Issue const& issue) } } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/KeyType.h b/include/xrpl/protocol/KeyType.h index 454c88780d..d05e421e4b 100644 --- a/include/xrpl/protocol/KeyType.h +++ b/include/xrpl/protocol/KeyType.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_KEYTYPE_H_INCLUDED -#define XRPL_PROTOCOL_KEYTYPE_H_INCLUDED +#pragma once #include #include @@ -43,5 +42,3 @@ operator<<(Stream& s, KeyType type) } } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/Keylet.h b/include/xrpl/protocol/Keylet.h index 4380fdfdac..2931486ac0 100644 --- a/include/xrpl/protocol/Keylet.h +++ b/include/xrpl/protocol/Keylet.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_KEYLET_H_INCLUDED -#define XRPL_PROTOCOL_KEYLET_H_INCLUDED +#pragma once #include #include @@ -31,5 +30,3 @@ struct Keylet }; } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/KnownFormats.h b/include/xrpl/protocol/KnownFormats.h index a928ed52be..67701c91ca 100644 --- a/include/xrpl/protocol/KnownFormats.h +++ b/include/xrpl/protocol/KnownFormats.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_KNOWNFORMATS_H_INCLUDED -#define XRPL_PROTOCOL_KNOWNFORMATS_H_INCLUDED +#pragma once #include #include @@ -37,8 +36,7 @@ public: { // Verify that KeyType is appropriate. static_assert( - std::is_enum::value || - std::is_integral::value, + std::is_enum::value || std::is_integral::value, "KnownFormats KeyType must be integral or enum."); } @@ -100,8 +98,7 @@ public: if (auto const result = findByName(name)) return result->getType(); Throw( - name_ + ": Unknown format name '" + - name.substr(0, std::min(name.size(), std::size_t(32))) + "'"); + name_ + ": Unknown format name '" + name.substr(0, std::min(name.size(), std::size_t(32))) + "'"); } /** Retrieve a format based on its type. @@ -157,9 +154,7 @@ protected: { if (auto const item = findByType(type)) { - LogicError( - std::string("Duplicate key for item '") + name + - "': already maps to " + item->getName()); + LogicError(std::string("Duplicate key for item '") + name + "': already maps to " + item->getName()); } formats_.emplace_front(name, type, uniqueFields, commonFields); @@ -184,5 +179,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/LedgerFormats.h b/include/xrpl/protocol/LedgerFormats.h index b52a25af17..fa39c15843 100644 --- a/include/xrpl/protocol/LedgerFormats.h +++ b/include/xrpl/protocol/LedgerFormats.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_LEDGERFORMATS_H_INCLUDED -#define XRPL_PROTOCOL_LEDGERFORMATS_H_INCLUDED +#pragma once #include @@ -211,5 +210,3 @@ public: }; } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/LedgerHeader.h b/include/xrpl/protocol/LedgerHeader.h index 641f794cdb..1dc67cada5 100644 --- a/include/xrpl/protocol/LedgerHeader.h +++ b/include/xrpl/protocol/LedgerHeader.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_LEDGERHEADER_H_INCLUDED -#define XRPL_PROTOCOL_LEDGERHEADER_H_INCLUDED +#pragma once #include #include @@ -74,5 +73,3 @@ LedgerHeader deserializePrefixedHeader(Slice data, bool hasHash = false); } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/LedgerShortcut.h b/include/xrpl/protocol/LedgerShortcut.h new file mode 100644 index 0000000000..68c31c4c3c --- /dev/null +++ b/include/xrpl/protocol/LedgerShortcut.h @@ -0,0 +1,22 @@ +#pragma once + +namespace xrpl { + +/** + * @brief Enumeration of ledger shortcuts for specifying which ledger to use. + * + * These shortcuts provide a convenient way to reference commonly used ledgers + * without needing to specify their exact hash or sequence number. + */ +enum class LedgerShortcut { + /** The current working ledger (open, not yet closed) */ + Current, + + /** The most recently closed ledger (may not be validated) */ + Closed, + + /** The most recently validated ledger */ + Validated +}; + +} // namespace xrpl diff --git a/include/xrpl/protocol/MPTAmount.h b/include/xrpl/protocol/MPTAmount.h index cc9528a923..66027185b3 100644 --- a/include/xrpl/protocol/MPTAmount.h +++ b/include/xrpl/protocol/MPTAmount.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_MPTAMOUNT_H_INCLUDED -#define XRPL_PROTOCOL_MPTAMOUNT_H_INCLUDED +#pragma once #include #include @@ -123,11 +122,7 @@ to_string(MPTAmount const& amount) } inline MPTAmount -mulRatio( - MPTAmount const& amt, - std::uint32_t num, - std::uint32_t den, - bool roundUp) +mulRatio(MPTAmount const& amt, std::uint32_t num, std::uint32_t den, bool roundUp) { using namespace boost::multiprecision; @@ -151,5 +146,3 @@ mulRatio( } } // namespace xrpl - -#endif // XRPL_BASICS_MPTAMOUNT_H_INCLUDED diff --git a/include/xrpl/protocol/MPTIssue.h b/include/xrpl/protocol/MPTIssue.h index ca81548a29..d84a610418 100644 --- a/include/xrpl/protocol/MPTIssue.h +++ b/include/xrpl/protocol/MPTIssue.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_MPTISSUE_H_INCLUDED -#define XRPL_PROTOCOL_MPTISSUE_H_INCLUDED +#pragma once #include #include @@ -84,5 +83,3 @@ MPTIssue mptIssueFromJson(Json::Value const& jv); } // namespace xrpl - -#endif // XRPL_PROTOCOL_MPTISSUE_H_INCLUDED diff --git a/include/xrpl/protocol/MultiApiJson.h b/include/xrpl/protocol/MultiApiJson.h index edf19b6f37..ad7a6b8f0d 100644 --- a/include/xrpl/protocol/MultiApiJson.h +++ b/include/xrpl/protocol/MultiApiJson.h @@ -1,5 +1,4 @@ -#ifndef XRPL_JSON_MULTIAPIJSON_H_INCLUDED -#define XRPL_JSON_MULTIAPIJSON_H_INCLUDED +#pragma once #include #include @@ -84,80 +83,48 @@ struct MultiApiJson static constexpr struct visitor_t final { // integral_constant version, extra arguments - template < - typename Json, - unsigned int Version, - typename... Args, - typename Fn> + template requires std::same_as, MultiApiJson> auto - operator()( - Json& json, - std::integral_constant const version, - Fn fn, - Args&&... args) const - -> std::invoke_result_t< - Fn, - decltype(json.val[0]), - std::integral_constant, - Args&&...> + operator()(Json& json, std::integral_constant const version, Fn fn, Args&&... args) const + -> std::invoke_result_t, Args&&...> { - static_assert( - valid(Version) && index(Version) >= 0 && index(Version) < size); - return std::invoke( - fn, - json.val[index(Version)], - version, - std::forward(args)...); + static_assert(valid(Version) && index(Version) >= 0 && index(Version) < size); + return std::invoke(fn, json.val[index(Version)], version, std::forward(args)...); } // integral_constant version, Json only template requires std::same_as, MultiApiJson> auto - operator()( - Json& json, - std::integral_constant const, - Fn fn) const -> std::invoke_result_t + operator()(Json& json, std::integral_constant const, Fn fn) const + -> std::invoke_result_t { - static_assert( - valid(Version) && index(Version) >= 0 && index(Version) < size); + static_assert(valid(Version) && index(Version) >= 0 && index(Version) < size); return std::invoke(fn, json.val[index(Version)]); } // unsigned int version, extra arguments - template < - typename Json, - typename Version, - typename... Args, - typename Fn> - requires(!some_integral_constant) && - std::convertible_to && + template + requires(!some_integral_constant) && std::convertible_to && std::same_as, MultiApiJson> auto operator()(Json& json, Version version, Fn fn, Args&&... args) const - -> std:: - invoke_result_t + -> std::invoke_result_t { XRPL_ASSERT( valid(version) && index(version) >= 0 && index(version) < size, "xrpl::detail::MultiApiJson::operator() : valid " "version"); - return std::invoke( - fn, - json.val[index(version)], - version, - std::forward(args)...); + return std::invoke(fn, json.val[index(version)], version, std::forward(args)...); } // unsigned int version, Json only template - requires(!some_integral_constant) && - std::convertible_to && + requires(!some_integral_constant) && std::convertible_to && std::same_as, MultiApiJson> auto - operator()(Json& json, Version version, Fn fn) const - -> std::invoke_result_t + operator()(Json& json, Version version, Fn fn) const -> std::invoke_result_t { XRPL_ASSERT( valid(version) && index(version) >= 0 && index(version) < size, @@ -170,11 +137,7 @@ struct MultiApiJson visit() { return [self = this](auto... args) - requires requires { - visitor( - std::declval(), - std::declval()...); - } + requires requires { visitor(std::declval(), std::declval()...); } { return visitor(*self, std::forward(args)...); }; } @@ -182,30 +145,22 @@ struct MultiApiJson visit() const { return [self = this](auto... args) - requires requires { - visitor( - std::declval(), - std::declval()...); - } + requires requires { visitor(std::declval(), std::declval()...); } { return visitor(*self, std::forward(args)...); }; } template auto - visit(Args... args) - -> std::invoke_result_t - requires(sizeof...(args) > 0) && - requires { visitor(*this, std::forward(args)...); } + visit(Args... args) -> std::invoke_result_t + requires(sizeof...(args) > 0) && requires { visitor(*this, std::forward(args)...); } { return visitor(*this, std::forward(args)...); } template auto - visit(Args... args) const - -> std::invoke_result_t - requires(sizeof...(args) > 0) && - requires { visitor(*this, std::forward(args)...); } + visit(Args... args) const -> std::invoke_result_t + requires(sizeof...(args) > 0) && requires { visitor(*this, std::forward(args)...); } { return visitor(*this, std::forward(args)...); } @@ -214,9 +169,6 @@ struct MultiApiJson } // namespace detail // Wrapper for Json for all supported API versions. -using MultiApiJson = detail:: - MultiApiJson; +using MultiApiJson = detail::MultiApiJson; } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/NFTSyntheticSerializer.h b/include/xrpl/protocol/NFTSyntheticSerializer.h index 7068ae34cd..c33a6edc7d 100644 --- a/include/xrpl/protocol/NFTSyntheticSerializer.h +++ b/include/xrpl/protocol/NFTSyntheticSerializer.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_NFTSYNTHETICSERIALIZER_H_INCLUDED -#define XRPL_PROTOCOL_NFTSYNTHETICSERIALIZER_H_INCLUDED +#pragma once #include #include @@ -17,13 +16,8 @@ namespace RPC { @{ */ void -insertNFTSyntheticInJson( - Json::Value&, - std::shared_ptr const&, - TxMeta const&); +insertNFTSyntheticInJson(Json::Value&, std::shared_ptr const&, TxMeta const&); /** @} */ } // namespace RPC } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/NFTokenID.h b/include/xrpl/protocol/NFTokenID.h index 03e30794d0..f3635d6fac 100644 --- a/include/xrpl/protocol/NFTokenID.h +++ b/include/xrpl/protocol/NFTokenID.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_NFTOKENID_H_INCLUDED -#define XRPL_PROTOCOL_NFTOKENID_H_INCLUDED +#pragma once #include #include @@ -21,9 +20,7 @@ namespace xrpl { @{ */ bool -canHaveNFTokenID( - std::shared_ptr const& serializedTx, - TxMeta const& transactionMeta); +canHaveNFTokenID(std::shared_ptr const& serializedTx, TxMeta const& transactionMeta); std::optional getNFTokenIDFromPage(TxMeta const& transactionMeta); @@ -32,12 +29,7 @@ std::vector getNFTokenIDFromDeletedOffer(TxMeta const& transactionMeta); void -insertNFTokenID( - Json::Value& response, - std::shared_ptr const& transaction, - TxMeta const& transactionMeta); +insertNFTokenID(Json::Value& response, std::shared_ptr const& transaction, TxMeta const& transactionMeta); /** @} */ } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/NFTokenOfferID.h b/include/xrpl/protocol/NFTokenOfferID.h index 5663653690..c3117db197 100644 --- a/include/xrpl/protocol/NFTokenOfferID.h +++ b/include/xrpl/protocol/NFTokenOfferID.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_NFTOKENOFFERID_H_INCLUDED -#define XRPL_PROTOCOL_NFTOKENOFFERID_H_INCLUDED +#pragma once #include #include @@ -19,9 +18,7 @@ namespace xrpl { @{ */ bool -canHaveNFTokenOfferID( - std::shared_ptr const& serializedTx, - TxMeta const& transactionMeta); +canHaveNFTokenOfferID(std::shared_ptr const& serializedTx, TxMeta const& transactionMeta); std::optional getOfferIDFromCreatedOffer(TxMeta const& transactionMeta); @@ -34,5 +31,3 @@ insertNFTokenOfferID( /** @} */ } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/PayChan.h b/include/xrpl/protocol/PayChan.h index ad70913c45..0a1496ca8e 100644 --- a/include/xrpl/protocol/PayChan.h +++ b/include/xrpl/protocol/PayChan.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_PAYCHAN_H_INCLUDED -#define XRPL_PROTOCOL_PAYCHAN_H_INCLUDED +#pragma once #include #include @@ -9,10 +8,7 @@ namespace xrpl { inline void -serializePayChanAuthorization( - Serializer& msg, - uint256 const& key, - XRPAmount const& amt) +serializePayChanAuthorization(Serializer& msg, uint256 const& key, XRPAmount const& amt) { msg.add32(HashPrefix::paymentChannelClaim); msg.addBitString(key); @@ -20,5 +16,3 @@ serializePayChanAuthorization( } } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/Permissions.h b/include/xrpl/protocol/Permissions.h index 74f539a3bf..e8800a41d2 100644 --- a/include/xrpl/protocol/Permissions.h +++ b/include/xrpl/protocol/Permissions.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_PERMISSION_H_INCLUDED -#define XRPL_PROTOCOL_PERMISSION_H_INCLUDED +#pragma once #include #include @@ -40,8 +39,7 @@ private: std::unordered_map delegableTx_; - std::unordered_map - granularPermissionMap_; + std::unordered_map granularPermissionMap_; std::unordered_map granularNameMap_; @@ -83,5 +81,3 @@ public: }; } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/Protocol.h b/include/xrpl/protocol/Protocol.h index 43be9d3b45..dfb2b9dfe8 100644 --- a/include/xrpl/protocol/Protocol.h +++ b/include/xrpl/protocol/Protocol.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_PROTOCOL_H_INCLUDED -#define XRPL_PROTOCOL_PROTOCOL_H_INCLUDED +#pragma once #include #include @@ -115,8 +114,7 @@ namespace Lending { Valid values are between 0 and 10% inclusive. */ -TenthBips16 constexpr maxManagementFeeRate( - unsafe_cast(percentageToTenthBips(10).value())); +TenthBips16 constexpr maxManagementFeeRate(unsafe_cast(percentageToTenthBips(10).value())); static_assert(maxManagementFeeRate == TenthBips16(std::uint16_t(10'000u))); /** The maximum coverage rate required of a loan broker in 1/10 bips. @@ -299,5 +297,3 @@ std::size_t constexpr permissionMaxSize = 10; std::size_t constexpr maxBatchTxCount = 8; } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/PublicKey.h b/include/xrpl/protocol/PublicKey.h index 51a7683ebc..eff2af6839 100644 --- a/include/xrpl/protocol/PublicKey.h +++ b/include/xrpl/protocol/PublicKey.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_PUBLICKEY_H_INCLUDED -#define XRPL_PROTOCOL_PUBLICKEY_H_INCLUDED +#pragma once #include #include @@ -126,11 +125,7 @@ operator==(PublicKey const& lhs, PublicKey const& rhs) inline bool operator<(PublicKey const& lhs, PublicKey const& rhs) { - return std::lexicographical_compare( - lhs.data(), - lhs.data() + lhs.size(), - rhs.data(), - rhs.data() + rhs.size()); + return std::lexicographical_compare(lhs.data(), lhs.data() + lhs.size(), rhs.data(), rhs.data() + rhs.size()); } template @@ -275,8 +270,7 @@ getOrThrow(Json::Value const& v, xrpl::SField const& field) { return PublicKey{makeSlice(*pubKeyBlob)}; } - for (auto const tokenType : - {TokenType::NodePublic, TokenType::AccountPublic}) + for (auto const tokenType : {TokenType::NodePublic, TokenType::AccountPublic}) { if (auto const pk = parseBase58(tokenType, b58)) return *pk; @@ -284,5 +278,3 @@ getOrThrow(Json::Value const& v, xrpl::SField const& field) Throw(field.getJsonName(), "PublicKey"); } } // namespace Json - -#endif diff --git a/include/xrpl/protocol/Quality.h b/include/xrpl/protocol/Quality.h index 83a038490a..4d3fcbfcc0 100644 --- a/include/xrpl/protocol/Quality.h +++ b/include/xrpl/protocol/Quality.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_QUALITY_H_INCLUDED -#define XRPL_PROTOCOL_QUALITY_H_INCLUDED +#pragma once #include #include @@ -115,15 +114,13 @@ public: /** Create a quality from the ratio of two amounts. */ template - explicit Quality(TAmounts const& amount) - : Quality(Amounts(toSTAmount(amount.in), toSTAmount(amount.out))) + explicit Quality(TAmounts const& amount) : Quality(Amounts(toSTAmount(amount.in), toSTAmount(amount.out))) { } /** Create a quality from the ratio of two amounts. */ template - Quality(Out const& out, In const& in) - : Quality(Amounts(toSTAmount(in), toSTAmount(out))) + Quality(Out const& out, In const& in) : Quality(Amounts(toSTAmount(in), toSTAmount(out))) { } @@ -173,15 +170,11 @@ public: // low order bits that could influence rounding decisions. This "strict" // method uses underlying functions that pay attention to all the bits. [[nodiscard]] Amounts - ceil_in_strict(Amounts const& amount, STAmount const& limit, bool roundUp) - const; + ceil_in_strict(Amounts const& amount, STAmount const& limit, bool roundUp) const; template [[nodiscard]] TAmounts - ceil_in_strict( - TAmounts const& amount, - In const& limit, - bool roundUp) const; + ceil_in_strict(TAmounts const& amount, In const& limit, bool roundUp) const; /** Returns the scaled amount with out capped. Math is avoided if the result is exact. The input is clamped @@ -198,26 +191,17 @@ public: // low order bits that could influence rounding decisions. This "strict" // method uses underlying functions that pay attention to all the bits. [[nodiscard]] Amounts - ceil_out_strict(Amounts const& amount, STAmount const& limit, bool roundUp) - const; + ceil_out_strict(Amounts const& amount, STAmount const& limit, bool roundUp) const; template [[nodiscard]] TAmounts - ceil_out_strict( - TAmounts const& amount, - Out const& limit, - bool roundUp) const; + ceil_out_strict(TAmounts const& amount, Out const& limit, bool roundUp) const; private: // The ceil_in and ceil_out methods that deal in TAmount all convert // their arguments to STAmount and convert the result back to TAmount. // This helper function takes care of all the conversion operations. - template < - class In, - class Out, - class Lim, - typename FnPtr, - std::same_as... Round> + template ... Round> [[nodiscard]] TAmounts ceil_TAmounts_helper( TAmounts const& amount, @@ -279,29 +263,22 @@ public: friend double relativeDistance(Quality const& q1, Quality const& q2) { - XRPL_ASSERT( - q1.m_value > 0 && q2.m_value > 0, - "xrpl::Quality::relativeDistance : minimum inputs"); + XRPL_ASSERT(q1.m_value > 0 && q2.m_value > 0, "xrpl::Quality::relativeDistance : minimum inputs"); if (q1.m_value == q2.m_value) // make expected common case fast return 0; auto const [minV, maxV] = std::minmax(q1.m_value, q2.m_value); - auto mantissa = [](std::uint64_t rate) { - return rate & ~(255ull << (64 - 8)); - }; - auto exponent = [](std::uint64_t rate) { - return static_cast(rate >> (64 - 8)) - 100; - }; + auto mantissa = [](std::uint64_t rate) { return rate & ~(255ull << (64 - 8)); }; + auto exponent = [](std::uint64_t rate) { return static_cast(rate >> (64 - 8)) - 100; }; auto const minVMantissa = mantissa(minV); auto const maxVMantissa = mantissa(maxV); auto const expDiff = exponent(maxV) - exponent(minV); double const minVD = static_cast(minVMantissa); - double const maxVD = expDiff ? maxVMantissa * pow(10, expDiff) - : static_cast(maxVMantissa); + double const maxVD = expDiff ? maxVMantissa * pow(10, expDiff) : static_cast(maxVMantissa); // maxVD and minVD are scaled so they have the same exponents. Dividing // cancels out the exponents, so we only need to deal with the (scaled) @@ -310,12 +287,7 @@ public: } }; -template < - class In, - class Out, - class Lim, - typename FnPtr, - std::same_as... Round> +template ... Round> TAmounts Quality::ceil_TAmounts_helper( TAmounts const& amount, @@ -340,25 +312,20 @@ TAmounts Quality::ceil_in(TAmounts const& amount, In const& limit) const { // Construct a function pointer to the function we want to call. - static constexpr Amounts (Quality::*ceil_in_fn_ptr)( - Amounts const&, STAmount const&) const = &Quality::ceil_in; + static constexpr Amounts (Quality::*ceil_in_fn_ptr)(Amounts const&, STAmount const&) const = &Quality::ceil_in; return ceil_TAmounts_helper(amount, limit, amount.in, ceil_in_fn_ptr); } template TAmounts -Quality::ceil_in_strict( - TAmounts const& amount, - In const& limit, - bool roundUp) const +Quality::ceil_in_strict(TAmounts const& amount, In const& limit, bool roundUp) const { // Construct a function pointer to the function we want to call. - static constexpr Amounts (Quality::*ceil_in_fn_ptr)( - Amounts const&, STAmount const&, bool) const = &Quality::ceil_in_strict; + static constexpr Amounts (Quality::*ceil_in_fn_ptr)(Amounts const&, STAmount const&, bool) const = + &Quality::ceil_in_strict; - return ceil_TAmounts_helper( - amount, limit, amount.in, ceil_in_fn_ptr, roundUp); + return ceil_TAmounts_helper(amount, limit, amount.in, ceil_in_fn_ptr, roundUp); } template @@ -366,26 +333,20 @@ TAmounts Quality::ceil_out(TAmounts const& amount, Out const& limit) const { // Construct a function pointer to the function we want to call. - static constexpr Amounts (Quality::*ceil_out_fn_ptr)( - Amounts const&, STAmount const&) const = &Quality::ceil_out; + static constexpr Amounts (Quality::*ceil_out_fn_ptr)(Amounts const&, STAmount const&) const = &Quality::ceil_out; return ceil_TAmounts_helper(amount, limit, amount.out, ceil_out_fn_ptr); } template TAmounts -Quality::ceil_out_strict( - TAmounts const& amount, - Out const& limit, - bool roundUp) const +Quality::ceil_out_strict(TAmounts const& amount, Out const& limit, bool roundUp) const { // Construct a function pointer to the function we want to call. - static constexpr Amounts (Quality::*ceil_out_fn_ptr)( - Amounts const&, STAmount const&, bool) const = + static constexpr Amounts (Quality::*ceil_out_fn_ptr)(Amounts const&, STAmount const&, bool) const = &Quality::ceil_out_strict; - return ceil_TAmounts_helper( - amount, limit, amount.out, ceil_out_fn_ptr, roundUp); + return ceil_TAmounts_helper(amount, limit, amount.out, ceil_out_fn_ptr, roundUp); } /** Calculate the quality of a two-hop path given the two hops. @@ -396,5 +357,3 @@ Quality composed_quality(Quality const& lhs, Quality const& rhs); } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/QualityFunction.h b/include/xrpl/protocol/QualityFunction.h index b7ec11fa69..4f76f4df0a 100644 --- a/include/xrpl/protocol/QualityFunction.h +++ b/include/xrpl/protocol/QualityFunction.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_QUALITYFUNCTION_H_INCLUDED -#define XRPL_PROTOCOL_QUALITYFUNCTION_H_INCLUDED +#pragma once #include #include @@ -38,10 +37,7 @@ public: }; QualityFunction(Quality const& quality, CLOBLikeTag); template - QualityFunction( - TAmounts const& amounts, - std::uint32_t tfee, - AMMTag); + QualityFunction(TAmounts const& amounts, std::uint32_t tfee, AMMTag); /** Combines QF with the next step QF */ @@ -71,10 +67,7 @@ public: }; template -QualityFunction::QualityFunction( - TAmounts const& amounts, - std::uint32_t tfee, - QualityFunction::AMMTag) +QualityFunction::QualityFunction(TAmounts const& amounts, std::uint32_t tfee, QualityFunction::AMMTag) { if (amounts.in <= beast::zero || amounts.out <= beast::zero) Throw("QualityFunction amounts are 0."); @@ -84,5 +77,3 @@ QualityFunction::QualityFunction( } } // namespace xrpl - -#endif // XRPL_PROTOCOL_QUALITYFUNCTION_H_INCLUDED diff --git a/include/xrpl/protocol/RPCErr.h b/include/xrpl/protocol/RPCErr.h index fcca15747e..34c4bf8f99 100644 --- a/include/xrpl/protocol/RPCErr.h +++ b/include/xrpl/protocol/RPCErr.h @@ -1,5 +1,4 @@ -#ifndef XRPL_NET_RPCERR_H_INCLUDED -#define XRPL_NET_RPCERR_H_INCLUDED +#pragma once #include @@ -12,5 +11,3 @@ Json::Value rpcError(error_code_i iError); } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/Rate.h b/include/xrpl/protocol/Rate.h index b8173a9392..e57d7e3a99 100644 --- a/include/xrpl/protocol/Rate.h +++ b/include/xrpl/protocol/Rate.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_RATE_H_INCLUDED -#define XRPL_PROTOCOL_RATE_H_INCLUDED +#pragma once #include #include @@ -54,11 +53,7 @@ STAmount multiplyRound(STAmount const& amount, Rate const& rate, bool roundUp); STAmount -multiplyRound( - STAmount const& amount, - Rate const& rate, - Asset const& asset, - bool roundUp); +multiplyRound(STAmount const& amount, Rate const& rate, Asset const& asset, bool roundUp); STAmount divide(STAmount const& amount, Rate const& rate); @@ -67,11 +62,7 @@ STAmount divideRound(STAmount const& amount, Rate const& rate, bool roundUp); STAmount -divideRound( - STAmount const& amount, - Rate const& rate, - Asset const& asset, - bool roundUp); +divideRound(STAmount const& amount, Rate const& rate, Asset const& asset, bool roundUp); namespace nft { /** Given a transfer fee (in basis points) convert it to a transfer rate. */ @@ -84,5 +75,3 @@ transferFeeAsRate(std::uint16_t fee); extern Rate const parityRate; } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/RippleLedgerHash.h b/include/xrpl/protocol/RippleLedgerHash.h index 516ab49029..2a51298d3d 100644 --- a/include/xrpl/protocol/RippleLedgerHash.h +++ b/include/xrpl/protocol/RippleLedgerHash.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_RIPPLELEDGERHASH_H_INCLUDED -#define XRPL_PROTOCOL_RIPPLELEDGERHASH_H_INCLUDED +#pragma once #include @@ -8,5 +7,3 @@ namespace xrpl { using LedgerHash = uint256; } - -#endif diff --git a/include/xrpl/protocol/Rules.h b/include/xrpl/protocol/Rules.h index 0ae6680d07..7d4a458fce 100644 --- a/include/xrpl/protocol/Rules.h +++ b/include/xrpl/protocol/Rules.h @@ -1,5 +1,4 @@ -#ifndef XRPL_LEDGER_RULES_H_INCLUDED -#define XRPL_LEDGER_RULES_H_INCLUDED +#pragma once #include #include @@ -47,14 +46,10 @@ public: private: // Allow a friend function to construct Rules. friend Rules - makeRulesGivenLedger( - DigestAwareReadView const& ledger, - Rules const& current); + makeRulesGivenLedger(DigestAwareReadView const& ledger, Rules const& current); friend Rules - makeRulesGivenLedger( - DigestAwareReadView const& ledger, - std::unordered_set> const& presets); + makeRulesGivenLedger(DigestAwareReadView const& ledger, std::unordered_set> const& presets); Rules( std::unordered_set> const& presets, @@ -91,8 +86,7 @@ setCurrentTransactionRules(std::optional r); class CurrentTransactionRulesGuard { public: - explicit CurrentTransactionRulesGuard(Rules r) - : saved_(getCurrentTransactionRules()) + explicit CurrentTransactionRulesGuard(Rules r) : saved_(getCurrentTransactionRules()) { setCurrentTransactionRules(std::move(r)); } @@ -112,4 +106,3 @@ private: }; } // namespace xrpl -#endif diff --git a/include/xrpl/protocol/SField.h b/include/xrpl/protocol/SField.h index 7f404b4d5f..7a864b1b58 100644 --- a/include/xrpl/protocol/SField.h +++ b/include/xrpl/protocol/SField.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_SFIELD_H_INCLUDED -#define XRPL_PROTOCOL_SFIELD_H_INCLUDED +#pragma once #include #include @@ -128,19 +127,18 @@ class SField public: enum { sMD_Never = 0x00, - sMD_ChangeOrig = 0x01, // original value when it changes - sMD_ChangeNew = 0x02, // new value when it changes - sMD_DeleteFinal = 0x04, // final value when it is deleted - sMD_Create = 0x08, // value when it's created - sMD_Always = 0x10, // value when node containing it is affected at all - sMD_BaseTen = 0x20, // value is treated as base 10, overriding behavior + sMD_ChangeOrig = 0x01, // original value when it changes + sMD_ChangeNew = 0x02, // new value when it changes + sMD_DeleteFinal = 0x04, // final value when it is deleted + sMD_Create = 0x08, // value when it's created + sMD_Always = 0x10, // value when node containing it is affected at all + sMD_BaseTen = 0x20, // value is treated as base 10, overriding behavior sMD_PseudoAccount = 0x40, // if this field is set in an ACCOUNT_ROOT // _only_, then it is a pseudo-account sMD_NeedsAsset = 0x80, // This field needs to be associated with an // asset before it is serialized as a ledger // object. Intended for STNumber. - sMD_Default = - sMD_ChangeOrig | sMD_ChangeNew | sMD_DeleteFinal | sMD_Create + sMD_Default = sMD_ChangeOrig | sMD_ChangeNew | sMD_DeleteFinal | sMD_Create }; enum class IsSigning : unsigned char { no, yes }; @@ -267,8 +265,7 @@ public: bool shouldInclude(bool withSigningField) const { - return (fieldValue < 256) && - (withSigningField || (signingField == IsSigning::yes)); + return (fieldValue < 256) && (withSigningField || (signingField == IsSigning::yes)); } bool @@ -362,10 +359,8 @@ using SF_XCHAIN_BRIDGE = TypedField; #pragma push_macro("TYPED_SFIELD") #undef TYPED_SFIELD -#define UNTYPED_SFIELD(sfName, stiSuffix, fieldValue, ...) \ - extern SField const sfName; -#define TYPED_SFIELD(sfName, stiSuffix, fieldValue, ...) \ - extern SF_##stiSuffix const sfName; +#define UNTYPED_SFIELD(sfName, stiSuffix, fieldValue, ...) extern SField const sfName; +#define TYPED_SFIELD(sfName, stiSuffix, fieldValue, ...) extern SF_##stiSuffix const sfName; extern SField const sfInvalid; extern SField const sfGeneric; @@ -378,5 +373,3 @@ extern SField const sfGeneric; #pragma pop_macro("UNTYPED_SFIELD") } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/SOTemplate.h b/include/xrpl/protocol/SOTemplate.h index 559117c274..794fc86c11 100644 --- a/include/xrpl/protocol/SOTemplate.h +++ b/include/xrpl/protocol/SOTemplate.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_SOTEMPLATE_H_INCLUDED -#define XRPL_PROTOCOL_SOTEMPLATE_H_INCLUDED +#pragma once #include #include @@ -42,24 +41,19 @@ private: auto nm = std::to_string(fieldName.getCode()); if (fieldName.hasName()) nm += ": '" + fieldName.getName() + "'"; - Throw( - "SField (" + nm + ") in SOElement must be useful."); + Throw("SField (" + nm + ") in SOElement must be useful."); } } public: - SOElement(SField const& fieldName, SOEStyle style) - : sField_(fieldName), style_(style) + SOElement(SField const& fieldName, SOEStyle style) : sField_(fieldName), style_(style) { init(fieldName); } template requires(std::is_same_v || std::is_same_v) - SOElement( - TypedField const& fieldName, - SOEStyle style, - SOETxMPTIssue supportMpt = soeMPTNotSupported) + SOElement(TypedField const& fieldName, SOEStyle style, SOETxMPTIssue supportMpt = soeMPTNotSupported) : sField_(fieldName), style_(style), supportMpt_(supportMpt) { init(fieldName); @@ -103,9 +97,7 @@ public: After creating the template fields cannot be added, modified, or removed. */ - SOTemplate( - std::initializer_list uniqueFields, - std::initializer_list commonFields = {}); + SOTemplate(std::initializer_list uniqueFields, std::initializer_list commonFields = {}); /* Provide for the enumeration of fields */ std::vector::const_iterator @@ -155,5 +147,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/STAccount.h b/include/xrpl/protocol/STAccount.h index 7c193d3425..3fdb2e015e 100644 --- a/include/xrpl/protocol/STAccount.h +++ b/include/xrpl/protocol/STAccount.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_STACCOUNT_H_INCLUDED -#define XRPL_PROTOCOL_STACCOUNT_H_INCLUDED +#pragma once #include #include @@ -113,5 +112,3 @@ operator<(AccountID const& lhs, STAccount const& rhs) } } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/STAmount.h b/include/xrpl/protocol/STAmount.h index 4d86aed2ec..df2b1c19a0 100644 --- a/include/xrpl/protocol/STAmount.h +++ b/include/xrpl/protocol/STAmount.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_STAMOUNT_H_INCLUDED -#define XRPL_PROTOCOL_STAMOUNT_H_INCLUDED +#pragma once #include #include @@ -81,12 +80,7 @@ public: unchecked); template - STAmount( - A const& asset, - mantissa_type mantissa, - exponent_type exponent, - bool negative, - unchecked); + STAmount(A const& asset, mantissa_type mantissa, exponent_type exponent, bool negative, unchecked); // Call canonicalize template @@ -99,36 +93,22 @@ public: STAmount(SField const& name, std::int64_t mantissa); - STAmount( - SField const& name, - std::uint64_t mantissa = 0, - bool negative = false); + STAmount(SField const& name, std::uint64_t mantissa = 0, bool negative = false); explicit STAmount(std::uint64_t mantissa = 0, bool negative = false); explicit STAmount(SField const& name, STAmount const& amt); template - STAmount( - A const& asset, - std::uint64_t mantissa = 0, - int exponent = 0, - bool negative = false) - : mAsset(asset) - , mValue(mantissa) - , mOffset(exponent) - , mIsNegative(negative) + STAmount(A const& asset, std::uint64_t mantissa = 0, int exponent = 0, bool negative = false) + : mAsset(asset), mValue(mantissa), mOffset(exponent), mIsNegative(negative) { canonicalize(); } // VFALCO Is this needed when we have the previous signature? template - STAmount( - A const& asset, - std::uint32_t mantissa, - int exponent = 0, - bool negative = false); + STAmount(A const& asset, std::uint32_t mantissa, int exponent = 0, bool negative = false); template STAmount(A const& asset, std::int64_t mantissa, int exponent = 0); @@ -137,8 +117,7 @@ public: STAmount(A const& asset, int mantissa, int exponent = 0); template - STAmount(A const& asset, Number const& number) - : STAmount(fromNumber(asset, number)) + STAmount(A const& asset, Number const& number) : STAmount(fromNumber(asset, number)) { } @@ -316,37 +295,19 @@ STAmount::STAmount( exponent_type exponent, bool negative, unchecked) - : STBase(name) - , mAsset(asset) - , mValue(mantissa) - , mOffset(exponent) - , mIsNegative(negative) + : STBase(name), mAsset(asset), mValue(mantissa), mOffset(exponent), mIsNegative(negative) { } template -STAmount::STAmount( - A const& asset, - mantissa_type mantissa, - exponent_type exponent, - bool negative, - unchecked) +STAmount::STAmount(A const& asset, mantissa_type mantissa, exponent_type exponent, bool negative, unchecked) : mAsset(asset), mValue(mantissa), mOffset(exponent), mIsNegative(negative) { } template -STAmount::STAmount( - SField const& name, - A const& asset, - std::uint64_t mantissa, - int exponent, - bool negative) - : STBase(name) - , mAsset(asset) - , mValue(mantissa) - , mOffset(exponent) - , mIsNegative(negative) +STAmount::STAmount(SField const& name, A const& asset, std::uint64_t mantissa, int exponent, bool negative) + : STBase(name), mAsset(asset), mValue(mantissa), mOffset(exponent), mIsNegative(negative) { // mValue is uint64, but needs to fit in the range of int64 if (Number::getMantissaScale() == MantissaRange::small) @@ -359,26 +320,20 @@ STAmount::STAmount( else { if (integral() && mValue > std::numeric_limits::max()) - throw std::overflow_error( - "STAmount mantissa is too large " + std::to_string(mantissa)); + throw std::overflow_error("STAmount mantissa is too large " + std::to_string(mantissa)); } canonicalize(); } template -STAmount::STAmount(A const& asset, std::int64_t mantissa, int exponent) - : mAsset(asset), mOffset(exponent) +STAmount::STAmount(A const& asset, std::int64_t mantissa, int exponent) : mAsset(asset), mOffset(exponent) { set(mantissa); canonicalize(); } template -STAmount::STAmount( - A const& asset, - std::uint32_t mantissa, - int exponent, - bool negative) +STAmount::STAmount(A const& asset, std::uint32_t mantissa, int exponent, bool negative) : STAmount(asset, safe_cast(mantissa), exponent, negative) { } @@ -391,9 +346,7 @@ STAmount::STAmount(A const& asset, int mantissa, int exponent) // Legacy support for new-style amounts inline STAmount::STAmount(IOUAmount const& amount, Issue const& issue) - : mAsset(issue) - , mOffset(amount.exponent()) - , mIsNegative(amount < beast::zero) + : mAsset(issue), mOffset(amount.exponent()), mIsNegative(amount < beast::zero) { if (mIsNegative) mValue = unsafe_cast(-amount.mantissa()); @@ -568,8 +521,7 @@ STAmount::fromNumber(A const& a, Number const& number) return STAmount{asset, intValue, 0, negative}; } - auto const [mantissa, exponent] = - working.normalizeToRange(cMinValue, cMaxValue); + auto const [mantissa, exponent] = working.normalizeToRange(cMinValue, cMaxValue); return STAmount{asset, mantissa, exponent, negative}; } @@ -673,35 +625,19 @@ multiply(STAmount const& v1, STAmount const& v2, Asset const& asset); // multiply rounding result in specified direction STAmount -mulRound( - STAmount const& v1, - STAmount const& v2, - Asset const& asset, - bool roundUp); +mulRound(STAmount const& v1, STAmount const& v2, Asset const& asset, bool roundUp); // multiply following the rounding directions more precisely. STAmount -mulRoundStrict( - STAmount const& v1, - STAmount const& v2, - Asset const& asset, - bool roundUp); +mulRoundStrict(STAmount const& v1, STAmount const& v2, Asset const& asset, bool roundUp); // divide rounding result in specified direction STAmount -divRound( - STAmount const& v1, - STAmount const& v2, - Asset const& asset, - bool roundUp); +divRound(STAmount const& v1, STAmount const& v2, Asset const& asset, bool roundUp); // divide following the rounding directions more precisely. STAmount -divRoundStrict( - STAmount const& v1, - STAmount const& v2, - Asset const& asset, - bool roundUp); +divRoundStrict(STAmount const& v1, STAmount const& v2, Asset const& asset, bool roundUp); // Someone is offering X for Y, what is the rate? // Rate: smaller is better, the taker wants the most out: in/out @@ -722,10 +658,7 @@ getRate(STAmount const& offerOut, STAmount const& offerIn); * */ [[nodiscard]] STAmount -roundToScale( - STAmount const& value, - std::int32_t scale, - Number::rounding_mode rounding = Number::getround()); +roundToScale(STAmount const& value, std::int32_t scale, Number::rounding_mode rounding = Number::getround()); /** Round an arbitrary precision Number IN PLACE to the precision of a given * Asset. @@ -801,4 +734,3 @@ getOrThrow(Json::Value const& v, xrpl::SField const& field) return amountFromJson(field, inner); } } // namespace Json -#endif diff --git a/include/xrpl/protocol/STArray.h b/include/xrpl/protocol/STArray.h index fb37e07226..d9c5306d14 100644 --- a/include/xrpl/protocol/STArray.h +++ b/include/xrpl/protocol/STArray.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_STARRAY_H_INCLUDED -#define XRPL_PROTOCOL_STARRAY_H_INCLUDED +#pragma once #include #include @@ -24,16 +23,12 @@ public: template < class Iter, - class = std::enable_if_t::reference, - STObject>>> + class = std::enable_if_t::reference, STObject>>> explicit STArray(Iter first, Iter last); template < class Iter, - class = std::enable_if_t::reference, - STObject>>> + class = std::enable_if_t::reference, STObject>>> STArray(SField const& f, Iter first, Iter last); STArray& @@ -153,8 +148,7 @@ STArray::STArray(Iter first, Iter last) : v_(first, last) } template -STArray::STArray(SField const& f, Iter first, Iter last) - : STBase(f), v_(first, last) +STArray::STArray(SField const& f, Iter first, Iter last) : STBase(f), v_(first, last) { } @@ -292,5 +286,3 @@ STArray::erase(const_iterator first, const_iterator last) } } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/STBase.h b/include/xrpl/protocol/STBase.h index f100b52426..7f06b01ca4 100644 --- a/include/xrpl/protocol/STBase.h +++ b/include/xrpl/protocol/STBase.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_STBASE_H_INCLUDED -#define XRPL_PROTOCOL_STBASE_H_INCLUDED +#pragma once #include #include @@ -220,5 +219,3 @@ STBase::emplace(std::size_t n, void* buf, T&& val) } } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/STBitString.h b/include/xrpl/protocol/STBitString.h index 2d26fe4bd7..e8b6e7282b 100644 --- a/include/xrpl/protocol/STBitString.h +++ b/include/xrpl/protocol/STBitString.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_STBITSTRING_H_INCLUDED -#define XRPL_PROTOCOL_STBITSTRING_H_INCLUDED +#pragma once #include #include @@ -79,14 +78,12 @@ inline STBitString::STBitString(value_type const& v) : value_(v) } template -inline STBitString::STBitString(SField const& n, value_type const& v) - : STBase(n), value_(v) +inline STBitString::STBitString(SField const& n, value_type const& v) : STBase(n), value_(v) { } template -inline STBitString::STBitString(SerialIter& sit, SField const& name) - : STBitString(name, sit.getBitString()) +inline STBitString::STBitString(SerialIter& sit, SField const& name) : STBitString(name, sit.getBitString()) { } @@ -151,11 +148,8 @@ template void STBitString::add(Serializer& s) const { - XRPL_ASSERT( - getFName().isBinary(), "xrpl::STBitString::add : field is binary"); - XRPL_ASSERT( - getFName().fieldType == getSType(), - "xrpl::STBitString::add : field type match"); + XRPL_ASSERT(getFName().isBinary(), "xrpl::STBitString::add : field is binary"); + XRPL_ASSERT(getFName().fieldType == getSType(), "xrpl::STBitString::add : field type match"); s.addBitString(value_); } @@ -188,5 +182,3 @@ STBitString::isDefault() const } } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/STBlob.h b/include/xrpl/protocol/STBlob.h index dc3f95e218..15a9bd5f78 100644 --- a/include/xrpl/protocol/STBlob.h +++ b/include/xrpl/protocol/STBlob.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_STBLOB_H_INCLUDED -#define XRPL_PROTOCOL_STBLOB_H_INCLUDED +#pragma once #include #include @@ -69,18 +68,15 @@ private: friend class detail::STVar; }; -inline STBlob::STBlob(STBlob const& rhs) - : STBase(rhs), CountedObject(rhs), value_(rhs.data(), rhs.size()) +inline STBlob::STBlob(STBlob const& rhs) : STBase(rhs), CountedObject(rhs), value_(rhs.data(), rhs.size()) { } -inline STBlob::STBlob(SField const& f, void const* data, std::size_t size) - : STBase(f), value_(data, size) +inline STBlob::STBlob(SField const& f, void const* data, std::size_t size) : STBase(f), value_(data, size) { } -inline STBlob::STBlob(SField const& f, Buffer&& b) - : STBase(f), value_(std::move(b)) +inline STBlob::STBlob(SField const& f, Buffer&& b) : STBase(f), value_(std::move(b)) { } @@ -127,5 +123,3 @@ STBlob::setValue(Buffer&& b) } } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/STCurrency.h b/include/xrpl/protocol/STCurrency.h index 1c59d48beb..dc5b079c6d 100644 --- a/include/xrpl/protocol/STCurrency.h +++ b/include/xrpl/protocol/STCurrency.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_STCURRENCY_H_INCLUDED -#define XRPL_PROTOCOL_STCURRENCY_H_INCLUDED +#pragma once #include #include @@ -115,5 +114,3 @@ operator<(STCurrency const& lhs, Currency const& rhs) } } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/STExchange.h b/include/xrpl/protocol/STExchange.h index 5f7e405599..4b576991b7 100644 --- a/include/xrpl/protocol/STExchange.h +++ b/include/xrpl/protocol/STExchange.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_STEXCHANGE_H_INCLUDED -#define XRPL_PROTOCOL_STEXCHANGE_H_INCLUDED +#pragma once #include #include @@ -124,8 +123,7 @@ template void set(STObject& st, TypedField const& f, T&& t) { - st.set(STExchange::type>::set( - f, std::forward(t))); + st.set(STExchange::type>::set(f, std::forward(t))); } /** Set a blob field using an init function. */ @@ -139,10 +137,7 @@ set(STObject& st, TypedField const& f, std::size_t size, Init&& init) /** Set a blob field from data. */ template void -set(STObject& st, - TypedField const& f, - void const* data, - std::size_t size) +set(STObject& st, TypedField const& f, void const* data, std::size_t size) { st.set(std::make_unique(f, data, size)); } @@ -156,5 +151,3 @@ erase(STObject& st, TypedField const& f) } } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/STInteger.h b/include/xrpl/protocol/STInteger.h index 9c8af4c08c..b5c4dbf6cf 100644 --- a/include/xrpl/protocol/STInteger.h +++ b/include/xrpl/protocol/STInteger.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_STINTEGER_H_INCLUDED -#define XRPL_PROTOCOL_STINTEGER_H_INCLUDED +#pragma once #include #include @@ -70,8 +69,7 @@ inline STInteger::STInteger(Integer v) : value_(v) } template -inline STInteger::STInteger(SField const& n, Integer v) - : STBase(n), value_(v) +inline STInteger::STInteger(SField const& n, Integer v) : STBase(n), value_(v) { } @@ -93,11 +91,8 @@ template inline void STInteger::add(Serializer& s) const { - XRPL_ASSERT( - getFName().isBinary(), "xrpl::STInteger::add : field is binary"); - XRPL_ASSERT( - getFName().fieldType == getSType(), - "xrpl::STInteger::add : field type match"); + XRPL_ASSERT(getFName().isBinary(), "xrpl::STInteger::add : field is binary"); + XRPL_ASSERT(getFName().fieldType == getSType(), "xrpl::STInteger::add : field type match"); s.addInteger(value_); } @@ -145,5 +140,3 @@ inline STInteger::operator Integer() const } } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/STIssue.h b/include/xrpl/protocol/STIssue.h index 6480482d08..7491e3b3ff 100644 --- a/include/xrpl/protocol/STIssue.h +++ b/include/xrpl/protocol/STIssue.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_STISSUE_H_INCLUDED -#define XRPL_PROTOCOL_STISSUE_H_INCLUDED +#pragma once #include #include @@ -83,12 +82,10 @@ private: }; template -STIssue::STIssue(SField const& name, A const& asset) - : STBase{name}, asset_{asset} +STIssue::STIssue(SField const& name, A const& asset) : STBase{name}, asset_{asset} { if (holds() && !isConsistent(asset_.get())) - Throw( - "Invalid asset: currency and account native mismatch"); + Throw("Invalid asset: currency and account native mismatch"); } STIssue @@ -120,8 +117,7 @@ inline void STIssue::setIssue(Asset const& asset) { if (holds() && !isConsistent(asset_.get())) - Throw( - "Invalid asset: currency and account native mismatch"); + Throw("Invalid asset: currency and account native mismatch"); asset_ = asset; } @@ -151,5 +147,3 @@ operator<=>(STIssue const& lhs, Asset const& rhs) } } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/STLedgerEntry.h b/include/xrpl/protocol/STLedgerEntry.h index 83e0f2cd27..6ba3b36c6b 100644 --- a/include/xrpl/protocol/STLedgerEntry.h +++ b/include/xrpl/protocol/STLedgerEntry.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_STLEDGERENTRY_H_INCLUDED -#define XRPL_PROTOCOL_STLEDGERENTRY_H_INCLUDED +#pragma once #include #include @@ -56,11 +55,7 @@ public: isThreadedType(Rules const& rules) const; bool - thread( - uint256 const& txID, - std::uint32_t ledgerSeq, - uint256& prevTxID, - std::uint32_t& prevLedgerID); + thread(uint256 const& txID, std::uint32_t ledgerSeq, uint256& prevTxID, std::uint32_t& prevLedgerID); private: /* Make STObject comply with the template for this SLE type @@ -82,13 +77,11 @@ private: using SLE = STLedgerEntry; -inline STLedgerEntry::STLedgerEntry(LedgerEntryType type, uint256 const& key) - : STLedgerEntry(Keylet(type, key)) +inline STLedgerEntry::STLedgerEntry(LedgerEntryType type, uint256 const& key) : STLedgerEntry(Keylet(type, key)) { } -inline STLedgerEntry::STLedgerEntry(SerialIter&& sit, uint256 const& index) - : STLedgerEntry(sit, index) +inline STLedgerEntry::STLedgerEntry(SerialIter&& sit, uint256 const& index) : STLedgerEntry(sit, index) { } @@ -109,5 +102,3 @@ STLedgerEntry::getType() const } } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/STNumber.h b/include/xrpl/protocol/STNumber.h index 39b0c3b042..137016dfe7 100644 --- a/include/xrpl/protocol/STNumber.h +++ b/include/xrpl/protocol/STNumber.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_STNUMBER_H_INCLUDED -#define XRPL_PROTOCOL_STNUMBER_H_INCLUDED +#pragma once #include #include @@ -100,5 +99,3 @@ STNumber numberFromJson(SField const& field, Json::Value const& value); } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/STObject.h b/include/xrpl/protocol/STObject.h index c6ca133e89..5d5d829c99 100644 --- a/include/xrpl/protocol/STObject.h +++ b/include/xrpl/protocol/STObject.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_STOBJECT_H_INCLUDED -#define XRPL_PROTOCOL_STOBJECT_H_INCLUDED +#pragma once #include #include @@ -61,15 +60,13 @@ class STObject : public STBase, public CountedObject SOTemplate const* mType; public: - using iterator = boost:: - transform_iterator; + using iterator = boost::transform_iterator; virtual ~STObject() = default; STObject(STObject const&) = default; template - STObject(SOTemplate const& type, SField const& name, F&& f) - : STObject(type, name) + STObject(SOTemplate const& type, SField const& name, F&& f) : STObject(type, name) { f(*this); } @@ -397,6 +394,9 @@ public: void delField(int index); + SOEStyle + getStyle(SField const& field) const; + bool hasMatchingEntry(STBase const&); @@ -431,8 +431,8 @@ private: // by value. template < typename T, - typename V = typename std::remove_cv().value())>::type>::type> + typename V = + typename std::remove_cv().value())>::type>::type> V getFieldByValue(SField const& field) const; @@ -507,26 +507,19 @@ protected: // Constraint += and -= ValueProxy operators // to value types that support arithmetic operations template -concept IsArithmeticNumber = std::is_arithmetic_v || - std::is_same_v || std::is_same_v; -template < - typename U, - typename Value = typename U::value_type, - typename Unit = typename U::unit_type> +concept IsArithmeticNumber = std::is_arithmetic_v || std::is_same_v || std::is_same_v; +template concept IsArithmeticValueUnit = - std::is_same_v> && - IsArithmeticNumber && std::is_class_v; + std::is_same_v> && IsArithmeticNumber && std::is_class_v; template concept IsArithmeticST = !IsArithmeticValueUnit && IsArithmeticNumber; template -concept IsArithmetic = - IsArithmeticNumber || IsArithmeticST || IsArithmeticValueUnit; +concept IsArithmetic = IsArithmeticNumber || IsArithmeticST || IsArithmeticValueUnit; template concept Addable = requires(T t, U u) { t = t + u; }; template -concept IsArithmeticCompatible = - IsArithmetic && Addable; +concept IsArithmeticCompatible = IsArithmetic && Addable; template class STObject::ValueProxy : public Proxy @@ -705,8 +698,7 @@ STObject::Proxy::Proxy(STObject* st, TypedField const* f) : st_(st), f_(f) { // STObject has associated template if (!st_->peekAtPField(*f_)) - Throw( - "Template field error '" + this->f_->getName() + "'"); + Throw("Template field error '" + this->f_->getName() + "'"); style_ = st_->mType->style(*f_); } else @@ -728,8 +720,7 @@ STObject::Proxy::value() const -> value_type } if (style_ != soeDEFAULT) { - Throw( - "Missing field '" + this->f_->getName() + "'"); + Throw("Missing field '" + this->f_->getName() + "'"); } return value_type{}; } @@ -814,8 +805,7 @@ STObject::ValueProxy::operator value_type() const } template -STObject::ValueProxy::ValueProxy(STObject* st, TypedField const* f) - : Proxy(st, f) +STObject::ValueProxy::ValueProxy(STObject* st, TypedField const* f) : Proxy(st, f) { } @@ -828,8 +818,7 @@ STObject::OptionalProxy::operator bool() const noexcept } template -STObject::OptionalProxy::operator typename STObject::OptionalProxy< - T>::optional_type() const +STObject::OptionalProxy::operator typename STObject::OptionalProxy::optional_type() const { return optional_value(); } @@ -881,8 +870,7 @@ STObject::OptionalProxy::operator=(U&& u) } template -STObject::OptionalProxy::OptionalProxy(STObject* st, TypedField const* f) - : Proxy(st, f) +STObject::OptionalProxy::OptionalProxy(STObject* st, TypedField const* f) : Proxy(st, f) { } @@ -898,8 +886,7 @@ void STObject::OptionalProxy::disengage() { if (this->style_ == soeREQUIRED || this->style_ == soeDEFAULT) - Throw( - "Template field error '" + this->f_->getName() + "'"); + Throw("Template field error '" + this->f_->getName() + "'"); if (this->style_ == soeINVALID) this->st_->delField(*this->f_); else @@ -932,8 +919,7 @@ STObject::Transform::operator()(detail::STVar const& e) const //------------------------------------------------------------------------------ -inline STObject::STObject(SerialIter&& sit, SField const& name) - : STObject(sit, name) +inline STObject::STObject(SerialIter&& sit, SField const& name) : STObject(sit, name) { } @@ -1063,18 +1049,13 @@ STObject::at(TypedField const& f) const if (auto const u = dynamic_cast(b)) return u->value(); - XRPL_ASSERT( - mType, "xrpl::STObject::at(TypedField auto) : field template non-null"); - XRPL_ASSERT( - b->getSType() == STI_NOTPRESENT, - "xrpl::STObject::at(TypedField auto) : type not present"); + XRPL_ASSERT(mType, "xrpl::STObject::at(TypedField auto) : field template non-null"); + XRPL_ASSERT(b->getSType() == STI_NOTPRESENT, "xrpl::STObject::at(TypedField auto) : type not present"); if (mType->style(f) == soeOPTIONAL) Throw("Missing optional field: " + f.getName()); - XRPL_ASSERT( - mType->style(f) == soeDEFAULT, - "xrpl::STObject::at(TypedField auto) : template style is default"); + XRPL_ASSERT(mType->style(f) == soeDEFAULT, "xrpl::STObject::at(TypedField auto) : template style is default"); // Used to help handle the case where value_type is a const reference, // otherwise we would return the address of a temporary. @@ -1096,9 +1077,7 @@ STObject::at(OptionaledField const& of) const mType, "xrpl::STObject::at(OptionaledField auto) : field template " "non-null"); - XRPL_ASSERT( - b->getSType() == STI_NOTPRESENT, - "xrpl::STObject::at(OptionaledField auto) : type not present"); + XRPL_ASSERT(b->getSType() == STI_NOTPRESENT, "xrpl::STObject::at(OptionaledField auto) : type not present"); if (mType->style(*of.f) == soeOPTIONAL) return std::nullopt; XRPL_ASSERT( @@ -1264,5 +1243,3 @@ STObject::peekField(SField const& field) } } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/STParsedJSON.h b/include/xrpl/protocol/STParsedJSON.h index 4be10840bd..772785fd70 100644 --- a/include/xrpl/protocol/STParsedJSON.h +++ b/include/xrpl/protocol/STParsedJSON.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_STPARSEDJSON_H_INCLUDED -#define XRPL_PROTOCOL_STPARSEDJSON_H_INCLUDED +#pragma once #include @@ -36,5 +35,3 @@ public: }; } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/STPathSet.h b/include/xrpl/protocol/STPathSet.h index cb7db2edf0..1bab654d3f 100644 --- a/include/xrpl/protocol/STPathSet.h +++ b/include/xrpl/protocol/STPathSet.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_STPATHSET_H_INCLUDED -#define XRPL_PROTOCOL_STPATHSET_H_INCLUDED +#pragma once #include #include @@ -26,8 +25,7 @@ class STPathElement final : public CountedObject public: enum Type { typeNone = 0x00, - typeAccount = - 0x01, // Rippling through an account (vs taking an offer). + typeAccount = 0x01, // Rippling through an account (vs taking an offer). typeCurrency = 0x10, // Currency follows. typeIssuer = 0x20, // Issuer follows. typeBoundary = 0xFF, // Boundary between alternate paths. @@ -51,11 +49,7 @@ public: AccountID const& issuer, bool forceCurrency = false); - STPathElement( - unsigned int uType, - AccountID const& account, - Currency const& currency, - AccountID const& issuer); + STPathElement(unsigned int uType, AccountID const& account, Currency const& currency, AccountID const& issuer); auto getNodeType() const; @@ -120,10 +114,7 @@ public: emplace_back(Args&&... args); bool - hasSeen( - AccountID const& account, - Currency const& currency, - AccountID const& issuer) const; + hasSeen(AccountID const& account, Currency const& currency, AccountID const& issuer) const; Json::Value getJson(JsonOptions) const; @@ -239,9 +230,7 @@ inline STPathElement::STPathElement( is_offer_ = false; mAccountID = *account; mType |= typeAccount; - XRPL_ASSERT( - mAccountID != noAccount(), - "xrpl::STPathElement::STPathElement : account is set"); + XRPL_ASSERT(mAccountID != noAccount(), "xrpl::STPathElement::STPathElement : account is set"); } if (currency) @@ -254,9 +243,7 @@ inline STPathElement::STPathElement( { mIssuerID = *issuer; mType |= typeIssuer; - XRPL_ASSERT( - mIssuerID != noAccount(), - "xrpl::STPathElement::STPathElement : issuer is set"); + XRPL_ASSERT(mIssuerID != noAccount(), "xrpl::STPathElement::STPathElement : issuer is set"); } hash_value_ = get_hash(*this); @@ -267,11 +254,7 @@ inline STPathElement::STPathElement( Currency const& currency, AccountID const& issuer, bool forceCurrency) - : mType(typeNone) - , mAccountID(account) - , mCurrencyID(currency) - , mIssuerID(issuer) - , is_offer_(isXRP(mAccountID)) + : mType(typeNone), mAccountID(account), mCurrencyID(currency), mIssuerID(issuer), is_offer_(isXRP(mAccountID)) { if (!is_offer_) mType |= typeAccount; @@ -290,11 +273,7 @@ inline STPathElement::STPathElement( AccountID const& account, Currency const& currency, AccountID const& issuer) - : mType(uType) - , mAccountID(account) - , mCurrencyID(currency) - , mIssuerID(issuer) - , is_offer_(isXRP(mAccountID)) + : mType(uType), mAccountID(account), mCurrencyID(currency), mIssuerID(issuer), is_offer_(isXRP(mAccountID)) { hash_value_ = get_hash(*this); } @@ -358,9 +337,8 @@ STPathElement::getIssuerID() const inline bool STPathElement::operator==(STPathElement const& t) const { - return (mType & typeAccount) == (t.mType & typeAccount) && - hash_value_ == t.hash_value_ && mAccountID == t.mAccountID && - mCurrencyID == t.mCurrencyID && mIssuerID == t.mIssuerID; + return (mType & typeAccount) == (t.mType & typeAccount) && hash_value_ == t.hash_value_ && + mAccountID == t.mAccountID && mCurrencyID == t.mCurrencyID && mIssuerID == t.mIssuerID; } inline bool @@ -505,5 +483,3 @@ STPathSet::emplace_back(Args&&... args) } } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/STTakesAsset.h b/include/xrpl/protocol/STTakesAsset.h index 767223b97d..bf75ffccf7 100644 --- a/include/xrpl/protocol/STTakesAsset.h +++ b/include/xrpl/protocol/STTakesAsset.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_STTAKESASSET_H_INCLUDED -#define XRPL_PROTOCOL_STTAKESASSET_H_INCLUDED +#pragma once #include #include @@ -59,5 +58,3 @@ void associateAsset(STLedgerEntry& sle, Asset const& asset); } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/STTx.h b/include/xrpl/protocol/STTx.h index 182e13433d..a12c658dc2 100644 --- a/include/xrpl/protocol/STTx.h +++ b/include/xrpl/protocol/STTx.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_STTX_H_INCLUDED -#define XRPL_PROTOCOL_STTX_H_INCLUDED +#pragma once #include #include @@ -100,8 +99,7 @@ public: sign( PublicKey const& publicKey, SecretKey const& secretKey, - std::optional> signatureTarget = - {}); + std::optional> signatureTarget = {}); /** Check the signature. @param rules The current ledger rules. @@ -118,15 +116,10 @@ public: getMetaSQLInsertReplaceHeader(); std::string - getMetaSQL(std::uint32_t inLedger, std::string const& escapedMetaData) - const; + getMetaSQL(std::uint32_t inLedger, std::string const& escapedMetaData) const; std::string - getMetaSQL( - Serializer rawTxn, - std::uint32_t inLedger, - char status, - std::string const& escapedMetaData) const; + getMetaSQL(Serializer rawTxn, std::uint32_t inLedger, char status, std::string const& escapedMetaData) const; std::vector const& getBatchTransactionIDs() const; @@ -202,5 +195,3 @@ STTx::getTransactionID() const } } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/STValidation.h b/include/xrpl/protocol/STValidation.h index 4d09397eaa..aa48161f68 100644 --- a/include/xrpl/protocol/STValidation.h +++ b/include/xrpl/protocol/STValidation.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_STVALIDATION_H_INCLUDED -#define XRPL_PROTOCOL_STVALIDATION_H_INCLUDED +#pragma once #include #include @@ -54,10 +53,7 @@ public: @note Throws if the object is not valid */ template - STValidation( - SerialIter& sit, - LookupNodeID&& lookupNodeID, - bool checkSignature); + STValidation(SerialIter& sit, LookupNodeID&& lookupNodeID, bool checkSignature); /** Construct, sign and trust a new STValidation issued by this node. @@ -68,12 +64,7 @@ public: @param f callback function to "fill" the validation with necessary data */ template - STValidation( - NetClock::time_point signTime, - PublicKey const& pk, - SecretKey const& sk, - NodeID const& nodeID, - F&& f); + STValidation(NetClock::time_point signTime, PublicKey const& pk, SecretKey const& sk, NodeID const& nodeID, F&& f); // Hash of the validated ledger uint256 @@ -126,14 +117,10 @@ public: render() const { std::stringstream ss; - ss << "validation: " << " ledger_hash: " << getLedgerHash() - << " consensus_hash: " << getConsensusHash() - << " sign_time: " << to_string(getSignTime()) - << " seen_time: " << to_string(getSeenTime()) - << " signer_public_key: " << getSignerPublic() - << " node_id: " << getNodeID() << " is_valid: " << isValid() - << " is_full: " << isFull() << " is_trusted: " << isTrusted() - << " signing_hash: " << getSigningHash() + ss << "validation: " << " ledger_hash: " << getLedgerHash() << " consensus_hash: " << getConsensusHash() + << " sign_time: " << to_string(getSignTime()) << " seen_time: " << to_string(getSeenTime()) + << " signer_public_key: " << getSignerPublic() << " node_id: " << getNodeID() << " is_valid: " << isValid() + << " is_full: " << isFull() << " is_trusted: " << isTrusted() << " signing_hash: " << getSigningHash() << " base58: " << toBase58(TokenType::NodePublic, getSignerPublic()); return ss.str(); } @@ -151,10 +138,7 @@ private: }; template -STValidation::STValidation( - SerialIter& sit, - LookupNodeID&& lookupNodeID, - bool checkSignature) +STValidation::STValidation(SerialIter& sit, LookupNodeID&& lookupNodeID, bool checkSignature) : STObject(validationFormat(), sit, sfValidation) , signingPubKey_([this]() { auto const spk = getFieldVL(sfSigningPubKey); @@ -168,14 +152,11 @@ STValidation::STValidation( { if (checkSignature && !isValid()) { - JLOG(debugLog().error()) << "Invalid signature in validation: " - << getJson(JsonOptions::none); + JLOG(debugLog().error()) << "Invalid signature in validation: " << getJson(JsonOptions::none); Throw("Invalid signature in validation"); } - XRPL_ASSERT( - nodeID_.isNonZero(), - "xrpl::STValidation::STValidation(SerialIter) : nonzero node"); + XRPL_ASSERT(nodeID_.isNonZero(), "xrpl::STValidation::STValidation(SerialIter) : nonzero node"); } /** Construct, sign and trust a new STValidation issued by this node. @@ -193,10 +174,7 @@ STValidation::STValidation( SecretKey const& sk, NodeID const& nodeID, F&& f) - : STObject(validationFormat(), sfValidation) - , signingPubKey_(pk) - , nodeID_(nodeID) - , seenTime_(signTime) + : STObject(validationFormat(), sfValidation), signingPubKey_(pk), nodeID_(nodeID), seenTime_(signTime) { XRPL_ASSERT( nodeID_.isNonZero(), @@ -222,9 +200,7 @@ STValidation::STValidation( for (auto const& e : validationFormat()) { if (e.style() == soeREQUIRED && !isFieldPresent(e.sField())) - LogicError( - "Required field '" + e.sField().getName() + - "' missing from validation."); + LogicError("Required field '" + e.sField().getName() + "' missing from validation."); } // We just signed this, so it should be valid. @@ -268,5 +244,3 @@ STValidation::setSeen(NetClock::time_point s) } } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/STVector256.h b/include/xrpl/protocol/STVector256.h index 94b16db90b..c83d981bfc 100644 --- a/include/xrpl/protocol/STVector256.h +++ b/include/xrpl/protocol/STVector256.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_STVECTOR256_H_INCLUDED -#define XRPL_PROTOCOL_STVECTOR256_H_INCLUDED +#pragma once #include #include @@ -107,15 +106,11 @@ inline STVector256::STVector256(SField const& n) : STBase(n) { } -inline STVector256::STVector256(std::vector const& vector) - : mValue(vector) +inline STVector256::STVector256(std::vector const& vector) : mValue(vector) { } -inline STVector256::STVector256( - SField const& n, - std::vector const& vector) - : STBase(n), mValue(vector) +inline STVector256::STVector256(SField const& n, std::vector const& vector) : STBase(n), mValue(vector) { } @@ -182,9 +177,7 @@ STVector256::value() const } inline std::vector::iterator -STVector256::insert( - std::vector::const_iterator pos, - uint256 const& value) +STVector256::insert(std::vector::const_iterator pos, uint256 const& value) { return mValue.insert(pos, value); } @@ -238,5 +231,3 @@ STVector256::clear() noexcept } } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/STXChainBridge.h b/include/xrpl/protocol/STXChainBridge.h index 89c6d60c13..709d3886b7 100644 --- a/include/xrpl/protocol/STXChainBridge.h +++ b/include/xrpl/protocol/STXChainBridge.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_STXCHAINBRIDGE_H_INCLUDED -#define XRPL_PROTOCOL_STXCHAINBRIDGE_H_INCLUDED +#pragma once #include #include @@ -115,31 +114,15 @@ private: inline bool operator==(STXChainBridge const& lhs, STXChainBridge const& rhs) { - return std::tie( - lhs.lockingChainDoor_, - lhs.lockingChainIssue_, - lhs.issuingChainDoor_, - lhs.issuingChainIssue_) == - std::tie( - rhs.lockingChainDoor_, - rhs.lockingChainIssue_, - rhs.issuingChainDoor_, - rhs.issuingChainIssue_); + return std::tie(lhs.lockingChainDoor_, lhs.lockingChainIssue_, lhs.issuingChainDoor_, lhs.issuingChainIssue_) == + std::tie(rhs.lockingChainDoor_, rhs.lockingChainIssue_, rhs.issuingChainDoor_, rhs.issuingChainIssue_); } inline bool operator<(STXChainBridge const& lhs, STXChainBridge const& rhs) { - return std::tie( - lhs.lockingChainDoor_, - lhs.lockingChainIssue_, - lhs.issuingChainDoor_, - lhs.issuingChainIssue_) < - std::tie( - rhs.lockingChainDoor_, - rhs.lockingChainIssue_, - rhs.issuingChainDoor_, - rhs.issuingChainIssue_); + return std::tie(lhs.lockingChainDoor_, lhs.lockingChainIssue_, lhs.issuingChainDoor_, lhs.issuingChainIssue_) < + std::tie(rhs.lockingChainDoor_, rhs.lockingChainIssue_, rhs.issuingChainDoor_, rhs.issuingChainIssue_); } inline AccountID const& @@ -213,5 +196,3 @@ STXChainBridge::dstChain(bool wasLockingChainSend) } } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/SecretKey.h b/include/xrpl/protocol/SecretKey.h index d5f1ce303f..a59b1150c1 100644 --- a/include/xrpl/protocol/SecretKey.h +++ b/include/xrpl/protocol/SecretKey.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_SECRETKEY_H_INCLUDED -#define XRPL_PROTOCOL_SECRETKEY_H_INCLUDED +#pragma once #include #include @@ -81,8 +80,7 @@ public: inline bool operator==(SecretKey const& lhs, SecretKey const& rhs) { - return lhs.size() == rhs.size() && - std::memcmp(lhs.data(), rhs.data(), rhs.size()) == 0; + return lhs.size() == rhs.size() && std::memcmp(lhs.data(), rhs.data(), rhs.size()) == 0; } inline bool @@ -163,5 +161,3 @@ sign(KeyType type, SecretKey const& sk, Slice const& message) /** @} */ } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/Seed.h b/include/xrpl/protocol/Seed.h index 36b2bbfee3..1fad94e2bd 100644 --- a/include/xrpl/protocol/Seed.h +++ b/include/xrpl/protocol/Seed.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_SEED_H_INCLUDED -#define XRPL_PROTOCOL_SEED_H_INCLUDED +#pragma once #include #include @@ -118,5 +117,3 @@ toBase58(Seed const& seed) } } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/SeqProxy.h b/include/xrpl/protocol/SeqProxy.h index 8dde232e75..563292f8b3 100644 --- a/include/xrpl/protocol/SeqProxy.h +++ b/include/xrpl/protocol/SeqProxy.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_SEQ_PROXY_H_INCLUDED -#define XRPL_PROTOCOL_SEQ_PROXY_H_INCLUDED +#pragma once #include #include @@ -147,5 +146,3 @@ public: } }; } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/Serializer.h b/include/xrpl/protocol/Serializer.h index f46073a977..98cefb4d08 100644 --- a/include/xrpl/protocol/Serializer.h +++ b/include/xrpl/protocol/Serializer.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_SERIALIZER_H_INCLUDED -#define XRPL_PROTOCOL_SERIALIZER_H_INCLUDED +#pragma once #include #include @@ -36,9 +35,7 @@ public: if (size) { - XRPL_ASSERT( - data, - "xrpl::Serializer::Serializer(void const*) : non-null input"); + XRPL_ASSERT(data, "xrpl::Serializer::Serializer(void const*) : non-null input"); std::memcpy(mData.data(), data, size); } } @@ -68,9 +65,7 @@ public: add16(std::uint16_t i); template - requires(std::is_same_v< - std::make_unsigned_t>, - std::uint32_t>) + requires(std::is_same_v>, std::uint32_t>) int add32(T i) { @@ -86,9 +81,7 @@ public: add32(HashPrefix p); template - requires(std::is_same_v< - std::make_unsigned_t>, - std::uint64_t>) + requires(std::is_same_v>, std::uint64_t>) int add64(T i) { @@ -453,5 +446,3 @@ SerialIter::getBitString() } } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/Sign.h b/include/xrpl/protocol/Sign.h index 6df4c55b65..9f0bf2f1ca 100644 --- a/include/xrpl/protocol/Sign.h +++ b/include/xrpl/protocol/Sign.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_SIGN_H_INCLUDED -#define XRPL_PROTOCOL_SIGN_H_INCLUDED +#pragma once #include #include @@ -20,12 +19,7 @@ namespace xrpl { @note If a signature already exists, it is overwritten. */ void -sign( - STObject& st, - HashPrefix const& prefix, - KeyType type, - SecretKey const& sk, - SF_VL const& sigField = sfSignature); +sign(STObject& st, HashPrefix const& prefix, KeyType type, SecretKey const& sk, SF_VL const& sigField = sfSignature); /** Returns `true` if STObject contains valid signature @@ -36,11 +30,7 @@ sign( If not specified the value defaults to `sfSignature`. */ bool -verify( - STObject const& st, - HashPrefix const& prefix, - PublicKey const& pk, - SF_VL const& sigField = sfSignature); +verify(STObject const& st, HashPrefix const& prefix, PublicKey const& pk, SF_VL const& sigField = sfSignature); /** Return a Serializer suitable for computing a multisigning TxnSignature. */ Serializer @@ -68,5 +58,3 @@ finishMultiSigningData(AccountID const& signingID, Serializer& s) } } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/SystemParameters.h b/include/xrpl/protocol/SystemParameters.h index c2f66e9ea1..70ab67c56f 100644 --- a/include/xrpl/protocol/SystemParameters.h +++ b/include/xrpl/protocol/SystemParameters.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_SYSTEMPARAMETERS_H_INCLUDED -#define XRPL_PROTOCOL_SYSTEMPARAMETERS_H_INCLUDED +#pragma once #include #include @@ -66,5 +65,3 @@ constexpr std::chrono::seconds const defaultAmendmentMajorityTime = weeks{2}; /** Default peer port (IANA registered) */ inline std::uint16_t constexpr DEFAULT_PEER_PORT{2459}; - -#endif diff --git a/include/xrpl/protocol/TER.h b/include/xrpl/protocol/TER.h index de2f596127..52001ce72b 100644 --- a/include/xrpl/protocol/TER.h +++ b/include/xrpl/protocol/TER.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_TER_H_INCLUDED -#define XRPL_PROTOCOL_TER_H_INCLUDED +#pragma once #include #include @@ -193,19 +192,19 @@ enum TERcodes : TERUnderlyingType { // - Hold // - Makes hole in sequence which jams transactions. terRETRY = -99, - terFUNDS_SPENT, // DEPRECATED. - terINSUF_FEE_B, // Can't pay fee, therefore don't burden network. - terNO_ACCOUNT, // Can't pay fee, therefore don't burden network. - terNO_AUTH, // Not authorized to hold IOUs. - terNO_LINE, // Internal flag. - terOWNERS, // Can't succeed with non-zero owner count. - terPRE_SEQ, // Can't pay fee, no point in forwarding, so don't - // burden network. - terLAST, // DEPRECATED. - terNO_RIPPLE, // Rippling not allowed - terQUEUED, // Transaction is being held in TxQ until fee drops - terPRE_TICKET, // Ticket is not yet in ledger but might be on its way - terNO_AMM, // AMM doesn't exist for the asset pair + terFUNDS_SPENT, // DEPRECATED. + terINSUF_FEE_B, // Can't pay fee, therefore don't burden network. + terNO_ACCOUNT, // Can't pay fee, therefore don't burden network. + terNO_AUTH, // Not authorized to hold IOUs. + terNO_LINE, // Internal flag. + terOWNERS, // Can't succeed with non-zero owner count. + terPRE_SEQ, // Can't pay fee, no point in forwarding, so don't + // burden network. + terLAST, // DEPRECATED. + terNO_RIPPLE, // Rippling not allowed + terQUEUED, // Transaction is being held in TxQ until fee drops + terPRE_TICKET, // Ticket is not yet in ledger but might be on its way + terNO_AMM, // AMM doesn't exist for the asset pair terADDRESS_COLLISION, // Failed to allocate AccountID when trying to // create a pseudo-account terNO_DELEGATE_PERMISSION, // Delegate does not have permission @@ -417,10 +416,7 @@ public: } // Trait tells enable_if which types are allowed for construction. - template < - typename T, - typename = std::enable_if_t< - Trait>>::value>> + template >>::value>> constexpr TERSubset(T rhs) : code_(TERtoInt(rhs)) { } @@ -490,8 +486,7 @@ template constexpr auto operator==(L const& lhs, R const& rhs) -> std::enable_if_t< - std::is_same::value && - std::is_same::value, + std::is_same::value && std::is_same::value, bool> { return TERtoInt(lhs) == TERtoInt(rhs); @@ -501,8 +496,7 @@ template constexpr auto operator!=(L const& lhs, R const& rhs) -> std::enable_if_t< - std::is_same::value && - std::is_same::value, + std::is_same::value && std::is_same::value, bool> { return TERtoInt(lhs) != TERtoInt(rhs); @@ -512,8 +506,7 @@ template constexpr auto operator<(L const& lhs, R const& rhs) -> std::enable_if_t< - std::is_same::value && - std::is_same::value, + std::is_same::value && std::is_same::value, bool> { return TERtoInt(lhs) < TERtoInt(rhs); @@ -523,8 +516,7 @@ template constexpr auto operator<=(L const& lhs, R const& rhs) -> std::enable_if_t< - std::is_same::value && - std::is_same::value, + std::is_same::value && std::is_same::value, bool> { return TERtoInt(lhs) <= TERtoInt(rhs); @@ -534,8 +526,7 @@ template constexpr auto operator>(L const& lhs, R const& rhs) -> std::enable_if_t< - std::is_same::value && - std::is_same::value, + std::is_same::value && std::is_same::value, bool> { return TERtoInt(lhs) > TERtoInt(rhs); @@ -545,8 +536,7 @@ template constexpr auto operator>=(L const& lhs, R const& rhs) -> std::enable_if_t< - std::is_same::value && - std::is_same::value, + std::is_same::value && std::is_same::value, bool> { return TERtoInt(lhs) >= TERtoInt(rhs); @@ -668,9 +658,7 @@ isTecClaim(TER x) noexcept return ((x) >= tecCLAIM); } -std::unordered_map< - TERUnderlyingType, - std::pair> const& +std::unordered_map> const& transResults(); bool @@ -686,5 +674,3 @@ std::optional transCode(std::string const& token); } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/TxFlags.h b/include/xrpl/protocol/TxFlags.h index 5527a264e4..6c6ef5e369 100644 --- a/include/xrpl/protocol/TxFlags.h +++ b/include/xrpl/protocol/TxFlags.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_TXFLAGS_H_INCLUDED -#define XRPL_PROTOCOL_TXFLAGS_H_INCLUDED +#pragma once #include @@ -295,5 +294,3 @@ constexpr std::uint32_t const tfLoanManageMask = ~(tfUniversal | tfLoanDefault | // clang-format on } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/TxFormats.h b/include/xrpl/protocol/TxFormats.h index 05f03c5cdc..b76eef7585 100644 --- a/include/xrpl/protocol/TxFormats.h +++ b/include/xrpl/protocol/TxFormats.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_TXFORMATS_H_INCLUDED -#define XRPL_PROTOCOL_TXFORMATS_H_INCLUDED +#pragma once #include @@ -77,5 +76,3 @@ public: }; } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/TxMeta.h b/include/xrpl/protocol/TxMeta.h index 5b6716e380..a295eb4569 100644 --- a/include/xrpl/protocol/TxMeta.h +++ b/include/xrpl/protocol/TxMeta.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_TX_TRANSACTIONMETA_H_INCLUDED -#define XRPL_APP_TX_TRANSACTIONMETA_H_INCLUDED +#pragma once #include #include @@ -118,5 +117,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/TxSearched.h b/include/xrpl/protocol/TxSearched.h new file mode 100644 index 0000000000..e085bff315 --- /dev/null +++ b/include/xrpl/protocol/TxSearched.h @@ -0,0 +1,7 @@ +#pragma once + +namespace xrpl { + +enum class TxSearched { all, some, unknown }; + +} diff --git a/include/xrpl/protocol/UintTypes.h b/include/xrpl/protocol/UintTypes.h index daa66e8286..fd48244d89 100644 --- a/include/xrpl/protocol/UintTypes.h +++ b/include/xrpl/protocol/UintTypes.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_UINTTYPES_H_INCLUDED -#define XRPL_PROTOCOL_UINTTYPES_H_INCLUDED +#pragma once #include #include @@ -125,5 +124,3 @@ struct hash : xrpl::uint256::hasher }; } // namespace std - -#endif diff --git a/include/xrpl/protocol/Units.h b/include/xrpl/protocol/Units.h index 72114ad8fe..ecf0bf7798 100644 --- a/include/xrpl/protocol/Units.h +++ b/include/xrpl/protocol/Units.h @@ -1,5 +1,4 @@ -#ifndef PROTOCOL_UNITS_H_INCLUDED -#define PROTOCOL_UNITS_H_INCLUDED +#pragma once #include #include @@ -36,8 +35,8 @@ class TenthBipsTag; // namespace. template -concept Valid = std::is_class_v && std::is_object_v && - std::is_object_v; +concept Valid = + std::is_class_v && std::is_object_v && std::is_object_v; /** `Usable` is checked to ensure that only values with known valid type tags can be used (sometimes transparently) in @@ -48,15 +47,12 @@ concept Valid = std::is_class_v && std::is_object_v && */ template concept Usable = Valid && - (std::is_same_v || - std::is_same_v || - std::is_same_v || - std::is_same_v || + (std::is_same_v || std::is_same_v || + std::is_same_v || std::is_same_v || std::is_same_v); template -concept Compatible = Valid && std::is_arithmetic_v && - std::is_arithmetic_v && +concept Compatible = Valid && std::is_arithmetic_v && std::is_arithmetic_v && std::is_convertible_v; template @@ -66,8 +62,8 @@ template concept IntegralValue = Integral; template -concept CastableValue = IntegralValue && IntegralValue && - std::is_same_v; +concept CastableValue = + IntegralValue && IntegralValue && std::is_same_v; template class ValueUnit : private boost::totally_ordered>, @@ -221,8 +217,7 @@ public: ValueUnit operator-() const { - static_assert( - std::is_signed_v, "- operator illegal on unsigned value types"); + static_assert(std::is_signed_v, "- operator illegal on unsigned value types"); return ValueUnit{-value_}; } @@ -297,10 +292,7 @@ public: { if constexpr (std::is_integral_v) { - using jsontype = std::conditional_t< - std::is_signed_v, - Json::Int, - Json::UInt>; + using jsontype = std::conditional_t, Json::Int, Json::UInt>; constexpr auto min = std::numeric_limits::min(); constexpr auto max = std::numeric_limits::max(); @@ -351,8 +343,7 @@ to_string(ValueUnit const& amount) } template -concept muldivSource = Valid && - std::is_convertible_v; +concept muldivSource = Valid && std::is_convertible_v; template concept muldivDest = muldivSource && // Dest is also a source @@ -368,8 +359,8 @@ concept muldivable = muldivSources && muldivDest; // Source and Dest can be the same by default template -concept muldivCommutable = muldivable && - !std::is_same_v; +concept muldivCommutable = + muldivable && !std::is_same_v; template ValueUnit @@ -387,10 +378,8 @@ mulDivU(Source1 value, Dest mul, Source2 div) { // split the asserts so if one hits, the user can tell which // without a debugger. - XRPL_ASSERT( - value.value() >= 0, "xrpl::unit::mulDivU : minimum value input"); - XRPL_ASSERT( - mul.value() >= 0, "xrpl::unit::mulDivU : minimum mul input"); + XRPL_ASSERT(value.value() >= 0, "xrpl::unit::mulDivU : minimum value input"); + XRPL_ASSERT(mul.value() >= 0, "xrpl::unit::mulDivU : minimum mul input"); XRPL_ASSERT(div.value() > 0, "xrpl::unit::mulDivU : minimum div input"); return std::nullopt; } @@ -411,10 +400,7 @@ mulDivU(Source1 value, Dest mul, Source2 div) using namespace boost::multiprecision; uint128_t product; - product = multiply( - product, - static_cast(value.value()), - static_cast(mul.value())); + product = multiply(product, static_cast(value.value()), static_cast(mul.value())); auto quotient = product / div.value(); @@ -449,10 +435,7 @@ mulDiv(Source1 value, Dest mul, Source2 div) return unit::mulDivU(value, mul, div); } -template < - class Source1, - class Source2, - unit::muldivCommutable Dest> +template Dest> std::optional mulDiv(Dest value, Source1 mul, Source2 div) { @@ -532,5 +515,3 @@ unsafe_cast(Src s) noexcept } } // namespace xrpl - -#endif // PROTOCOL_UNITS_H_INCLUDED diff --git a/include/xrpl/protocol/XChainAttestations.h b/include/xrpl/protocol/XChainAttestations.h index bd76936b49..fc3c464b92 100644 --- a/include/xrpl/protocol/XChainAttestations.h +++ b/include/xrpl/protocol/XChainAttestations.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_STXATTESTATIONS_H_INCLUDED -#define XRPL_PROTOCOL_STXATTESTATIONS_H_INCLUDED +#pragma once #include #include @@ -197,9 +196,7 @@ struct AttestationCreateAccount : AttestationBase sameEvent(AttestationCreateAccount const& rhs) const; friend bool - operator==( - AttestationCreateAccount const& lhs, - AttestationCreateAccount const& rhs); + operator==(AttestationCreateAccount const& lhs, AttestationCreateAccount const& rhs); [[nodiscard]] static std::vector message( @@ -223,9 +220,7 @@ private: struct CmpByCreateCount { bool - operator()( - AttestationCreateAccount const& lhs, - AttestationCreateAccount const& rhs) const + operator()(AttestationCreateAccount const& lhs, AttestationCreateAccount const& rhs) const { return lhs.createCount < rhs.createCount; } @@ -261,10 +256,7 @@ struct XChainClaimAttestation bool wasLockingChainSend; std::optional dst; MatchFields(TSignedAttestation const& att); - MatchFields( - STAmount const& a, - bool b, - std::optional const& d) + MatchFields(STAmount const& a, bool b, std::optional const& d) : amount{a}, wasLockingChainSend{b}, dst{d} { } @@ -299,9 +291,7 @@ struct XChainClaimAttestation toSTObject() const; friend bool - operator==( - XChainClaimAttestation const& lhs, - XChainClaimAttestation const& rhs); + operator==(XChainClaimAttestation const& lhs, XChainClaimAttestation const& rhs); }; struct XChainCreateAccountAttestation @@ -349,9 +339,7 @@ struct XChainCreateAccountAttestation match(MatchFields const& rhs) const; friend bool - operator==( - XChainCreateAccountAttestation const& lhs, - XChainCreateAccountAttestation const& rhs); + operator==(XChainCreateAccountAttestation const& lhs, XChainCreateAccountAttestation const& rhs); }; // Attestations from witness servers for a particular claim ID and bridge. @@ -420,9 +408,7 @@ public: template [[nodiscard]] inline bool -operator==( - XChainAttestationsBase const& lhs, - XChainAttestationsBase const& rhs) +operator==(XChainAttestationsBase const& lhs, XChainAttestationsBase const& rhs) { return lhs.attestations() == rhs.attestations(); } @@ -464,20 +450,16 @@ XChainAttestationsBase::empty() const return attestations_.empty(); } -class XChainClaimAttestations final - : public XChainAttestationsBase +class XChainClaimAttestations final : public XChainAttestationsBase { using TBase = XChainAttestationsBase; using TBase::TBase; }; -class XChainCreateAccountAttestations final - : public XChainAttestationsBase +class XChainCreateAccountAttestations final : public XChainAttestationsBase { using TBase = XChainAttestationsBase; using TBase::TBase; }; } // namespace xrpl - -#endif // STXCHAINATTESTATIONS_H_ diff --git a/include/xrpl/protocol/XRPAmount.h b/include/xrpl/protocol/XRPAmount.h index ef283f4154..c1af338e4b 100644 --- a/include/xrpl/protocol/XRPAmount.h +++ b/include/xrpl/protocol/XRPAmount.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_XRPAMOUNT_H_INCLUDED -#define XRPL_PROTOCOL_XRPAMOUNT_H_INCLUDED +#pragma once #include #include @@ -167,10 +166,8 @@ public: std::optional dropsAs() const { - if ((drops_ > std::numeric_limits::max()) || - (!std::numeric_limits::is_signed && drops_ < 0) || - (std::numeric_limits::is_signed && - drops_ < std::numeric_limits::lowest())) + if ((drops_ > std::numeric_limits::max()) || (!std::numeric_limits::is_signed && drops_ < 0) || + (std::numeric_limits::is_signed && drops_ < std::numeric_limits::lowest())) { return std::nullopt; } @@ -260,11 +257,7 @@ to_string(XRPAmount const& amount) } inline XRPAmount -mulRatio( - XRPAmount const& amt, - std::uint32_t num, - std::uint32_t den, - bool roundUp) +mulRatio(XRPAmount const& amt, std::uint32_t num, std::uint32_t den, bool roundUp) { using namespace boost::multiprecision; @@ -288,5 +281,3 @@ mulRatio( } } // namespace xrpl - -#endif // XRPL_BASICS_XRPAMOUNT_H_INCLUDED diff --git a/include/xrpl/protocol/detail/STVar.h b/include/xrpl/protocol/detail/STVar.h index 219d1ed738..b5373d1a4a 100644 --- a/include/xrpl/protocol/detail/STVar.h +++ b/include/xrpl/protocol/detail/STVar.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_STVAR_H_INCLUDED -#define XRPL_PROTOCOL_STVAR_H_INCLUDED +#pragma once #include #include @@ -163,5 +162,3 @@ operator!=(STVar const& lhs, STVar const& rhs) } // namespace detail } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/detail/b58_utils.h b/include/xrpl/protocol/detail/b58_utils.h index 4ea00e6d5e..a34104555e 100644 --- a/include/xrpl/protocol/detail/b58_utils.h +++ b/include/xrpl/protocol/detail/b58_utils.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_B58_UTILS_H_INCLUDED -#define XRPL_PROTOCOL_B58_UTILS_H_INCLUDED +#pragma once #include #include @@ -118,15 +117,12 @@ inplace_bigint_div_rem(std::span numerator, std::uint64_t divisor) // LCOV_EXCL_STOP } - auto to_u128 = [](std::uint64_t high, - std::uint64_t low) -> unsigned __int128 { + auto to_u128 = [](std::uint64_t high, std::uint64_t low) -> unsigned __int128 { unsigned __int128 const high128 = high; unsigned __int128 const low128 = low; return ((high128 << 64) | low128); }; - auto div_rem_64 = - [](unsigned __int128 num, - std::uint64_t denom) -> std::tuple { + auto div_rem_64 = [](unsigned __int128 num, std::uint64_t denom) -> std::tuple { unsigned __int128 const denom128 = denom; unsigned __int128 const d = num / denom128; unsigned __int128 const r = num - (denom128 * d); @@ -143,8 +139,7 @@ inplace_bigint_div_rem(std::span numerator, std::uint64_t divisor) std::uint64_t prev_rem = 0; int const last_index = numerator.size() - 1; - std::tie(numerator[last_index], prev_rem) = - div_rem(numerator[last_index], divisor); + std::tie(numerator[last_index], prev_rem) = div_rem(numerator[last_index], divisor); for (int i = last_index - 1; i >= 0; --i) { unsigned __int128 const cur_num = to_u128(prev_rem, numerator[i]); @@ -159,11 +154,8 @@ inplace_bigint_div_rem(std::span numerator, std::uint64_t divisor) [[nodiscard]] inline std::array b58_10_to_b58_be(std::uint64_t input) { - [[maybe_unused]] static constexpr std::uint64_t B_58_10 = - 430804206899405824; // 58^10; - XRPL_ASSERT( - input < B_58_10, - "xrpl::b58_fast::detail::b58_10_to_b58_be : valid input"); + [[maybe_unused]] static constexpr std::uint64_t B_58_10 = 430804206899405824; // 58^10; + XRPL_ASSERT(input < B_58_10, "xrpl::b58_fast::detail::b58_10_to_b58_be : valid input"); constexpr std::size_t resultSize = 10; std::array result{}; int i = 0; @@ -182,4 +174,3 @@ b58_10_to_b58_be(std::uint64_t input) #endif } // namespace xrpl -#endif // XRPL_PROTOCOL_B58_UTILS_H_INCLUDED diff --git a/include/xrpl/protocol/detail/features.macro b/include/xrpl/protocol/detail/features.macro index 0c952bf59b..961bc6e44c 100644 --- a/include/xrpl/protocol/detail/features.macro +++ b/include/xrpl/protocol/detail/features.macro @@ -15,7 +15,8 @@ // Add new amendments to the top of this list. // Keep it sorted in reverse chronological order. - +XRPL_FIX (PermissionedDomainInvariant, Supported::yes, VoteBehavior::DefaultNo) +XRPL_FIX (ExpiredNFTokenOfferRemoval, Supported::yes, VoteBehavior::DefaultNo) XRPL_FIX (BatchInnerSigs, Supported::yes, VoteBehavior::DefaultNo) XRPL_FEATURE(LendingProtocol, Supported::yes, VoteBehavior::DefaultNo) XRPL_FEATURE(PermissionDelegationV1_1, Supported::no, VoteBehavior::DefaultNo) diff --git a/include/xrpl/protocol/detail/secp256k1.h b/include/xrpl/protocol/detail/secp256k1.h index c3ac76d7ed..0ac810fd80 100644 --- a/include/xrpl/protocol/detail/secp256k1.h +++ b/include/xrpl/protocol/detail/secp256k1.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_SECP256K1_H_INCLUDED -#define XRPL_PROTOCOL_SECP256K1_H_INCLUDED +#pragma once #include @@ -12,9 +11,7 @@ secp256k1Context() struct holder { secp256k1_context* impl; - holder() - : impl(secp256k1_context_create( - SECP256K1_CONTEXT_VERIFY | SECP256K1_CONTEXT_SIGN)) + holder() : impl(secp256k1_context_create(SECP256K1_CONTEXT_VERIFY | SECP256K1_CONTEXT_SIGN)) { } @@ -28,5 +25,3 @@ secp256k1Context() } } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/detail/token_errors.h b/include/xrpl/protocol/detail/token_errors.h index 1d5276e78b..686851f508 100644 --- a/include/xrpl/protocol/detail/token_errors.h +++ b/include/xrpl/protocol/detail/token_errors.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_TOKEN_ERRORS_H_INCLUDED -#define XRPL_PROTOCOL_TOKEN_ERRORS_H_INCLUDED +#pragma once #include @@ -80,4 +79,3 @@ make_error_code(xrpl::TokenCodecErrc e) return {static_cast(e), TokenCodecErrcCategory()}; } } // namespace xrpl -#endif // TOKEN_ERRORS_H_ diff --git a/include/xrpl/protocol/digest.h b/include/xrpl/protocol/digest.h index bafac699f5..b5ec277e7b 100644 --- a/include/xrpl/protocol/digest.h +++ b/include/xrpl/protocol/digest.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_DIGEST_H_INCLUDED -#define XRPL_PROTOCOL_DIGEST_H_INCLUDED +#pragma once #include #include @@ -227,5 +226,3 @@ sha512Half_s(Args const&... args) } } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/json_get_or_throw.h b/include/xrpl/protocol/json_get_or_throw.h index bdf572bed6..7cdf481ad3 100644 --- a/include/xrpl/protocol/json_get_or_throw.h +++ b/include/xrpl/protocol/json_get_or_throw.h @@ -1,5 +1,4 @@ -#ifndef PROTOCOL_GET_OR_THROW_H_ -#define PROTOCOL_GET_OR_THROW_H_ +#pragma once #include #include @@ -35,8 +34,7 @@ struct JsonTypeMismatchError : std::exception char const* const key; std::string const expectedType; mutable std::string msg; - JsonTypeMismatchError(Json::StaticString const& k, std::string et) - : key{k.c_str()}, expectedType{std::move(et)} + JsonTypeMismatchError(Json::StaticString const& k, std::string et) : key{k.c_str()}, expectedType{std::move(et)} { } char const* @@ -44,8 +42,7 @@ struct JsonTypeMismatchError : std::exception { if (msg.empty()) { - msg = std::string("Type mismatch on json key: ") + key + - "; expected type: " + expectedType; + msg = std::string("Type mismatch on json key: ") + key + "; expected type: " + expectedType; } return msg.c_str(); } @@ -154,5 +151,3 @@ getOptional(Json::Value const& v, xrpl::SField const& field) } } // namespace Json - -#endif // PROTOCOL_GET_OR_THROW_H_ diff --git a/include/xrpl/protocol/jss.h b/include/xrpl/protocol/jss.h index d86ca9bf1f..0264f625eb 100644 --- a/include/xrpl/protocol/jss.h +++ b/include/xrpl/protocol/jss.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_JSONFIELDS_H_INCLUDED -#define XRPL_PROTOCOL_JSONFIELDS_H_INCLUDED +#pragma once #include @@ -726,5 +725,3 @@ JSS(write_load); // out: GetCounts } // namespace jss } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/messages.h b/include/xrpl/protocol/messages.h index d14739d532..e6654cc183 100644 --- a/include/xrpl/protocol/messages.h +++ b/include/xrpl/protocol/messages.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_MESSAGES_H_INCLUDED -#define XRPL_PROTOCOL_MESSAGES_H_INCLUDED +#pragma once // Some versions of protobuf generate code that will produce errors during // compilation. See https://github.com/google/protobuf/issues/549 for more @@ -13,5 +12,3 @@ #endif #include - -#endif diff --git a/include/xrpl/protocol/nft.h b/include/xrpl/protocol/nft.h index 3a8cdcd6e2..4be58c381c 100644 --- a/include/xrpl/protocol/nft.h +++ b/include/xrpl/protocol/nft.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_NFT_H_INCLUDED -#define XRPL_PROTOCOL_NFT_H_INCLUDED +#pragma once #include #include @@ -105,5 +104,3 @@ getIssuer(uint256 const& id) } // namespace nft } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/nftPageMask.h b/include/xrpl/protocol/nftPageMask.h index 4d23e45f53..05a42ce294 100644 --- a/include/xrpl/protocol/nftPageMask.h +++ b/include/xrpl/protocol/nftPageMask.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_NFT_PAGE_MASK_H_INCLUDED -#define XRPL_PROTOCOL_NFT_PAGE_MASK_H_INCLUDED +#pragma once #include @@ -10,10 +9,7 @@ namespace nft { // NFT directory pages order their contents based only on the low 96 bits of // the NFToken value. This mask provides easy access to the necessary mask. -uint256 constexpr pageMask(std::string_view( - "0000000000000000000000000000000000000000ffffffffffffffffffffffff")); +uint256 constexpr pageMask(std::string_view("0000000000000000000000000000000000000000ffffffffffffffffffffffff")); } // namespace nft } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/serialize.h b/include/xrpl/protocol/serialize.h index eedf041baa..5b84a28b5d 100644 --- a/include/xrpl/protocol/serialize.h +++ b/include/xrpl/protocol/serialize.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_SERIALIZE_H_INCLUDED -#define XRPL_PROTOCOL_SERIALIZE_H_INCLUDED +#pragma once #include #include @@ -25,5 +24,3 @@ serializeHex(STObject const& o) } } // namespace xrpl - -#endif diff --git a/include/xrpl/protocol/st.h b/include/xrpl/protocol/st.h index 115c373c7f..61571196f2 100644 --- a/include/xrpl/protocol/st.h +++ b/include/xrpl/protocol/st.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_ST_H_INCLUDED -#define XRPL_PROTOCOL_ST_H_INCLUDED +#pragma once #include #include @@ -17,5 +16,3 @@ #include #include #include - -#endif diff --git a/include/xrpl/protocol/tokens.h b/include/xrpl/protocol/tokens.h index ac13a10e06..8cda8efc86 100644 --- a/include/xrpl/protocol/tokens.h +++ b/include/xrpl/protocol/tokens.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PROTOCOL_TOKENS_H_INCLUDED -#define XRPL_PROTOCOL_TOKENS_H_INCLUDED +#pragma once #include #include @@ -63,11 +62,7 @@ decodeBase58Token(std::string const& s, TokenType type); namespace detail { // Expose detail functions for unit tests only std::string -encodeBase58( - void const* message, - std::size_t size, - void* temp, - std::size_t temp_size); +encodeBase58(void const* message, std::size_t size, void* temp, std::size_t temp_size); std::string decodeBase58(std::string const& s); @@ -79,16 +74,10 @@ namespace b58_fast { // Use the fast version (10-15x faster) is using gcc extensions (int128 in // particular) [[nodiscard]] B58Result> -encodeBase58Token( - TokenType token_type, - std::span input, - std::span out); +encodeBase58Token(TokenType token_type, std::span input, std::span out); [[nodiscard]] B58Result> -decodeBase58Token( - TokenType type, - std::string_view s, - std::span outBuf); +decodeBase58Token(TokenType type, std::string_view s, std::span outBuf); // This interface matches the old interface, but requires additional allocation [[nodiscard]] std::string @@ -101,9 +90,7 @@ decodeBase58Token(std::string const& s, TokenType type); namespace detail { // Expose detail functions for unit tests only B58Result> -b256_to_b58_be( - std::span input, - std::span out); +b256_to_b58_be(std::span input, std::span out); B58Result> b58_to_b256_be(std::string_view input, std::span out); @@ -112,5 +99,3 @@ b58_to_b256_be(std::string_view input, std::span out); } // namespace b58_fast #endif // _MSC_VER } // namespace xrpl - -#endif diff --git a/src/xrpld/app/main/DBInit.h b/include/xrpl/rdb/DBInit.h similarity index 98% rename from src/xrpld/app/main/DBInit.h rename to include/xrpl/rdb/DBInit.h index 60ff4b498b..56bc752343 100644 --- a/src/xrpld/app/main/DBInit.h +++ b/include/xrpl/rdb/DBInit.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_DATA_DBINIT_H_INCLUDED -#define XRPL_APP_DATA_DBINIT_H_INCLUDED +#pragma once #include #include @@ -117,5 +116,3 @@ inline constexpr std::array WalletDBInit{ "END TRANSACTION;"}}; } // namespace xrpl - -#endif diff --git a/src/xrpld/core/DatabaseCon.h b/include/xrpl/rdb/DatabaseCon.h similarity index 85% rename from src/xrpld/core/DatabaseCon.h rename to include/xrpl/rdb/DatabaseCon.h index a7fc21bc38..37a53044e4 100644 --- a/src/xrpld/core/DatabaseCon.h +++ b/include/xrpl/rdb/DatabaseCon.h @@ -1,11 +1,9 @@ -#ifndef XRPL_APP_DATA_DATABASECON_H_INCLUDED -#define XRPL_APP_DATA_DATABASECON_H_INCLUDED - -#include -#include -#include +#pragma once #include +#include +#include +#include #include @@ -29,12 +27,10 @@ private: std::unique_lock lock_; public: - LockedSociSession(std::shared_ptr it, mutex& m) - : session_(std::move(it)), lock_(m) + LockedSociSession(std::shared_ptr it, mutex& m) : session_(std::move(it)), lock_(m) { } - LockedSociSession(LockedSociSession&& rhs) noexcept - : session_(std::move(rhs.session_)), lock_(std::move(rhs.lock_)) + LockedSociSession(LockedSociSession&& rhs) noexcept : session_(std::move(rhs.session_)), lock_(std::move(rhs.lock_)) { } LockedSociSession() = delete; @@ -71,7 +67,7 @@ public: { explicit Setup() = default; - Config::StartUpType startUp = Config::NORMAL; + StartUpType startUp = StartUpType::NORMAL; bool standAlone = false; boost::filesystem::path dataDir; // Indicates whether or not to return the `globalPragma` @@ -85,8 +81,7 @@ public: !useGlobalPragma || globalPragma, "xrpl::DatabaseCon::Setup::commonPragma : consistent global " "pragma"); - return useGlobalPragma && globalPragma ? globalPragma.get() - : nullptr; + return useGlobalPragma && globalPragma ? globalPragma.get() : nullptr; } static std::unique_ptr const> globalPragma; @@ -109,9 +104,8 @@ public: beast::Journal journal) // Use temporary files or regular DB files? : DatabaseCon( - setup.standAlone && setup.startUp != Config::LOAD && - setup.startUp != Config::LOAD_FILE && - setup.startUp != Config::REPLAY + setup.standAlone && setup.startUp != StartUpType::LOAD && setup.startUp != StartUpType::LOAD_FILE && + setup.startUp != StartUpType::REPLAY ? "" : (setup.dataDir / dbName), setup.commonPragma(), @@ -172,11 +166,8 @@ public: checkoutDb() { using namespace std::chrono_literals; - LockedSociSession session = perf::measureDurationAndLog( - [&]() { return LockedSociSession(session_, lock_); }, - "checkoutDb", - 10ms, - j_); + LockedSociSession session = + perf::measureDurationAndLog([&]() { return LockedSociSession(session_, lock_); }, "checkoutDb", 10ms, j_); return session; } @@ -237,11 +228,4 @@ private: std::shared_ptr checkpointerFromId(std::uintptr_t id); -DatabaseCon::Setup -setup_DatabaseCon( - Config const& c, - std::optional j = std::nullopt); - } // namespace xrpl - -#endif diff --git a/include/xrpl/rdb/RelationalDatabase.h b/include/xrpl/rdb/RelationalDatabase.h new file mode 100644 index 0000000000..b80c6c8331 --- /dev/null +++ b/include/xrpl/rdb/RelationalDatabase.h @@ -0,0 +1,475 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace xrpl { + +class Transaction; +class Ledger; + +struct LedgerHashPair +{ + uint256 ledgerHash; + uint256 parentHash; +}; + +struct LedgerRange +{ + uint32_t min; + uint32_t max; +}; + +class RelationalDatabase +{ +public: + struct CountMinMax + { + std::size_t numberOfRows; + LedgerIndex minLedgerSequence; + LedgerIndex maxLedgerSequence; + }; + + struct AccountTxMarker + { + std::uint32_t ledgerSeq = 0; + std::uint32_t txnSeq = 0; + }; + + struct AccountTxOptions + { + AccountID const& account; + std::uint32_t minLedger; + std::uint32_t maxLedger; + std::uint32_t offset; + std::uint32_t limit; + bool bUnlimited; + }; + + struct AccountTxPageOptions + { + AccountID const& account; + std::uint32_t minLedger; + std::uint32_t maxLedger; + std::optional marker; + std::uint32_t limit; + bool bAdmin; + }; + + using AccountTx = std::pair, std::shared_ptr>; + using AccountTxs = std::vector; + using txnMetaLedgerType = std::tuple; + using MetaTxsList = std::vector; + + using LedgerSequence = uint32_t; + using LedgerHash = uint256; + using LedgerSpecifier = std::variant; + + struct AccountTxArgs + { + AccountID account; + std::optional ledger; + bool binary = false; + bool forward = false; + uint32_t limit = 0; + std::optional marker; + }; + + struct AccountTxResult + { + std::variant transactions; + LedgerRange ledgerRange; + uint32_t limit; + std::optional marker; + }; + + virtual ~RelationalDatabase() = default; + + /** + * @brief getMinLedgerSeq Returns the minimum ledger sequence in the Ledgers + * table. + * @return Ledger sequence or no value if no ledgers exist. + */ + virtual std::optional + getMinLedgerSeq() = 0; + + /** + * @brief getMaxLedgerSeq Returns the maximum ledger sequence in the Ledgers + * table. + * @return Ledger sequence or none if no ledgers exist. + */ + virtual std::optional + getMaxLedgerSeq() = 0; + + /** + * @brief getLedgerInfoByIndex Returns a ledger by its sequence. + * @param ledgerSeq Ledger sequence. + * @return The ledger if found, otherwise no value. + */ + virtual std::optional + getLedgerInfoByIndex(LedgerIndex ledgerSeq) = 0; + + /** + * @brief getNewestLedgerInfo Returns the info of the newest saved ledger. + * @return Ledger info if found, otherwise no value. + */ + virtual std::optional + getNewestLedgerInfo() = 0; + + /** + * @brief getLedgerInfoByHash Returns the info of the ledger with given + * hash. + * @param ledgerHash Hash of the ledger. + * @return Ledger if found, otherwise no value. + */ + virtual std::optional + getLedgerInfoByHash(uint256 const& ledgerHash) = 0; + + /** + * @brief getHashByIndex Returns the hash of the ledger with the given + * sequence. + * @param ledgerIndex Ledger sequence. + * @return Hash of the ledger. + */ + virtual uint256 + getHashByIndex(LedgerIndex ledgerIndex) = 0; + + /** + * @brief getHashesByIndex Returns the hashes of the ledger and its parent + * as specified by the ledgerIndex. + * @param ledgerIndex Ledger sequence. + * @return Struct LedgerHashPair which contains hashes of the ledger and + * its parent. + */ + virtual std::optional + getHashesByIndex(LedgerIndex ledgerIndex) = 0; + + /** + * @brief getHashesByIndex Returns hashes of each ledger and its parent for + * all ledgers within the provided range. + * @param minSeq Minimum ledger sequence. + * @param maxSeq Maximum ledger sequence. + * @return Container that maps the sequence number of a found ledger to the + * struct LedgerHashPair which contains the hashes of the ledger and + * its parent. + */ + virtual std::map + getHashesByIndex(LedgerIndex minSeq, LedgerIndex maxSeq) = 0; + + /** + * @brief getTxHistory Returns the 20 most recent transactions starting from + * the given number. + * @param startIndex First number of returned entry. + * @return Vector of shared pointers to transactions sorted in + * descending order by ledger sequence. + */ + virtual std::vector> + getTxHistory(LedgerIndex startIndex) = 0; + + /** + * @brief getTransactionsMinLedgerSeq Returns the minimum ledger sequence + * stored in the Transactions table. + * @return Ledger sequence or no value if no ledgers exist. + */ + virtual std::optional + getTransactionsMinLedgerSeq() = 0; + + /** + * @brief getAccountTransactionsMinLedgerSeq Returns the minimum ledger + * sequence stored in the AccountTransactions table. + * @return Ledger sequence or no value if no ledgers exist. + */ + virtual std::optional + getAccountTransactionsMinLedgerSeq() = 0; + + /** + * @brief deleteTransactionByLedgerSeq Deletes transactions from the ledger + * with the given sequence. + * @param ledgerSeq Ledger sequence. + */ + virtual void + deleteTransactionByLedgerSeq(LedgerIndex ledgerSeq) = 0; + + /** + * @brief deleteBeforeLedgerSeq Deletes all ledgers with a sequence number + * less than or equal to the given ledger sequence. + * @param ledgerSeq Ledger sequence. + */ + virtual void + deleteBeforeLedgerSeq(LedgerIndex ledgerSeq) = 0; + + /** + * @brief deleteTransactionsBeforeLedgerSeq Deletes all transactions with + * a sequence number less than or equal to the given ledger + * sequence. + * @param ledgerSeq Ledger sequence. + */ + virtual void + deleteTransactionsBeforeLedgerSeq(LedgerIndex ledgerSeq) = 0; + + /** + * @brief deleteAccountTransactionsBeforeLedgerSeq Deletes all account + * transactions with a sequence number less than or equal to the + * given ledger sequence. + * @param ledgerSeq Ledger sequence. + */ + virtual void + deleteAccountTransactionsBeforeLedgerSeq(LedgerIndex ledgerSeq) = 0; + + /** + * @brief getTransactionCount Returns the number of transactions. + * @return Number of transactions. + */ + virtual std::size_t + getTransactionCount() = 0; + + /** + * @brief getAccountTransactionCount Returns the number of account + * transactions. + * @return Number of account transactions. + */ + virtual std::size_t + getAccountTransactionCount() = 0; + + /** + * @brief getLedgerCountMinMax Returns the minimum ledger sequence, + * maximum ledger sequence and total number of saved ledgers. + * @return Struct CountMinMax which contains the minimum sequence, + * maximum sequence and number of ledgers. + */ + virtual struct CountMinMax + getLedgerCountMinMax() = 0; + + /** + * @brief saveValidatedLedger Saves a ledger into the database. + * @param ledger The ledger. + * @param current True if the ledger is current. + * @return True if saving was successful. + */ + virtual bool + saveValidatedLedger(std::shared_ptr const& ledger, bool current) = 0; + + /** + * @brief getLimitedOldestLedgerInfo Returns the info of the oldest ledger + * whose sequence number is greater than or equal to the given + * sequence number. + * @param ledgerFirstIndex Minimum ledger sequence. + * @return Ledger info if found, otherwise no value. + */ + virtual std::optional + getLimitedOldestLedgerInfo(LedgerIndex ledgerFirstIndex) = 0; + + /** + * @brief getLimitedNewestLedgerInfo Returns the info of the newest ledger + * whose sequence number is greater than or equal to the given + * sequence number. + * @param ledgerFirstIndex Minimum ledger sequence. + * @return Ledger info if found, otherwise no value. + */ + virtual std::optional + getLimitedNewestLedgerInfo(LedgerIndex ledgerFirstIndex) = 0; + + /** + * @brief getOldestAccountTxs Returns the oldest transactions for the + * account that matches the given criteria starting from the provided + * offset. + * @param options Struct AccountTxOptions which contains the criteria to + * match: the account, ledger search range, the offset of the first + * entry to return, the number of transactions to return, a flag if + * this number is unlimited. + * @return Vector of pairs of found transactions and their metadata + * sorted in ascending order by account sequence. + */ + virtual AccountTxs + getOldestAccountTxs(AccountTxOptions const& options) = 0; + + /** + * @brief getNewestAccountTxs Returns the newest transactions for the + * account that matches the given criteria starting from the provided + * offset. + * @param options Struct AccountTxOptions which contains the criteria to + * match: the account, the ledger search range, the offset of the + * first entry to return, the number of transactions to return, a + * flag if this number unlimited. + * @return Vector of pairs of found transactions and their metadata + * sorted in descending order by account sequence. + */ + virtual AccountTxs + getNewestAccountTxs(AccountTxOptions const& options) = 0; + + /** + * @brief getOldestAccountTxsB Returns the oldest transactions in binary + * form for the account that matches the given criteria starting from + * the provided offset. + * @param options Struct AccountTxOptions which contains the criteria to + * match: the account, the ledger search range, the offset of the + * first entry to return, the number of transactions to return, a + * flag if this number unlimited. + * @return Vector of tuples of found transactions, their metadata and + * account sequences sorted in ascending order by account sequence. + */ + virtual MetaTxsList + getOldestAccountTxsB(AccountTxOptions const& options) = 0; + + /** + * @brief getNewestAccountTxsB Returns the newest transactions in binary + * form for the account that matches the given criteria starting from + * the provided offset. + * @param options Struct AccountTxOptions which contains the criteria to + * match: the account, the ledger search range, the offset of the + * first entry to return, the number of transactions to return, a + * flag if this number is unlimited. + * @return Vector of tuples of found transactions, their metadata and + * account sequences sorted in descending order by account + * sequence. + */ + virtual MetaTxsList + getNewestAccountTxsB(AccountTxOptions const& options) = 0; + + /** + * @brief oldestAccountTxPage Returns the oldest transactions for the + * account that matches the given criteria starting from the + * provided marker. + * @param options Struct AccountTxPageOptions which contains the criteria to + * match: the account, the ledger search range, the marker of first + * returned entry, the number of transactions to return, a flag if + * this number is unlimited. + * @return Vector of pairs of found transactions and their metadata + * sorted in ascending order by account sequence and a marker + * for the next search if the search was not finished. + */ + virtual std::pair> + oldestAccountTxPage(AccountTxPageOptions const& options) = 0; + + /** + * @brief newestAccountTxPage Returns the newest transactions for the + * account that matches the given criteria starting from the provided + * marker. + * @param options Struct AccountTxPageOptions which contains the criteria to + * match: the account, the ledger search range, the marker of the + * first returned entry, the number of transactions to return, a flag + * if this number unlimited. + * @return Vector of pairs of found transactions and their metadata + * sorted in descending order by account sequence and a marker + * for the next search if the search was not finished. + */ + virtual std::pair> + newestAccountTxPage(AccountTxPageOptions const& options) = 0; + + /** + * @brief oldestAccountTxPageB Returns the oldest transactions in binary + * form for the account that matches the given criteria starting from + * the provided marker. + * @param options Struct AccountTxPageOptions which contains criteria to + * match: the account, the ledger search range, the marker of the + * first returned entry, the number of transactions to return, a flag + * if this number unlimited. + * @return Vector of tuples of found transactions, their metadata and + * account sequences sorted in ascending order by account + * sequence and a marker for the next search if the search was not + * finished. + */ + virtual std::pair> + oldestAccountTxPageB(AccountTxPageOptions const& options) = 0; + + /** + * @brief newestAccountTxPageB Returns the newest transactions in binary + * form for the account that matches the given criteria starting from + * the provided marker. + * @param options Struct AccountTxPageOptions which contains the criteria to + * match: the account, the ledger search range, the marker of the + * first returned entry, the number of transactions to return, a flag + * if this number is unlimited. + * @return Vector of tuples of found transactions, their metadata and + * account sequences sorted in descending order by account + * sequence and a marker for the next search if the search was not + * finished. + */ + virtual std::pair> + newestAccountTxPageB(AccountTxPageOptions const& options) = 0; + + /** + * @brief getTransaction Returns the transaction with the given hash. If a + * range is provided but the transaction is not found, then check if + * all ledgers in the range are present in the database. + * @param id Hash of the transaction. + * @param range Range of ledgers to check, if present. + * @param ec Default error code value. + * @return Transaction and its metadata if found, otherwise TxSearched::all + * if a range is provided and all ledgers from the range are present + * in the database, TxSearched::some if a range is provided and not + * all ledgers are present, TxSearched::unknown if the range is not + * provided or a deserializing error occurred. In the last case the + * error code is returned via the ec parameter, in other cases the + * default error code is not changed. + */ + virtual std::variant + getTransaction(uint256 const& id, std::optional> const& range, error_code_i& ec) = 0; + + /** + * @brief getKBUsedAll Returns the amount of space used by all databases. + * @return Space in kilobytes. + */ + virtual uint32_t + getKBUsedAll() = 0; + + /** + * @brief getKBUsedLedger Returns the amount of space space used by the + * ledger database. + * @return Space in kilobytes. + */ + virtual uint32_t + getKBUsedLedger() = 0; + + /** + * @brief getKBUsedTransaction Returns the amount of space used by the + * transaction database. + * @return Space in kilobytes. + */ + virtual uint32_t + getKBUsedTransaction() = 0; + + /** + * @brief Closes the ledger database + */ + virtual void + closeLedgerDB() = 0; + + /** + * @brief Closes the transaction database + */ + virtual void + closeTransactionDB() = 0; +}; + +template +T +rangeCheckedCast(C c) +{ + if ((c > std::numeric_limits::max()) || (!std::numeric_limits::is_signed && c < 0) || + (std::numeric_limits::is_signed && std::numeric_limits::is_signed && + c < std::numeric_limits::lowest())) + { + // This should never happen + // LCOV_EXCL_START + UNREACHABLE("xrpl::rangeCheckedCast : domain error"); + JLOG(debugLog().error()) << "rangeCheckedCast domain error:" + << " value = " << c << " min = " << std::numeric_limits::lowest() + << " max: " << std::numeric_limits::max(); + // LCOV_EXCL_STOP + } + + return static_cast(c); +} + +} // namespace xrpl diff --git a/src/xrpld/core/SociDB.h b/include/xrpl/rdb/SociDB.h similarity index 91% rename from src/xrpld/core/SociDB.h rename to include/xrpl/rdb/SociDB.h index fe3c15e26e..acfc183076 100644 --- a/src/xrpld/core/SociDB.h +++ b/include/xrpl/rdb/SociDB.h @@ -1,5 +1,4 @@ -#ifndef XRPL_SOCIDB_H_INCLUDED -#define XRPL_SOCIDB_H_INCLUDED +#pragma once /** An embedded database wrapper with an intuitive, type-safe interface. @@ -75,10 +74,7 @@ open(soci::session& s, BasicConfig const& config, std::string const& dbName); * */ void -open( - soci::session& s, - std::string const& beName, - std::string const& connectionString); +open(soci::session& s, std::string const& beName, std::string const& connectionString); std::uint32_t getKBUsedAll(soci::session& s); @@ -115,16 +111,10 @@ public: and so must outlive them both. */ std::shared_ptr -makeCheckpointer( - std::uintptr_t id, - std::weak_ptr, - JobQueue&, - Logs&); +makeCheckpointer(std::uintptr_t id, std::weak_ptr, JobQueue&, Logs&); } // namespace xrpl #if defined(__clang__) #pragma clang diagnostic pop #endif - -#endif diff --git a/include/xrpl/resource/Charge.h b/include/xrpl/resource/Charge.h index 1edaca28b4..55b13731b9 100644 --- a/include/xrpl/resource/Charge.h +++ b/include/xrpl/resource/Charge.h @@ -1,5 +1,4 @@ -#ifndef XRPL_RESOURCE_CHARGE_H_INCLUDED -#define XRPL_RESOURCE_CHARGE_H_INCLUDED +#pragma once #include @@ -50,5 +49,3 @@ operator<<(std::ostream& os, Charge const& v); } // namespace Resource } // namespace xrpl - -#endif diff --git a/include/xrpl/resource/Consumer.h b/include/xrpl/resource/Consumer.h index 6e973d824c..45cc221212 100644 --- a/include/xrpl/resource/Consumer.h +++ b/include/xrpl/resource/Consumer.h @@ -1,5 +1,4 @@ -#ifndef XRPL_RESOURCE_CONSUMER_H_INCLUDED -#define XRPL_RESOURCE_CONSUMER_H_INCLUDED +#pragma once #include #include @@ -82,5 +81,3 @@ operator<<(std::ostream& os, Consumer const& v); } // namespace Resource } // namespace xrpl - -#endif diff --git a/include/xrpl/resource/Disposition.h b/include/xrpl/resource/Disposition.h index 81675e8376..096afb6a6f 100644 --- a/include/xrpl/resource/Disposition.h +++ b/include/xrpl/resource/Disposition.h @@ -1,5 +1,4 @@ -#ifndef XRPL_RESOURCE_DISPOSITION_H_INCLUDED -#define XRPL_RESOURCE_DISPOSITION_H_INCLUDED +#pragma once namespace xrpl { namespace Resource { @@ -20,5 +19,3 @@ enum Disposition { } // namespace Resource } // namespace xrpl - -#endif diff --git a/include/xrpl/resource/Fees.h b/include/xrpl/resource/Fees.h index 643a8e624c..0ba083d4fe 100644 --- a/include/xrpl/resource/Fees.h +++ b/include/xrpl/resource/Fees.h @@ -1,5 +1,4 @@ -#ifndef XRPL_RESOURCE_FEES_H_INCLUDED -#define XRPL_RESOURCE_FEES_H_INCLUDED +#pragma once #include @@ -41,5 +40,3 @@ extern Charge const feeDrop; // The cost of being dropped for } // namespace Resource } // namespace xrpl - -#endif diff --git a/include/xrpl/resource/Gossip.h b/include/xrpl/resource/Gossip.h index dfd04288fc..e581145149 100644 --- a/include/xrpl/resource/Gossip.h +++ b/include/xrpl/resource/Gossip.h @@ -1,5 +1,4 @@ -#ifndef XRPL_RESOURCE_GOSSIP_H_INCLUDED -#define XRPL_RESOURCE_GOSSIP_H_INCLUDED +#pragma once #include @@ -27,5 +26,3 @@ struct Gossip } // namespace Resource } // namespace xrpl - -#endif diff --git a/include/xrpl/resource/ResourceManager.h b/include/xrpl/resource/ResourceManager.h index 19690d6bc4..c04e7bb79b 100644 --- a/include/xrpl/resource/ResourceManager.h +++ b/include/xrpl/resource/ResourceManager.h @@ -1,5 +1,4 @@ -#ifndef XRPL_RESOURCE_MANAGER_H_INCLUDED -#define XRPL_RESOURCE_MANAGER_H_INCLUDED +#pragma once #include #include @@ -28,10 +27,7 @@ public: virtual Consumer newInboundEndpoint(beast::IP::Endpoint const& address) = 0; virtual Consumer - newInboundEndpoint( - beast::IP::Endpoint const& address, - bool const proxy, - std::string_view forwardedFor) = 0; + newInboundEndpoint(beast::IP::Endpoint const& address, bool const proxy, std::string_view forwardedFor) = 0; /** Create a new endpoint keyed by outbound IP address and port. */ virtual Consumer @@ -61,11 +57,7 @@ public: //------------------------------------------------------------------------------ std::unique_ptr -make_Manager( - beast::insight::Collector::ptr const& collector, - beast::Journal journal); +make_Manager(beast::insight::Collector::ptr const& collector, beast::Journal journal); } // namespace Resource } // namespace xrpl - -#endif diff --git a/include/xrpl/resource/Types.h b/include/xrpl/resource/Types.h index 8923933f0f..fb71cffe37 100644 --- a/include/xrpl/resource/Types.h +++ b/include/xrpl/resource/Types.h @@ -1,5 +1,4 @@ -#ifndef XRPL_RESOURCE_TYPES_H_INCLUDED -#define XRPL_RESOURCE_TYPES_H_INCLUDED +#pragma once namespace xrpl { namespace Resource { @@ -9,5 +8,3 @@ struct Entry; } // namespace Resource } // namespace xrpl - -#endif diff --git a/include/xrpl/resource/detail/Entry.h b/include/xrpl/resource/detail/Entry.h index ce55c46064..ecff8828af 100644 --- a/include/xrpl/resource/detail/Entry.h +++ b/include/xrpl/resource/detail/Entry.h @@ -1,5 +1,4 @@ -#ifndef XRPL_RESOURCE_ENTRY_H_INCLUDED -#define XRPL_RESOURCE_ENTRY_H_INCLUDED +#pragma once #include #include @@ -23,11 +22,7 @@ struct Entry : public beast::List::Node @param now Construction time of Entry. */ explicit Entry(clock_type::time_point const now) - : refcount(0) - , local_balance(now) - , remote_balance(0) - , lastWarningTime() - , whenExpires() + : refcount(0), local_balance(now), remote_balance(0), lastWarningTime(), whenExpires() { } @@ -94,5 +89,3 @@ operator<<(std::ostream& os, Entry const& v) } // namespace Resource } // namespace xrpl - -#endif diff --git a/include/xrpl/resource/detail/Import.h b/include/xrpl/resource/detail/Import.h index d33bd5f156..790fc0596a 100644 --- a/include/xrpl/resource/detail/Import.h +++ b/include/xrpl/resource/detail/Import.h @@ -1,5 +1,4 @@ -#ifndef XRPL_RESOURCE_IMPORT_H_INCLUDED -#define XRPL_RESOURCE_IMPORT_H_INCLUDED +#pragma once #include #include @@ -32,5 +31,3 @@ struct Import } // namespace Resource } // namespace xrpl - -#endif diff --git a/include/xrpl/resource/detail/Key.h b/include/xrpl/resource/detail/Key.h index e63d2827ea..0c5164a7d8 100644 --- a/include/xrpl/resource/detail/Key.h +++ b/include/xrpl/resource/detail/Key.h @@ -1,5 +1,4 @@ -#ifndef XRPL_RESOURCE_KEY_H_INCLUDED -#define XRPL_RESOURCE_KEY_H_INCLUDED +#pragma once #include #include @@ -48,5 +47,3 @@ struct Key } // namespace Resource } // namespace xrpl - -#endif diff --git a/include/xrpl/resource/detail/Kind.h b/include/xrpl/resource/detail/Kind.h index 0e55b65780..fbb6b65e25 100644 --- a/include/xrpl/resource/detail/Kind.h +++ b/include/xrpl/resource/detail/Kind.h @@ -1,5 +1,4 @@ -#ifndef XRPL_RESOURCE_KIND_H_INCLUDED -#define XRPL_RESOURCE_KIND_H_INCLUDED +#pragma once namespace xrpl { namespace Resource { @@ -16,5 +15,3 @@ enum Kind { kindInbound, kindOutbound, kindUnlimited }; } // namespace Resource } // namespace xrpl - -#endif diff --git a/include/xrpl/resource/detail/Logic.h b/include/xrpl/resource/detail/Logic.h index 5bcfa42f31..066e416550 100644 --- a/include/xrpl/resource/detail/Logic.h +++ b/include/xrpl/resource/detail/Logic.h @@ -1,5 +1,4 @@ -#ifndef XRPL_RESOURCE_LOGIC_H_INCLUDED -#define XRPL_RESOURCE_LOGIC_H_INCLUDED +#pragma once #include #include @@ -69,10 +68,7 @@ private: //-------------------------------------------------------------------------- public: - Logic( - beast::insight::Collector::ptr const& collector, - clock_type& clock, - beast::Journal journal) + Logic(beast::insight::Collector::ptr const& collector, clock_type& clock, beast::Journal journal) : m_stats(collector), m_clock(clock), m_journal(journal) { } @@ -199,8 +195,7 @@ public: int localBalance = inboundEntry.local_balance.value(now); if ((localBalance + inboundEntry.remote_balance) >= threshold) { - Json::Value& entry = - (ret[inboundEntry.to_string()] = Json::objectValue); + Json::Value& entry = (ret[inboundEntry.to_string()] = Json::objectValue); entry[jss::local] = localBalance; entry[jss::remote] = inboundEntry.remote_balance; entry[jss::type] = "inbound"; @@ -211,8 +206,7 @@ public: int localBalance = outboundEntry.local_balance.value(now); if ((localBalance + outboundEntry.remote_balance) >= threshold) { - Json::Value& entry = - (ret[outboundEntry.to_string()] = Json::objectValue); + Json::Value& entry = (ret[outboundEntry.to_string()] = Json::objectValue); entry[jss::local] = localBalance; entry[jss::remote] = outboundEntry.remote_balance; entry[jss::type] = "outbound"; @@ -223,8 +217,7 @@ public: int localBalance = adminEntry.local_balance.value(now); if ((localBalance + adminEntry.remote_balance) >= threshold) { - Json::Value& entry = - (ret[adminEntry.to_string()] = Json::objectValue); + Json::Value& entry = (ret[adminEntry.to_string()] = Json::objectValue); entry[jss::local] = localBalance; entry[jss::remote] = adminEntry.remote_balance; entry[jss::type] = "admin"; @@ -268,9 +261,8 @@ public: std::lock_guard _(lock_); auto [resultIt, resultInserted] = importTable_.emplace( std::piecewise_construct, - std::make_tuple(origin), // Key - std::make_tuple( - m_clock.now().time_since_epoch().count())); // Import + std::make_tuple(origin), // Key + std::make_tuple(m_clock.now().time_since_epoch().count())); // Import if (resultInserted) { @@ -348,12 +340,9 @@ public: Import& import(iter->second); if (iter->second.whenExpires <= elapsed) { - for (auto item_iter(import.items.begin()); - item_iter != import.items.end(); - ++item_iter) + for (auto item_iter(import.items.begin()); item_iter != import.items.end(); ++item_iter) { - item_iter->consumer.entry().remote_balance -= - item_iter->balance; + item_iter->consumer.entry().remote_balance -= item_iter->balance; } iter = importTable_.erase(iter); @@ -383,9 +372,7 @@ public: { std::lock_guard _(lock_); Entry& entry(iter->second); - XRPL_ASSERT( - entry.refcount == 0, - "xrpl::Resource::Logic::erase : entry not used"); + XRPL_ASSERT(entry.refcount == 0, "xrpl::Resource::Logic::erase : entry not used"); inactive_.erase(inactive_.iterator_to(entry)); table_.erase(iter); } @@ -435,12 +422,9 @@ public: static constexpr Charge::value_type feeLogAsWarn = 3000; static constexpr Charge::value_type feeLogAsInfo = 1000; static constexpr Charge::value_type feeLogAsDebug = 100; - static_assert( - feeLogAsWarn > feeLogAsInfo && feeLogAsInfo > feeLogAsDebug && - feeLogAsDebug > 10); + static_assert(feeLogAsWarn > feeLogAsInfo && feeLogAsInfo > feeLogAsDebug && feeLogAsDebug > 10); - static auto getStream = [](Resource::Charge::value_type cost, - beast::Journal& journal) { + static auto getStream = [](Resource::Charge::value_type cost, beast::Journal& journal) { if (cost >= feeLogAsWarn) return journal.warn(); if (cost >= feeLogAsInfo) @@ -456,8 +440,7 @@ public: std::lock_guard _(lock_); clock_type::time_point const now(m_clock.now()); int const balance(entry.add(fee.cost(), now)); - JLOG(getStream(fee.cost(), m_journal)) - << "Charging " << entry << " for " << fee << context; + JLOG(getStream(fee.cost(), m_journal)) << "Charging " << entry << " for " << fee << context; return disposition(balance); } @@ -470,8 +453,7 @@ public: std::lock_guard _(lock_); bool notify(false); auto const elapsed = m_clock.now(); - if (entry.balance(m_clock.now()) >= warningThreshold && - elapsed != entry.lastWarningTime) + if (entry.balance(m_clock.now()) >= warningThreshold && elapsed != entry.lastWarningTime) { charge(entry, feeWarning); notify = true; @@ -497,9 +479,8 @@ public: int const balance(entry.balance(now)); if (balance >= dropThreshold) { - JLOG(m_journal.warn()) - << "Consumer entry " << entry << " dropped with balance " - << balance << " at or above drop threshold " << dropThreshold; + JLOG(m_journal.warn()) << "Consumer entry " << entry << " dropped with balance " << balance + << " at or above drop threshold " << dropThreshold; // Adding feeDrop at this point keeps the dropped connection // from re-connecting for at least a little while after it is @@ -521,10 +502,7 @@ public: //-------------------------------------------------------------------------- void - writeList( - clock_type::time_point const now, - beast::PropertyStream::Set& items, - EntryIntrusiveList& list) + writeList(clock_type::time_point const now, beast::PropertyStream::Set& items, EntryIntrusiveList& list) { for (auto& entry : list) { @@ -569,5 +547,3 @@ public: } // namespace Resource } // namespace xrpl - -#endif diff --git a/include/xrpl/resource/detail/Tuning.h b/include/xrpl/resource/detail/Tuning.h index 9d7ba31303..d5be5cf0b6 100644 --- a/include/xrpl/resource/detail/Tuning.h +++ b/include/xrpl/resource/detail/Tuning.h @@ -1,5 +1,4 @@ -#ifndef XRPL_RESOURCE_TUNING_H_INCLUDED -#define XRPL_RESOURCE_TUNING_H_INCLUDED +#pragma once #include @@ -33,5 +32,3 @@ std::chrono::seconds constexpr gossipExpirationSeconds{30}; } // namespace Resource } // namespace xrpl - -#endif diff --git a/include/xrpl/server/Handoff.h b/include/xrpl/server/Handoff.h index 49a5851251..60ed16def4 100644 --- a/include/xrpl/server/Handoff.h +++ b/include/xrpl/server/Handoff.h @@ -1,5 +1,4 @@ -#ifndef XRPL_SERVER_HANDOFF_H_INCLUDED -#define XRPL_SERVER_HANDOFF_H_INCLUDED +#pragma once #include @@ -10,11 +9,9 @@ namespace xrpl { -using http_request_type = - boost::beast::http::request; +using http_request_type = boost::beast::http::request; -using http_response_type = - boost::beast::http::response; +using http_response_type = boost::beast::http::response; /** Used to indicate the result of a server connection handoff. */ struct Handoff @@ -37,5 +34,3 @@ struct Handoff }; } // namespace xrpl - -#endif diff --git a/src/xrpld/rpc/InfoSub.h b/include/xrpl/server/InfoSub.h similarity index 87% rename from src/xrpld/rpc/InfoSub.h rename to include/xrpl/server/InfoSub.h index 97ff266364..1a7222bf5d 100644 --- a/src/xrpld/rpc/InfoSub.h +++ b/include/xrpl/server/InfoSub.h @@ -1,13 +1,11 @@ -#ifndef XRPL_NET_INFOSUB_H_INCLUDED -#define XRPL_NET_INFOSUB_H_INCLUDED - -#include +#pragma once #include #include #include #include #include +#include namespace xrpl { @@ -55,25 +53,16 @@ public: // you get transactions as they occur or once their // results are confirmed virtual void - subAccount( - ref ispListener, - hash_set const& vnaAccountIDs, - bool realTime) = 0; + subAccount(ref ispListener, hash_set const& vnaAccountIDs, bool realTime) = 0; // for normal use, removes from InfoSub and server virtual void - unsubAccount( - ref isplistener, - hash_set const& vnaAccountIDs, - bool realTime) = 0; + unsubAccount(ref isplistener, hash_set const& vnaAccountIDs, bool realTime) = 0; // for use during InfoSub destruction // Removes only from the server virtual void - unsubAccountInternal( - std::uint64_t uListener, - hash_set const& vnaAccountIDs, - bool realTime) = 0; + unsubAccountInternal(std::uint64_t uListener, hash_set const& vnaAccountIDs, bool realTime) = 0; /** * subscribe an account's new transactions and retrieve the account's @@ -92,16 +81,10 @@ public: * transactions. */ virtual void - unsubAccountHistory( - ref ispListener, - AccountID const& account, - bool historyOnly) = 0; + unsubAccountHistory(ref ispListener, AccountID const& account, bool historyOnly) = 0; virtual void - unsubAccountHistoryInternal( - std::uint64_t uListener, - AccountID const& account, - bool historyOnly) = 0; + unsubAccountHistoryInternal(std::uint64_t uListener, AccountID const& account, bool historyOnly) = 0; // VFALCO TODO Document the bool return value virtual bool @@ -148,6 +131,7 @@ public: virtual bool subPeerStatus(ref ispListener) = 0; + virtual bool unsubPeerStatus(std::uint64_t uListener) = 0; virtual void @@ -238,5 +222,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/src/xrpld/app/misc/Manifest.h b/include/xrpl/server/Manifest.h similarity index 92% rename from src/xrpld/app/misc/Manifest.h rename to include/xrpl/server/Manifest.h index c1a77be63b..79426a1a46 100644 --- a/src/xrpld/app/misc/Manifest.h +++ b/include/xrpl/server/Manifest.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_MISC_MANIFEST_H_INCLUDED -#define XRPL_APP_MISC_MANIFEST_H_INCLUDED +#pragma once #include #include @@ -86,11 +85,7 @@ struct Manifest std::optional const& signingKey_, std::uint32_t seq, std::string const& domain_) - : serialized(serialized_) - , masterKey(masterKey_) - , signingKey(signingKey_) - , sequence(seq) - , domain(domain_) + : serialized(serialized_), masterKey(masterKey_), signingKey(signingKey_), sequence(seq), domain(domain_) { } @@ -146,21 +141,14 @@ std::optional deserializeManifest(Slice s, beast::Journal journal); inline std::optional -deserializeManifest( - std::string const& s, - beast::Journal journal = beast::Journal(beast::Journal::getNullSink())) +deserializeManifest(std::string const& s, beast::Journal journal = beast::Journal(beast::Journal::getNullSink())) { return deserializeManifest(makeSlice(s), journal); } -template < - class T, - class = std::enable_if_t< - std::is_same::value || std::is_same::value>> +template ::value || std::is_same::value>> std::optional -deserializeManifest( - std::vector const& v, - beast::Journal journal = beast::Journal(beast::Journal::getNullSink())) +deserializeManifest(std::vector const& v, beast::Journal journal = beast::Journal(beast::Journal::getNullSink())) { return deserializeManifest(makeSlice(v), journal); } @@ -171,9 +159,8 @@ operator==(Manifest const& lhs, Manifest const& rhs) { // In theory, comparing the two serialized strings should be // sufficient. - return lhs.sequence == rhs.sequence && lhs.masterKey == rhs.masterKey && - lhs.signingKey == rhs.signingKey && lhs.domain == rhs.domain && - lhs.serialized == rhs.serialized; + return lhs.sequence == rhs.sequence && lhs.masterKey == rhs.masterKey && lhs.signingKey == rhs.signingKey && + lhs.domain == rhs.domain && lhs.serialized == rhs.serialized; } inline bool @@ -248,9 +235,7 @@ private: std::atomic seq_{0}; public: - explicit ManifestCache( - beast::Journal j = beast::Journal(beast::Journal::getNullSink())) - : j_(j) + explicit ManifestCache(beast::Journal j = beast::Journal(beast::Journal::getNullSink())) : j_(j) { } @@ -383,10 +368,7 @@ public: May be called concurrently */ void - save( - DatabaseCon& dbCon, - std::string const& dbTable, - std::function const& isTrusted); + save(DatabaseCon& dbCon, std::string const& dbTable, std::function const& isTrusted); /** Invokes the callback once for every populated manifest. @@ -444,5 +426,3 @@ public: }; } // namespace xrpl - -#endif diff --git a/src/xrpld/app/misc/NetworkOPs.h b/include/xrpl/server/NetworkOPs.h similarity index 83% rename from src/xrpld/app/misc/NetworkOPs.h rename to include/xrpl/server/NetworkOPs.h index 5b92e4574b..ce55f667f7 100644 --- a/src/xrpld/app/misc/NetworkOPs.h +++ b/include/xrpl/server/NetworkOPs.h @@ -1,14 +1,12 @@ -#ifndef XRPL_APP_MISC_NETWORKOPS_H_INCLUDED -#define XRPL_APP_MISC_NETWORKOPS_H_INCLUDED - -#include -#include -#include +#pragma once #include -#include +#include #include +#include #include +#include +#include #include @@ -20,10 +18,13 @@ namespace xrpl { // Master operational handler, server sequencer, network tracker class Peer; +class STTx; +class ReadView; class LedgerMaster; class Transaction; class ValidatorKeys; class CanonicalTXSet; +class RCLCxPeerPos; // This is the primary interface into the "client" portion of the program. // Code that wants to do normal operations on the network such as @@ -92,8 +93,7 @@ public: virtual OperatingMode getOperatingMode() const = 0; virtual std::string - strOperatingMode(OperatingMode const mode, bool const admin = false) - const = 0; + strOperatingMode(OperatingMode const mode, bool const admin = false) const = 0; virtual std::string strOperatingMode(bool const admin = false) const = 0; @@ -116,11 +116,7 @@ public: * @param failType fail_hard setting from transaction submission. */ virtual void - processTransaction( - std::shared_ptr& transaction, - bool bUnlimited, - bool bLocal, - FailHard failType) = 0; + processTransaction(std::shared_ptr& transaction, bool bUnlimited, bool bLocal, FailHard failType) = 0; /** * Process a set of transactions synchronously, and ensuring that they are @@ -137,9 +133,7 @@ public: // virtual Json::Value - getOwnerInfo( - std::shared_ptr lpLedger, - AccountID const& account) = 0; + getOwnerInfo(std::shared_ptr lpLedger, AccountID const& account) = 0; //-------------------------------------------------------------------------- // @@ -163,18 +157,14 @@ public: processTrustedProposal(RCLCxPeerPos peerPos) = 0; virtual bool - recvValidation( - std::shared_ptr const& val, - std::string const& source) = 0; + recvValidation(std::shared_ptr const& val, std::string const& source) = 0; virtual void mapComplete(std::shared_ptr const& map, bool fromAcquire) = 0; // network state machine virtual bool - beginConsensus( - uint256 const& netLCL, - std::unique_ptr const& clog) = 0; + beginConsensus(uint256 const& netLCL, std::unique_ptr const& clog) = 0; virtual void endConsensus(std::unique_ptr const& clog) = 0; virtual void @@ -229,9 +219,7 @@ public: proposing being accepted. */ virtual std::uint32_t - acceptLedger( - std::optional consensusDelay = - std::nullopt) = 0; + acceptLedger(std::optional consensusDelay = std::nullopt) = 0; virtual void reportFeeChange() = 0; @@ -259,22 +247,4 @@ public: stateAccounting(Json::Value& obj) = 0; }; -//------------------------------------------------------------------------------ - -std::unique_ptr -make_NetworkOPs( - Application& app, - NetworkOPs::clock_type& clock, - bool standalone, - std::size_t minPeerCount, - bool start_valid, - JobQueue& job_queue, - LedgerMaster& ledgerMaster, - ValidatorKeys const& validatorKeys, - boost::asio::io_context& io_svc, - beast::Journal journal, - beast::insight::Collector::ptr const& collector); - } // namespace xrpl - -#endif diff --git a/include/xrpl/server/Port.h b/include/xrpl/server/Port.h index 995401f8fd..1dfa93b0a7 100644 --- a/include/xrpl/server/Port.h +++ b/include/xrpl/server/Port.h @@ -1,5 +1,4 @@ -#ifndef XRPL_SERVER_PORT_H_INCLUDED -#define XRPL_SERVER_PORT_H_INCLUDED +#pragma once #include #include @@ -105,5 +104,3 @@ void parse_Port(ParsedPort& port, Section const& section, std::ostream& log); } // namespace xrpl - -#endif diff --git a/include/xrpl/server/Server.h b/include/xrpl/server/Server.h index b553b9e72a..52340ac900 100644 --- a/include/xrpl/server/Server.h +++ b/include/xrpl/server/Server.h @@ -1,5 +1,4 @@ -#ifndef XRPL_SERVER_SERVER_H_INCLUDED -#define XRPL_SERVER_SERVER_H_INCLUDED +#pragma once #include #include @@ -13,14 +12,9 @@ namespace xrpl { /** Create the HTTP server using the specified handler. */ template std::unique_ptr -make_Server( - Handler& handler, - boost::asio::io_context& io_context, - beast::Journal journal) +make_Server(Handler& handler, boost::asio::io_context& io_context, beast::Journal journal) { return std::make_unique>(handler, io_context, journal); } } // namespace xrpl - -#endif diff --git a/include/xrpl/server/Session.h b/include/xrpl/server/Session.h index 4570e90f7e..37cbf59775 100644 --- a/include/xrpl/server/Session.h +++ b/include/xrpl/server/Session.h @@ -1,5 +1,4 @@ -#ifndef XRPL_SERVER_SESSION_H_INCLUDED -#define XRPL_SERVER_SESSION_H_INCLUDED +#pragma once #include #include @@ -64,9 +63,7 @@ public: void write(BufferSequence const& buffers) { - for (typename BufferSequence::const_iterator iter(buffers.begin()); - iter != buffers.end(); - ++iter) + for (typename BufferSequence::const_iterator iter(buffers.begin()); iter != buffers.end(); ++iter) { typename BufferSequence::value_type const& buffer(*iter); write(buffer.data(), boost::asio::buffer_size(buffer)); @@ -112,5 +109,3 @@ public: }; } // namespace xrpl - -#endif diff --git a/include/xrpl/server/SimpleWriter.h b/include/xrpl/server/SimpleWriter.h index cf41f1c82a..87b94507a4 100644 --- a/include/xrpl/server/SimpleWriter.h +++ b/include/xrpl/server/SimpleWriter.h @@ -1,5 +1,4 @@ -#ifndef XRPL_SERVER_SIMPLEWRITER_H_INCLUDED -#define XRPL_SERVER_SIMPLEWRITER_H_INCLUDED +#pragma once #include @@ -19,8 +18,7 @@ class SimpleWriter : public Writer public: template - explicit SimpleWriter( - boost::beast::http::message const& msg) + explicit SimpleWriter(boost::beast::http::message const& msg) { boost::beast::ostream(sb_) << msg; } @@ -56,5 +54,3 @@ public: }; } // namespace xrpl - -#endif diff --git a/src/xrpld/app/rdb/State.h b/include/xrpl/server/State.h similarity index 83% rename from src/xrpld/app/rdb/State.h rename to include/xrpl/server/State.h index e8c14fdd29..48e11869f4 100644 --- a/src/xrpld/app/rdb/State.h +++ b/include/xrpl/server/State.h @@ -1,11 +1,8 @@ -#ifndef XRPL_APP_RDB_STATE_H_INCLUDED -#define XRPL_APP_RDB_STATE_H_INCLUDED +#pragma once -#include -#include -#include -#include -#include +#include +#include +#include #include @@ -25,10 +22,7 @@ struct SavedState * @param dbName Name of the database. */ void -initStateDB( - soci::session& session, - BasicConfig const& config, - std::string const& dbName); +initStateDB(soci::session& session, BasicConfig const& config, std::string const& dbName); /** * @brief getCanDelete Returns the ledger sequence which can be deleted. @@ -75,5 +69,3 @@ void setLastRotated(soci::session& session, LedgerIndex seq); } // namespace xrpl - -#endif diff --git a/src/xrpld/app/rdb/Vacuum.h b/include/xrpl/server/Vacuum.h similarity index 73% rename from src/xrpld/app/rdb/Vacuum.h rename to include/xrpl/server/Vacuum.h index d7ca5f8bce..5f80eced87 100644 --- a/src/xrpld/app/rdb/Vacuum.h +++ b/include/xrpl/server/Vacuum.h @@ -1,7 +1,6 @@ -#ifndef XRPL_APP_RDB_VACUUM_H_INCLUDED -#define XRPL_APP_RDB_VACUUM_H_INCLUDED +#pragma once -#include +#include namespace xrpl { @@ -15,5 +14,3 @@ bool doVacuumDB(DatabaseCon::Setup const& setup, beast::Journal j); } // namespace xrpl - -#endif diff --git a/include/xrpl/server/WSSession.h b/include/xrpl/server/WSSession.h index fb8af7118c..56105739e9 100644 --- a/include/xrpl/server/WSSession.h +++ b/include/xrpl/server/WSSession.h @@ -1,5 +1,4 @@ -#ifndef XRPL_SERVER_WSSESSION_H_INCLUDED -#define XRPL_SERVER_WSSESSION_H_INCLUDED +#pragma once #include #include @@ -78,8 +77,7 @@ public: done = true; } auto const pb = boost::beast::buffers_prefix(n_, sb_.data()); - std::vector vb( - std::distance(pb.begin(), pb.end())); + std::vector vb(std::distance(pb.begin(), pb.end())); std::copy(pb.begin(), pb.end(), std::back_inserter(vb)); return {done, vb}; } @@ -126,5 +124,3 @@ struct WSSession }; } // namespace xrpl - -#endif diff --git a/src/xrpld/app/rdb/Wallet.h b/include/xrpl/server/Wallet.h similarity index 85% rename from src/xrpld/app/rdb/Wallet.h rename to include/xrpl/server/Wallet.h index 961b12d7ef..dcfbada8eb 100644 --- a/src/xrpld/app/rdb/Wallet.h +++ b/include/xrpl/server/Wallet.h @@ -1,10 +1,8 @@ -#ifndef XRPL_APP_RDB_WALLET_H_INCLUDED -#define XRPL_APP_RDB_WALLET_H_INCLUDED +#pragma once -#include -#include -#include -#include +#include +#include +#include namespace xrpl { @@ -25,10 +23,7 @@ makeWalletDB(DatabaseCon::Setup const& setup, beast::Journal j); * @return Unique pointer to the database descriptor. */ std::unique_ptr -makeTestWalletDB( - DatabaseCon::Setup const& setup, - std::string const& dbname, - beast::Journal j); +makeTestWalletDB(DatabaseCon::Setup const& setup, std::string const& dbname, beast::Journal j); /** * @brief getManifests Loads a manifest from the wallet database and stores it @@ -40,11 +35,7 @@ makeTestWalletDB( * @param j Journal. */ void -getManifests( - soci::session& session, - std::string const& dbTable, - ManifestCache& mCache, - beast::Journal j); +getManifests(soci::session& session, std::string const& dbTable, ManifestCache& mCache, beast::Journal j); /** * @brief saveManifests Saves all given manifests to the database. @@ -104,10 +95,7 @@ getPeerReservationTable(soci::session& session, beast::Journal j); * @param description Description of the node. */ void -insertPeerReservation( - soci::session& session, - PublicKey const& nodeId, - std::string const& description); +insertPeerReservation(soci::session& session, PublicKey const& nodeId, std::string const& description); /** * @brief deletePeerReservation Deletes an entry from the peer reservation @@ -152,12 +140,6 @@ readAmendments( * @param vote Whether to vote in favor of this amendment. */ void -voteAmendment( - soci::session& session, - uint256 const& amendment, - std::string const& name, - AmendmentVote vote); +voteAmendment(soci::session& session, uint256 const& amendment, std::string const& name, AmendmentVote vote); } // namespace xrpl - -#endif diff --git a/include/xrpl/server/Writer.h b/include/xrpl/server/Writer.h index 7e0c304ea9..05fea863be 100644 --- a/include/xrpl/server/Writer.h +++ b/include/xrpl/server/Writer.h @@ -1,5 +1,4 @@ -#ifndef XRPL_SERVER_WRITER_H_INCLUDED -#define XRPL_SERVER_WRITER_H_INCLUDED +#pragma once #include @@ -38,5 +37,3 @@ public: }; } // namespace xrpl - -#endif diff --git a/include/xrpl/server/detail/BaseHTTPPeer.h b/include/xrpl/server/detail/BaseHTTPPeer.h index 5b7327c6b9..ab85cb7c89 100644 --- a/include/xrpl/server/detail/BaseHTTPPeer.h +++ b/include/xrpl/server/detail/BaseHTTPPeer.h @@ -1,5 +1,4 @@ -#ifndef XRPL_SERVER_BASEHTTPPEER_H_INCLUDED -#define XRPL_SERVER_BASEHTTPPEER_H_INCLUDED +#pragma once #include #include @@ -49,8 +48,7 @@ protected: struct buffer { - buffer(void const* ptr, std::size_t len) - : data(new char[len]), bytes(len), used(0) + buffer(void const* ptr, std::size_t len) : data(new char[len]), bytes(len), used(0) { memcpy(data.get(), ptr, len); } @@ -132,10 +130,7 @@ protected: on_write(error_code const& ec, std::size_t bytes_transferred); void - do_writer( - std::shared_ptr const& writer, - bool keep_alive, - yield_context do_yield); + do_writer(std::shared_ptr const& writer, bool keep_alive, yield_context do_yield); virtual void do_request() = 0; @@ -203,8 +198,7 @@ BaseHTTPPeer::BaseHTTPPeer( , remote_address_(remote_address) , journal_(journal) { - read_buf_.commit(boost::asio::buffer_copy( - read_buf_.prepare(boost::asio::buffer_size(buffers)), buffers)); + read_buf_.commit(boost::asio::buffer_copy(read_buf_.prepare(boost::asio::buffer_size(buffers)), buffers)); static std::atomic sid; nid_ = ++sid; id_ = std::string("#") + std::to_string(nid_) + " "; @@ -216,8 +210,7 @@ BaseHTTPPeer::~BaseHTTPPeer() { handler_.onClose(session(), ec_); JLOG(journal_.trace()) << id_ << "destroyed: " << request_count_ - << ((request_count_ == 1) ? " request" - : " requests"); + << ((request_count_ == 1) ? " request" : " requests"); } template @@ -225,11 +218,7 @@ void BaseHTTPPeer::close() { if (!strand_.running_in_this_thread()) - return post( - strand_, - std::bind( - (void(BaseHTTPPeer::*)(void)) & BaseHTTPPeer::close, - impl().shared_from_this())); + return post(strand_, std::bind((void(BaseHTTPPeer::*)(void)) & BaseHTTPPeer::close, impl().shared_from_this())); boost::beast::get_lowest_layer(impl().stream_).close(); } @@ -242,8 +231,7 @@ BaseHTTPPeer::fail(error_code ec, char const* what) if (!ec_ && ec != boost::asio::error::operation_aborted) { ec_ = ec; - JLOG(journal_.trace()) - << id_ << std::string(what) << ": " << ec.message(); + JLOG(journal_.trace()) << id_ << std::string(what) << ": " << ec.message(); boost::beast::get_lowest_layer(impl().stream_).close(); } } @@ -253,9 +241,8 @@ void BaseHTTPPeer::start_timer() { boost::beast::get_lowest_layer(impl().stream_) - .expires_after(std::chrono::seconds( - remote_address_.address().is_loopback() ? timeoutSecondsLocal - : timeoutSeconds)); + .expires_after( + std::chrono::seconds(remote_address_.address().is_loopback() ? timeoutSecondsLocal : timeoutSeconds)); } // Convenience for discarding the error code @@ -271,8 +258,7 @@ template void BaseHTTPPeer::on_timer() { - auto ec = - boost::system::errc::make_error_code(boost::system::errc::timed_out); + auto ec = boost::system::errc::make_error_code(boost::system::errc::timed_out); fail(ec, "timer"); } @@ -285,8 +271,7 @@ BaseHTTPPeer::do_read(yield_context do_yield) complete_ = false; error_code ec; start_timer(); - boost::beast::http::async_read( - impl().stream_, read_buf_, message_, do_yield[ec]); + boost::beast::http::async_read(impl().stream_, read_buf_, message_, do_yield[ec]); cancel_timer(); if (ec == boost::beast::http::error::end_of_stream) return do_close(); @@ -301,9 +286,7 @@ BaseHTTPPeer::do_read(yield_context do_yield) // The write queue must not be empty upon entry. template void -BaseHTTPPeer::on_write( - error_code const& ec, - std::size_t bytes_transferred) +BaseHTTPPeer::on_write(error_code const& ec, std::size_t bytes_transferred) { cancel_timer(); if (ec == boost::beast::error::timeout) @@ -330,29 +313,19 @@ BaseHTTPPeer::on_write( bind_executor( strand_, std::bind( - &BaseHTTPPeer::on_write, - impl().shared_from_this(), - std::placeholders::_1, - std::placeholders::_2))); + &BaseHTTPPeer::on_write, impl().shared_from_this(), std::placeholders::_1, std::placeholders::_2))); } if (!complete_) return; if (graceful_) return do_close(); util::spawn( - strand_, - std::bind( - &BaseHTTPPeer::do_read, - impl().shared_from_this(), - std::placeholders::_1)); + strand_, std::bind(&BaseHTTPPeer::do_read, impl().shared_from_this(), std::placeholders::_1)); } template void -BaseHTTPPeer::do_writer( - std::shared_ptr const& writer, - bool keep_alive, - yield_context do_yield) +BaseHTTPPeer::do_writer(std::shared_ptr const& writer, bool keep_alive, yield_context do_yield) { std::function resume; { @@ -360,12 +333,7 @@ BaseHTTPPeer::do_writer( resume = std::function([this, p, writer, keep_alive]() { util::spawn( strand_, - std::bind( - &BaseHTTPPeer::do_writer, - p, - writer, - keep_alive, - std::placeholders::_1)); + std::bind(&BaseHTTPPeer::do_writer, p, writer, keep_alive, std::placeholders::_1)); }); } @@ -374,11 +342,8 @@ BaseHTTPPeer::do_writer( if (!writer->prepare(bufferSize, resume)) return; error_code ec; - auto const bytes_transferred = boost::asio::async_write( - impl().stream_, - writer->data(), - boost::asio::transfer_at_least(1), - do_yield[ec]); + auto const bytes_transferred = + boost::asio::async_write(impl().stream_, writer->data(), boost::asio::transfer_at_least(1), do_yield[ec]); if (ec) return fail(ec, "writer"); writer->consume(bytes_transferred); @@ -390,11 +355,7 @@ BaseHTTPPeer::do_writer( return do_close(); util::spawn( - strand_, - std::bind( - &BaseHTTPPeer::do_read, - impl().shared_from_this(), - std::placeholders::_1)); + strand_, std::bind(&BaseHTTPPeer::do_read, impl().shared_from_this(), std::placeholders::_1)); } //------------------------------------------------------------------------------ @@ -413,13 +374,7 @@ BaseHTTPPeer::write(void const* buf, std::size_t bytes) }()) { if (!strand_.running_in_this_thread()) - return post( - strand_, - std::bind( - &BaseHTTPPeer::on_write, - impl().shared_from_this(), - error_code{}, - 0)); + return post(strand_, std::bind(&BaseHTTPPeer::on_write, impl().shared_from_this(), error_code{}, 0)); else return on_write(error_code{}, 0); } @@ -427,9 +382,7 @@ BaseHTTPPeer::write(void const* buf, std::size_t bytes) template void -BaseHTTPPeer::write( - std::shared_ptr const& writer, - bool keep_alive) +BaseHTTPPeer::write(std::shared_ptr const& writer, bool keep_alive) { util::spawn( strand_, @@ -457,11 +410,7 @@ void BaseHTTPPeer::complete() { if (!strand_.running_in_this_thread()) - return post( - strand_, - std::bind( - &BaseHTTPPeer::complete, - impl().shared_from_this())); + return post(strand_, std::bind(&BaseHTTPPeer::complete, impl().shared_from_this())); message_ = {}; complete_ = true; @@ -474,11 +423,7 @@ BaseHTTPPeer::complete() // keep-alive util::spawn( - strand_, - std::bind( - &BaseHTTPPeer::do_read, - impl().shared_from_this(), - std::placeholders::_1)); + strand_, std::bind(&BaseHTTPPeer::do_read, impl().shared_from_this(), std::placeholders::_1)); } // DEPRECATED @@ -491,8 +436,7 @@ BaseHTTPPeer::close(bool graceful) return post( strand_, std::bind( - (void(BaseHTTPPeer::*)(bool)) & - BaseHTTPPeer::close, + (void(BaseHTTPPeer::*)(bool)) & BaseHTTPPeer::close, impl().shared_from_this(), graceful)); @@ -512,5 +456,3 @@ BaseHTTPPeer::close(bool graceful) } } // namespace xrpl - -#endif diff --git a/include/xrpl/server/detail/BasePeer.h b/include/xrpl/server/detail/BasePeer.h index fa82a1bb37..afa1ceb993 100644 --- a/include/xrpl/server/detail/BasePeer.h +++ b/include/xrpl/server/detail/BasePeer.h @@ -1,5 +1,4 @@ -#ifndef XRPL_SERVER_BASEPEER_H_INCLUDED -#define XRPL_SERVER_BASEPEER_H_INCLUDED +#pragma once #include #include @@ -82,12 +81,9 @@ void BasePeer::close() { if (!strand_.running_in_this_thread()) - return post( - strand_, std::bind(&BasePeer::close, impl().shared_from_this())); + return post(strand_, std::bind(&BasePeer::close, impl().shared_from_this())); error_code ec; xrpl::get_lowest_layer(impl().ws_).socket().close(ec); } } // namespace xrpl - -#endif diff --git a/include/xrpl/server/detail/BaseWSPeer.h b/include/xrpl/server/detail/BaseWSPeer.h index f0649b221c..ab985dfac5 100644 --- a/include/xrpl/server/detail/BaseWSPeer.h +++ b/include/xrpl/server/detail/BaseWSPeer.h @@ -1,5 +1,4 @@ -#ifndef XRPL_SERVER_BASEWSPEER_H_INCLUDED -#define XRPL_SERVER_BASEWSPEER_H_INCLUDED +#pragma once #include #include @@ -49,9 +48,7 @@ private: bool ping_active_ = false; boost::beast::websocket::ping_data payload_; error_code ec_; - std::function< - void(boost::beast::websocket::frame_type, boost::beast::string_view)> - control_callback_; + std::function control_callback_; public: template @@ -139,9 +136,7 @@ protected: on_ping(error_code const& ec); void - on_ping_pong( - boost::beast::websocket::frame_type kind, - boost::beast::string_view payload); + on_ping_pong(boost::beast::websocket::frame_type kind, boost::beast::string_view payload); void on_timer(error_code ec); @@ -175,33 +170,20 @@ void BaseWSPeer::run() { if (!strand_.running_in_this_thread()) - return post( - strand_, std::bind(&BaseWSPeer::run, impl().shared_from_this())); + return post(strand_, std::bind(&BaseWSPeer::run, impl().shared_from_this())); impl().ws_.set_option(port().pmd_options); // Must manage the control callback memory outside of the `control_callback` // function - control_callback_ = std::bind( - &BaseWSPeer::on_ping_pong, - this, - std::placeholders::_1, - std::placeholders::_2); + control_callback_ = std::bind(&BaseWSPeer::on_ping_pong, this, std::placeholders::_1, std::placeholders::_2); impl().ws_.control_callback(control_callback_); start_timer(); close_on_timer_ = true; - impl().ws_.set_option( - boost::beast::websocket::stream_base::decorator([](auto& res) { - res.set( - boost::beast::http::field::server, - BuildInfo::getFullVersionString()); - })); + impl().ws_.set_option(boost::beast::websocket::stream_base::decorator( + [](auto& res) { res.set(boost::beast::http::field::server, BuildInfo::getFullVersionString()); })); impl().ws_.async_accept( request_, bind_executor( - strand_, - std::bind( - &BaseWSPeer::on_ws_handshake, - impl().shared_from_this(), - std::placeholders::_1))); + strand_, std::bind(&BaseWSPeer::on_ws_handshake, impl().shared_from_this(), std::placeholders::_1))); } template @@ -209,16 +191,12 @@ void BaseWSPeer::send(std::shared_ptr w) { if (!strand_.running_in_this_thread()) - return post( - strand_, - std::bind( - &BaseWSPeer::send, impl().shared_from_this(), std::move(w))); + return post(strand_, std::bind(&BaseWSPeer::send, impl().shared_from_this(), std::move(w))); if (do_close_) return; if (wq_.size() > port().ws_queue_limit) { - cr_.code = safe_cast( - boost::beast::websocket::close_code::policy_error); + cr_.code = safe_cast(boost::beast::websocket::close_code::policy_error); cr_.reason = "Policy error: client is too slow."; JLOG(this->j_.info()) << cr_.reason; wq_.erase(std::next(wq_.begin()), wq_.end()); @@ -239,26 +217,19 @@ BaseWSPeer::close() template void -BaseWSPeer::close( - boost::beast::websocket::close_reason const& reason) +BaseWSPeer::close(boost::beast::websocket::close_reason const& reason) { if (!strand_.running_in_this_thread()) - return post(strand_, [self = impl().shared_from_this(), reason] { - self->close(reason); - }); + return post(strand_, [self = impl().shared_from_this(), reason] { self->close(reason); }); if (do_close_) return; do_close_ = true; if (wq_.empty()) { impl().ws_.async_close( - reason, - bind_executor( - strand_, - [self = impl().shared_from_this()]( - boost::beast::error_code const& ec) { - self->on_close(ec); - })); + reason, bind_executor(strand_, [self = impl().shared_from_this()](boost::beast::error_code const& ec) { + self->on_close(ec); + })); } else { @@ -271,9 +242,7 @@ void BaseWSPeer::complete() { if (!strand_.running_in_this_thread()) - return post( - strand_, - std::bind(&BaseWSPeer::complete, impl().shared_from_this())); + return post(strand_, std::bind(&BaseWSPeer::complete, impl().shared_from_this())); do_read(); } @@ -292,9 +261,7 @@ void BaseWSPeer::do_write() { if (!strand_.running_in_this_thread()) - return post( - strand_, - std::bind(&BaseWSPeer::do_write, impl().shared_from_this())); + return post(strand_, std::bind(&BaseWSPeer::do_write, impl().shared_from_this())); on_write({}); } @@ -305,8 +272,7 @@ BaseWSPeer::on_write(error_code const& ec) if (ec) return fail(ec, "write"); auto& w = *wq_.front(); - auto const result = w.prepare( - 65536, std::bind(&BaseWSPeer::do_write, impl().shared_from_this())); + auto const result = w.prepare(65536, std::bind(&BaseWSPeer::do_write, impl().shared_from_this())); if (boost::indeterminate(result.first)) return; start_timer(); @@ -314,22 +280,13 @@ BaseWSPeer::on_write(error_code const& ec) impl().ws_.async_write_some( static_cast(result.first), result.second, - bind_executor( - strand_, - std::bind( - &BaseWSPeer::on_write, - impl().shared_from_this(), - std::placeholders::_1))); + bind_executor(strand_, std::bind(&BaseWSPeer::on_write, impl().shared_from_this(), std::placeholders::_1))); else impl().ws_.async_write_some( static_cast(result.first), result.second, bind_executor( - strand_, - std::bind( - &BaseWSPeer::on_write_fin, - impl().shared_from_this(), - std::placeholders::_1))); + strand_, std::bind(&BaseWSPeer::on_write_fin, impl().shared_from_this(), std::placeholders::_1))); } template @@ -343,12 +300,7 @@ BaseWSPeer::on_write_fin(error_code const& ec) { impl().ws_.async_close( cr_, - bind_executor( - strand_, - std::bind( - &BaseWSPeer::on_close, - impl().shared_from_this(), - std::placeholders::_1))); + bind_executor(strand_, std::bind(&BaseWSPeer::on_close, impl().shared_from_this(), std::placeholders::_1))); } else if (!wq_.empty()) on_write({}); @@ -359,17 +311,9 @@ void BaseWSPeer::do_read() { if (!strand_.running_in_this_thread()) - return post( - strand_, - std::bind(&BaseWSPeer::do_read, impl().shared_from_this())); + return post(strand_, std::bind(&BaseWSPeer::do_read, impl().shared_from_this())); impl().ws_.async_read( - rb_, - bind_executor( - strand_, - std::bind( - &BaseWSPeer::on_read, - impl().shared_from_this(), - std::placeholders::_1))); + rb_, bind_executor(strand_, std::bind(&BaseWSPeer::on_read, impl().shared_from_this(), std::placeholders::_1))); } template @@ -405,8 +349,7 @@ BaseWSPeer::start_timer() try { - timer_.expires_after( - remote_endpoint().address().is_loopback() ? timeoutLocal : timeout); + timer_.expires_after(remote_endpoint().address().is_loopback() ? timeoutLocal : timeout); } catch (boost::system::system_error const& e) { @@ -414,11 +357,7 @@ BaseWSPeer::start_timer() } timer_.async_wait(bind_executor( - strand_, - std::bind( - &BaseWSPeer::on_timer, - impl().shared_from_this(), - std::placeholders::_1))); + strand_, std::bind(&BaseWSPeer::on_timer, impl().shared_from_this(), std::placeholders::_1))); } // Convenience for discarding the error code @@ -450,9 +389,7 @@ BaseWSPeer::on_ping(error_code const& ec) template void -BaseWSPeer::on_ping_pong( - boost::beast::websocket::frame_type kind, - boost::beast::string_view payload) +BaseWSPeer::on_ping_pong(boost::beast::websocket::frame_type kind, boost::beast::string_view payload) { if (kind == boost::beast::websocket::frame_type::pong) { @@ -487,16 +424,11 @@ BaseWSPeer::on_timer(error_code ec) impl().ws_.async_ping( payload_, bind_executor( - strand_, - std::bind( - &BaseWSPeer::on_ping, - impl().shared_from_this(), - std::placeholders::_1))); + strand_, std::bind(&BaseWSPeer::on_ping, impl().shared_from_this(), std::placeholders::_1))); JLOG(this->j_.trace()) << "sent ping"; return; } - ec = boost::system::errc::make_error_code( - boost::system::errc::timed_out); + ec = boost::system::errc::make_error_code(boost::system::errc::timed_out); } fail(ec, "timer"); } @@ -506,9 +438,7 @@ template void BaseWSPeer::fail(error_code ec, String const& what) { - XRPL_ASSERT( - strand_.running_in_this_thread(), - "xrpl::BaseWSPeer::fail : strand in this thread"); + XRPL_ASSERT(strand_.running_in_this_thread(), "xrpl::BaseWSPeer::fail : strand in this thread"); cancel_timer(); if (!ec_ && ec != boost::asio::error::operation_aborted) @@ -520,5 +450,3 @@ BaseWSPeer::fail(error_code ec, String const& what) } } // namespace xrpl - -#endif diff --git a/include/xrpl/server/detail/Door.h b/include/xrpl/server/detail/Door.h index 140afb1808..e41049f203 100644 --- a/include/xrpl/server/detail/Door.h +++ b/include/xrpl/server/detail/Door.h @@ -1,5 +1,4 @@ -#ifndef XRPL_SERVER_DOOR_H_INCLUDED -#define XRPL_SERVER_DOOR_H_INCLUDED +#pragma once #include #include @@ -39,8 +38,7 @@ namespace xrpl { /** A listening socket. */ template -class Door : public io_list::work, - public std::enable_shared_from_this> +class Door : public io_list::work, public std::enable_shared_from_this> { private: using clock_type = std::chrono::steady_clock; @@ -54,8 +52,7 @@ private: using stream_type = boost::beast::tcp_stream; // Detects SSL on a socket - class Detector : public io_list::work, - public std::enable_shared_from_this + class Detector : public io_list::work, public std::enable_shared_from_this { private: Port const& port_; @@ -115,11 +112,7 @@ private: should_throttle_for_fds(); public: - Door( - Handler& handler, - boost::asio::io_context& io_context, - Port const& port, - beast::Journal j); + Door(Handler& handler, boost::asio::io_context& io_context, Port const& port, beast::Journal j); // Work-around because we can't call shared_from_this in ctor void @@ -143,11 +136,7 @@ public: private: template void - create( - bool ssl, - ConstBufferSequence const& buffers, - stream_type&& stream, - endpoint_type remote_address); + create(bool ssl, ConstBufferSequence const& buffers, stream_type&& stream, endpoint_type remote_address); void do_accept(yield_context yield); @@ -176,12 +165,7 @@ template void Door::Detector::run() { - util::spawn( - strand_, - std::bind( - &Detector::do_detect, - this->shared_from_this(), - std::placeholders::_1)); + util::spawn(strand_, std::bind(&Detector::do_detect, this->shared_from_this(), std::placeholders::_1)); } template @@ -205,31 +189,18 @@ Door::Detector::do_detect(boost::asio::yield_context do_yield) if (ssl) { if (auto sp = ios().template emplace>( - port_, - handler_, - ioc_, - j_, - remote_address_, - buf.data(), - std::move(stream_))) + port_, handler_, ioc_, j_, remote_address_, buf.data(), std::move(stream_))) sp->run(); return; } if (auto sp = ios().template emplace>( - port_, - handler_, - ioc_, - j_, - remote_address_, - buf.data(), - std::move(stream_))) + port_, handler_, ioc_, j_, remote_address_, buf.data(), std::move(stream_))) sp->run(); return; } if (ec != boost::asio::error::operation_aborted) { - JLOG(j_.trace()) << "Error detecting ssl: " << ec.message() << " from " - << remote_address_; + JLOG(j_.trace()) << "Error detecting ssl: " << ec.message() << " from " << remote_address_; } } @@ -247,8 +218,7 @@ Door::reOpen() if (ec) { std::stringstream ss; - ss << "Can't close acceptor: " << port_.name << ", " - << ec.message(); + ss << "Can't close acceptor: " << port_.name << ", " << ec.message(); JLOG(j_.error()) << ss.str(); Throw(ss.str()); } @@ -259,33 +229,28 @@ Door::reOpen() acceptor_.open(local_address.protocol(), ec); if (ec) { - JLOG(j_.error()) << "Open port '" << port_.name - << "' failed:" << ec.message(); + JLOG(j_.error()) << "Open port '" << port_.name << "' failed:" << ec.message(); Throw(); } - acceptor_.set_option( - boost::asio::ip::tcp::acceptor::reuse_address(true), ec); + acceptor_.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true), ec); if (ec) { - JLOG(j_.error()) << "Option for port '" << port_.name - << "' failed:" << ec.message(); + JLOG(j_.error()) << "Option for port '" << port_.name << "' failed:" << ec.message(); Throw(); } acceptor_.bind(local_address, ec); if (ec) { - JLOG(j_.error()) << "Bind port '" << port_.name - << "' failed:" << ec.message(); + JLOG(j_.error()) << "Bind port '" << port_.name << "' failed:" << ec.message(); Throw(); } acceptor_.listen(boost::asio::socket_base::max_listen_connections, ec); if (ec) { - JLOG(j_.error()) << "Listen on port '" << port_.name - << "' failed:" << ec.message(); + JLOG(j_.error()) << "Listen on port '" << port_.name << "' failed:" << ec.message(); Throw(); } @@ -293,11 +258,7 @@ Door::reOpen() } template -Door::Door( - Handler& handler, - boost::asio::io_context& io_context, - Port const& port, - beast::Journal j) +Door::Door(Handler& handler, boost::asio::io_context& io_context, Port const& port, beast::Journal j) : j_(j) , port_(port) , handler_(handler) @@ -305,12 +266,9 @@ Door::Door( , acceptor_(io_context) , strand_(boost::asio::make_strand(io_context)) , ssl_( - port_.protocol.count("https") > 0 || - port_.protocol.count("wss") > 0 || port_.protocol.count("wss2") > 0 || + port_.protocol.count("https") > 0 || port_.protocol.count("wss") > 0 || port_.protocol.count("wss2") > 0 || port_.protocol.count("peer") > 0) - , plain_( - port_.protocol.count("http") > 0 || port_.protocol.count("ws") > 0 || - port_.protocol.count("ws2")) + , plain_(port_.protocol.count("http") > 0 || port_.protocol.count("ws") > 0 || port_.protocol.count("ws2")) , backoff_timer_(io_context) { reOpen(); @@ -320,12 +278,7 @@ template void Door::run() { - util::spawn( - strand_, - std::bind( - &Door::do_accept, - this->shared_from_this(), - std::placeholders::_1)); + util::spawn(strand_, std::bind(&Door::do_accept, this->shared_from_this(), std::placeholders::_1)); } template @@ -333,9 +286,7 @@ void Door::close() { if (!strand_.running_in_this_thread()) - return boost::asio::post( - strand_, - std::bind(&Door::close, this->shared_from_this())); + return boost::asio::post(strand_, std::bind(&Door::close, this->shared_from_this())); backoff_timer_.cancel(); error_code ec; acceptor_.close(ec); @@ -346,33 +297,17 @@ Door::close() template template void -Door::create( - bool ssl, - ConstBufferSequence const& buffers, - stream_type&& stream, - endpoint_type remote_address) +Door::create(bool ssl, ConstBufferSequence const& buffers, stream_type&& stream, endpoint_type remote_address) { if (ssl) { if (auto sp = ios().template emplace>( - port_, - handler_, - ioc_, - j_, - remote_address, - buffers, - std::move(stream))) + port_, handler_, ioc_, j_, remote_address, buffers, std::move(stream))) sp->run(); return; } if (auto sp = ios().template emplace>( - port_, - handler_, - ioc_, - j_, - remote_address, - buffers, - std::move(stream))) + port_, handler_, ioc_, j_, remote_address, buffers, std::move(stream))) sp->run(); } @@ -388,8 +323,7 @@ Door::do_accept(boost::asio::yield_context do_yield) boost::system::error_code tec; backoff_timer_.async_wait(do_yield[tec]); accept_delay_ = std::min(accept_delay_ * 2, MAX_ACCEPT_DELAY); - JLOG(j_.warn()) << "Throttling do_accept for " - << accept_delay_.count() << "ms."; + JLOG(j_.warn()) << "Throttling do_accept for " << accept_delay_.count() << "ms."; continue; } @@ -403,11 +337,9 @@ Door::do_accept(boost::asio::yield_context do_yield) if (ec == boost::asio::error::operation_aborted) break; - if (ec == boost::asio::error::no_descriptors || - ec == boost::asio::error::no_buffer_space) + if (ec == boost::asio::error::no_descriptors || ec == boost::asio::error::no_buffer_space) { - JLOG(j_.warn()) << "accept: Too many open files. Pausing for " - << accept_delay_.count() << "ms."; + JLOG(j_.warn()) << "accept: Too many open files. Pausing for " << accept_delay_.count() << "ms."; backoff_timer_.expires_after(accept_delay_); boost::system::error_code tec; @@ -426,22 +358,13 @@ Door::do_accept(boost::asio::yield_context do_yield) if (ssl_ && plain_) { - if (auto sp = ios().template emplace( - port_, - handler_, - ioc_, - std::move(stream), - remote_address, - j_)) + if (auto sp = + ios().template emplace(port_, handler_, ioc_, std::move(stream), remote_address, j_)) sp->run(); } else if (ssl_ || plain_) { - create( - ssl_, - boost::asio::null_buffers{}, - std::move(stream), - remote_address); + create(ssl_, boost::asio::null_buffers{}, std::move(stream), remote_address); } } } @@ -490,8 +413,7 @@ Door::should_throttle_for_fds() auto const& s = *stats; auto const free = (s.limit > s.used) ? (s.limit - s.used) : 0ull; - double const free_ratio = - static_cast(free) / static_cast(s.limit); + double const free_ratio = static_cast(free) / static_cast(s.limit); if (free_ratio < FREE_FD_THRESHOLD) { return true; @@ -501,5 +423,3 @@ Door::should_throttle_for_fds() } } // namespace xrpl - -#endif diff --git a/include/xrpl/server/detail/JSONRPCUtil.h b/include/xrpl/server/detail/JSONRPCUtil.h index d75825a1ea..934085f8e6 100644 --- a/include/xrpl/server/detail/JSONRPCUtil.h +++ b/include/xrpl/server/detail/JSONRPCUtil.h @@ -1,5 +1,4 @@ -#ifndef XRPL_SERVER_JSONRPCUTIL_H_INCLUDED -#define XRPL_SERVER_JSONRPCUTIL_H_INCLUDED +#pragma once #include #include @@ -8,12 +7,6 @@ namespace xrpl { void -HTTPReply( - int nStatus, - std::string const& strMsg, - Json::Output const&, - beast::Journal j); +HTTPReply(int nStatus, std::string const& strMsg, Json::Output const&, beast::Journal j); } // namespace xrpl - -#endif diff --git a/include/xrpl/server/detail/LowestLayer.h b/include/xrpl/server/detail/LowestLayer.h index c45d948241..b8b0d46180 100644 --- a/include/xrpl/server/detail/LowestLayer.h +++ b/include/xrpl/server/detail/LowestLayer.h @@ -1,5 +1,4 @@ -#ifndef XRPL_SERVER_LOWESTLAYER_H_INCLUDED -#define XRPL_SERVER_LOWESTLAYER_H_INCLUDED +#pragma once #if BOOST_VERSION >= 107000 #include @@ -22,5 +21,3 @@ get_lowest_layer(T& t) noexcept } } // namespace xrpl - -#endif diff --git a/include/xrpl/server/detail/PlainHTTPPeer.h b/include/xrpl/server/detail/PlainHTTPPeer.h index 8f7d86f8e5..94c84336f9 100644 --- a/include/xrpl/server/detail/PlainHTTPPeer.h +++ b/include/xrpl/server/detail/PlainHTTPPeer.h @@ -1,5 +1,4 @@ -#ifndef XRPL_SERVER_PLAINHTTPPEER_H_INCLUDED -#define XRPL_SERVER_PLAINHTTPPEER_H_INCLUDED +#pragma once #include #include @@ -12,9 +11,8 @@ namespace xrpl { template -class PlainHTTPPeer - : public BaseHTTPPeer>, - public std::enable_shared_from_this> +class PlainHTTPPeer : public BaseHTTPPeer>, + public std::enable_shared_from_this> { private: friend class BaseHTTPPeer; @@ -62,13 +60,7 @@ PlainHTTPPeer::PlainHTTPPeer( endpoint_type remote_endpoint, ConstBufferSequence const& buffers, stream_type&& stream) - : BaseHTTPPeer( - port, - handler, - ioc.get_executor(), - journal, - remote_endpoint, - buffers) + : BaseHTTPPeer(port, handler, ioc.get_executor(), journal, remote_endpoint, buffers) , stream_(std::move(stream)) , socket_(stream_.socket()) { @@ -86,21 +78,14 @@ PlainHTTPPeer::run() { if (!this->handler_.onAccept(this->session(), this->remote_address_)) { - util::spawn( - this->strand_, - std::bind(&PlainHTTPPeer::do_close, this->shared_from_this())); + util::spawn(this->strand_, std::bind(&PlainHTTPPeer::do_close, this->shared_from_this())); return; } if (!socket_.is_open()) return; - util::spawn( - this->strand_, - std::bind( - &PlainHTTPPeer::do_read, - this->shared_from_this(), - std::placeholders::_1)); + util::spawn(this->strand_, std::bind(&PlainHTTPPeer::do_read, this->shared_from_this(), std::placeholders::_1)); } template @@ -122,8 +107,7 @@ void PlainHTTPPeer::do_request() { ++this->request_count_; - auto const what = this->handler_.onHandoff( - this->session(), std::move(this->message_), this->remote_address_); + auto const what = this->handler_.onHandoff(this->session(), std::move(this->message_), this->remote_address_); if (what.moved) return; boost::system::error_code ec; @@ -155,5 +139,3 @@ PlainHTTPPeer::do_close() } } // namespace xrpl - -#endif diff --git a/include/xrpl/server/detail/PlainWSPeer.h b/include/xrpl/server/detail/PlainWSPeer.h index 4d5c57533b..9196d5ea49 100644 --- a/include/xrpl/server/detail/PlainWSPeer.h +++ b/include/xrpl/server/detail/PlainWSPeer.h @@ -1,5 +1,4 @@ -#ifndef XRPL_SERVER_PLAINWSPEER_H_INCLUDED -#define XRPL_SERVER_PLAINWSPEER_H_INCLUDED +#pragma once #include @@ -59,5 +58,3 @@ PlainWSPeer::PlainWSPeer( } } // namespace xrpl - -#endif diff --git a/include/xrpl/server/detail/SSLHTTPPeer.h b/include/xrpl/server/detail/SSLHTTPPeer.h index 56b2d1c52f..138145544e 100644 --- a/include/xrpl/server/detail/SSLHTTPPeer.h +++ b/include/xrpl/server/detail/SSLHTTPPeer.h @@ -1,5 +1,4 @@ -#ifndef XRPL_SERVER_SSLHTTPPEER_H_INCLUDED -#define XRPL_SERVER_SSLHTTPPEER_H_INCLUDED +#pragma once #include #include @@ -74,16 +73,8 @@ SSLHTTPPeer::SSLHTTPPeer( endpoint_type remote_address, ConstBufferSequence const& buffers, middle_type&& stream) - : BaseHTTPPeer( - port, - handler, - ioc.get_executor(), - journal, - remote_address, - buffers) - , stream_ptr_(std::make_unique( - middle_type(std::move(stream)), - *port.context)) + : BaseHTTPPeer(port, handler, ioc.get_executor(), journal, remote_address, buffers) + , stream_ptr_(std::make_unique(middle_type(std::move(stream)), *port.context)) , stream_(*stream_ptr_) , socket_(stream_.next_layer().socket()) { @@ -96,19 +87,12 @@ SSLHTTPPeer::run() { if (!this->handler_.onAccept(this->session(), this->remote_address_)) { - util::spawn( - this->strand_, - std::bind(&SSLHTTPPeer::do_close, this->shared_from_this())); + util::spawn(this->strand_, std::bind(&SSLHTTPPeer::do_close, this->shared_from_this())); return; } if (!socket_.is_open()) return; - util::spawn( - this->strand_, - std::bind( - &SSLHTTPPeer::do_handshake, - this->shared_from_this(), - std::placeholders::_1)); + util::spawn(this->strand_, std::bind(&SSLHTTPPeer::do_handshake, this->shared_from_this(), std::placeholders::_1)); } template @@ -132,25 +116,17 @@ SSLHTTPPeer::do_handshake(yield_context do_yield) boost::system::error_code ec; stream_.set_verify_mode(boost::asio::ssl::verify_none); this->start_timer(); - this->read_buf_.consume(stream_.async_handshake( - stream_type::server, this->read_buf_.data(), do_yield[ec])); + this->read_buf_.consume(stream_.async_handshake(stream_type::server, this->read_buf_.data(), do_yield[ec])); this->cancel_timer(); if (ec == boost::beast::error::timeout) return this->on_timer(); if (ec) return this->fail(ec, "handshake"); - bool const http = this->port().protocol.count("peer") > 0 || - this->port().protocol.count("wss") > 0 || - this->port().protocol.count("wss2") > 0 || - this->port().protocol.count("https") > 0; + bool const http = this->port().protocol.count("peer") > 0 || this->port().protocol.count("wss") > 0 || + this->port().protocol.count("wss2") > 0 || this->port().protocol.count("https") > 0; if (http) { - util::spawn( - this->strand_, - std::bind( - &SSLHTTPPeer::do_read, - this->shared_from_this(), - std::placeholders::_1)); + util::spawn(this->strand_, std::bind(&SSLHTTPPeer::do_read, this->shared_from_this(), std::placeholders::_1)); return; } // `this` will be destroyed @@ -162,10 +138,7 @@ SSLHTTPPeer::do_request() { ++this->request_count_; auto const what = this->handler_.onHandoff( - this->session(), - std::move(stream_ptr_), - std::move(this->message_), - this->remote_address_); + this->session(), std::move(stream_ptr_), std::move(this->message_), this->remote_address_); if (what.moved) return; if (what.response) @@ -180,11 +153,7 @@ SSLHTTPPeer::do_close() { this->start_timer(); stream_.async_shutdown(bind_executor( - this->strand_, - std::bind( - &SSLHTTPPeer::on_shutdown, - this->shared_from_this(), - std::placeholders::_1))); + this->strand_, std::bind(&SSLHTTPPeer::on_shutdown, this->shared_from_this(), std::placeholders::_1))); } template @@ -205,5 +174,3 @@ SSLHTTPPeer::on_shutdown(error_code ec) } } // namespace xrpl - -#endif diff --git a/include/xrpl/server/detail/SSLWSPeer.h b/include/xrpl/server/detail/SSLWSPeer.h index bb5da1c6e7..b80312e55f 100644 --- a/include/xrpl/server/detail/SSLWSPeer.h +++ b/include/xrpl/server/detail/SSLWSPeer.h @@ -1,5 +1,4 @@ -#ifndef XRPL_SERVER_SSLWSPEER_H_INCLUDED -#define XRPL_SERVER_SSLWSPEER_H_INCLUDED +#pragma once #include #include @@ -68,5 +67,3 @@ SSLWSPeer::SSLWSPeer( } } // namespace xrpl - -#endif diff --git a/include/xrpl/server/detail/ServerImpl.h b/include/xrpl/server/detail/ServerImpl.h index 6ff93e83cb..e836b964d2 100644 --- a/include/xrpl/server/detail/ServerImpl.h +++ b/include/xrpl/server/detail/ServerImpl.h @@ -1,5 +1,4 @@ -#ifndef XRPL_SERVER_SERVERIMPL_H_INCLUDED -#define XRPL_SERVER_SERVERIMPL_H_INCLUDED +#pragma once #include #include @@ -18,8 +17,7 @@ namespace xrpl { -using Endpoints = - std::unordered_map; +using Endpoints = std::unordered_map; /** A multi-protocol server. @@ -70,9 +68,7 @@ private: beast::Journal const j_; boost::asio::io_context& io_context_; boost::asio::strand strand_; - std::optional> - work_; + std::optional> work_; std::mutex m_; std::vector ports_; @@ -83,10 +79,7 @@ private: io_list ios_; public: - ServerImpl( - Handler& handler, - boost::asio::io_context& io_context, - beast::Journal journal); + ServerImpl(Handler& handler, boost::asio::io_context& io_context, beast::Journal journal); ~ServerImpl(); @@ -123,10 +116,7 @@ private: }; template -ServerImpl::ServerImpl( - Handler& handler, - boost::asio::io_context& io_context, - beast::Journal journal) +ServerImpl::ServerImpl(Handler& handler, boost::asio::io_context& io_context, beast::Journal journal) : handler_(handler) , j_(journal) , io_context_(io_context) @@ -157,8 +147,7 @@ ServerImpl::ports(std::vector const& ports) { ports_.push_back(port); auto& internalPort = ports_.back(); - if (auto sp = ios_.emplace>( - handler_, io_context_, internalPort, j_)) + if (auto sp = ios_.emplace>(handler_, io_context_, internalPort, j_)) { list_.push_back(sp); @@ -190,5 +179,3 @@ ServerImpl::closed() return ios_.closed(); } } // namespace xrpl - -#endif diff --git a/include/xrpl/server/detail/Spawn.h b/include/xrpl/server/detail/Spawn.h index 4c424a1956..d94fb4fa05 100644 --- a/include/xrpl/server/detail/Spawn.h +++ b/include/xrpl/server/detail/Spawn.h @@ -1,5 +1,4 @@ -#ifndef XRPL_SERVER_SPAWN_H_INCLUDED -#define XRPL_SERVER_SPAWN_H_INCLUDED +#pragma once #include @@ -13,9 +12,7 @@ namespace xrpl::util { namespace impl { template -concept IsStrand = std::same_as< - std::decay_t, - boost::asio::strand::inner_executor_type>>; +concept IsStrand = std::same_as, boost::asio::strand::inner_executor_type>>; /** * @brief A completion handler that restores `boost::asio::spawn`'s behaviour @@ -69,21 +66,15 @@ spawn(Ctx&& ctx, F&& func) { if constexpr (impl::IsStrand) { - boost::asio::spawn( - std::forward(ctx), - std::forward(func), - impl::kPROPAGATE_EXCEPTIONS); + boost::asio::spawn(std::forward(ctx), std::forward(func), impl::kPROPAGATE_EXCEPTIONS); } else { boost::asio::spawn( - boost::asio::make_strand( - boost::asio::get_associated_executor(std::forward(ctx))), + boost::asio::make_strand(boost::asio::get_associated_executor(std::forward(ctx))), std::forward(func), impl::kPROPAGATE_EXCEPTIONS); } } } // namespace xrpl::util - -#endif diff --git a/include/xrpl/server/detail/io_list.h b/include/xrpl/server/detail/io_list.h index 0e67595dbe..5b1a02e039 100644 --- a/include/xrpl/server/detail/io_list.h +++ b/include/xrpl/server/detail/io_list.h @@ -1,5 +1,4 @@ -#ifndef XRPL_SERVER_IO_LIST_H_INCLUDED -#define XRPL_SERVER_IO_LIST_H_INCLUDED +#pragma once #include @@ -190,8 +189,7 @@ template std::shared_ptr io_list::emplace(Args&&... args) { - static_assert( - std::is_base_of::value, "T must derive from io_list::work"); + static_assert(std::is_base_of::value, "T must derive from io_list::work"); if (closed_) return nullptr; auto sp = std::make_shared(std::forward(args)...); @@ -244,5 +242,3 @@ io_list::join() } } // namespace xrpl - -#endif diff --git a/include/xrpl/shamap/Family.h b/include/xrpl/shamap/Family.h index 6638d67df8..73887fb2dc 100644 --- a/include/xrpl/shamap/Family.h +++ b/include/xrpl/shamap/Family.h @@ -1,5 +1,4 @@ -#ifndef XRPL_SHAMAP_FAMILY_H_INCLUDED -#define XRPL_SHAMAP_FAMILY_H_INCLUDED +#pragma once #include #include @@ -66,5 +65,3 @@ public: }; } // namespace xrpl - -#endif diff --git a/include/xrpl/shamap/FullBelowCache.h b/include/xrpl/shamap/FullBelowCache.h index 9434b40011..6a6da1463a 100644 --- a/include/xrpl/shamap/FullBelowCache.h +++ b/include/xrpl/shamap/FullBelowCache.h @@ -1,5 +1,4 @@ -#ifndef XRPL_SHAMAP_FULLBELOWCACHE_H_INCLUDED -#define XRPL_SHAMAP_FULLBELOWCACHE_H_INCLUDED +#pragma once #include #include @@ -39,8 +38,7 @@ public: std::string const& name, clock_type& clock, beast::Journal j, - beast::insight::Collector::ptr const& collector = - beast::insight::NullCollector::New(), + beast::insight::Collector::ptr const& collector = beast::insight::NullCollector::New(), std::size_t target_size = defaultCacheTargetSize, std::chrono::seconds expiration = std::chrono::minutes{2}) : m_cache(name, target_size, expiration, clock, j, collector), m_gen(1) @@ -130,5 +128,3 @@ private: using FullBelowCache = detail::BasicFullBelowCache; } // namespace xrpl - -#endif diff --git a/include/xrpl/shamap/SHAMap.h b/include/xrpl/shamap/SHAMap.h index 94fd926718..cd084ab48b 100644 --- a/include/xrpl/shamap/SHAMap.h +++ b/include/xrpl/shamap/SHAMap.h @@ -1,5 +1,4 @@ -#ifndef XRPL_SHAMAP_SHAMAP_H_INCLUDED -#define XRPL_SHAMAP_SHAMAP_H_INCLUDED +#pragma once #include #include @@ -95,15 +94,12 @@ private: public: /** Number of children each non-leaf node has (the 'radix tree' part of the * map) */ - static inline constexpr unsigned int branchFactor = - SHAMapInnerNode::branchFactor; + static inline constexpr unsigned int branchFactor = SHAMapInnerNode::branchFactor; /** The depth of the hash map: data is only present in the leaves */ static inline constexpr unsigned int leafDepth = 64; - using DeltaItem = std::pair< - boost::intrusive_ptr, - boost::intrusive_ptr>; + using DeltaItem = std::pair, boost::intrusive_ptr>; using Delta = std::map; SHAMap() = delete; @@ -183,14 +179,10 @@ public: // save a copy if you have a temporary anyway bool - updateGiveItem( - SHAMapNodeType type, - boost::intrusive_ptr item); + updateGiveItem(SHAMapNodeType type, boost::intrusive_ptr item); bool - addGiveItem( - SHAMapNodeType type, - boost::intrusive_ptr item); + addGiveItem(SHAMapNodeType type, boost::intrusive_ptr item); // Save a copy if you need to extend the life // of the SHAMapItem beyond this SHAMap @@ -233,18 +225,14 @@ public: If function returns false, visitDifferences exits. */ void - visitDifferences( - SHAMap const* have, - std::function const&) const; + visitDifferences(SHAMap const* have, std::function const&) const; /** Visit every leaf node in this SHAMap @param function called with every non inner node visited. */ void - visitLeaves( - std::function< - void(boost::intrusive_ptr const&)> const&) const; + visitLeaves(std::function const&)> const&) const; // comparison/sync functions @@ -285,25 +273,16 @@ public: * @return true if verified successfully */ static bool - verifyProofPath( - uint256 const& rootHash, - uint256 const& key, - std::vector const& path); + verifyProofPath(uint256 const& rootHash, uint256 const& key, std::vector const& path); /** Serializes the root in a format appropriate for sending over the wire */ void serializeRoot(Serializer& s) const; SHAMapAddNode - addRootNode( - SHAMapHash const& hash, - Slice const& rootNode, - SHAMapSyncFilter* filter); + addRootNode(SHAMapHash const& hash, Slice const& rootNode, SHAMapSyncFilter* filter); SHAMapAddNode - addKnownNode( - SHAMapNodeID const& nodeID, - Slice const& rawNode, - SHAMapSyncFilter* filter); + addKnownNode(SHAMapNodeID const& nodeID, Slice const& rawNode, SHAMapSyncFilter* filter); // status functions void @@ -333,9 +312,7 @@ public: void walkMap(std::vector& missingNodes, int maxMissing) const; bool - walkMapParallel( - std::vector& missingNodes, - int maxMissing) const; + walkMapParallel(std::vector& missingNodes, int maxMissing) const; bool deepCompare(SHAMap& other) const; // Intended for debug/test only @@ -348,19 +325,15 @@ public: invariants() const; private: - using SharedPtrNodeStack = std::stack< - std::pair, SHAMapNodeID>>; - using DeltaRef = std::pair< - boost::intrusive_ptr, - boost::intrusive_ptr>; + using SharedPtrNodeStack = std::stack, SHAMapNodeID>>; + using DeltaRef = std::pair, boost::intrusive_ptr>; // tree node cache operations intr_ptr::SharedPtr cacheLookup(SHAMapHash const& hash) const; void - canonicalize(SHAMapHash const& hash, intr_ptr::SharedPtr&) - const; + canonicalize(SHAMapHash const& hash, intr_ptr::SharedPtr&) const; // database operations intr_ptr::SharedPtr @@ -376,17 +349,13 @@ private: /** Update hashes up to the root */ void - dirtyUp( - SharedPtrNodeStack& stack, - uint256 const& target, - intr_ptr::SharedPtr terminal); + dirtyUp(SharedPtrNodeStack& stack, uint256 const& target, intr_ptr::SharedPtr terminal); /** Walk towards the specified id, returning the node. Caller must check if the return is nullptr, and if not, if the node->peekItem()->key() == id */ SHAMapLeafNode* - walkTowardsKey(uint256 const& id, SharedPtrNodeStack* stack = nullptr) - const; + walkTowardsKey(uint256 const& id, SharedPtrNodeStack* stack = nullptr) const; /** Return nullptr if key not found */ SHAMapLeafNode* findKey(uint256 const& id) const; @@ -407,17 +376,11 @@ private: // returns the first item at or below this node SHAMapLeafNode* - firstBelow( - intr_ptr::SharedPtr, - SharedPtrNodeStack& stack, - int branch = 0) const; + firstBelow(intr_ptr::SharedPtr, SharedPtrNodeStack& stack, int branch = 0) const; // returns the last item at or below this node SHAMapLeafNode* - lastBelow( - intr_ptr::SharedPtr node, - SharedPtrNodeStack& stack, - int branch = branchFactor) const; + lastBelow(intr_ptr::SharedPtr node, SharedPtrNodeStack& stack, int branch = branchFactor) const; // helper function for firstBelow and lastBelow SHAMapLeafNode* @@ -425,10 +388,7 @@ private: intr_ptr::SharedPtr node, SharedPtrNodeStack& stack, int branch, - std::tuple< - int, - std::function, - std::function> const& loopParams) const; + std::tuple, std::function> const& loopParams) const; // Simple descent // Get a child of the specified node @@ -443,22 +403,12 @@ private: // Descend with filter // If pending, callback is called as if it called fetchNodeNT - using descendCallback = std::function< - void(intr_ptr::SharedPtr, SHAMapHash const&)>; + using descendCallback = std::function, SHAMapHash const&)>; SHAMapTreeNode* - descendAsync( - SHAMapInnerNode* parent, - int branch, - SHAMapSyncFilter* filter, - bool& pending, - descendCallback&&) const; + descendAsync(SHAMapInnerNode* parent, int branch, SHAMapSyncFilter* filter, bool& pending, descendCallback&&) const; std::pair - descend( - SHAMapInnerNode* parent, - SHAMapNodeID const& parentID, - int branch, - SHAMapSyncFilter* filter) const; + descend(SHAMapInnerNode* parent, SHAMapNodeID const& parentID, int branch, SHAMapSyncFilter* filter) const; // Non-storing // Does not hook the returned node to its parent @@ -538,16 +488,8 @@ private: // reads std::map resumes_; - MissingNodes( - int max, - SHAMapSyncFilter* filter, - int maxDefer, - std::uint32_t generation) - : max_(max) - , filter_(filter) - , maxDefer_(maxDefer) - , generation_(generation) - , deferred_(0) + MissingNodes(int max, SHAMapSyncFilter* filter, int maxDefer, std::uint32_t generation) + : max_(max), filter_(filter), maxDefer_(maxDefer), generation_(generation), deferred_(0) { missingNodes_.reserve(max); finishedReads_.reserve(maxDefer); @@ -562,9 +504,7 @@ private: // fetch from DB helper function intr_ptr::SharedPtr - finishFetch( - SHAMapHash const& hash, - std::shared_ptr const& object) const; + finishFetch(SHAMapHash const& hash, std::shared_ptr const& object) const; }; inline void @@ -582,9 +522,7 @@ SHAMap::setLedgerSeq(std::uint32_t lseq) inline void SHAMap::setImmutable() { - XRPL_ASSERT( - state_ != SHAMapState::Invalid, - "xrpl::SHAMap::setImmutable : state is valid"); + XRPL_ASSERT(state_ != SHAMapState::Invalid, "xrpl::SHAMap::setImmutable : state is valid"); state_ = SHAMapState::Immutable; } @@ -665,22 +603,17 @@ private: inline SHAMap::const_iterator::const_iterator(SHAMap const* map) : map_(map) { - XRPL_ASSERT( - map_, "xrpl::SHAMap::const_iterator::const_iterator : non-null input"); + XRPL_ASSERT(map_, "xrpl::SHAMap::const_iterator::const_iterator : non-null input"); if (auto temp = map_->peekFirstItem(stack_)) item_ = temp->peekItem().get(); } -inline SHAMap::const_iterator::const_iterator(SHAMap const* map, std::nullptr_t) - : map_(map) +inline SHAMap::const_iterator::const_iterator(SHAMap const* map, std::nullptr_t) : map_(map) { } -inline SHAMap::const_iterator::const_iterator( - SHAMap const* map, - pointer item, - SharedPtrNodeStack&& stack) +inline SHAMap::const_iterator::const_iterator(SHAMap const* map, pointer item, SharedPtrNodeStack&& stack) : stack_(std::move(stack)), map_(map), item_(item) { } @@ -744,5 +677,3 @@ SHAMap::end() const } } // namespace xrpl - -#endif diff --git a/include/xrpl/shamap/SHAMapAccountStateLeafNode.h b/include/xrpl/shamap/SHAMapAccountStateLeafNode.h index 288fc416b5..552d2b4692 100644 --- a/include/xrpl/shamap/SHAMapAccountStateLeafNode.h +++ b/include/xrpl/shamap/SHAMapAccountStateLeafNode.h @@ -1,5 +1,4 @@ -#ifndef XRPL_SHAMAP_SHAMAPACCOUNTSTATELEAFNODE_H_INCLUDED -#define XRPL_SHAMAP_SHAMAPACCOUNTSTATELEAFNODE_H_INCLUDED +#pragma once #include #include @@ -10,23 +9,16 @@ namespace xrpl { /** A leaf node for a state object. */ -class SHAMapAccountStateLeafNode final - : public SHAMapLeafNode, - public CountedObject +class SHAMapAccountStateLeafNode final : public SHAMapLeafNode, public CountedObject { public: - SHAMapAccountStateLeafNode( - boost::intrusive_ptr item, - std::uint32_t cowid) + SHAMapAccountStateLeafNode(boost::intrusive_ptr item, std::uint32_t cowid) : SHAMapLeafNode(std::move(item), cowid) { updateHash(); } - SHAMapAccountStateLeafNode( - boost::intrusive_ptr item, - std::uint32_t cowid, - SHAMapHash const& hash) + SHAMapAccountStateLeafNode(boost::intrusive_ptr item, std::uint32_t cowid, SHAMapHash const& hash) : SHAMapLeafNode(std::move(item), cowid, hash) { } @@ -34,8 +26,7 @@ public: intr_ptr::SharedPtr clone(std::uint32_t cowid) const final override { - return intr_ptr::make_shared( - item_, cowid, hash_); + return intr_ptr::make_shared(item_, cowid, hash_); } SHAMapNodeType @@ -47,8 +38,7 @@ public: void updateHash() final override { - hash_ = SHAMapHash{ - sha512Half(HashPrefix::leafNode, item_->slice(), item_->key())}; + hash_ = SHAMapHash{sha512Half(HashPrefix::leafNode, item_->slice(), item_->key())}; } void @@ -69,5 +59,3 @@ public: }; } // namespace xrpl - -#endif diff --git a/include/xrpl/shamap/SHAMapAddNode.h b/include/xrpl/shamap/SHAMapAddNode.h index 0385f64f52..7d0aaf3be4 100644 --- a/include/xrpl/shamap/SHAMapAddNode.h +++ b/include/xrpl/shamap/SHAMapAddNode.h @@ -1,5 +1,4 @@ -#ifndef XRPL_SHAMAP_SHAMAPADDNODE_H_INCLUDED -#define XRPL_SHAMAP_SHAMAPADDNODE_H_INCLUDED +#pragma once #include @@ -52,8 +51,7 @@ inline SHAMapAddNode::SHAMapAddNode() : mGood(0), mBad(0), mDuplicate(0) { } -inline SHAMapAddNode::SHAMapAddNode(int good, int bad, int duplicate) - : mGood(good), mBad(bad), mDuplicate(duplicate) +inline SHAMapAddNode::SHAMapAddNode(int good, int bad, int duplicate) : mGood(good), mBad(bad), mDuplicate(duplicate) { } @@ -162,5 +160,3 @@ SHAMapAddNode::get() const } } // namespace xrpl - -#endif diff --git a/include/xrpl/shamap/SHAMapInnerNode.h b/include/xrpl/shamap/SHAMapInnerNode.h index 72a7fe52d4..73d59cc1fe 100644 --- a/include/xrpl/shamap/SHAMapInnerNode.h +++ b/include/xrpl/shamap/SHAMapInnerNode.h @@ -1,5 +1,4 @@ -#ifndef XRPL_SHAMAP_SHAMAPINNERNODE_H_INCLUDED -#define XRPL_SHAMAP_SHAMAPINNERNODE_H_INCLUDED +#pragma once #include #include @@ -12,8 +11,7 @@ namespace xrpl { -class SHAMapInnerNode final : public SHAMapTreeNode, - public CountedObject +class SHAMapInnerNode final : public SHAMapTreeNode, public CountedObject { public: /** Each inner node has 16 children (the 'radix tree' part of the map) */ @@ -78,9 +76,7 @@ private: iterNonEmptyChildIndexes(F&& f) const; public: - explicit SHAMapInnerNode( - std::uint32_t cowid, - std::uint8_t numAllocatedChildren = 2); + explicit SHAMapInnerNode(std::uint32_t cowid, std::uint8_t numAllocatedChildren = 2); SHAMapInnerNode(SHAMapInnerNode const&) = delete; SHAMapInnerNode& @@ -203,4 +199,3 @@ SHAMapInnerNode::setFullBelowGen(std::uint32_t gen) } } // namespace xrpl -#endif diff --git a/include/xrpl/shamap/SHAMapItem.h b/include/xrpl/shamap/SHAMapItem.h index e8d95b0684..ab9cf74dc8 100644 --- a/include/xrpl/shamap/SHAMapItem.h +++ b/include/xrpl/shamap/SHAMapItem.h @@ -1,5 +1,4 @@ -#ifndef XRPL_SHAMAP_SHAMAPITEM_H_INCLUDED -#define XRPL_SHAMAP_SHAMAPITEM_H_INCLUDED +#pragma once #include #include @@ -43,13 +42,9 @@ private: // the only way to properly create one is to first allocate enough memory // so we limit this constructor to codepaths that do this right and limit // arbitrary construction. - SHAMapItem(uint256 const& tag, Slice data) - : tag_(tag), size_(static_cast(data.size())) + SHAMapItem(uint256 const& tag, Slice data) : tag_(tag), size_(static_cast(data.size())) { - std::memcpy( - reinterpret_cast(this) + sizeof(*this), - data.data(), - data.size()); + std::memcpy(reinterpret_cast(this) + sizeof(*this), data.data(), data.size()); } public: @@ -141,9 +136,7 @@ intrusive_ptr_release(SHAMapItem const* x) inline boost::intrusive_ptr make_shamapitem(uint256 const& tag, Slice data) { - XRPL_ASSERT( - data.size() <= megabytes(16), - "xrpl::make_shamapitem : maximum input size"); + XRPL_ASSERT(data.size() <= megabytes(16), "xrpl::make_shamapitem : maximum input size"); std::uint8_t* raw = detail::slabber.allocate(data.size()); @@ -169,5 +162,3 @@ make_shamapitem(SHAMapItem const& other) } } // namespace xrpl - -#endif diff --git a/include/xrpl/shamap/SHAMapLeafNode.h b/include/xrpl/shamap/SHAMapLeafNode.h index d87ede16ad..aedcb3b79c 100644 --- a/include/xrpl/shamap/SHAMapLeafNode.h +++ b/include/xrpl/shamap/SHAMapLeafNode.h @@ -1,5 +1,4 @@ -#ifndef XRPL_SHAMAP_SHAMAPLEAFNODE_H_INCLUDED -#define XRPL_SHAMAP_SHAMAPLEAFNODE_H_INCLUDED +#pragma once #include #include @@ -13,14 +12,9 @@ class SHAMapLeafNode : public SHAMapTreeNode protected: boost::intrusive_ptr item_; - SHAMapLeafNode( - boost::intrusive_ptr item, - std::uint32_t cowid); + SHAMapLeafNode(boost::intrusive_ptr item, std::uint32_t cowid); - SHAMapLeafNode( - boost::intrusive_ptr item, - std::uint32_t cowid, - SHAMapHash const& hash); + SHAMapLeafNode(boost::intrusive_ptr item, std::uint32_t cowid, SHAMapHash const& hash); public: SHAMapLeafNode(SHAMapLeafNode const&) = delete; @@ -60,5 +54,3 @@ public: }; } // namespace xrpl - -#endif diff --git a/include/xrpl/shamap/SHAMapMissingNode.h b/include/xrpl/shamap/SHAMapMissingNode.h index 0cb18238af..f1670587eb 100644 --- a/include/xrpl/shamap/SHAMapMissingNode.h +++ b/include/xrpl/shamap/SHAMapMissingNode.h @@ -1,5 +1,4 @@ -#ifndef XRPL_SHAMAP_SHAMAPMISSINGNODE_H_INCLUDED -#define XRPL_SHAMAP_SHAMAPMISSINGNODE_H_INCLUDED +#pragma once #include #include @@ -29,8 +28,7 @@ to_string(SHAMapType t) case SHAMapType::FREE: return "Free Tree"; default: - return std::to_string( - safe_cast>(t)); + return std::to_string(safe_cast>(t)); } } @@ -38,18 +36,14 @@ class SHAMapMissingNode : public std::runtime_error { public: SHAMapMissingNode(SHAMapType t, SHAMapHash const& hash) - : std::runtime_error( - "Missing Node: " + to_string(t) + ": hash " + to_string(hash)) + : std::runtime_error("Missing Node: " + to_string(t) + ": hash " + to_string(hash)) { } SHAMapMissingNode(SHAMapType t, uint256 const& id) - : std::runtime_error( - "Missing Node: " + to_string(t) + ": id " + to_string(id)) + : std::runtime_error("Missing Node: " + to_string(t) + ": id " + to_string(id)) { } }; } // namespace xrpl - -#endif diff --git a/include/xrpl/shamap/SHAMapNodeID.h b/include/xrpl/shamap/SHAMapNodeID.h index 2a9e4446f4..3517246f90 100644 --- a/include/xrpl/shamap/SHAMapNodeID.h +++ b/include/xrpl/shamap/SHAMapNodeID.h @@ -1,5 +1,4 @@ -#ifndef XRPL_SHAMAP_SHAMAPNODEID_H_INCLUDED -#define XRPL_SHAMAP_SHAMAPNODEID_H_INCLUDED +#pragma once #include #include @@ -106,8 +105,7 @@ to_string(SHAMapNodeID const& node) if (node.isRoot()) return "NodeID(root)"; - return "NodeID(" + std::to_string(node.getDepth()) + "," + - to_string(node.getNodeID()) + ")"; + return "NodeID(" + std::to_string(node.getDepth()) + "," + to_string(node.getNodeID()) + ")"; } inline std::ostream& @@ -140,5 +138,3 @@ deserializeSHAMapNodeID(std::string const& s) selectBranch(SHAMapNodeID const& id, uint256 const& hash); } // namespace xrpl - -#endif diff --git a/include/xrpl/shamap/SHAMapSyncFilter.h b/include/xrpl/shamap/SHAMapSyncFilter.h index 16b2389745..219f9ac558 100644 --- a/include/xrpl/shamap/SHAMapSyncFilter.h +++ b/include/xrpl/shamap/SHAMapSyncFilter.h @@ -1,5 +1,4 @@ -#ifndef XRPL_SHAMAP_SHAMAPSYNCFILTER_H_INCLUDED -#define XRPL_SHAMAP_SHAMAPSYNCFILTER_H_INCLUDED +#pragma once #include @@ -19,17 +18,11 @@ public: // Note that the nodeData is overwritten by this call virtual void - gotNode( - bool fromFilter, - SHAMapHash const& nodeHash, - std::uint32_t ledgerSeq, - Blob&& nodeData, - SHAMapNodeType type) const = 0; + gotNode(bool fromFilter, SHAMapHash const& nodeHash, std::uint32_t ledgerSeq, Blob&& nodeData, SHAMapNodeType type) + const = 0; virtual std::optional getNode(SHAMapHash const& nodeHash) const = 0; }; } // namespace xrpl - -#endif diff --git a/include/xrpl/shamap/SHAMapTreeNode.h b/include/xrpl/shamap/SHAMapTreeNode.h index 75992a9bce..668f658754 100644 --- a/include/xrpl/shamap/SHAMapTreeNode.h +++ b/include/xrpl/shamap/SHAMapTreeNode.h @@ -1,5 +1,4 @@ -#ifndef XRPL_SHAMAP_SHAMAPTREENODE_H_INCLUDED -#define XRPL_SHAMAP_SHAMAPTREENODE_H_INCLUDED +#pragma once #include #include @@ -56,10 +55,7 @@ protected: { } - explicit SHAMapTreeNode( - std::uint32_t cowid, - SHAMapHash const& hash) noexcept - : hash_(hash), cowid_(cowid) + explicit SHAMapTreeNode(std::uint32_t cowid, SHAMapHash const& hash) noexcept : hash_(hash), cowid_(cowid) { } /** @} */ @@ -171,5 +167,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/include/xrpl/shamap/SHAMapTxLeafNode.h b/include/xrpl/shamap/SHAMapTxLeafNode.h index e7b73ecde9..0a44380b9b 100644 --- a/include/xrpl/shamap/SHAMapTxLeafNode.h +++ b/include/xrpl/shamap/SHAMapTxLeafNode.h @@ -1,5 +1,4 @@ -#ifndef XRPL_SHAMAP_SHAMAPTXLEAFNODE_H_INCLUDED -#define XRPL_SHAMAP_SHAMAPTXLEAFNODE_H_INCLUDED +#pragma once #include #include @@ -10,22 +9,16 @@ namespace xrpl { /** A leaf node for a transaction. No metadata is included. */ -class SHAMapTxLeafNode final : public SHAMapLeafNode, - public CountedObject +class SHAMapTxLeafNode final : public SHAMapLeafNode, public CountedObject { public: - SHAMapTxLeafNode( - boost::intrusive_ptr item, - std::uint32_t cowid) + SHAMapTxLeafNode(boost::intrusive_ptr item, std::uint32_t cowid) : SHAMapLeafNode(std::move(item), cowid) { updateHash(); } - SHAMapTxLeafNode( - boost::intrusive_ptr item, - std::uint32_t cowid, - SHAMapHash const& hash) + SHAMapTxLeafNode(boost::intrusive_ptr item, std::uint32_t cowid, SHAMapHash const& hash) : SHAMapLeafNode(std::move(item), cowid, hash) { } @@ -45,8 +38,7 @@ public: void updateHash() final override { - hash_ = - SHAMapHash{sha512Half(HashPrefix::transactionID, item_->slice())}; + hash_ = SHAMapHash{sha512Half(HashPrefix::transactionID, item_->slice())}; } void @@ -65,5 +57,3 @@ public: }; } // namespace xrpl - -#endif diff --git a/include/xrpl/shamap/SHAMapTxPlusMetaLeafNode.h b/include/xrpl/shamap/SHAMapTxPlusMetaLeafNode.h index c38277ef73..d11cc87ff7 100644 --- a/include/xrpl/shamap/SHAMapTxPlusMetaLeafNode.h +++ b/include/xrpl/shamap/SHAMapTxPlusMetaLeafNode.h @@ -1,5 +1,4 @@ -#ifndef XRPL_SHAMAP_SHAMAPLEAFTXPLUSMETANODE_H_INCLUDED -#define XRPL_SHAMAP_SHAMAPLEAFTXPLUSMETANODE_H_INCLUDED +#pragma once #include #include @@ -10,23 +9,16 @@ namespace xrpl { /** A leaf node for a transaction and its associated metadata. */ -class SHAMapTxPlusMetaLeafNode final - : public SHAMapLeafNode, - public CountedObject +class SHAMapTxPlusMetaLeafNode final : public SHAMapLeafNode, public CountedObject { public: - SHAMapTxPlusMetaLeafNode( - boost::intrusive_ptr item, - std::uint32_t cowid) + SHAMapTxPlusMetaLeafNode(boost::intrusive_ptr item, std::uint32_t cowid) : SHAMapLeafNode(std::move(item), cowid) { updateHash(); } - SHAMapTxPlusMetaLeafNode( - boost::intrusive_ptr item, - std::uint32_t cowid, - SHAMapHash const& hash) + SHAMapTxPlusMetaLeafNode(boost::intrusive_ptr item, std::uint32_t cowid, SHAMapHash const& hash) : SHAMapLeafNode(std::move(item), cowid, hash) { } @@ -34,8 +26,7 @@ public: intr_ptr::SharedPtr clone(std::uint32_t cowid) const override { - return intr_ptr::make_shared( - item_, cowid, hash_); + return intr_ptr::make_shared(item_, cowid, hash_); } SHAMapNodeType @@ -47,8 +38,7 @@ public: void updateHash() final override { - hash_ = SHAMapHash{ - sha512Half(HashPrefix::txNode, item_->slice(), item_->key())}; + hash_ = SHAMapHash{sha512Half(HashPrefix::txNode, item_->slice(), item_->key())}; } void @@ -69,5 +59,3 @@ public: }; } // namespace xrpl - -#endif diff --git a/include/xrpl/shamap/TreeNodeCache.h b/include/xrpl/shamap/TreeNodeCache.h index bf9797c745..4edb6348ec 100644 --- a/include/xrpl/shamap/TreeNodeCache.h +++ b/include/xrpl/shamap/TreeNodeCache.h @@ -1,5 +1,4 @@ -#ifndef XRPL_SHAMAP_TREENODECACHE_H_INCLUDED -#define XRPL_SHAMAP_TREENODECACHE_H_INCLUDED +#pragma once #include #include @@ -14,5 +13,3 @@ using TreeNodeCache = TaggedCache< intr_ptr::SharedWeakUnionPtr, intr_ptr::SharedPtr>; } // namespace xrpl - -#endif diff --git a/include/xrpl/shamap/detail/TaggedPointer.h b/include/xrpl/shamap/detail/TaggedPointer.h index 53a53960d4..217cd93d0a 100644 --- a/include/xrpl/shamap/detail/TaggedPointer.h +++ b/include/xrpl/shamap/detail/TaggedPointer.h @@ -1,5 +1,4 @@ -#ifndef XRPL_SHAMAP_TAGGEDPOINTER_H_INCLUDED -#define XRPL_SHAMAP_TAGGEDPOINTER_H_INCLUDED +#pragma once #include #include @@ -40,9 +39,7 @@ namespace xrpl { class TaggedPointer { private: - static_assert( - alignof(SHAMapHash) >= 4, - "Bad alignment: Tag pointer requires low two bits to be zero."); + static_assert(alignof(SHAMapHash) >= 4, "Bad alignment: Tag pointer requires low two bits to be zero."); /** Upper bits are the pointer, lowest two bits are the tag A moved-from object will have a tp_ of zero. */ @@ -92,10 +89,7 @@ public: @param toAllocate allocate space for at least this number of children (must be <= branchFactor) */ - explicit TaggedPointer( - TaggedPointer&& other, - std::uint16_t isBranch, - std::uint8_t toAllocate); + explicit TaggedPointer(TaggedPointer&& other, std::uint16_t isBranch, std::uint8_t toAllocate); /** Given `other` with the specified children in `srcBranches`, create a new TaggedPointer with the allocated number of children and the @@ -152,9 +146,8 @@ public: /** Get the number of elements in each array and a pointer to the start of each array. */ - [[nodiscard]] std:: - tuple*> - getHashesAndChildren() const; + [[nodiscard]] std::tuple*> + getHashesAndChildren() const; /** Get the `hashes` array */ [[nodiscard]] SHAMapHash* @@ -227,5 +220,3 @@ popcnt16(std::uint16_t a) } } // namespace xrpl - -#endif diff --git a/include/xrpl/shamap/detail/TaggedPointer.ipp b/include/xrpl/shamap/detail/TaggedPointer.ipp index e88b4b11c4..bedb33a733 100644 --- a/include/xrpl/shamap/detail/TaggedPointer.ipp +++ b/include/xrpl/shamap/detail/TaggedPointer.ipp @@ -13,11 +13,7 @@ namespace { // Given n children, an array of size `*std::lower_bound(boundaries.begin(), // boundaries.end(), n);` is used to store the children. Note that the last // element must be the number of children in a dense array. -constexpr std::array boundaries{ - 2, - 4, - 6, - SHAMapInnerNode::branchFactor}; +constexpr std::array boundaries{2, 4, 6, SHAMapInnerNode::branchFactor}; static_assert( boundaries.size() <= 4, "The hashesAndChildren member uses a tagged array format with two bits " @@ -29,8 +25,7 @@ static_assert( // Terminology: A chunk is the memory being allocated from a block. A block // contains multiple chunks. This is the terminology the boost documentation // uses. Pools use "Simple Segregated Storage" as their storage format. -constexpr size_t elementSizeBytes = - (sizeof(SHAMapHash) + sizeof(intr_ptr::SharedPtr)); +constexpr size_t elementSizeBytes = (sizeof(SHAMapHash) + sizeof(intr_ptr::SharedPtr)); constexpr size_t blockSizeBytes = kilobytes(512); @@ -42,8 +37,7 @@ initArrayChunkSizeBytes(std::index_sequence) boundaries[I] * elementSizeBytes..., }; } -constexpr auto arrayChunkSizeBytes = - initArrayChunkSizeBytes(std::make_index_sequence{}); +constexpr auto arrayChunkSizeBytes = initArrayChunkSizeBytes(std::make_index_sequence{}); template constexpr std::array @@ -53,27 +47,20 @@ initArrayChunksPerBlock(std::index_sequence) blockSizeBytes / arrayChunkSizeBytes[I]..., }; } -constexpr auto chunksPerBlock = - initArrayChunksPerBlock(std::make_index_sequence{}); +constexpr auto chunksPerBlock = initArrayChunksPerBlock(std::make_index_sequence{}); [[nodiscard]] inline std::uint8_t numAllocatedChildren(std::uint8_t n) { - XRPL_ASSERT( - n <= SHAMapInnerNode::branchFactor, - "xrpl::numAllocatedChildren : valid input"); + XRPL_ASSERT(n <= SHAMapInnerNode::branchFactor, "xrpl::numAllocatedChildren : valid input"); return *std::lower_bound(boundaries.begin(), boundaries.end(), n); } [[nodiscard]] inline std::size_t boundariesIndex(std::uint8_t numChildren) { - XRPL_ASSERT( - numChildren <= SHAMapInnerNode::branchFactor, - "xrpl::boundariesIndex : valid input"); - return std::distance( - boundaries.begin(), - std::lower_bound(boundaries.begin(), boundaries.end(), numChildren)); + XRPL_ASSERT(numChildren <= SHAMapInnerNode::branchFactor, "xrpl::boundariesIndex : valid input"); + return std::distance(boundaries.begin(), std::lower_bound(boundaries.begin(), boundaries.end(), numChildren)); } template @@ -124,9 +111,8 @@ initIsFromArrayFuns(std::index_sequence) chunksPerBlock[I]>::is_from..., }; } -std::array, boundaries.size()> const - isFromArrayFuns = - initIsFromArrayFuns(std::make_index_sequence{}); +std::array, boundaries.size()> const isFromArrayFuns = + initIsFromArrayFuns(std::make_index_sequence{}); // This function returns an untagged pointer [[nodiscard]] inline std::pair @@ -140,9 +126,7 @@ allocateArrays(std::uint8_t numChildren) inline void deallocateArrays(std::uint8_t boundaryIndex, void* p) { - XRPL_ASSERT( - isFromArrayFuns[boundaryIndex](p), - "xrpl::deallocateArrays : valid inputs"); + XRPL_ASSERT(isFromArrayFuns[boundaryIndex](p), "xrpl::deallocateArrays : valid inputs"); freeArrayFuns[boundaryIndex](p); } @@ -261,8 +245,7 @@ inline TaggedPointer::TaggedPointer(RawAllocateTag, std::uint8_t numChildren) "xrpl::TaggedPointer::TaggedPointer(RawAllocateTag, std::uint8_t) : " "maximum tag"); XRPL_ASSERT( - (reinterpret_cast(p) & ptrMask) == - reinterpret_cast(p), + (reinterpret_cast(p) & ptrMask) == reinterpret_cast(p), "xrpl::TaggedPointer::TaggedPointer(RawAllocateTag, std::uint8_t) : " "valid pointer"); tp_ = reinterpret_cast(p) + tag; @@ -283,8 +266,7 @@ inline TaggedPointer::TaggedPointer( { // in place *this = std::move(other); - auto [srcDstNumAllocated, srcDstHashes, srcDstChildren] = - getHashesAndChildren(); + auto [srcDstNumAllocated, srcDstHashes, srcDstChildren] = getHashesAndChildren(); bool const srcDstIsDense = isDense(); int srcDstIndex = 0; for (int i = 0; i < SHAMapInnerNode::branchFactor; ++i) @@ -358,13 +340,11 @@ inline TaggedPointer::TaggedPointer( { // not in place TaggedPointer dst{RawAllocateTag{}, toAllocate}; - auto [dstNumAllocated, dstHashes, dstChildren] = - dst.getHashesAndChildren(); + auto [dstNumAllocated, dstHashes, dstChildren] = dst.getHashesAndChildren(); // Move `other` into a local var so it's not in a partially moved from // state after this function runs TaggedPointer src(std::move(other)); - auto [srcNumAllocated, srcHashes, srcChildren] = - src.getHashesAndChildren(); + auto [srcNumAllocated, srcHashes, srcChildren] = src.getHashesAndChildren(); bool const srcIsDense = src.isDense(); bool const dstIsDense = dst.isDense(); int srcIndex = 0, dstIndex = 0; @@ -378,9 +358,7 @@ inline TaggedPointer::TaggedPointer( // keep new (&dstHashes[dstIndex]) SHAMapHash{srcHashes[srcIndex]}; - new (&dstChildren[dstIndex]) - intr_ptr::SharedPtr{ - std::move(srcChildren[srcIndex])}; + new (&dstChildren[dstIndex]) intr_ptr::SharedPtr{std::move(srcChildren[srcIndex])}; ++dstIndex; ++srcIndex; } @@ -391,8 +369,7 @@ inline TaggedPointer::TaggedPointer( if (dstIsDense) { new (&dstHashes[dstIndex]) SHAMapHash{}; - new (&dstChildren[dstIndex]) - intr_ptr::SharedPtr{}; + new (&dstChildren[dstIndex]) intr_ptr::SharedPtr{}; ++dstIndex; } } @@ -400,8 +377,7 @@ inline TaggedPointer::TaggedPointer( { // add new (&dstHashes[dstIndex]) SHAMapHash{}; - new (&dstChildren[dstIndex]) - intr_ptr::SharedPtr{}; + new (&dstChildren[dstIndex]) intr_ptr::SharedPtr{}; ++dstIndex; if (srcIsDense) { @@ -414,8 +390,7 @@ inline TaggedPointer::TaggedPointer( if (dstIsDense) { new (&dstHashes[dstIndex]) SHAMapHash{}; - new (&dstChildren[dstIndex]) - intr_ptr::SharedPtr{}; + new (&dstChildren[dstIndex]) intr_ptr::SharedPtr{}; ++dstIndex; } if (srcIsDense) @@ -438,10 +413,7 @@ inline TaggedPointer::TaggedPointer( } } -inline TaggedPointer::TaggedPointer( - TaggedPointer&& other, - std::uint16_t isBranch, - std::uint8_t toAllocate) +inline TaggedPointer::TaggedPointer(TaggedPointer&& other, std::uint16_t isBranch, std::uint8_t toAllocate) : TaggedPointer(std::move(other)) { auto const oldNumAllocated = capacity(); @@ -455,8 +427,7 @@ inline TaggedPointer::TaggedPointer( intr_ptr::SharedPtr*newChildren, *oldChildren; std::uint8_t newNumAllocated; // structured bindings can't be captured in c++ 17; use tie instead - std::tie(newNumAllocated, newHashes, newChildren) = - newHashesAndChildren.getHashesAndChildren(); + std::tie(newNumAllocated, newHashes, newChildren) = newHashesAndChildren.getHashesAndChildren(); std::tie(std::ignore, oldHashes, oldChildren) = getHashesAndChildren(); if (newNumAllocated == SHAMapInnerNode::branchFactor) @@ -464,8 +435,7 @@ inline TaggedPointer::TaggedPointer( // new arrays are dense, old arrays are sparse iterNonEmptyChildIndexes(isBranch, [&](auto branchNum, auto indexNum) { new (&newHashes[branchNum]) SHAMapHash{oldHashes[indexNum]}; - new (&newChildren[branchNum]) intr_ptr::SharedPtr{ - std::move(oldChildren[indexNum])}; + new (&newChildren[branchNum]) intr_ptr::SharedPtr{std::move(oldChildren[indexNum])}; }); // Run the constructors for the remaining elements for (int i = 0; i < SHAMapInnerNode::branchFactor; ++i) @@ -481,11 +451,9 @@ inline TaggedPointer::TaggedPointer( // new arrays are sparse, old arrays may be sparse or dense int curCompressedIndex = 0; iterNonEmptyChildIndexes(isBranch, [&](auto branchNum, auto indexNum) { - new (&newHashes[curCompressedIndex]) - SHAMapHash{oldHashes[indexNum]}; + new (&newHashes[curCompressedIndex]) SHAMapHash{oldHashes[indexNum]}; new (&newChildren[curCompressedIndex]) - intr_ptr::SharedPtr{ - std::move(oldChildren[indexNum])}; + intr_ptr::SharedPtr{std::move(oldChildren[indexNum])}; ++curCompressedIndex; }); // Run the constructors for the remaining elements @@ -544,16 +512,13 @@ TaggedPointer::isDense() const return (tp_ & tagMask) == boundaries.size() - 1; } -[[nodiscard]] inline std:: - tuple*> - TaggedPointer::getHashesAndChildren() const +[[nodiscard]] inline std::tuple*> +TaggedPointer::getHashesAndChildren() const { auto const [tag, ptr] = decode(); auto const hashes = reinterpret_cast(ptr); std::uint8_t numAllocated = boundaries[tag]; - auto const children = - reinterpret_cast*>( - hashes + numAllocated); + auto const children = reinterpret_cast*>(hashes + numAllocated); return {numAllocated, hashes, children}; }; diff --git a/src/libxrpl/basics/Archive.cpp b/src/libxrpl/basics/Archive.cpp index 8ee23afda0..a4100e8196 100644 --- a/src/libxrpl/basics/Archive.cpp +++ b/src/libxrpl/basics/Archive.cpp @@ -14,17 +14,13 @@ namespace xrpl { void -extractTarLz4( - boost::filesystem::path const& src, - boost::filesystem::path const& dst) +extractTarLz4(boost::filesystem::path const& src, boost::filesystem::path const& dst) { if (!is_regular_file(src)) Throw("Invalid source file"); - using archive_ptr = - std::unique_ptr; - archive_ptr ar{ - archive_read_new(), [](struct archive* a) { archive_read_free(a); }}; + using archive_ptr = std::unique_ptr; + archive_ptr ar{archive_read_new(), [](struct archive* a) { archive_read_free(a); }}; if (!ar) Throw("Failed to allocate archive"); @@ -35,22 +31,18 @@ extractTarLz4( Throw(archive_error_string(ar.get())); // Examples suggest this block size - if (archive_read_open_filename(ar.get(), src.string().c_str(), 10240) < - ARCHIVE_OK) + if (archive_read_open_filename(ar.get(), src.string().c_str(), 10240) < ARCHIVE_OK) { Throw(archive_error_string(ar.get())); } - archive_ptr aw{archive_write_disk_new(), [](struct archive* a) { - archive_write_free(a); - }}; + archive_ptr aw{archive_write_disk_new(), [](struct archive* a) { archive_write_free(a); }}; if (!aw) Throw("Failed to allocate archive"); if (archive_write_disk_set_options( - aw.get(), - ARCHIVE_EXTRACT_TIME | ARCHIVE_EXTRACT_PERM | ARCHIVE_EXTRACT_ACL | - ARCHIVE_EXTRACT_FFLAGS) < ARCHIVE_OK) + aw.get(), ARCHIVE_EXTRACT_TIME | ARCHIVE_EXTRACT_PERM | ARCHIVE_EXTRACT_ACL | ARCHIVE_EXTRACT_FFLAGS) < + ARCHIVE_OK) { Throw(archive_error_string(aw.get())); } @@ -68,8 +60,7 @@ extractTarLz4( if (result < ARCHIVE_OK) Throw(archive_error_string(ar.get())); - archive_entry_set_pathname( - entry, (dst / archive_entry_pathname(entry)).string().c_str()); + archive_entry_set_pathname(entry, (dst / archive_entry_pathname(entry)).string().c_str()); if (archive_write_header(aw.get(), entry) < ARCHIVE_OK) Throw(archive_error_string(aw.get())); @@ -86,8 +77,7 @@ extractTarLz4( if (result < ARCHIVE_OK) Throw(archive_error_string(ar.get())); - if (archive_write_data_block(aw.get(), buf, sz, offset) < - ARCHIVE_OK) + if (archive_write_data_block(aw.get(), buf, sz, offset) < ARCHIVE_OK) { Throw(archive_error_string(aw.get())); } diff --git a/src/libxrpl/basics/BasicConfig.cpp b/src/libxrpl/basics/BasicConfig.cpp index a5ad7730dd..64e80c63ec 100644 --- a/src/libxrpl/basics/BasicConfig.cpp +++ b/src/libxrpl/basics/BasicConfig.cpp @@ -130,15 +130,9 @@ BasicConfig::section(std::string const& name) const } void -BasicConfig::overwrite( - std::string const& section, - std::string const& key, - std::string const& value) +BasicConfig::overwrite(std::string const& section, std::string const& key, std::string const& value) { - auto const result = map_.emplace( - std::piecewise_construct, - std::make_tuple(section), - std::make_tuple(section)); + auto const result = map_.emplace(std::piecewise_construct, std::make_tuple(section), std::make_tuple(section)); result.first->second.set(key, value); } @@ -167,10 +161,8 @@ BasicConfig::build(IniFileSections const& ifs) { for (auto const& entry : ifs) { - auto const result = map_.emplace( - std::piecewise_construct, - std::make_tuple(entry.first), - std::make_tuple(entry.first)); + auto const result = + map_.emplace(std::piecewise_construct, std::make_tuple(entry.first), std::make_tuple(entry.first)); result.first->second.append(entry.second); } } diff --git a/src/libxrpl/basics/FileUtilities.cpp b/src/libxrpl/basics/FileUtilities.cpp index 981fdd5360..35cc4350ef 100644 --- a/src/libxrpl/basics/FileUtilities.cpp +++ b/src/libxrpl/basics/FileUtilities.cpp @@ -45,9 +45,7 @@ getFileContents( return {}; } - std::string const result{ - std::istreambuf_iterator{fileStream}, - std::istreambuf_iterator{}}; + std::string const result{std::istreambuf_iterator{fileStream}, std::istreambuf_iterator{}}; if (fileStream.bad()) { @@ -59,16 +57,12 @@ getFileContents( } void -writeFileContents( - boost::system::error_code& ec, - boost::filesystem::path const& destPath, - std::string const& contents) +writeFileContents(boost::system::error_code& ec, boost::filesystem::path const& destPath, std::string const& contents) { using namespace boost::filesystem; using namespace boost::system::errc; - std::ofstream fileStream( - destPath.string(), std::ios::out | std::ios::trunc); + std::ofstream fileStream(destPath.string(), std::ios::out | std::ios::trunc); if (!fileStream) { diff --git a/src/libxrpl/basics/Log.cpp b/src/libxrpl/basics/Log.cpp index 33d6f6559e..fc5100a152 100644 --- a/src/libxrpl/basics/Log.cpp +++ b/src/libxrpl/basics/Log.cpp @@ -19,10 +19,7 @@ namespace xrpl { -Logs::Sink::Sink( - std::string const& partition, - beast::severities::Severity thresh, - Logs& logs) +Logs::Sink::Sink(std::string const& partition, beast::severities::Severity thresh, Logs& logs) : beast::Journal::Sink(thresh, false), logs_(logs), partition_(partition) { } @@ -37,9 +34,7 @@ Logs::Sink::write(beast::severities::Severity level, std::string const& text) } void -Logs::Sink::writeAlways( - beast::severities::Severity level, - std::string const& text) +Logs::Sink::writeAlways(beast::severities::Severity level, std::string const& text) { logs_.write(level, partition_, text, console()); } @@ -64,8 +59,7 @@ Logs::File::open(boost::filesystem::path const& path) bool wasOpened = false; // VFALCO TODO Make this work with Unicode file paths - std::unique_ptr stream( - new std::ofstream(path.c_str(), std::fstream::app)); + std::unique_ptr stream(new std::ofstream(path.c_str(), std::fstream::app)); if (stream->good()) { @@ -112,8 +106,7 @@ Logs::File::writeln(char const* text) //------------------------------------------------------------------------------ -Logs::Logs(beast::severities::Severity thresh) - : thresh_(thresh) // default severity +Logs::Logs(beast::severities::Severity thresh) : thresh_(thresh) // default severity { } @@ -170,11 +163,7 @@ Logs::partition_severities() const } void -Logs::write( - beast::severities::Severity level, - std::string const& partition, - std::string const& text, - bool console) +Logs::write(beast::severities::Severity level, std::string const& partition, std::string const& text, bool console) { std::string s; format(s, text, level, partition); @@ -297,8 +286,7 @@ Logs::fromString(std::string const& s) if (boost::iequals(s, "info") || boost::iequals(s, "information")) return lsINFO; - if (boost::iequals(s, "warn") || boost::iequals(s, "warning") || - boost::iequals(s, "warnings")) + if (boost::iequals(s, "warn") || boost::iequals(s, "warning") || boost::iequals(s, "warnings")) return lsWARNING; if (boost::iequals(s, "error") || boost::iequals(s, "errors")) diff --git a/src/libxrpl/basics/Number.cpp b/src/libxrpl/basics/Number.cpp index 436ebf6779..1651e8aba2 100644 --- a/src/libxrpl/basics/Number.cpp +++ b/src/libxrpl/basics/Number.cpp @@ -27,8 +27,7 @@ using int128_t = __int128_t; namespace xrpl { thread_local Number::rounding_mode Number::mode_ = Number::to_nearest; -thread_local std::reference_wrapper Number::range_ = - largeRange; +thread_local std::reference_wrapper Number::range_ = largeRange; Number::rounding_mode Number::getround() @@ -63,8 +62,7 @@ Number::setMantissaScale(MantissaRange::mantissa_scale scale) // to be correctly rounded to the internal precision of Number. template -concept UnsignedMantissa = - std::is_unsigned_v || std::is_same_v; +concept UnsignedMantissa = std::is_unsigned_v || std::is_same_v; class Number::Guard { @@ -114,11 +112,7 @@ public: // Modify the result to the correctly rounded value template void - doRoundDown( - bool& negative, - T& mantissa, - int& exponent, - internalrep const& minMantissa); + doRoundDown(bool& negative, T& mantissa, int& exponent, internalrep const& minMantissa); // Modify the result to the correctly rounded value void @@ -130,11 +124,7 @@ private: template void - bringIntoRange( - bool& negative, - T& mantissa, - int& exponent, - internalrep const& minMantissa); + bringIntoRange(bool& negative, T& mantissa, int& exponent, internalrep const& minMantissa); }; inline void @@ -221,11 +211,7 @@ Number::Guard::round() noexcept template void -Number::Guard::bringIntoRange( - bool& negative, - T& mantissa, - int& exponent, - internalrep const& minMantissa) +Number::Guard::bringIntoRange(bool& negative, T& mantissa, int& exponent, internalrep const& minMantissa) { // Bring mantissa back into the minMantissa / maxMantissa range AFTER // rounding @@ -273,11 +259,7 @@ Number::Guard::doRoundUp( template void -Number::Guard::doRoundDown( - bool& negative, - T& mantissa, - int& exponent, - internalrep const& minMantissa) +Number::Guard::doRoundDown(bool& negative, T& mantissa, int& exponent, internalrep const& minMantissa) { auto r = round(); if (r == 1 || (r == 0 && (mantissa & 1) == 1)) @@ -344,11 +326,7 @@ Number::externalToInternal(rep mantissa) constexpr Number Number::oneSmall() { - return Number{ - false, - Number::smallRange.min, - -Number::smallRange.log, - Number::unchecked{}}; + return Number{false, Number::smallRange.min, -Number::smallRange.log, Number::unchecked{}}; }; constexpr Number oneSml = Number::oneSmall(); @@ -356,11 +334,7 @@ constexpr Number oneSml = Number::oneSmall(); constexpr Number Number::oneLarge() { - return Number{ - false, - Number::largeRange.min, - -Number::largeRange.log, - Number::unchecked{}}; + return Number{false, Number::largeRange.min, -Number::largeRange.log, Number::unchecked{}}; }; constexpr Number oneLrg = Number::oneLarge(); @@ -449,23 +423,12 @@ doNormalize( // modification, it must be less than maxRep. In other words, the original // value should have been no more than maxRep * 10. // (maxRep * 10 > maxMantissa) - XRPL_ASSERT_PARTS( - m <= maxRep, - "xrpl::doNormalize", - "intermediate mantissa fits in int64"); + XRPL_ASSERT_PARTS(m <= maxRep, "xrpl::doNormalize", "intermediate mantissa fits in int64"); mantissa_ = m; - g.doRoundUp( - negative, - mantissa_, - exponent_, - minMantissa, - maxMantissa, - "Number::normalize 2"); + g.doRoundUp(negative, mantissa_, exponent_, minMantissa, maxMantissa, "Number::normalize 2"); XRPL_ASSERT_PARTS( - mantissa_ >= minMantissa && mantissa_ <= maxMantissa, - "xrpl::doNormalize", - "final mantissa fits in range"); + mantissa_ >= minMantissa && mantissa_ <= maxMantissa, "xrpl::doNormalize", "final mantissa fits in range"); } template <> @@ -526,10 +489,7 @@ Number::shiftExponent(int exponentDelta) const return Number{}; } Number const result{negative_, mantissa_, newExponent, unchecked{}}; - XRPL_ASSERT_PARTS( - result.isnormal(), - "xrpl::Number::shiftExponent", - "result is normalized"); + XRPL_ASSERT_PARTS(result.isnormal(), "xrpl::Number::shiftExponent", "result is normalized"); return result; } @@ -550,9 +510,7 @@ Number::operator+=(Number const& y) return *this; } - XRPL_ASSERT( - isnormal() && y.isnormal(), - "xrpl::Number::operator+=(Number) : is normal"); + XRPL_ASSERT(isnormal() && y.isnormal(), "xrpl::Number::operator+=(Number) : is normal"); // *n = negative // *s = sign // *m = mantissa @@ -604,8 +562,7 @@ Number::operator+=(Number const& y) xm /= 10; ++xe; } - g.doRoundUp( - xn, xm, xe, minMantissa, maxMantissa, "Number::addition overflow"); + g.doRoundUp(xn, xm, xe, minMantissa, maxMantissa, "Number::addition overflow"); } else { @@ -712,12 +669,7 @@ Number::operator*=(Number const& y) xm = static_cast(zm); xe = ze; g.doRoundUp( - zn, - xm, - xe, - minMantissa, - maxMantissa, - "Number::multiplication overflow : exponent is " + std::to_string(xe)); + zn, xm, xe, minMantissa, maxMantissa, "Number::multiplication overflow : exponent is " + std::to_string(xe)); negative_ = zn; mantissa_ = xm; exponent_ = xe; @@ -764,10 +716,8 @@ Number::operator/=(Number const& y) static_assert(smallRange.log == 15); static_assert(largeRange.log == 18); bool small = Number::getMantissaScale() == MantissaRange::small; - uint128_t const f = - small ? 100'000'000'000'000'000 : 10'000'000'000'000'000'000ULL; - XRPL_ASSERT_PARTS( - f >= minMantissa * 10, "Number::operator/=", "factor expected size"); + uint128_t const f = small ? 100'000'000'000'000'000 : 10'000'000'000'000'000'000ULL; + XRPL_ASSERT_PARTS(f >= minMantissa * 10, "Number::operator/=", "factor expected size"); // unsigned denominator auto const dmu = static_cast(dm); @@ -818,8 +768,7 @@ Number::operator/=(Number const& y) negative_ = zn; mantissa_ = static_cast(zm); exponent_ = ze; - XRPL_ASSERT_PARTS( - isnormal(), "xrpl::Number::operator/=", "result is normalized"); + XRPL_ASSERT_PARTS(isnormal(), "xrpl::Number::operator/=", "result is normalized"); return *this; } @@ -884,11 +833,9 @@ to_string(Number const& amount) // Use scientific notation for exponents that are too small or too large auto const rangeLog = Number::mantissaLog(); - if (((exponent != 0) && - ((exponent < -(rangeLog + 10)) || (exponent > -(rangeLog - 10))))) + if (((exponent != 0) && ((exponent < -(rangeLog + 10)) || (exponent > -(rangeLog - 10))))) { - while (mantissa != 0 && mantissa % 10 == 0 && - exponent < Number::maxExponent) + while (mantissa != 0 && mantissa % 10 == 0 && exponent < Number::maxExponent) { mantissa /= 10; ++exponent; @@ -900,8 +847,7 @@ to_string(Number const& amount) return ret; } - XRPL_ASSERT( - exponent + 43 > 0, "xrpl::to_string(Number) : minimum exponent"); + XRPL_ASSERT(exponent + 43 > 0, "xrpl::to_string(Number) : minimum exponent"); ptrdiff_t const pad_prefix = rangeLog + 12; ptrdiff_t const pad_suffix = rangeLog + 8; @@ -927,8 +873,7 @@ to_string(Number const& amount) if (std::distance(pre_from, pre_to) > pad_prefix) pre_from += pad_prefix; - XRPL_ASSERT( - post_to >= post_from, "xrpl::to_string(Number) : first distance check"); + XRPL_ASSERT(post_to >= post_from, "xrpl::to_string(Number) : first distance check"); pre_from = std::find_if(pre_from, pre_to, [](char c) { return c != '0'; }); @@ -937,15 +882,11 @@ to_string(Number const& amount) if (std::distance(post_from, post_to) > pad_suffix) post_to -= pad_suffix; - XRPL_ASSERT( - post_to >= post_from, - "xrpl::to_string(Number) : second distance check"); + XRPL_ASSERT(post_to >= post_from, "xrpl::to_string(Number) : second distance check"); - post_to = std::find_if( - std::make_reverse_iterator(post_to), - std::make_reverse_iterator(post_from), - [](char c) { return c != '0'; }) - .base(); + post_to = std::find_if(std::make_reverse_iterator(post_to), std::make_reverse_iterator(post_from), [](char c) { + return c != '0'; + }).base(); std::string ret; @@ -1028,8 +969,7 @@ root(Number f, unsigned d) e += ex; f = f.shiftExponent(-e); // f /= 10^e; - XRPL_ASSERT_PARTS( - f.isnormal(), "xrpl::root(Number, unsigned)", "f is normalized"); + XRPL_ASSERT_PARTS(f.isnormal(), "xrpl::root(Number, unsigned)", "f is normalized"); bool neg = false; if (f < zero) { @@ -1062,10 +1002,7 @@ root(Number f, unsigned d) // return r * 10^(e/d) to reverse scaling auto const result = r.shiftExponent(e / di); - XRPL_ASSERT_PARTS( - result.isnormal(), - "xrpl::root(Number, unsigned)", - "result is normalized"); + XRPL_ASSERT_PARTS(result.isnormal(), "xrpl::root(Number, unsigned)", "result is normalized"); return result; } @@ -1109,8 +1046,7 @@ root2(Number f) // return r * 10^(e/2) to reverse scaling auto const result = r.shiftExponent(e / 2); - XRPL_ASSERT_PARTS( - result.isnormal(), "xrpl::root2(Number)", "result is normalized"); + XRPL_ASSERT_PARTS(result.isnormal(), "xrpl::root2(Number)", "result is normalized"); return result; } diff --git a/src/libxrpl/basics/ResolverAsio.cpp b/src/libxrpl/basics/ResolverAsio.cpp index 8b9b2a9c4c..78346870a7 100644 --- a/src/libxrpl/basics/ResolverAsio.cpp +++ b/src/libxrpl/basics/ResolverAsio.cpp @@ -44,9 +44,7 @@ public: ~AsyncObject() { // Destroying the object with I/O pending? Not a clean exit! - XRPL_ASSERT( - m_pending.load() == 0, - "xrpl::AsyncObject::~AsyncObject : nothing pending"); + XRPL_ASSERT(m_pending.load() == 0, "xrpl::AsyncObject::~AsyncObject : nothing pending"); } /** RAII container that maintains the count of pending I/O. @@ -61,8 +59,7 @@ public: ++m_owner->m_pending; } - CompletionCounter(CompletionCounter const& other) - : m_owner(other.m_owner) + CompletionCounter(CompletionCounter const& other) : m_owner(other.m_owner) { ++m_owner->m_pending; } @@ -98,8 +95,7 @@ private: std::atomic m_pending; }; -class ResolverAsioImpl : public ResolverAsio, - public AsyncObject +class ResolverAsioImpl : public ResolverAsio, public AsyncObject { public: using HostAndPort = std::pair; @@ -124,21 +120,17 @@ public: HandlerType handler; template - Work(StringSequence const& names_, HandlerType const& handler_) - : handler(handler_) + Work(StringSequence const& names_, HandlerType const& handler_) : handler(handler_) { names.reserve(names_.size()); - std::reverse_copy( - names_.begin(), names_.end(), std::back_inserter(names)); + std::reverse_copy(names_.begin(), names_.end(), std::back_inserter(names)); } }; std::deque m_work; - ResolverAsioImpl( - boost::asio::io_context& io_context, - beast::Journal journal) + ResolverAsioImpl(boost::asio::io_context& io_context, beast::Journal journal) : m_journal(journal) , m_io_context(io_context) , m_strand(boost::asio::make_strand(io_context)) @@ -151,11 +143,8 @@ public: ~ResolverAsioImpl() override { - XRPL_ASSERT( - m_work.empty(), - "xrpl::ResolverAsioImpl::~ResolverAsioImpl : no pending work"); - XRPL_ASSERT( - m_stopped, "xrpl::ResolverAsioImpl::~ResolverAsioImpl : stopped"); + XRPL_ASSERT(m_work.empty(), "xrpl::ResolverAsioImpl::~ResolverAsioImpl : no pending work"); + XRPL_ASSERT(m_stopped, "xrpl::ResolverAsioImpl::~ResolverAsioImpl : stopped"); } //------------------------------------------------------------------------- @@ -177,11 +166,8 @@ public: void start() override { - XRPL_ASSERT( - m_stopped == true, "xrpl::ResolverAsioImpl::start : stopped"); - XRPL_ASSERT( - m_stop_called == false, - "xrpl::ResolverAsioImpl::start : not stopping"); + XRPL_ASSERT(m_stopped == true, "xrpl::ResolverAsioImpl::start : stopped"); + XRPL_ASSERT(m_stop_called == false, "xrpl::ResolverAsioImpl::start : not stopping"); if (m_stopped.exchange(false) == true) { @@ -201,11 +187,7 @@ public: boost::asio::dispatch( m_io_context, boost::asio::bind_executor( - m_strand, - std::bind( - &ResolverAsioImpl::do_stop, - this, - CompletionCounter(this)))); + m_strand, std::bind(&ResolverAsioImpl::do_stop, this, CompletionCounter(this)))); JLOG(m_journal.debug()) << "Queued a stop request"; } @@ -224,28 +206,17 @@ public: } void - resolve(std::vector const& names, HandlerType const& handler) - override + resolve(std::vector const& names, HandlerType const& handler) override { - XRPL_ASSERT( - m_stop_called == false, - "xrpl::ResolverAsioImpl::resolve : not stopping"); - XRPL_ASSERT( - !names.empty(), - "xrpl::ResolverAsioImpl::resolve : names non-empty"); + XRPL_ASSERT(m_stop_called == false, "xrpl::ResolverAsioImpl::resolve : not stopping"); + XRPL_ASSERT(!names.empty(), "xrpl::ResolverAsioImpl::resolve : names non-empty"); // TODO NIKB use rvalue references to construct and move // reducing cost. boost::asio::dispatch( m_io_context, boost::asio::bind_executor( - m_strand, - std::bind( - &ResolverAsioImpl::do_resolve, - this, - names, - handler, - CompletionCounter(this)))); + m_strand, std::bind(&ResolverAsioImpl::do_resolve, this, names, handler, CompletionCounter(this)))); } //------------------------------------------------------------------------- @@ -253,9 +224,7 @@ public: void do_stop(CompletionCounter) { - XRPL_ASSERT( - m_stop_called == true, - "xrpl::ResolverAsioImpl::do_stop : stopping"); + XRPL_ASSERT(m_stop_called == true, "xrpl::ResolverAsioImpl::do_stop : stopping"); if (m_stopped.exchange(true) == false) { @@ -286,8 +255,7 @@ public: { while (iter != results.end()) { - addresses.push_back( - beast::IPAddressConversion::from_asio(*iter)); + addresses.push_back(beast::IPAddressConversion::from_asio(*iter)); ++iter; } } @@ -296,12 +264,7 @@ public: boost::asio::post( m_io_context, - boost::asio::bind_executor( - m_strand, - std::bind( - &ResolverAsioImpl::do_work, - this, - CompletionCounter(this)))); + boost::asio::bind_executor(m_strand, std::bind(&ResolverAsioImpl::do_work, this, CompletionCounter(this)))); } HostAndPort @@ -312,8 +275,7 @@ public: if (auto const result = beast::IP::Endpoint::from_string_checked(str)) { - return make_pair( - result->address().to_string(), std::to_string(result->port())); + return make_pair(result->address().to_string(), std::to_string(result->port())); } // generic name/port parsing, which doesn't work for @@ -321,16 +283,12 @@ public: // a port separator // Attempt to find the first and last non-whitespace - auto const find_whitespace = std::bind( - &std::isspace, - std::placeholders::_1, - std::locale()); + auto const find_whitespace = + std::bind(&std::isspace, std::placeholders::_1, std::locale()); - auto host_first = - std::find_if_not(str.begin(), str.end(), find_whitespace); + auto host_first = std::find_if_not(str.begin(), str.end(), find_whitespace); - auto port_last = - std::find_if_not(str.rbegin(), str.rend(), find_whitespace).base(); + auto port_last = std::find_if_not(str.rbegin(), str.rend(), find_whitespace).base(); // This should only happen for all-whitespace strings if (host_first >= port_last) @@ -347,15 +305,11 @@ public: return false; }; - auto host_last = - std::find_if(host_first, port_last, find_port_separator); + auto host_last = std::find_if(host_first, port_last, find_port_separator); - auto port_first = - std::find_if_not(host_last, port_last, find_port_separator); + auto port_first = std::find_if_not(host_last, port_last, find_port_separator); - return make_pair( - std::string(host_first, host_last), - std::string(port_first, port_last)); + return make_pair(std::string(host_first, host_last), std::string(port_first, port_last)); } void @@ -385,11 +339,7 @@ public: boost::asio::post( m_io_context, boost::asio::bind_executor( - m_strand, - std::bind( - &ResolverAsioImpl::do_work, - this, - CompletionCounter(this)))); + m_strand, std::bind(&ResolverAsioImpl::do_work, this, CompletionCounter(this)))); return; } @@ -408,33 +358,23 @@ public: } void - do_resolve( - std::vector const& names, - HandlerType const& handler, - CompletionCounter) + do_resolve(std::vector const& names, HandlerType const& handler, CompletionCounter) { - XRPL_ASSERT( - !names.empty(), - "xrpl::ResolverAsioImpl::do_resolve : names non-empty"); + XRPL_ASSERT(!names.empty(), "xrpl::ResolverAsioImpl::do_resolve : names non-empty"); if (m_stop_called == false) { m_work.emplace_back(names, handler); - JLOG(m_journal.debug()) - << "Queued new job with " << names.size() << " tasks. " - << m_work.size() << " jobs outstanding."; + JLOG(m_journal.debug()) << "Queued new job with " << names.size() << " tasks. " << m_work.size() + << " jobs outstanding."; if (m_work.size() > 0) { boost::asio::post( m_io_context, boost::asio::bind_executor( - m_strand, - std::bind( - &ResolverAsioImpl::do_work, - this, - CompletionCounter(this)))); + m_strand, std::bind(&ResolverAsioImpl::do_work, this, CompletionCounter(this)))); } } } diff --git a/src/libxrpl/basics/base64.cpp b/src/libxrpl/basics/base64.cpp index 4a5cbacaef..3b692bc743 100644 --- a/src/libxrpl/basics/base64.cpp +++ b/src/libxrpl/basics/base64.cpp @@ -47,8 +47,7 @@ namespace base64 { inline char const* get_alphabet() { - static char constexpr tab[] = { - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"}; + static char constexpr tab[] = {"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"}; return &tab[0]; } @@ -56,38 +55,22 @@ inline signed char const* get_inverse() { static signed char constexpr tab[] = { - -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, // 0-15 - -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, // 16-31 - -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, 62, -1, -1, -1, 63, // 32-47 - 52, 53, 54, 55, 56, 57, 58, 59, - 60, 61, -1, -1, -1, -1, -1, -1, // 48-63 - -1, 0, 1, 2, 3, 4, 5, 6, - 7, 8, 9, 10, 11, 12, 13, 14, // 64-79 - 15, 16, 17, 18, 19, 20, 21, 22, - 23, 24, 25, -1, -1, -1, -1, -1, // 80-95 - -1, 26, 27, 28, 29, 30, 31, 32, - 33, 34, 35, 36, 37, 38, 39, 40, // 96-111 - 41, 42, 43, 44, 45, 46, 47, 48, - 49, 50, 51, -1, -1, -1, -1, -1, // 112-127 - -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, // 128-143 - -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, // 144-159 - -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, // 160-175 - -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, // 176-191 - -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, // 192-207 - -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, // 208-223 - -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, // 224-239 - -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1 // 240-255 + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0-15 + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 16-31 + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, // 32-47 + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, // 48-63 + -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, // 64-79 + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, // 80-95 + -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, // 96-111 + 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, // 112-127 + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 128-143 + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 144-159 + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 160-175 + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 176-191 + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 192-207 + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 208-223 + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 224-239 + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 // 240-255 }; return &tab[0]; } @@ -206,9 +189,7 @@ decode(void* dest, char const* src, std::size_t len) *out++ = c3[j]; } - return { - out - static_cast(dest), - in - reinterpret_cast(src)}; + return {out - static_cast(dest), in - reinterpret_cast(src)}; } } // namespace base64 diff --git a/src/libxrpl/basics/make_SSLContext.cpp b/src/libxrpl/basics/make_SSLContext.cpp index ef5996e051..57cbf7a24a 100644 --- a/src/libxrpl/basics/make_SSLContext.cpp +++ b/src/libxrpl/basics/make_SSLContext.cpp @@ -115,8 +115,7 @@ initAnonymous(boost::asio::ssl::context& context) // We need to up the reference count of here, since we are retaining a // copy of the key for (potential) reuse. if (RSA_up_ref(defaultRSA) != 1) - LogicError( - "EVP_PKEY_assign_RSA: incrementing reference count failed"); + LogicError("EVP_PKEY_assign_RSA: incrementing reference count failed"); if (!EVP_PKEY_assign_RSA(pkey, defaultRSA)) LogicError("EVP_PKEY_assign_RSA failed"); @@ -141,8 +140,7 @@ initAnonymous(boost::asio::ssl::context& context) auto const ts = std::time(nullptr) - (25 * 60 * 60); - int ret = std::strftime( - buf, sizeof(buf) - 1, "%y%m%d000000Z", std::gmtime(&ts)); + int ret = std::strftime(buf, sizeof(buf) - 1, "%y%m%d000000Z", std::gmtime(&ts)); buf[ret] = 0; @@ -176,32 +174,25 @@ initAnonymous(boost::asio::ssl::context& context) X509V3_set_ctx_nodb(&ctx); X509V3_set_ctx(&ctx, x509, x509, nullptr, nullptr, 0); - if (auto ext = X509V3_EXT_conf_nid( - nullptr, &ctx, NID_basic_constraints, "critical,CA:FALSE")) + if (auto ext = X509V3_EXT_conf_nid(nullptr, &ctx, NID_basic_constraints, "critical,CA:FALSE")) { X509_add_ext(x509, ext, -1); X509_EXTENSION_free(ext); } - if (auto ext = X509V3_EXT_conf_nid( - nullptr, - &ctx, - NID_ext_key_usage, - "critical,serverAuth,clientAuth")) + if (auto ext = X509V3_EXT_conf_nid(nullptr, &ctx, NID_ext_key_usage, "critical,serverAuth,clientAuth")) { X509_add_ext(x509, ext, -1); X509_EXTENSION_free(ext); } - if (auto ext = X509V3_EXT_conf_nid( - nullptr, &ctx, NID_key_usage, "critical,digitalSignature")) + if (auto ext = X509V3_EXT_conf_nid(nullptr, &ctx, NID_key_usage, "critical,digitalSignature")) { X509_add_ext(x509, ext, -1); X509_EXTENSION_free(ext); } - if (auto ext = X509V3_EXT_conf_nid( - nullptr, &ctx, NID_subject_key_identifier, "hash")) + if (auto ext = X509V3_EXT_conf_nid(nullptr, &ctx, NID_subject_key_identifier, "hash")) { X509_add_ext(x509, ext, -1); X509_EXTENSION_free(ext); @@ -245,8 +236,7 @@ initAuthenticated( { boost::system::error_code ec; - context.use_certificate_file( - cert_file, boost::asio::ssl::context::pem, ec); + context.use_certificate_file(cert_file, boost::asio::ssl::context::pem, ec); if (ec) LogicError("Problem with SSL certificate file" + fmt_error(ec)); @@ -263,8 +253,7 @@ initAuthenticated( { LogicError( "Problem opening SSL chain file" + - fmt_error(boost::system::error_code( - errno, boost::system::generic_category()))); + fmt_error(boost::system::error_code(errno, boost::system::generic_category()))); } try @@ -297,10 +286,7 @@ initAuthenticated( catch (std::exception const& ex) { fclose(f); - LogicError( - std::string( - "Reading the SSL chain file generated an exception: ") + - ex.what()); + LogicError(std::string("Reading the SSL chain file generated an exception: ") + ex.what()); } } @@ -308,13 +294,11 @@ initAuthenticated( { boost::system::error_code ec; - context.use_private_key_file( - key_file, boost::asio::ssl::context::pem, ec); + context.use_private_key_file(key_file, boost::asio::ssl::context::pem, ec); if (ec) { - LogicError( - "Problem using the SSL private key file" + fmt_error(ec)); + LogicError("Problem using the SSL private key file" + fmt_error(ec)); } } @@ -327,24 +311,18 @@ initAuthenticated( std::shared_ptr get_context(std::string cipherList) { - auto c = std::make_shared( - boost::asio::ssl::context::sslv23); + auto c = std::make_shared(boost::asio::ssl::context::sslv23); c->set_options( - boost::asio::ssl::context::default_workarounds | - boost::asio::ssl::context::no_sslv2 | - boost::asio::ssl::context::no_sslv3 | - boost::asio::ssl::context::no_tlsv1 | - boost::asio::ssl::context::no_tlsv1_1 | - boost::asio::ssl::context::single_dh_use | + boost::asio::ssl::context::default_workarounds | boost::asio::ssl::context::no_sslv2 | + boost::asio::ssl::context::no_sslv3 | boost::asio::ssl::context::no_tlsv1 | + boost::asio::ssl::context::no_tlsv1_1 | boost::asio::ssl::context::single_dh_use | boost::asio::ssl::context::no_compression); if (cipherList.empty()) cipherList = defaultCipherList; - if (auto result = - SSL_CTX_set_cipher_list(c->native_handle(), cipherList.c_str()); - result != 1) + if (auto result = SSL_CTX_set_cipher_list(c->native_handle(), cipherList.c_str()); result != 1) LogicError("SSL_CTX_set_cipher_list failed"); c->use_tmp_dh({std::addressof(detail::defaultDH), sizeof(defaultDH)}); diff --git a/src/libxrpl/beast/clock/basic_seconds_clock.cpp b/src/libxrpl/beast/clock/basic_seconds_clock.cpp index 3ab6bd72cd..27fb7b78c9 100644 --- a/src/libxrpl/beast/clock/basic_seconds_clock.cpp +++ b/src/libxrpl/beast/clock/basic_seconds_clock.cpp @@ -38,9 +38,7 @@ static_assert(std::atomic::is_always_lock_free); seconds_clock_thread::~seconds_clock_thread() { - XRPL_ASSERT( - thread_.joinable(), - "beast::seconds_clock_thread::~seconds_clock_thread : thread joinable"); + XRPL_ASSERT(thread_.joinable(), "beast::seconds_clock_thread::~seconds_clock_thread : thread joinable"); { std::lock_guard lock(mut_); stop_ = true; @@ -49,8 +47,7 @@ seconds_clock_thread::~seconds_clock_thread() thread_.join(); } -seconds_clock_thread::seconds_clock_thread() - : stop_{false}, tp_{Clock::now().time_since_epoch().count()} +seconds_clock_thread::seconds_clock_thread() : stop_{false}, tp_{Clock::now().time_since_epoch().count()} { thread_ = std::thread(&seconds_clock_thread::run, this); } diff --git a/src/libxrpl/beast/core/CurrentThreadName.cpp b/src/libxrpl/beast/core/CurrentThreadName.cpp index e8f7b629a7..9d8d4e4bf2 100644 --- a/src/libxrpl/beast/core/CurrentThreadName.cpp +++ b/src/libxrpl/beast/core/CurrentThreadName.cpp @@ -1,4 +1,5 @@ #include +#include #include #include @@ -41,8 +42,7 @@ setCurrentThreadNameImpl(std::string_view name) #pragma warning(disable : 6320 6322) __try { - RaiseException( - 0x406d1388, 0, sizeof(ni) / sizeof(ULONG_PTR), (ULONG_PTR*)&ni); + RaiseException(0x406d1388, 0, sizeof(ni) / sizeof(ULONG_PTR), (ULONG_PTR*)&ni); } __except (EXCEPTION_CONTINUE_EXECUTION) { @@ -80,21 +80,20 @@ setCurrentThreadNameImpl(std::string_view name) { // truncate and set the thread name. char boundedName[maxThreadNameLength + 1]; - std::snprintf( - boundedName, - sizeof(boundedName), - "%.*s", - static_cast(maxThreadNameLength), - name.data()); + std::snprintf(boundedName, sizeof(boundedName), "%.*s", static_cast(maxThreadNameLength), name.data()); pthread_setname_np(pthread_self(), boundedName); #ifdef TRUNCATED_THREAD_NAME_LOGS if (name.size() > maxThreadNameLength) { - std::cerr << "WARNING: Thread name \"" << name << "\" (length " - << name.size() << ") exceeds maximum of " + std::cerr << "WARNING: Thread name \"" << name << "\" (length " << name.size() << ") exceeds maximum of " << maxThreadNameLength << " characters on Linux.\n"; + + XRPL_ASSERT( + false, + "beast::detail::setCurrentThreadNameImpl : Thread name exceeds " + "maximum length for Linux"); } #endif } diff --git a/src/libxrpl/beast/core/SemanticVersion.cpp b/src/libxrpl/beast/core/SemanticVersion.cpp index 2a42a3b7ab..d22211cc7d 100644 --- a/src/libxrpl/beast/core/SemanticVersion.cpp +++ b/src/libxrpl/beast/core/SemanticVersion.cpp @@ -59,9 +59,7 @@ chopUInt(int& value, int limit, std::string& input) return false; auto left_iter = std::find_if_not( - input.begin(), input.end(), [](std::string::value_type c) { - return std::isdigit(c, std::locale::classic()); - }); + input.begin(), input.end(), [](std::string::value_type c) { return std::isdigit(c, std::locale::classic()); }); std::string item(input.begin(), left_iter); @@ -90,10 +88,7 @@ chopUInt(int& value, int limit, std::string& input) } bool -extract_identifier( - std::string& value, - bool allowLeadingZeroes, - std::string& input) +extract_identifier(std::string& value, bool allowLeadingZeroes, std::string& input) { // Must not be empty if (input.empty()) @@ -103,8 +98,7 @@ extract_identifier( if (!allowLeadingZeroes && input[0] == '0') return false; - auto last = input.find_first_not_of( - "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-"); + auto last = input.find_first_not_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-"); // Must not be empty if (last == 0) @@ -116,10 +110,7 @@ extract_identifier( } bool -extract_identifiers( - SemanticVersion::identifier_list& identifiers, - bool allowLeadingZeroes, - std::string& input) +extract_identifiers(SemanticVersion::identifier_list& identifiers, bool allowLeadingZeroes, std::string& input) { if (input.empty()) return false; @@ -138,8 +129,7 @@ extract_identifiers( //------------------------------------------------------------------------------ -SemanticVersion::SemanticVersion() - : majorVersion(0), minorVersion(0), patchVersion(0) +SemanticVersion::SemanticVersion() : majorVersion(0), minorVersion(0), patchVersion(0) { } @@ -154,17 +144,11 @@ SemanticVersion::parse(std::string const& input) { // May not have leading or trailing whitespace auto left_iter = std::find_if_not( - input.begin(), input.end(), [](std::string::value_type c) { - return std::isspace(c, std::locale::classic()); - }); + input.begin(), input.end(), [](std::string::value_type c) { return std::isspace(c, std::locale::classic()); }); - auto right_iter = std::find_if_not( - input.rbegin(), - input.rend(), - [](std::string::value_type c) { - return std::isspace(c, std::locale::classic()); - }) - .base(); + auto right_iter = std::find_if_not(input.rbegin(), input.rend(), [](std::string::value_type c) { + return std::isspace(c, std::locale::classic()); + }).base(); // Must not be empty! if (left_iter >= right_iter) @@ -222,8 +206,7 @@ SemanticVersion::print() const { std::string s; - s = std::to_string(majorVersion) + "." + std::to_string(minorVersion) + - "." + std::to_string(patchVersion); + s = std::to_string(majorVersion) + "." + std::to_string(minorVersion) + "." + std::to_string(patchVersion); if (!preReleaseIdentifiers.empty()) { @@ -267,10 +250,7 @@ compare(SemanticVersion const& lhs, SemanticVersion const& rhs) return -1; // Compare pre-release identifiers - for (int i = 0; i < - std::max(lhs.preReleaseIdentifiers.size(), - rhs.preReleaseIdentifiers.size()); - ++i) + for (int i = 0; i < std::max(lhs.preReleaseIdentifiers.size(), rhs.preReleaseIdentifiers.size()); ++i) { // A larger list of identifiers has a higher precedence if (i >= rhs.preReleaseIdentifiers.size()) @@ -289,8 +269,7 @@ compare(SemanticVersion const& lhs, SemanticVersion const& rhs) if (isNumeric(left)) { - XRPL_ASSERT( - isNumeric(right), "beast::compare : both inputs numeric"); + XRPL_ASSERT(isNumeric(right), "beast::compare : both inputs numeric"); int const iLeft(lexicalCastThrow(left)); int const iRight(lexicalCastThrow(right)); @@ -302,9 +281,7 @@ compare(SemanticVersion const& lhs, SemanticVersion const& rhs) } else { - XRPL_ASSERT( - !isNumeric(right), - "beast::compare : both inputs non-numeric"); + XRPL_ASSERT(!isNumeric(right), "beast::compare : both inputs non-numeric"); int result = left.compare(right); diff --git a/src/libxrpl/beast/insight/Groups.cpp b/src/libxrpl/beast/insight/Groups.cpp index 78d43067c2..1ff8dbc4c1 100644 --- a/src/libxrpl/beast/insight/Groups.cpp +++ b/src/libxrpl/beast/insight/Groups.cpp @@ -25,8 +25,7 @@ public: std::string const m_name; Collector::ptr m_collector; - GroupImp(std::string const& name_, Collector::ptr const& collector) - : m_name(name_), m_collector(collector) + GroupImp(std::string const& name_, Collector::ptr const& collector) : m_name(name_), m_collector(collector) { } @@ -84,8 +83,7 @@ private: class GroupsImp : public Groups { public: - using Items = - std::unordered_map, uhash<>>; + using Items = std::unordered_map, uhash<>>; Collector::ptr m_collector; Items m_items; @@ -99,8 +97,7 @@ public: Group::ptr const& get(std::string const& name) override { - std::pair result( - m_items.emplace(name, Group::ptr())); + std::pair result(m_items.emplace(name, Group::ptr())); Group::ptr& group(result.first->second); if (result.second) group = std::make_shared(name, m_collector); diff --git a/src/libxrpl/beast/insight/StatsDCollector.cpp b/src/libxrpl/beast/insight/StatsDCollector.cpp index 33bef8ac16..e005a0b177 100644 --- a/src/libxrpl/beast/insight/StatsDCollector.cpp +++ b/src/libxrpl/beast/insight/StatsDCollector.cpp @@ -64,9 +64,7 @@ public: class StatsDHookImpl : public HookImpl, public StatsDMetricBase { public: - StatsDHookImpl( - HandlerType const& handler, - std::shared_ptr const& impl); + StatsDHookImpl(HandlerType const& handler, std::shared_ptr const& impl); ~StatsDHookImpl() override; @@ -86,9 +84,7 @@ private: class StatsDCounterImpl : public CounterImpl, public StatsDMetricBase { public: - StatsDCounterImpl( - std::string const& name, - std::shared_ptr const& impl); + StatsDCounterImpl(std::string const& name, std::shared_ptr const& impl); ~StatsDCounterImpl() override; @@ -117,9 +113,7 @@ private: class StatsDEventImpl : public EventImpl { public: - StatsDEventImpl( - std::string const& name, - std::shared_ptr const& impl); + StatsDEventImpl(std::string const& name, std::shared_ptr const& impl); ~StatsDEventImpl() = default; @@ -144,9 +138,7 @@ private: class StatsDGaugeImpl : public GaugeImpl, public StatsDMetricBase { public: - StatsDGaugeImpl( - std::string const& name, - std::shared_ptr const& impl); + StatsDGaugeImpl(std::string const& name, std::shared_ptr const& impl); ~StatsDGaugeImpl() override; @@ -180,9 +172,7 @@ private: class StatsDMeterImpl : public MeterImpl, public StatsDMetricBase { public: - explicit StatsDMeterImpl( - std::string const& name, - std::shared_ptr const& impl); + explicit StatsDMeterImpl(std::string const& name, std::shared_ptr const& impl); ~StatsDMeterImpl() override; @@ -208,9 +198,7 @@ private: //------------------------------------------------------------------------------ -class StatsDCollectorImp - : public StatsDCollector, - public std::enable_shared_from_this +class StatsDCollectorImp : public StatsDCollector, public std::enable_shared_from_this { private: enum { @@ -222,9 +210,7 @@ private: IP::Endpoint m_address; std::string m_prefix; boost::asio::io_context m_io_context; - std::optional> - m_work; + std::optional> m_work; boost::asio::strand m_strand; boost::asio::basic_waitable_timer m_timer; boost::asio::ip::udp::socket m_socket; @@ -242,10 +228,7 @@ private: } public: - StatsDCollectorImp( - IP::Endpoint const& address, - std::string const& prefix, - Journal journal) + StatsDCollectorImp(IP::Endpoint const& address, std::string const& prefix, Journal journal) : m_journal(journal) , m_address(address) , m_prefix(prefix) @@ -275,36 +258,31 @@ public: Hook make_hook(HookImpl::HandlerType const& handler) override { - return Hook(std::make_shared( - handler, shared_from_this())); + return Hook(std::make_shared(handler, shared_from_this())); } Counter make_counter(std::string const& name) override { - return Counter(std::make_shared( - name, shared_from_this())); + return Counter(std::make_shared(name, shared_from_this())); } Event make_event(std::string const& name) override { - return Event(std::make_shared( - name, shared_from_this())); + return Event(std::make_shared(name, shared_from_this())); } Gauge make_gauge(std::string const& name) override { - return Gauge(std::make_shared( - name, shared_from_this())); + return Gauge(std::make_shared(name, shared_from_this())); } Meter make_meter(std::string const& name) override { - return Meter(std::make_shared( - name, shared_from_this())); + return Meter(std::make_shared(name, shared_from_this())); } //-------------------------------------------------------------------------- @@ -349,20 +327,13 @@ public: boost::asio::dispatch( m_io_context, boost::asio::bind_executor( - m_strand, - std::bind( - &StatsDCollectorImp::do_post_buffer, - this, - std::move(buffer)))); + m_strand, std::bind(&StatsDCollectorImp::do_post_buffer, this, std::move(buffer)))); } // The keepAlive parameter makes sure the buffers sent to // boost::asio::async_send do not go away until the call is finished void - on_send( - std::shared_ptr> /*keepAlive*/, - boost::system::error_code ec, - std::size_t) + on_send(std::shared_ptr> /*keepAlive*/, boost::system::error_code ec, std::size_t) { if (ec == boost::asio::error::operation_aborted) return; @@ -382,8 +353,7 @@ public: #if BEAST_STATSDCOLLECTOR_TRACING_ENABLED for (auto const& buffer : buffers) { - std::string const s( - buffer.data(), boost::asio::buffer_size(buffer)); + std::string const s(buffer.data(), boost::asio::buffer_size(buffer)); std::cerr << s; } std::cerr << '\n'; @@ -404,8 +374,7 @@ public: buffers.reserve(m_data.size()); std::size_t size(0); - auto keepAlive = - std::make_shared>(std::move(m_data)); + auto keepAlive = std::make_shared>(std::move(m_data)); m_data.clear(); for (auto const& s : *keepAlive) @@ -421,11 +390,7 @@ public: m_socket.async_send( buffers, std::bind( - &StatsDCollectorImp::on_send, - this, - keepAlive, - std::placeholders::_1, - std::placeholders::_2)); + &StatsDCollectorImp::on_send, this, keepAlive, std::placeholders::_1, std::placeholders::_2)); buffers.clear(); size = 0; } @@ -439,12 +404,7 @@ public: log(buffers); m_socket.async_send( buffers, - std::bind( - &StatsDCollectorImp::on_send, - this, - keepAlive, - std::placeholders::_1, - std::placeholders::_2)); + std::bind(&StatsDCollectorImp::on_send, this, keepAlive, std::placeholders::_1, std::placeholders::_2)); } } @@ -453,8 +413,7 @@ public: { using namespace std::chrono_literals; m_timer.expires_after(1s); - m_timer.async_wait(std::bind( - &StatsDCollectorImp::on_timer, this, std::placeholders::_1)); + m_timer.async_wait(std::bind(&StatsDCollectorImp::on_timer, this, std::placeholders::_1)); } void @@ -506,9 +465,7 @@ public: //------------------------------------------------------------------------------ -StatsDHookImpl::StatsDHookImpl( - HandlerType const& handler, - std::shared_ptr const& impl) +StatsDHookImpl::StatsDHookImpl(HandlerType const& handler, std::shared_ptr const& impl) : m_impl(impl), m_handler(handler) { m_impl->add(*this); @@ -527,9 +484,7 @@ StatsDHookImpl::do_process() //------------------------------------------------------------------------------ -StatsDCounterImpl::StatsDCounterImpl( - std::string const& name, - std::shared_ptr const& impl) +StatsDCounterImpl::StatsDCounterImpl(std::string const& name, std::shared_ptr const& impl) : m_impl(impl), m_name(name), m_value(0), m_dirty(false) { m_impl->add(*this); @@ -546,9 +501,7 @@ StatsDCounterImpl::increment(CounterImpl::value_type amount) boost::asio::dispatch( m_impl->get_io_context(), std::bind( - &StatsDCounterImpl::do_increment, - std::static_pointer_cast(shared_from_this()), - amount)); + &StatsDCounterImpl::do_increment, std::static_pointer_cast(shared_from_this()), amount)); } void @@ -580,9 +533,7 @@ StatsDCounterImpl::do_process() //------------------------------------------------------------------------------ -StatsDEventImpl::StatsDEventImpl( - std::string const& name, - std::shared_ptr const& impl) +StatsDEventImpl::StatsDEventImpl(std::string const& name, std::shared_ptr const& impl) : m_impl(impl), m_name(name) { } @@ -592,10 +543,7 @@ StatsDEventImpl::notify(EventImpl::value_type const& value) { boost::asio::dispatch( m_impl->get_io_context(), - std::bind( - &StatsDEventImpl::do_notify, - std::static_pointer_cast(shared_from_this()), - value)); + std::bind(&StatsDEventImpl::do_notify, std::static_pointer_cast(shared_from_this()), value)); } void @@ -609,9 +557,7 @@ StatsDEventImpl::do_notify(EventImpl::value_type const& value) //------------------------------------------------------------------------------ -StatsDGaugeImpl::StatsDGaugeImpl( - std::string const& name, - std::shared_ptr const& impl) +StatsDGaugeImpl::StatsDGaugeImpl(std::string const& name, std::shared_ptr const& impl) : m_impl(impl), m_name(name), m_last_value(0), m_value(0), m_dirty(false) { m_impl->add(*this); @@ -627,10 +573,7 @@ StatsDGaugeImpl::set(GaugeImpl::value_type value) { boost::asio::dispatch( m_impl->get_io_context(), - std::bind( - &StatsDGaugeImpl::do_set, - std::static_pointer_cast(shared_from_this()), - value)); + std::bind(&StatsDGaugeImpl::do_set, std::static_pointer_cast(shared_from_this()), value)); } void @@ -639,9 +582,7 @@ StatsDGaugeImpl::increment(GaugeImpl::difference_type amount) boost::asio::dispatch( m_impl->get_io_context(), std::bind( - &StatsDGaugeImpl::do_increment, - std::static_pointer_cast(shared_from_this()), - amount)); + &StatsDGaugeImpl::do_increment, std::static_pointer_cast(shared_from_this()), amount)); } void @@ -676,17 +617,14 @@ StatsDGaugeImpl::do_increment(GaugeImpl::difference_type amount) if (amount > 0) { - GaugeImpl::value_type const d( - static_cast(amount)); - value += - (d >= std::numeric_limits::max() - m_value) + GaugeImpl::value_type const d(static_cast(amount)); + value += (d >= std::numeric_limits::max() - m_value) ? std::numeric_limits::max() - m_value : d; } else if (amount < 0) { - GaugeImpl::value_type const d( - static_cast(-amount)); + GaugeImpl::value_type const d(static_cast(-amount)); value = (d >= value) ? 0 : value - d; } @@ -701,9 +639,7 @@ StatsDGaugeImpl::do_process() //------------------------------------------------------------------------------ -StatsDMeterImpl::StatsDMeterImpl( - std::string const& name, - std::shared_ptr const& impl) +StatsDMeterImpl::StatsDMeterImpl(std::string const& name, std::shared_ptr const& impl) : m_impl(impl), m_name(name), m_value(0), m_dirty(false) { m_impl->add(*this); @@ -720,9 +656,7 @@ StatsDMeterImpl::increment(MeterImpl::value_type amount) boost::asio::dispatch( m_impl->get_io_context(), std::bind( - &StatsDMeterImpl::do_increment, - std::static_pointer_cast(shared_from_this()), - amount)); + &StatsDMeterImpl::do_increment, std::static_pointer_cast(shared_from_this()), amount)); } void @@ -757,13 +691,9 @@ StatsDMeterImpl::do_process() //------------------------------------------------------------------------------ std::shared_ptr -StatsDCollector::New( - IP::Endpoint const& address, - std::string const& prefix, - Journal journal) +StatsDCollector::New(IP::Endpoint const& address, std::string const& prefix, Journal journal) { - return std::make_shared( - address, prefix, journal); + return std::make_shared(address, prefix, journal); } } // namespace insight diff --git a/src/libxrpl/beast/net/IPAddressV4.cpp b/src/libxrpl/beast/net/IPAddressV4.cpp index fcb782133e..021b7588d9 100644 --- a/src/libxrpl/beast/net/IPAddressV4.cpp +++ b/src/libxrpl/beast/net/IPAddressV4.cpp @@ -6,12 +6,9 @@ namespace IP { bool is_private(AddressV4 const& addr) { - return ((addr.to_uint() & 0xff000000) == - 0x0a000000) || // Prefix /8, 10. #.#.# - ((addr.to_uint() & 0xfff00000) == - 0xac100000) || // Prefix /12 172. 16.#.# - 172.31.#.# - ((addr.to_uint() & 0xffff0000) == - 0xc0a80000) || // Prefix /16 192.168.#.# + return ((addr.to_uint() & 0xff000000) == 0x0a000000) || // Prefix /8, 10. #.#.# + ((addr.to_uint() & 0xfff00000) == 0xac100000) || // Prefix /12 172. 16.#.# - 172.31.#.# + ((addr.to_uint() & 0xffff0000) == 0xc0a80000) || // Prefix /16 192.168.#.# addr.is_loopback(); } diff --git a/src/libxrpl/beast/net/IPAddressV6.cpp b/src/libxrpl/beast/net/IPAddressV6.cpp index 9ac51875eb..b1db5ae09c 100644 --- a/src/libxrpl/beast/net/IPAddressV6.cpp +++ b/src/libxrpl/beast/net/IPAddressV6.cpp @@ -11,9 +11,7 @@ is_private(AddressV6 const& addr) { return ( (addr.to_bytes()[0] & 0xfd) || // TODO fc00::/8 too ? - (addr.is_v4_mapped() && - is_private(boost::asio::ip::make_address_v4( - boost::asio::ip::v4_mapped, addr)))); + (addr.is_v4_mapped() && is_private(boost::asio::ip::make_address_v4(boost::asio::ip::v4_mapped, addr)))); } bool diff --git a/src/libxrpl/beast/net/IPEndpoint.cpp b/src/libxrpl/beast/net/IPEndpoint.cpp index 701181ef88..a79b0d750c 100644 --- a/src/libxrpl/beast/net/IPEndpoint.cpp +++ b/src/libxrpl/beast/net/IPEndpoint.cpp @@ -50,9 +50,7 @@ std::string Endpoint::to_string() const { std::string s; - s.reserve( - (address().is_v6() ? INET6_ADDRSTRLEN - 1 : 15) + - (port() == 0 ? 0 : 6 + (address().is_v6() ? 2 : 0))); + s.reserve((address().is_v6() ? INET6_ADDRSTRLEN - 1 : 15) + (port() == 0 ? 0 : 6 + (address().is_v6() ? 2 : 0))); if (port() != 0 && address().is_v6()) s += '['; @@ -110,14 +108,12 @@ operator>>(std::istream& is, Endpoint& endpoint) if (isspace(static_cast(i)) || (readTo && i == readTo)) break; - if ((i == '.') || (i >= '0' && i <= ':') || (i >= 'a' && i <= 'f') || - (i >= 'A' && i <= 'F')) + if ((i == '.') || (i >= '0' && i <= ':') || (i >= 'a' && i <= 'f') || (i >= 'A' && i <= 'F')) { addrStr += i; // don't exceed a reasonable length... - if (addrStr.size() == INET6_ADDRSTRLEN || - (readTo && readTo == ':' && addrStr.size() > 15)) + if (addrStr.size() == INET6_ADDRSTRLEN || (readTo && readTo == ':' && addrStr.size() > 15)) { is.setstate(std::ios_base::failbit); return is; diff --git a/src/libxrpl/beast/utility/beast_Journal.cpp b/src/libxrpl/beast/utility/beast_Journal.cpp index 24e17b18c6..f9ee0cdb73 100644 --- a/src/libxrpl/beast/utility/beast_Journal.cpp +++ b/src/libxrpl/beast/utility/beast_Journal.cpp @@ -68,8 +68,7 @@ Journal::getNullSink() //------------------------------------------------------------------------------ -Journal::Sink::Sink(Severity thresh, bool console) - : thresh_(thresh), m_console(console) +Journal::Sink::Sink(Severity thresh, bool console) : thresh_(thresh), m_console(console) { } @@ -107,16 +106,13 @@ Journal::Sink::threshold(Severity thresh) //------------------------------------------------------------------------------ -Journal::ScopedStream::ScopedStream(Sink& sink, Severity level) - : m_sink(sink), m_level(level) +Journal::ScopedStream::ScopedStream(Sink& sink, Severity level) : m_sink(sink), m_level(level) { // Modifiers applied from all ctors m_ostream << std::boolalpha << std::showbase; } -Journal::ScopedStream::ScopedStream( - Stream const& stream, - std::ostream& manip(std::ostream&)) +Journal::ScopedStream::ScopedStream(Stream const& stream, std::ostream& manip(std::ostream&)) : ScopedStream(stream.sink(), stream.level()) { m_ostream << manip; diff --git a/src/libxrpl/beast/utility/beast_PropertyStream.cpp b/src/libxrpl/beast/utility/beast_PropertyStream.cpp index 991dbaef51..daf6bc4526 100644 --- a/src/libxrpl/beast/utility/beast_PropertyStream.cpp +++ b/src/libxrpl/beast/utility/beast_PropertyStream.cpp @@ -43,13 +43,11 @@ PropertyStream::Item::operator*() const // //------------------------------------------------------------------------------ -PropertyStream::Proxy::Proxy(Map const& map, std::string const& key) - : m_map(&map), m_key(key) +PropertyStream::Proxy::Proxy(Map const& map, std::string const& key) : m_map(&map), m_key(key) { } -PropertyStream::Proxy::Proxy(Proxy const& other) - : m_map(other.m_map), m_key(other.m_key) +PropertyStream::Proxy::Proxy(Proxy const& other) : m_map(other.m_map), m_key(other.m_key) { } @@ -81,14 +79,12 @@ PropertyStream::Map::Map(Set& parent) : m_stream(parent.stream()) m_stream.map_begin(); } -PropertyStream::Map::Map(std::string const& key, Map& map) - : m_stream(map.stream()) +PropertyStream::Map::Map(std::string const& key, Map& map) : m_stream(map.stream()) { m_stream.map_begin(key); } -PropertyStream::Map::Map(std::string const& key, PropertyStream& stream) - : m_stream(stream) +PropertyStream::Map::Map(std::string const& key, PropertyStream& stream) : m_stream(stream) { m_stream.map_begin(key); } @@ -122,14 +118,12 @@ PropertyStream::Map::operator[](std::string const& key) // //------------------------------------------------------------------------------ -PropertyStream::Set::Set(std::string const& key, Map& map) - : m_stream(map.stream()) +PropertyStream::Set::Set(std::string const& key, Map& map) : m_stream(map.stream()) { m_stream.array_begin(key); } -PropertyStream::Set::Set(std::string const& key, PropertyStream& stream) - : m_stream(stream) +PropertyStream::Set::Set(std::string const& key, PropertyStream& stream) : m_stream(stream) { m_stream.array_begin(key); } @@ -157,8 +151,7 @@ PropertyStream::Set::stream() const // //------------------------------------------------------------------------------ -PropertyStream::Source::Source(std::string const& name) - : m_name(name), item_(this), parent_(nullptr) +PropertyStream::Source::Source(std::string const& name) : m_name(name), item_(this), parent_(nullptr) { } @@ -183,9 +176,7 @@ PropertyStream::Source::add(Source& source) std::lock_guard lk1(lock_, std::adopt_lock); std::lock_guard lk2(source.lock_, std::adopt_lock); - XRPL_ASSERT( - source.parent_ == nullptr, - "beast::PropertyStream::Source::add : null source parent"); + XRPL_ASSERT(source.parent_ == nullptr, "beast::PropertyStream::Source::add : null source parent"); children_.push_back(source.item_); source.parent_ = this; } @@ -197,9 +188,7 @@ PropertyStream::Source::remove(Source& child) std::lock_guard lk1(lock_, std::adopt_lock); std::lock_guard lk2(child.lock_, std::adopt_lock); - XRPL_ASSERT( - child.parent_ == this, - "beast::PropertyStream::Source::remove : child parent match"); + XRPL_ASSERT(child.parent_ == this, "beast::PropertyStream::Source::remove : child parent match"); children_.erase(children_.iterator_to(child.item_)); child.parent_ = nullptr; } diff --git a/src/xrpld/conditions/detail/Condition.cpp b/src/libxrpl/conditions/Condition.cpp similarity index 95% rename from src/xrpld/conditions/detail/Condition.cpp rename to src/libxrpl/conditions/Condition.cpp index ebf61dd245..30beba3402 100644 --- a/src/xrpld/conditions/detail/Condition.cpp +++ b/src/libxrpl/conditions/Condition.cpp @@ -1,6 +1,6 @@ -#include -#include -#include +#include +#include +#include namespace xrpl { namespace cryptoconditions { @@ -175,8 +175,7 @@ Condition::deserialize(Slice s, std::error_code& ec) switch (p.tag) { case 0: // PreimageSha256 - c = detail::loadSimpleSha256( - Type::preimageSha256, Slice(s.data(), p.length), ec); + c = detail::loadSimpleSha256(Type::preimageSha256, Slice(s.data(), p.length), ec); if (!ec) s += p.length; break; diff --git a/src/xrpld/conditions/detail/Fulfillment.cpp b/src/libxrpl/conditions/Fulfillment.cpp similarity index 94% rename from src/xrpld/conditions/detail/Fulfillment.cpp rename to src/libxrpl/conditions/Fulfillment.cpp index 9ecaa44ab8..11581a8705 100644 --- a/src/xrpld/conditions/detail/Fulfillment.cpp +++ b/src/libxrpl/conditions/Fulfillment.cpp @@ -1,9 +1,8 @@ -#include -#include -#include -#include - #include +#include +#include +#include +#include namespace xrpl { namespace cryptoconditions { diff --git a/src/xrpld/conditions/detail/error.cpp b/src/libxrpl/conditions/error.cpp similarity index 92% rename from src/xrpld/conditions/detail/error.cpp rename to src/libxrpl/conditions/error.cpp index a74aa79e3f..3124be6fdd 100644 --- a/src/xrpld/conditions/detail/error.cpp +++ b/src/libxrpl/conditions/error.cpp @@ -1,6 +1,5 @@ -#include - #include +#include #include @@ -85,8 +84,7 @@ public: } bool - equivalent(int ev, std::error_condition const& condition) - const noexcept override + equivalent(int ev, std::error_condition const& condition) const noexcept override { return &condition.category() == this && condition.value() == ev; } @@ -111,8 +109,7 @@ std::error_code make_error_code(error ev) { return std::error_code{ - safe_cast::type>(ev), - detail::get_cryptoconditions_error_category()}; + safe_cast::type>(ev), detail::get_cryptoconditions_error_category()}; } } // namespace cryptoconditions diff --git a/src/xrpld/app/misc/HashRouter.cpp b/src/libxrpl/core/HashRouter.cpp similarity index 58% rename from src/xrpld/app/misc/HashRouter.cpp rename to src/libxrpl/core/HashRouter.cpp index a2ba41b361..dff1394f77 100644 --- a/src/xrpld/app/misc/HashRouter.cpp +++ b/src/libxrpl/core/HashRouter.cpp @@ -1,5 +1,4 @@ -#include -#include +#include namespace xrpl { @@ -17,8 +16,7 @@ HashRouter::emplace(uint256 const& key) -> std::pair // See if any suppressions need to be expired expire(suppressionMap_, setup_.holdTime); - return std::make_pair( - std::ref(suppressionMap_.emplace(key, Entry()).first->second), true); + return std::make_pair(std::ref(suppressionMap_.emplace(key, Entry()).first->second), true); } void @@ -46,10 +44,7 @@ HashRouter::addSuppressionPeerWithStatus(uint256 const& key, PeerShortID peer) } bool -HashRouter::addSuppressionPeer( - uint256 const& key, - PeerShortID peer, - HashRouterFlags& flags) +HashRouter::addSuppressionPeer(uint256 const& key, PeerShortID peer, HashRouterFlags& flags) { std::lock_guard lock(mutex_); @@ -86,8 +81,7 @@ HashRouter::getFlags(uint256 const& key) bool HashRouter::setFlags(uint256 const& key, HashRouterFlags flags) { - XRPL_ASSERT( - static_cast(flags), "xrpl::HashRouter::setFlags : valid input"); + XRPL_ASSERT(static_cast(flags), "xrpl::HashRouter::setFlags : valid input"); std::lock_guard lock(mutex_); @@ -101,8 +95,7 @@ HashRouter::setFlags(uint256 const& key, HashRouterFlags flags) } auto -HashRouter::shouldRelay(uint256 const& key) - -> std::optional> +HashRouter::shouldRelay(uint256 const& key) -> std::optional> { std::lock_guard lock(mutex_); @@ -114,39 +107,4 @@ HashRouter::shouldRelay(uint256 const& key) return s.releasePeerSet(); } -HashRouter::Setup -setup_HashRouter(Config const& config) -{ - using namespace std::chrono; - - HashRouter::Setup setup; - auto const& section = config.section("hashrouter"); - - std::int32_t tmp; - - if (set(tmp, "hold_time", section)) - { - if (tmp < 12) - Throw( - "HashRouter hold time must be at least 12 seconds (the " - "approximate validation time for three ledgers)."); - setup.holdTime = seconds(tmp); - } - if (set(tmp, "relay_time", section)) - { - if (tmp < 8) - Throw( - "HashRouter relay time must be at least 8 seconds (the " - "approximate validation time for two ledgers)."); - setup.relayTime = seconds(tmp); - } - if (setup.relayTime > setup.holdTime) - { - Throw( - "HashRouter relay time must be less than or equal to hold time"); - } - - return setup; -} - } // namespace xrpl diff --git a/src/libxrpl/core/detail/Job.cpp b/src/libxrpl/core/detail/Job.cpp index 3968c3ede4..4e957b9619 100644 --- a/src/libxrpl/core/detail/Job.cpp +++ b/src/libxrpl/core/detail/Job.cpp @@ -11,17 +11,8 @@ Job::Job(JobType type, std::uint64_t index) : mType(type), mJobIndex(index) { } -Job::Job( - JobType type, - std::string const& name, - std::uint64_t index, - LoadMonitor& lm, - std::function const& job) - : mType(type) - , mJobIndex(index) - , mJob(job) - , mName(name) - , m_queue_time(clock_type::now()) +Job::Job(JobType type, std::string const& name, std::uint64_t index, LoadMonitor& lm, std::function const& job) + : mType(type), mJobIndex(index), mJob(job), mName(name), m_queue_time(clock_type::now()) { m_loadEvent = std::make_shared(std::ref(lm), name, false); } @@ -41,7 +32,7 @@ Job::queue_time() const void Job::doJob() { - beast::setCurrentThreadName("doJob: " + mName); + beast::setCurrentThreadName("j:" + mName); m_loadEvent->start(); m_loadEvent->setName(mName); diff --git a/src/libxrpl/core/detail/JobQueue.cpp b/src/libxrpl/core/detail/JobQueue.cpp index 7393278fef..37e5402946 100644 --- a/src/libxrpl/core/detail/JobQueue.cpp +++ b/src/libxrpl/core/detail/JobQueue.cpp @@ -37,8 +37,7 @@ JobQueue::JobQueue( std::piecewise_construct, std::forward_as_tuple(jt.type()), std::forward_as_tuple(jt, m_collector, logs))); - XRPL_ASSERT( - result.second == true, "xrpl::JobQueue::JobQueue : jobs added"); + XRPL_ASSERT(result.second == true, "xrpl::JobQueue::JobQueue : jobs added"); (void)result.second; } } @@ -58,47 +57,33 @@ JobQueue::collect() } bool -JobQueue::addRefCountedJob( - JobType type, - std::string const& name, - JobFunction const& func) +JobQueue::addRefCountedJob(JobType type, std::string const& name, JobFunction const& func) { - XRPL_ASSERT( - type != jtINVALID, - "xrpl::JobQueue::addRefCountedJob : valid input job type"); + XRPL_ASSERT(type != jtINVALID, "xrpl::JobQueue::addRefCountedJob : valid input job type"); auto iter(m_jobData.find(type)); - XRPL_ASSERT( - iter != m_jobData.end(), - "xrpl::JobQueue::addRefCountedJob : job type found in jobs"); + XRPL_ASSERT(iter != m_jobData.end(), "xrpl::JobQueue::addRefCountedJob : job type found in jobs"); if (iter == m_jobData.end()) return false; - JLOG(m_journal.debug()) - << __func__ << " : Adding job : " << name << " : " << type; + JLOG(m_journal.debug()) << __func__ << " : Adding job : " << name << " : " << type; JobTypeData& data(iter->second); // FIXME: Workaround incorrect client shutdown ordering // do not add jobs to a queue with no threads XRPL_ASSERT( - (type >= jtCLIENT && type <= jtCLIENT_WEBSOCKET) || - m_workers.getNumberOfThreads() > 0, + (type >= jtCLIENT && type <= jtCLIENT_WEBSOCKET) || m_workers.getNumberOfThreads() > 0, "xrpl::JobQueue::addRefCountedJob : threads available or job " "requires no threads"); { std::lock_guard lock(m_mutex); - auto result = - m_jobSet.emplace(type, name, ++m_lastJob, data.load(), func); + auto result = m_jobSet.emplace(type, name, ++m_lastJob, data.load(), func); auto const& job = *result.first; JobType const type(job.getType()); - XRPL_ASSERT( - type != jtINVALID, - "xrpl::JobQueue::addRefCountedJob : has valid job type"); - XRPL_ASSERT( - m_jobSet.find(job) != m_jobSet.end(), - "xrpl::JobQueue::addRefCountedJob : job found"); + XRPL_ASSERT(type != jtINVALID, "xrpl::JobQueue::addRefCountedJob : has valid job type"); + XRPL_ASSERT(m_jobSet.find(job) != m_jobSet.end(), "xrpl::JobQueue::addRefCountedJob : job found"); perfLog_.jobQueue(type); JobTypeData& data(getJobTypeData(type)); @@ -158,9 +143,7 @@ std::unique_ptr JobQueue::makeLoadEvent(JobType t, std::string const& name) { JobDataMap::iterator iter(m_jobData.find(t)); - XRPL_ASSERT( - iter != m_jobData.end(), - "xrpl::JobQueue::makeLoadEvent : valid job type input"); + XRPL_ASSERT(iter != m_jobData.end(), "xrpl::JobQueue::makeLoadEvent : valid job type input"); if (iter == m_jobData.end()) return {}; @@ -175,18 +158,14 @@ JobQueue::addLoadEvents(JobType t, int count, std::chrono::milliseconds elapsed) LogicError("JobQueue::addLoadEvents() called after JobQueue stopped"); JobDataMap::iterator iter(m_jobData.find(t)); - XRPL_ASSERT( - iter != m_jobData.end(), - "xrpl::JobQueue::addLoadEvents : valid job type input"); + XRPL_ASSERT(iter != m_jobData.end(), "xrpl::JobQueue::addLoadEvents : valid job type input"); iter->second.load().addSamples(count, elapsed); } bool JobQueue::isOverloaded() { - return std::any_of(m_jobData.begin(), m_jobData.end(), [](auto& entry) { - return entry.second.load().isOver(); - }); + return std::any_of(m_jobData.begin(), m_jobData.end(), [](auto& entry) { return entry.second.load().isOver(); }); } Json::Value @@ -203,8 +182,7 @@ JobQueue::getJson(int c) for (auto& x : m_jobData) { - XRPL_ASSERT( - x.first != jtINVALID, "xrpl::JobQueue::getJson : valid job type"); + XRPL_ASSERT(x.first != jtINVALID, "xrpl::JobQueue::getJson : valid job type"); if (x.first == jtGENERIC) continue; @@ -216,8 +194,7 @@ JobQueue::getJson(int c) int waiting(data.waiting); int running(data.running); - if ((stats.count != 0) || (waiting != 0) || - (stats.latencyPeak != 0ms) || (running != 0)) + if ((stats.count != 0) || (waiting != 0) || (stats.latencyPeak != 0ms) || (running != 0)) { Json::Value& pri = priorities.append(Json::objectValue); @@ -259,9 +236,7 @@ JobTypeData& JobQueue::getJobTypeData(JobType type) { JobDataMap::iterator c(m_jobData.find(type)); - XRPL_ASSERT( - c != m_jobData.end(), - "xrpl::JobQueue::getJobTypeData : valid job type input"); + XRPL_ASSERT(c != m_jobData.end(), "xrpl::JobQueue::getJobTypeData : valid job type input"); // NIKB: This is ugly and I hate it. We must remove jtINVALID completely // and use something sane. @@ -284,15 +259,10 @@ JobQueue::stop() // `Job::doJob` and the return of `JobQueue::processTask`. That is why // we must wait on the condition variable to make these assertions. std::unique_lock lock(m_mutex); - cv_.wait( - lock, [this] { return m_processCount == 0 && m_jobSet.empty(); }); - XRPL_ASSERT( - m_processCount == 0, - "xrpl::JobQueue::stop : all processes completed"); - XRPL_ASSERT( - m_jobSet.empty(), "xrpl::JobQueue::stop : all jobs completed"); - XRPL_ASSERT( - nSuspend_ == 0, "xrpl::JobQueue::stop : no coros suspended"); + cv_.wait(lock, [this] { return m_processCount == 0 && m_jobSet.empty(); }); + XRPL_ASSERT(m_processCount == 0, "xrpl::JobQueue::stop : all processes completed"); + XRPL_ASSERT(m_jobSet.empty(), "xrpl::JobQueue::stop : all jobs completed"); + XRPL_ASSERT(nSuspend_ == 0, "xrpl::JobQueue::stop : no coros suspended"); stopped_ = true; } } @@ -306,35 +276,28 @@ JobQueue::isStopped() const void JobQueue::getNextJob(Job& job) { - XRPL_ASSERT( - !m_jobSet.empty(), "xrpl::JobQueue::getNextJob : non-empty jobs"); + XRPL_ASSERT(!m_jobSet.empty(), "xrpl::JobQueue::getNextJob : non-empty jobs"); std::set::const_iterator iter; for (iter = m_jobSet.begin(); iter != m_jobSet.end(); ++iter) { JobType const type = iter->getType(); - XRPL_ASSERT( - type != jtINVALID, "xrpl::JobQueue::getNextJob : valid job type"); + XRPL_ASSERT(type != jtINVALID, "xrpl::JobQueue::getNextJob : valid job type"); JobTypeData& data(getJobTypeData(type)); - XRPL_ASSERT( - data.running <= getJobLimit(type), - "xrpl::JobQueue::getNextJob : maximum jobs running"); + XRPL_ASSERT(data.running <= getJobLimit(type), "xrpl::JobQueue::getNextJob : maximum jobs running"); // Run this job if we're running below the limit. if (data.running < getJobLimit(data.type())) { - XRPL_ASSERT( - data.waiting > 0, - "xrpl::JobQueue::getNextJob : positive data waiting"); + XRPL_ASSERT(data.waiting > 0, "xrpl::JobQueue::getNextJob : positive data waiting"); --data.waiting; ++data.running; break; } } - XRPL_ASSERT( - iter != m_jobSet.end(), "xrpl::JobQueue::getNextJob : found next job"); + XRPL_ASSERT(iter != m_jobSet.end(), "xrpl::JobQueue::getNextJob : found next job"); job = *iter; m_jobSet.erase(iter); } @@ -342,17 +305,14 @@ JobQueue::getNextJob(Job& job) void JobQueue::finishJob(JobType type) { - XRPL_ASSERT( - type != jtINVALID, "xrpl::JobQueue::finishJob : valid input job type"); + XRPL_ASSERT(type != jtINVALID, "xrpl::JobQueue::finishJob : valid input job type"); JobTypeData& data = getJobTypeData(type); // Queue a deferred task if possible if (data.deferred > 0) { - XRPL_ASSERT( - data.running + data.waiting >= getJobLimit(type), - "xrpl::JobQueue::finishJob : job limit"); + XRPL_ASSERT(data.running + data.waiting >= getJobLimit(type), "xrpl::JobQueue::finishJob : job limit"); --data.deferred; m_workers.addTask(); @@ -381,15 +341,13 @@ JobQueue::processTask(int instance) JLOG(m_journal.trace()) << "Doing " << data.name() << "job"; // The amount of time that the job was in the queue - auto const q_time = - ceil(start_time - job.queue_time()); + auto const q_time = ceil(start_time - job.queue_time()); perfLog_.jobStart(type, q_time, start_time, instance); job.doJob(); // The amount of time it took to execute the job - auto const x_time = - ceil(Job::clock_type::now() - start_time); + auto const x_time = ceil(Job::clock_type::now() - start_time); if (x_time >= 10ms || q_time >= 10ms) { @@ -418,8 +376,7 @@ int JobQueue::getJobLimit(JobType type) { JobTypeInfo const& j(JobTypes::instance().get(type)); - XRPL_ASSERT( - j.type() != jtINVALID, "xrpl::JobQueue::getJobLimit : valid job type"); + XRPL_ASSERT(j.type() != jtINVALID, "xrpl::JobQueue::getJobLimit : valid job type"); return j.limit(); } diff --git a/src/libxrpl/core/detail/LoadEvent.cpp b/src/libxrpl/core/detail/LoadEvent.cpp index 43a2c491c3..1370e9089f 100644 --- a/src/libxrpl/core/detail/LoadEvent.cpp +++ b/src/libxrpl/core/detail/LoadEvent.cpp @@ -4,10 +4,7 @@ namespace xrpl { -LoadEvent::LoadEvent( - LoadMonitor& monitor, - std::string const& name, - bool shouldStart) +LoadEvent::LoadEvent(LoadMonitor& monitor, std::string const& name, bool shouldStart) : monitor_(monitor) , running_(shouldStart) , name_(name) diff --git a/src/libxrpl/core/detail/LoadMonitor.cpp b/src/libxrpl/core/detail/LoadMonitor.cpp index 933fea5877..376b25c178 100644 --- a/src/libxrpl/core/detail/LoadMonitor.cpp +++ b/src/libxrpl/core/detail/LoadMonitor.cpp @@ -15,8 +15,7 @@ TODO //------------------------------------------------------------------------------ -LoadMonitor::Stats::Stats() - : count(0), latencyAvg(0), latencyPeak(0), isOverloaded(false) +LoadMonitor::Stats::Stats() : count(0), latencyAvg(0), latencyPeak(0), isOverloaded(false) { } @@ -90,10 +89,8 @@ LoadMonitor::addLoadSample(LoadEvent const& s) if (latency > 500ms) { auto mj = (latency > 1s) ? j_.warn() : j_.info(); - JLOG(mj) << "Job: " << s.name() - << " run: " << round(s.runTime()).count() << "ms" - << " wait: " << round(s.waitTime()).count() - << "ms"; + JLOG(mj) << "Job: " << s.name() << " run: " << round(s.runTime()).count() << "ms" + << " wait: " << round(s.waitTime()).count() << "ms"; } addSamples(1, latency); @@ -121,18 +118,14 @@ LoadMonitor::addSamples(int count, std::chrono::milliseconds latency) } void -LoadMonitor::setTargetLatency( - std::chrono::milliseconds avg, - std::chrono::milliseconds pk) +LoadMonitor::setTargetLatency(std::chrono::milliseconds avg, std::chrono::milliseconds pk) { mTargetLatencyAvg = avg; mTargetLatencyPk = pk; } bool -LoadMonitor::isOverTarget( - std::chrono::milliseconds avg, - std::chrono::milliseconds peak) +LoadMonitor::isOverTarget(std::chrono::milliseconds avg, std::chrono::milliseconds peak) { using namespace std::chrono_literals; return (mTargetLatencyPk > 0ms && (peak > mTargetLatencyPk)) || @@ -149,9 +142,7 @@ LoadMonitor::isOver() if (mLatencyEvents == 0) return 0; - return isOverTarget( - mLatencyMSAvg / (mLatencyEvents * 4), - mLatencyMSPeak / (mLatencyEvents * 4)); + return isOverTarget(mLatencyMSAvg / (mLatencyEvents * 4), mLatencyMSPeak / (mLatencyEvents * 4)); } LoadMonitor::Stats diff --git a/src/libxrpl/core/detail/Workers.cpp b/src/libxrpl/core/detail/Workers.cpp index aa4731a0ff..27103d765d 100644 --- a/src/libxrpl/core/detail/Workers.cpp +++ b/src/libxrpl/core/detail/Workers.cpp @@ -5,11 +5,7 @@ namespace xrpl { -Workers::Workers( - Callback& callback, - perf::PerfLog* perfLog, - std::string const& threadNames, - int numberOfThreads) +Workers::Workers(Callback& callback, perf::PerfLog* perfLog, std::string const& threadNames, int numberOfThreads) : m_callback(callback) , perfLog_(perfLog) , m_threadNames(threadNames) @@ -100,9 +96,7 @@ Workers::stop() m_cv.wait(lk, [this] { return m_allPaused; }); lk.unlock(); - XRPL_ASSERT( - numberOfCurrentlyRunningTasks() == 0, - "xrpl::Workers::stop : zero running tasks"); + XRPL_ASSERT(numberOfCurrentlyRunningTasks() == 0, "xrpl::Workers::stop : zero running tasks"); } void @@ -138,15 +132,8 @@ Workers::deleteWorkers(beast::LockFreeStack& stack) //------------------------------------------------------------------------------ -Workers::Worker::Worker( - Workers& workers, - std::string const& threadName, - int const instance) - : m_workers{workers} - , threadName_{threadName} - , instance_{instance} - , wakeCount_{0} - , shouldExit_{false} +Workers::Worker::Worker(Workers& workers, std::string const& threadName, int const instance) + : m_workers{workers}, threadName_{threadName}, instance_{instance}, wakeCount_{0}, shouldExit_{false} { thread_ = std::thread{&Workers::Worker::run, this}; } diff --git a/src/libxrpl/crypto/RFC1751.cpp b/src/libxrpl/crypto/RFC1751.cpp index 86ee8ad382..dc841fca83 100644 --- a/src/libxrpl/crypto/RFC1751.cpp +++ b/src/libxrpl/crypto/RFC1751.cpp @@ -21,234 +21,153 @@ namespace xrpl { // char const* RFC1751::s_dictionary[2048] = { - "A", "ABE", "ACE", "ACT", "AD", "ADA", "ADD", "AGO", "AID", - "AIM", "AIR", "ALL", "ALP", "AM", "AMY", "AN", "ANA", "AND", - "ANN", "ANT", "ANY", "APE", "APS", "APT", "ARC", "ARE", "ARK", - "ARM", "ART", "AS", "ASH", "ASK", "AT", "ATE", "AUG", "AUK", - "AVE", "AWE", "AWK", "AWL", "AWN", "AX", "AYE", "BAD", "BAG", - "BAH", "BAM", "BAN", "BAR", "BAT", "BAY", "BE", "BED", "BEE", - "BEG", "BEN", "BET", "BEY", "BIB", "BID", "BIG", "BIN", "BIT", - "BOB", "BOG", "BON", "BOO", "BOP", "BOW", "BOY", "BUB", "BUD", - "BUG", "BUM", "BUN", "BUS", "BUT", "BUY", "BY", "BYE", "CAB", - "CAL", "CAM", "CAN", "CAP", "CAR", "CAT", "CAW", "COD", "COG", - "COL", "CON", "COO", "COP", "COT", "COW", "COY", "CRY", "CUB", - "CUE", "CUP", "CUR", "CUT", "DAB", "DAD", "DAM", "DAN", "DAR", - "DAY", "DEE", "DEL", "DEN", "DES", "DEW", "DID", "DIE", "DIG", - "DIN", "DIP", "DO", "DOE", "DOG", "DON", "DOT", "DOW", "DRY", - "DUB", "DUD", "DUE", "DUG", "DUN", "EAR", "EAT", "ED", "EEL", - "EGG", "EGO", "ELI", "ELK", "ELM", "ELY", "EM", "END", "EST", - "ETC", "EVA", "EVE", "EWE", "EYE", "FAD", "FAN", "FAR", "FAT", - "FAY", "FED", "FEE", "FEW", "FIB", "FIG", "FIN", "FIR", "FIT", - "FLO", "FLY", "FOE", "FOG", "FOR", "FRY", "FUM", "FUN", "FUR", - "GAB", "GAD", "GAG", "GAL", "GAM", "GAP", "GAS", "GAY", "GEE", - "GEL", "GEM", "GET", "GIG", "GIL", "GIN", "GO", "GOT", "GUM", - "GUN", "GUS", "GUT", "GUY", "GYM", "GYP", "HA", "HAD", "HAL", - "HAM", "HAN", "HAP", "HAS", "HAT", "HAW", "HAY", "HE", "HEM", - "HEN", "HER", "HEW", "HEY", "HI", "HID", "HIM", "HIP", "HIS", - "HIT", "HO", "HOB", "HOC", "HOE", "HOG", "HOP", "HOT", "HOW", - "HUB", "HUE", "HUG", "HUH", "HUM", "HUT", "I", "ICY", "IDA", - "IF", "IKE", "ILL", "INK", "INN", "IO", "ION", "IQ", "IRA", - "IRE", "IRK", "IS", "IT", "ITS", "IVY", "JAB", "JAG", "JAM", - "JAN", "JAR", "JAW", "JAY", "JET", "JIG", "JIM", "JO", "JOB", - "JOE", "JOG", "JOT", "JOY", "JUG", "JUT", "KAY", "KEG", "KEN", - "KEY", "KID", "KIM", "KIN", "KIT", "LA", "LAB", "LAC", "LAD", - "LAG", "LAM", "LAP", "LAW", "LAY", "LEA", "LED", "LEE", "LEG", - "LEN", "LEO", "LET", "LEW", "LID", "LIE", "LIN", "LIP", "LIT", - "LO", "LOB", "LOG", "LOP", "LOS", "LOT", "LOU", "LOW", "LOY", - "LUG", "LYE", "MA", "MAC", "MAD", "MAE", "MAN", "MAO", "MAP", - "MAT", "MAW", "MAY", "ME", "MEG", "MEL", "MEN", "MET", "MEW", - "MID", "MIN", "MIT", "MOB", "MOD", "MOE", "MOO", "MOP", "MOS", - "MOT", "MOW", "MUD", "MUG", "MUM", "MY", "NAB", "NAG", "NAN", - "NAP", "NAT", "NAY", "NE", "NED", "NEE", "NET", "NEW", "NIB", - "NIL", "NIP", "NIT", "NO", "NOB", "NOD", "NON", "NOR", "NOT", - "NOV", "NOW", "NU", "NUN", "NUT", "O", "OAF", "OAK", "OAR", - "OAT", "ODD", "ODE", "OF", "OFF", "OFT", "OH", "OIL", "OK", - "OLD", "ON", "ONE", "OR", "ORB", "ORE", "ORR", "OS", "OTT", - "OUR", "OUT", "OVA", "OW", "OWE", "OWL", "OWN", "OX", "PA", - "PAD", "PAL", "PAM", "PAN", "PAP", "PAR", "PAT", "PAW", "PAY", - "PEA", "PEG", "PEN", "PEP", "PER", "PET", "PEW", "PHI", "PI", - "PIE", "PIN", "PIT", "PLY", "PO", "POD", "POE", "POP", "POT", - "POW", "PRO", "PRY", "PUB", "PUG", "PUN", "PUP", "PUT", "QUO", - "RAG", "RAM", "RAN", "RAP", "RAT", "RAW", "RAY", "REB", "RED", - "REP", "RET", "RIB", "RID", "RIG", "RIM", "RIO", "RIP", "ROB", - "ROD", "ROE", "RON", "ROT", "ROW", "ROY", "RUB", "RUE", "RUG", - "RUM", "RUN", "RYE", "SAC", "SAD", "SAG", "SAL", "SAM", "SAN", - "SAP", "SAT", "SAW", "SAY", "SEA", "SEC", "SEE", "SEN", "SET", - "SEW", "SHE", "SHY", "SIN", "SIP", "SIR", "SIS", "SIT", "SKI", - "SKY", "SLY", "SO", "SOB", "SOD", "SON", "SOP", "SOW", "SOY", - "SPA", "SPY", "SUB", "SUD", "SUE", "SUM", "SUN", "SUP", "TAB", - "TAD", "TAG", "TAN", "TAP", "TAR", "TEA", "TED", "TEE", "TEN", - "THE", "THY", "TIC", "TIE", "TIM", "TIN", "TIP", "TO", "TOE", - "TOG", "TOM", "TON", "TOO", "TOP", "TOW", "TOY", "TRY", "TUB", - "TUG", "TUM", "TUN", "TWO", "UN", "UP", "US", "USE", "VAN", - "VAT", "VET", "VIE", "WAD", "WAG", "WAR", "WAS", "WAY", "WE", - "WEB", "WED", "WEE", "WET", "WHO", "WHY", "WIN", "WIT", "WOK", - "WON", "WOO", "WOW", "WRY", "WU", "YAM", "YAP", "YAW", "YE", - "YEA", "YES", "YET", "YOU", "ABED", "ABEL", "ABET", "ABLE", "ABUT", - "ACHE", "ACID", "ACME", "ACRE", "ACTA", "ACTS", "ADAM", "ADDS", "ADEN", - "AFAR", "AFRO", "AGEE", "AHEM", "AHOY", "AIDA", "AIDE", "AIDS", "AIRY", - "AJAR", "AKIN", "ALAN", "ALEC", "ALGA", "ALIA", "ALLY", "ALMA", "ALOE", - "ALSO", "ALTO", "ALUM", "ALVA", "AMEN", "AMES", "AMID", "AMMO", "AMOK", - "AMOS", "AMRA", "ANDY", "ANEW", "ANNA", "ANNE", "ANTE", "ANTI", "AQUA", - "ARAB", "ARCH", "AREA", "ARGO", "ARID", "ARMY", "ARTS", "ARTY", "ASIA", - "ASKS", "ATOM", "AUNT", "AURA", "AUTO", "AVER", "AVID", "AVIS", "AVON", - "AVOW", "AWAY", "AWRY", "BABE", "BABY", "BACH", "BACK", "BADE", "BAIL", - "BAIT", "BAKE", "BALD", "BALE", "BALI", "BALK", "BALL", "BALM", "BAND", - "BANE", "BANG", "BANK", "BARB", "BARD", "BARE", "BARK", "BARN", "BARR", - "BASE", "BASH", "BASK", "BASS", "BATE", "BATH", "BAWD", "BAWL", "BEAD", - "BEAK", "BEAM", "BEAN", "BEAR", "BEAT", "BEAU", "BECK", "BEEF", "BEEN", - "BEER", "BEET", "BELA", "BELL", "BELT", "BEND", "BENT", "BERG", "BERN", - "BERT", "BESS", "BEST", "BETA", "BETH", "BHOY", "BIAS", "BIDE", "BIEN", - "BILE", "BILK", "BILL", "BIND", "BING", "BIRD", "BITE", "BITS", "BLAB", - "BLAT", "BLED", "BLEW", "BLOB", "BLOC", "BLOT", "BLOW", "BLUE", "BLUM", - "BLUR", "BOAR", "BOAT", "BOCA", "BOCK", "BODE", "BODY", "BOGY", "BOHR", - "BOIL", "BOLD", "BOLO", "BOLT", "BOMB", "BONA", "BOND", "BONE", "BONG", - "BONN", "BONY", "BOOK", "BOOM", "BOON", "BOOT", "BORE", "BORG", "BORN", - "BOSE", "BOSS", "BOTH", "BOUT", "BOWL", "BOYD", "BRAD", "BRAE", "BRAG", - "BRAN", "BRAY", "BRED", "BREW", "BRIG", "BRIM", "BROW", "BUCK", "BUDD", - "BUFF", "BULB", "BULK", "BULL", "BUNK", "BUNT", "BUOY", "BURG", "BURL", - "BURN", "BURR", "BURT", "BURY", "BUSH", "BUSS", "BUST", "BUSY", "BYTE", - "CADY", "CAFE", "CAGE", "CAIN", "CAKE", "CALF", "CALL", "CALM", "CAME", - "CANE", "CANT", "CARD", "CARE", "CARL", "CARR", "CART", "CASE", "CASH", - "CASK", "CAST", "CAVE", "CEIL", "CELL", "CENT", "CERN", "CHAD", "CHAR", - "CHAT", "CHAW", "CHEF", "CHEN", "CHEW", "CHIC", "CHIN", "CHOU", "CHOW", - "CHUB", "CHUG", "CHUM", "CITE", "CITY", "CLAD", "CLAM", "CLAN", "CLAW", - "CLAY", "CLOD", "CLOG", "CLOT", "CLUB", "CLUE", "COAL", "COAT", "COCA", - "COCK", "COCO", "CODA", "CODE", "CODY", "COED", "COIL", "COIN", "COKE", - "COLA", "COLD", "COLT", "COMA", "COMB", "COME", "COOK", "COOL", "COON", - "COOT", "CORD", "CORE", "CORK", "CORN", "COST", "COVE", "COWL", "CRAB", - "CRAG", "CRAM", "CRAY", "CREW", "CRIB", "CROW", "CRUD", "CUBA", "CUBE", - "CUFF", "CULL", "CULT", "CUNY", "CURB", "CURD", "CURE", "CURL", "CURT", - "CUTS", "DADE", "DALE", "DAME", "DANA", "DANE", "DANG", "DANK", "DARE", - "DARK", "DARN", "DART", "DASH", "DATA", "DATE", "DAVE", "DAVY", "DAWN", - "DAYS", "DEAD", "DEAF", "DEAL", "DEAN", "DEAR", "DEBT", "DECK", "DEED", - "DEEM", "DEER", "DEFT", "DEFY", "DELL", "DENT", "DENY", "DESK", "DIAL", - "DICE", "DIED", "DIET", "DIME", "DINE", "DING", "DINT", "DIRE", "DIRT", - "DISC", "DISH", "DISK", "DIVE", "DOCK", "DOES", "DOLE", "DOLL", "DOLT", - "DOME", "DONE", "DOOM", "DOOR", "DORA", "DOSE", "DOTE", "DOUG", "DOUR", - "DOVE", "DOWN", "DRAB", "DRAG", "DRAM", "DRAW", "DREW", "DRUB", "DRUG", - "DRUM", "DUAL", "DUCK", "DUCT", "DUEL", "DUET", "DUKE", "DULL", "DUMB", - "DUNE", "DUNK", "DUSK", "DUST", "DUTY", "EACH", "EARL", "EARN", "EASE", - "EAST", "EASY", "EBEN", "ECHO", "EDDY", "EDEN", "EDGE", "EDGY", "EDIT", - "EDNA", "EGAN", "ELAN", "ELBA", "ELLA", "ELSE", "EMIL", "EMIT", "EMMA", - "ENDS", "ERIC", "EROS", "EVEN", "EVER", "EVIL", "EYED", "FACE", "FACT", - "FADE", "FAIL", "FAIN", "FAIR", "FAKE", "FALL", "FAME", "FANG", "FARM", - "FAST", "FATE", "FAWN", "FEAR", "FEAT", "FEED", "FEEL", "FEET", "FELL", - "FELT", "FEND", "FERN", "FEST", "FEUD", "FIEF", "FIGS", "FILE", "FILL", - "FILM", "FIND", "FINE", "FINK", "FIRE", "FIRM", "FISH", "FISK", "FIST", - "FITS", "FIVE", "FLAG", "FLAK", "FLAM", "FLAT", "FLAW", "FLEA", "FLED", - "FLEW", "FLIT", "FLOC", "FLOG", "FLOW", "FLUB", "FLUE", "FOAL", "FOAM", - "FOGY", "FOIL", "FOLD", "FOLK", "FOND", "FONT", "FOOD", "FOOL", "FOOT", - "FORD", "FORE", "FORK", "FORM", "FORT", "FOSS", "FOUL", "FOUR", "FOWL", - "FRAU", "FRAY", "FRED", "FREE", "FRET", "FREY", "FROG", "FROM", "FUEL", - "FULL", "FUME", "FUND", "FUNK", "FURY", "FUSE", "FUSS", "GAFF", "GAGE", - "GAIL", "GAIN", "GAIT", "GALA", "GALE", "GALL", "GALT", "GAME", "GANG", - "GARB", "GARY", "GASH", "GATE", "GAUL", "GAUR", "GAVE", "GAWK", "GEAR", - "GELD", "GENE", "GENT", "GERM", "GETS", "GIBE", "GIFT", "GILD", "GILL", - "GILT", "GINA", "GIRD", "GIRL", "GIST", "GIVE", "GLAD", "GLEE", "GLEN", - "GLIB", "GLOB", "GLOM", "GLOW", "GLUE", "GLUM", "GLUT", "GOAD", "GOAL", - "GOAT", "GOER", "GOES", "GOLD", "GOLF", "GONE", "GONG", "GOOD", "GOOF", - "GORE", "GORY", "GOSH", "GOUT", "GOWN", "GRAB", "GRAD", "GRAY", "GREG", - "GREW", "GREY", "GRID", "GRIM", "GRIN", "GRIT", "GROW", "GRUB", "GULF", - "GULL", "GUNK", "GURU", "GUSH", "GUST", "GWEN", "GWYN", "HAAG", "HAAS", - "HACK", "HAIL", "HAIR", "HALE", "HALF", "HALL", "HALO", "HALT", "HAND", - "HANG", "HANK", "HANS", "HARD", "HARK", "HARM", "HART", "HASH", "HAST", - "HATE", "HATH", "HAUL", "HAVE", "HAWK", "HAYS", "HEAD", "HEAL", "HEAR", - "HEAT", "HEBE", "HECK", "HEED", "HEEL", "HEFT", "HELD", "HELL", "HELM", - "HERB", "HERD", "HERE", "HERO", "HERS", "HESS", "HEWN", "HICK", "HIDE", - "HIGH", "HIKE", "HILL", "HILT", "HIND", "HINT", "HIRE", "HISS", "HIVE", - "HOBO", "HOCK", "HOFF", "HOLD", "HOLE", "HOLM", "HOLT", "HOME", "HONE", - "HONK", "HOOD", "HOOF", "HOOK", "HOOT", "HORN", "HOSE", "HOST", "HOUR", - "HOVE", "HOWE", "HOWL", "HOYT", "HUCK", "HUED", "HUFF", "HUGE", "HUGH", - "HUGO", "HULK", "HULL", "HUNK", "HUNT", "HURD", "HURL", "HURT", "HUSH", - "HYDE", "HYMN", "IBIS", "ICON", "IDEA", "IDLE", "IFFY", "INCA", "INCH", - "INTO", "IONS", "IOTA", "IOWA", "IRIS", "IRMA", "IRON", "ISLE", "ITCH", - "ITEM", "IVAN", "JACK", "JADE", "JAIL", "JAKE", "JANE", "JAVA", "JEAN", - "JEFF", "JERK", "JESS", "JEST", "JIBE", "JILL", "JILT", "JIVE", "JOAN", - "JOBS", "JOCK", "JOEL", "JOEY", "JOHN", "JOIN", "JOKE", "JOLT", "JOVE", - "JUDD", "JUDE", "JUDO", "JUDY", "JUJU", "JUKE", "JULY", "JUNE", "JUNK", - "JUNO", "JURY", "JUST", "JUTE", "KAHN", "KALE", "KANE", "KANT", "KARL", - "KATE", "KEEL", "KEEN", "KENO", "KENT", "KERN", "KERR", "KEYS", "KICK", - "KILL", "KIND", "KING", "KIRK", "KISS", "KITE", "KLAN", "KNEE", "KNEW", - "KNIT", "KNOB", "KNOT", "KNOW", "KOCH", "KONG", "KUDO", "KURD", "KURT", - "KYLE", "LACE", "LACK", "LACY", "LADY", "LAID", "LAIN", "LAIR", "LAKE", - "LAMB", "LAME", "LAND", "LANE", "LANG", "LARD", "LARK", "LASS", "LAST", - "LATE", "LAUD", "LAVA", "LAWN", "LAWS", "LAYS", "LEAD", "LEAF", "LEAK", - "LEAN", "LEAR", "LEEK", "LEER", "LEFT", "LEND", "LENS", "LENT", "LEON", - "LESK", "LESS", "LEST", "LETS", "LIAR", "LICE", "LICK", "LIED", "LIEN", - "LIES", "LIEU", "LIFE", "LIFT", "LIKE", "LILA", "LILT", "LILY", "LIMA", - "LIMB", "LIME", "LIND", "LINE", "LINK", "LINT", "LION", "LISA", "LIST", - "LIVE", "LOAD", "LOAF", "LOAM", "LOAN", "LOCK", "LOFT", "LOGE", "LOIS", - "LOLA", "LONE", "LONG", "LOOK", "LOON", "LOOT", "LORD", "LORE", "LOSE", - "LOSS", "LOST", "LOUD", "LOVE", "LOWE", "LUCK", "LUCY", "LUGE", "LUKE", - "LULU", "LUND", "LUNG", "LURA", "LURE", "LURK", "LUSH", "LUST", "LYLE", - "LYNN", "LYON", "LYRA", "MACE", "MADE", "MAGI", "MAID", "MAIL", "MAIN", - "MAKE", "MALE", "MALI", "MALL", "MALT", "MANA", "MANN", "MANY", "MARC", - "MARE", "MARK", "MARS", "MART", "MARY", "MASH", "MASK", "MASS", "MAST", - "MATE", "MATH", "MAUL", "MAYO", "MEAD", "MEAL", "MEAN", "MEAT", "MEEK", - "MEET", "MELD", "MELT", "MEMO", "MEND", "MENU", "MERT", "MESH", "MESS", - "MICE", "MIKE", "MILD", "MILE", "MILK", "MILL", "MILT", "MIMI", "MIND", - "MINE", "MINI", "MINK", "MINT", "MIRE", "MISS", "MIST", "MITE", "MITT", - "MOAN", "MOAT", "MOCK", "MODE", "MOLD", "MOLE", "MOLL", "MOLT", "MONA", - "MONK", "MONT", "MOOD", "MOON", "MOOR", "MOOT", "MORE", "MORN", "MORT", - "MOSS", "MOST", "MOTH", "MOVE", "MUCH", "MUCK", "MUDD", "MUFF", "MULE", - "MULL", "MURK", "MUSH", "MUST", "MUTE", "MUTT", "MYRA", "MYTH", "NAGY", - "NAIL", "NAIR", "NAME", "NARY", "NASH", "NAVE", "NAVY", "NEAL", "NEAR", - "NEAT", "NECK", "NEED", "NEIL", "NELL", "NEON", "NERO", "NESS", "NEST", - "NEWS", "NEWT", "NIBS", "NICE", "NICK", "NILE", "NINA", "NINE", "NOAH", - "NODE", "NOEL", "NOLL", "NONE", "NOOK", "NOON", "NORM", "NOSE", "NOTE", - "NOUN", "NOVA", "NUDE", "NULL", "NUMB", "OATH", "OBEY", "OBOE", "ODIN", - "OHIO", "OILY", "OINT", "OKAY", "OLAF", "OLDY", "OLGA", "OLIN", "OMAN", - "OMEN", "OMIT", "ONCE", "ONES", "ONLY", "ONTO", "ONUS", "ORAL", "ORGY", - "OSLO", "OTIS", "OTTO", "OUCH", "OUST", "OUTS", "OVAL", "OVEN", "OVER", - "OWLY", "OWNS", "QUAD", "QUIT", "QUOD", "RACE", "RACK", "RACY", "RAFT", - "RAGE", "RAID", "RAIL", "RAIN", "RAKE", "RANK", "RANT", "RARE", "RASH", - "RATE", "RAVE", "RAYS", "READ", "REAL", "REAM", "REAR", "RECK", "REED", - "REEF", "REEK", "REEL", "REID", "REIN", "RENA", "REND", "RENT", "REST", - "RICE", "RICH", "RICK", "RIDE", "RIFT", "RILL", "RIME", "RING", "RINK", - "RISE", "RISK", "RITE", "ROAD", "ROAM", "ROAR", "ROBE", "ROCK", "RODE", - "ROIL", "ROLL", "ROME", "ROOD", "ROOF", "ROOK", "ROOM", "ROOT", "ROSA", - "ROSE", "ROSS", "ROSY", "ROTH", "ROUT", "ROVE", "ROWE", "ROWS", "RUBE", - "RUBY", "RUDE", "RUDY", "RUIN", "RULE", "RUNG", "RUNS", "RUNT", "RUSE", - "RUSH", "RUSK", "RUSS", "RUST", "RUTH", "SACK", "SAFE", "SAGE", "SAID", - "SAIL", "SALE", "SALK", "SALT", "SAME", "SAND", "SANE", "SANG", "SANK", - "SARA", "SAUL", "SAVE", "SAYS", "SCAN", "SCAR", "SCAT", "SCOT", "SEAL", - "SEAM", "SEAR", "SEAT", "SEED", "SEEK", "SEEM", "SEEN", "SEES", "SELF", - "SELL", "SEND", "SENT", "SETS", "SEWN", "SHAG", "SHAM", "SHAW", "SHAY", - "SHED", "SHIM", "SHIN", "SHOD", "SHOE", "SHOT", "SHOW", "SHUN", "SHUT", - "SICK", "SIDE", "SIFT", "SIGH", "SIGN", "SILK", "SILL", "SILO", "SILT", - "SINE", "SING", "SINK", "SIRE", "SITE", "SITS", "SITU", "SKAT", "SKEW", - "SKID", "SKIM", "SKIN", "SKIT", "SLAB", "SLAM", "SLAT", "SLAY", "SLED", - "SLEW", "SLID", "SLIM", "SLIT", "SLOB", "SLOG", "SLOT", "SLOW", "SLUG", - "SLUM", "SLUR", "SMOG", "SMUG", "SNAG", "SNOB", "SNOW", "SNUB", "SNUG", - "SOAK", "SOAR", "SOCK", "SODA", "SOFA", "SOFT", "SOIL", "SOLD", "SOME", - "SONG", "SOON", "SOOT", "SORE", "SORT", "SOUL", "SOUR", "SOWN", "STAB", - "STAG", "STAN", "STAR", "STAY", "STEM", "STEW", "STIR", "STOW", "STUB", - "STUN", "SUCH", "SUDS", "SUIT", "SULK", "SUMS", "SUNG", "SUNK", "SURE", - "SURF", "SWAB", "SWAG", "SWAM", "SWAN", "SWAT", "SWAY", "SWIM", "SWUM", - "TACK", "TACT", "TAIL", "TAKE", "TALE", "TALK", "TALL", "TANK", "TASK", - "TATE", "TAUT", "TEAL", "TEAM", "TEAR", "TECH", "TEEM", "TEEN", "TEET", - "TELL", "TEND", "TENT", "TERM", "TERN", "TESS", "TEST", "THAN", "THAT", - "THEE", "THEM", "THEN", "THEY", "THIN", "THIS", "THUD", "THUG", "TICK", - "TIDE", "TIDY", "TIED", "TIER", "TILE", "TILL", "TILT", "TIME", "TINA", - "TINE", "TINT", "TINY", "TIRE", "TOAD", "TOGO", "TOIL", "TOLD", "TOLL", - "TONE", "TONG", "TONY", "TOOK", "TOOL", "TOOT", "TORE", "TORN", "TOTE", - "TOUR", "TOUT", "TOWN", "TRAG", "TRAM", "TRAY", "TREE", "TREK", "TRIG", - "TRIM", "TRIO", "TROD", "TROT", "TROY", "TRUE", "TUBA", "TUBE", "TUCK", - "TUFT", "TUNA", "TUNE", "TUNG", "TURF", "TURN", "TUSK", "TWIG", "TWIN", - "TWIT", "ULAN", "UNIT", "URGE", "USED", "USER", "USES", "UTAH", "VAIL", - "VAIN", "VALE", "VARY", "VASE", "VAST", "VEAL", "VEDA", "VEIL", "VEIN", - "VEND", "VENT", "VERB", "VERY", "VETO", "VICE", "VIEW", "VINE", "VISE", - "VOID", "VOLT", "VOTE", "WACK", "WADE", "WAGE", "WAIL", "WAIT", "WAKE", - "WALE", "WALK", "WALL", "WALT", "WAND", "WANE", "WANG", "WANT", "WARD", - "WARM", "WARN", "WART", "WASH", "WAST", "WATS", "WATT", "WAVE", "WAVY", - "WAYS", "WEAK", "WEAL", "WEAN", "WEAR", "WEED", "WEEK", "WEIR", "WELD", - "WELL", "WELT", "WENT", "WERE", "WERT", "WEST", "WHAM", "WHAT", "WHEE", - "WHEN", "WHET", "WHOA", "WHOM", "WICK", "WIFE", "WILD", "WILL", "WIND", - "WINE", "WING", "WINK", "WINO", "WIRE", "WISE", "WISH", "WITH", "WOLF", - "WONT", "WOOD", "WOOL", "WORD", "WORE", "WORK", "WORM", "WORN", "WOVE", - "WRIT", "WYNN", "YALE", "YANG", "YANK", "YARD", "YARN", "YAWL", "YAWN", - "YEAH", "YEAR", "YELL", "YOGA", "YOKE"}; + "A", "ABE", "ACE", "ACT", "AD", "ADA", "ADD", "AGO", "AID", "AIM", "AIR", "ALL", "ALP", "AM", + "AMY", "AN", "ANA", "AND", "ANN", "ANT", "ANY", "APE", "APS", "APT", "ARC", "ARE", "ARK", "ARM", + "ART", "AS", "ASH", "ASK", "AT", "ATE", "AUG", "AUK", "AVE", "AWE", "AWK", "AWL", "AWN", "AX", + "AYE", "BAD", "BAG", "BAH", "BAM", "BAN", "BAR", "BAT", "BAY", "BE", "BED", "BEE", "BEG", "BEN", + "BET", "BEY", "BIB", "BID", "BIG", "BIN", "BIT", "BOB", "BOG", "BON", "BOO", "BOP", "BOW", "BOY", + "BUB", "BUD", "BUG", "BUM", "BUN", "BUS", "BUT", "BUY", "BY", "BYE", "CAB", "CAL", "CAM", "CAN", + "CAP", "CAR", "CAT", "CAW", "COD", "COG", "COL", "CON", "COO", "COP", "COT", "COW", "COY", "CRY", + "CUB", "CUE", "CUP", "CUR", "CUT", "DAB", "DAD", "DAM", "DAN", "DAR", "DAY", "DEE", "DEL", "DEN", + "DES", "DEW", "DID", "DIE", "DIG", "DIN", "DIP", "DO", "DOE", "DOG", "DON", "DOT", "DOW", "DRY", + "DUB", "DUD", "DUE", "DUG", "DUN", "EAR", "EAT", "ED", "EEL", "EGG", "EGO", "ELI", "ELK", "ELM", + "ELY", "EM", "END", "EST", "ETC", "EVA", "EVE", "EWE", "EYE", "FAD", "FAN", "FAR", "FAT", "FAY", + "FED", "FEE", "FEW", "FIB", "FIG", "FIN", "FIR", "FIT", "FLO", "FLY", "FOE", "FOG", "FOR", "FRY", + "FUM", "FUN", "FUR", "GAB", "GAD", "GAG", "GAL", "GAM", "GAP", "GAS", "GAY", "GEE", "GEL", "GEM", + "GET", "GIG", "GIL", "GIN", "GO", "GOT", "GUM", "GUN", "GUS", "GUT", "GUY", "GYM", "GYP", "HA", + "HAD", "HAL", "HAM", "HAN", "HAP", "HAS", "HAT", "HAW", "HAY", "HE", "HEM", "HEN", "HER", "HEW", + "HEY", "HI", "HID", "HIM", "HIP", "HIS", "HIT", "HO", "HOB", "HOC", "HOE", "HOG", "HOP", "HOT", + "HOW", "HUB", "HUE", "HUG", "HUH", "HUM", "HUT", "I", "ICY", "IDA", "IF", "IKE", "ILL", "INK", + "INN", "IO", "ION", "IQ", "IRA", "IRE", "IRK", "IS", "IT", "ITS", "IVY", "JAB", "JAG", "JAM", + "JAN", "JAR", "JAW", "JAY", "JET", "JIG", "JIM", "JO", "JOB", "JOE", "JOG", "JOT", "JOY", "JUG", + "JUT", "KAY", "KEG", "KEN", "KEY", "KID", "KIM", "KIN", "KIT", "LA", "LAB", "LAC", "LAD", "LAG", + "LAM", "LAP", "LAW", "LAY", "LEA", "LED", "LEE", "LEG", "LEN", "LEO", "LET", "LEW", "LID", "LIE", + "LIN", "LIP", "LIT", "LO", "LOB", "LOG", "LOP", "LOS", "LOT", "LOU", "LOW", "LOY", "LUG", "LYE", + "MA", "MAC", "MAD", "MAE", "MAN", "MAO", "MAP", "MAT", "MAW", "MAY", "ME", "MEG", "MEL", "MEN", + "MET", "MEW", "MID", "MIN", "MIT", "MOB", "MOD", "MOE", "MOO", "MOP", "MOS", "MOT", "MOW", "MUD", + "MUG", "MUM", "MY", "NAB", "NAG", "NAN", "NAP", "NAT", "NAY", "NE", "NED", "NEE", "NET", "NEW", + "NIB", "NIL", "NIP", "NIT", "NO", "NOB", "NOD", "NON", "NOR", "NOT", "NOV", "NOW", "NU", "NUN", + "NUT", "O", "OAF", "OAK", "OAR", "OAT", "ODD", "ODE", "OF", "OFF", "OFT", "OH", "OIL", "OK", + "OLD", "ON", "ONE", "OR", "ORB", "ORE", "ORR", "OS", "OTT", "OUR", "OUT", "OVA", "OW", "OWE", + "OWL", "OWN", "OX", "PA", "PAD", "PAL", "PAM", "PAN", "PAP", "PAR", "PAT", "PAW", "PAY", "PEA", + "PEG", "PEN", "PEP", "PER", "PET", "PEW", "PHI", "PI", "PIE", "PIN", "PIT", "PLY", "PO", "POD", + "POE", "POP", "POT", "POW", "PRO", "PRY", "PUB", "PUG", "PUN", "PUP", "PUT", "QUO", "RAG", "RAM", + "RAN", "RAP", "RAT", "RAW", "RAY", "REB", "RED", "REP", "RET", "RIB", "RID", "RIG", "RIM", "RIO", + "RIP", "ROB", "ROD", "ROE", "RON", "ROT", "ROW", "ROY", "RUB", "RUE", "RUG", "RUM", "RUN", "RYE", + "SAC", "SAD", "SAG", "SAL", "SAM", "SAN", "SAP", "SAT", "SAW", "SAY", "SEA", "SEC", "SEE", "SEN", + "SET", "SEW", "SHE", "SHY", "SIN", "SIP", "SIR", "SIS", "SIT", "SKI", "SKY", "SLY", "SO", "SOB", + "SOD", "SON", "SOP", "SOW", "SOY", "SPA", "SPY", "SUB", "SUD", "SUE", "SUM", "SUN", "SUP", "TAB", + "TAD", "TAG", "TAN", "TAP", "TAR", "TEA", "TED", "TEE", "TEN", "THE", "THY", "TIC", "TIE", "TIM", + "TIN", "TIP", "TO", "TOE", "TOG", "TOM", "TON", "TOO", "TOP", "TOW", "TOY", "TRY", "TUB", "TUG", + "TUM", "TUN", "TWO", "UN", "UP", "US", "USE", "VAN", "VAT", "VET", "VIE", "WAD", "WAG", "WAR", + "WAS", "WAY", "WE", "WEB", "WED", "WEE", "WET", "WHO", "WHY", "WIN", "WIT", "WOK", "WON", "WOO", + "WOW", "WRY", "WU", "YAM", "YAP", "YAW", "YE", "YEA", "YES", "YET", "YOU", "ABED", "ABEL", "ABET", + "ABLE", "ABUT", "ACHE", "ACID", "ACME", "ACRE", "ACTA", "ACTS", "ADAM", "ADDS", "ADEN", "AFAR", "AFRO", "AGEE", + "AHEM", "AHOY", "AIDA", "AIDE", "AIDS", "AIRY", "AJAR", "AKIN", "ALAN", "ALEC", "ALGA", "ALIA", "ALLY", "ALMA", + "ALOE", "ALSO", "ALTO", "ALUM", "ALVA", "AMEN", "AMES", "AMID", "AMMO", "AMOK", "AMOS", "AMRA", "ANDY", "ANEW", + "ANNA", "ANNE", "ANTE", "ANTI", "AQUA", "ARAB", "ARCH", "AREA", "ARGO", "ARID", "ARMY", "ARTS", "ARTY", "ASIA", + "ASKS", "ATOM", "AUNT", "AURA", "AUTO", "AVER", "AVID", "AVIS", "AVON", "AVOW", "AWAY", "AWRY", "BABE", "BABY", + "BACH", "BACK", "BADE", "BAIL", "BAIT", "BAKE", "BALD", "BALE", "BALI", "BALK", "BALL", "BALM", "BAND", "BANE", + "BANG", "BANK", "BARB", "BARD", "BARE", "BARK", "BARN", "BARR", "BASE", "BASH", "BASK", "BASS", "BATE", "BATH", + "BAWD", "BAWL", "BEAD", "BEAK", "BEAM", "BEAN", "BEAR", "BEAT", "BEAU", "BECK", "BEEF", "BEEN", "BEER", "BEET", + "BELA", "BELL", "BELT", "BEND", "BENT", "BERG", "BERN", "BERT", "BESS", "BEST", "BETA", "BETH", "BHOY", "BIAS", + "BIDE", "BIEN", "BILE", "BILK", "BILL", "BIND", "BING", "BIRD", "BITE", "BITS", "BLAB", "BLAT", "BLED", "BLEW", + "BLOB", "BLOC", "BLOT", "BLOW", "BLUE", "BLUM", "BLUR", "BOAR", "BOAT", "BOCA", "BOCK", "BODE", "BODY", "BOGY", + "BOHR", "BOIL", "BOLD", "BOLO", "BOLT", "BOMB", "BONA", "BOND", "BONE", "BONG", "BONN", "BONY", "BOOK", "BOOM", + "BOON", "BOOT", "BORE", "BORG", "BORN", "BOSE", "BOSS", "BOTH", "BOUT", "BOWL", "BOYD", "BRAD", "BRAE", "BRAG", + "BRAN", "BRAY", "BRED", "BREW", "BRIG", "BRIM", "BROW", "BUCK", "BUDD", "BUFF", "BULB", "BULK", "BULL", "BUNK", + "BUNT", "BUOY", "BURG", "BURL", "BURN", "BURR", "BURT", "BURY", "BUSH", "BUSS", "BUST", "BUSY", "BYTE", "CADY", + "CAFE", "CAGE", "CAIN", "CAKE", "CALF", "CALL", "CALM", "CAME", "CANE", "CANT", "CARD", "CARE", "CARL", "CARR", + "CART", "CASE", "CASH", "CASK", "CAST", "CAVE", "CEIL", "CELL", "CENT", "CERN", "CHAD", "CHAR", "CHAT", "CHAW", + "CHEF", "CHEN", "CHEW", "CHIC", "CHIN", "CHOU", "CHOW", "CHUB", "CHUG", "CHUM", "CITE", "CITY", "CLAD", "CLAM", + "CLAN", "CLAW", "CLAY", "CLOD", "CLOG", "CLOT", "CLUB", "CLUE", "COAL", "COAT", "COCA", "COCK", "COCO", "CODA", + "CODE", "CODY", "COED", "COIL", "COIN", "COKE", "COLA", "COLD", "COLT", "COMA", "COMB", "COME", "COOK", "COOL", + "COON", "COOT", "CORD", "CORE", "CORK", "CORN", "COST", "COVE", "COWL", "CRAB", "CRAG", "CRAM", "CRAY", "CREW", + "CRIB", "CROW", "CRUD", "CUBA", "CUBE", "CUFF", "CULL", "CULT", "CUNY", "CURB", "CURD", "CURE", "CURL", "CURT", + "CUTS", "DADE", "DALE", "DAME", "DANA", "DANE", "DANG", "DANK", "DARE", "DARK", "DARN", "DART", "DASH", "DATA", + "DATE", "DAVE", "DAVY", "DAWN", "DAYS", "DEAD", "DEAF", "DEAL", "DEAN", "DEAR", "DEBT", "DECK", "DEED", "DEEM", + "DEER", "DEFT", "DEFY", "DELL", "DENT", "DENY", "DESK", "DIAL", "DICE", "DIED", "DIET", "DIME", "DINE", "DING", + "DINT", "DIRE", "DIRT", "DISC", "DISH", "DISK", "DIVE", "DOCK", "DOES", "DOLE", "DOLL", "DOLT", "DOME", "DONE", + "DOOM", "DOOR", "DORA", "DOSE", "DOTE", "DOUG", "DOUR", "DOVE", "DOWN", "DRAB", "DRAG", "DRAM", "DRAW", "DREW", + "DRUB", "DRUG", "DRUM", "DUAL", "DUCK", "DUCT", "DUEL", "DUET", "DUKE", "DULL", "DUMB", "DUNE", "DUNK", "DUSK", + "DUST", "DUTY", "EACH", "EARL", "EARN", "EASE", "EAST", "EASY", "EBEN", "ECHO", "EDDY", "EDEN", "EDGE", "EDGY", + "EDIT", "EDNA", "EGAN", "ELAN", "ELBA", "ELLA", "ELSE", "EMIL", "EMIT", "EMMA", "ENDS", "ERIC", "EROS", "EVEN", + "EVER", "EVIL", "EYED", "FACE", "FACT", "FADE", "FAIL", "FAIN", "FAIR", "FAKE", "FALL", "FAME", "FANG", "FARM", + "FAST", "FATE", "FAWN", "FEAR", "FEAT", "FEED", "FEEL", "FEET", "FELL", "FELT", "FEND", "FERN", "FEST", "FEUD", + "FIEF", "FIGS", "FILE", "FILL", "FILM", "FIND", "FINE", "FINK", "FIRE", "FIRM", "FISH", "FISK", "FIST", "FITS", + "FIVE", "FLAG", "FLAK", "FLAM", "FLAT", "FLAW", "FLEA", "FLED", "FLEW", "FLIT", "FLOC", "FLOG", "FLOW", "FLUB", + "FLUE", "FOAL", "FOAM", "FOGY", "FOIL", "FOLD", "FOLK", "FOND", "FONT", "FOOD", "FOOL", "FOOT", "FORD", "FORE", + "FORK", "FORM", "FORT", "FOSS", "FOUL", "FOUR", "FOWL", "FRAU", "FRAY", "FRED", "FREE", "FRET", "FREY", "FROG", + "FROM", "FUEL", "FULL", "FUME", "FUND", "FUNK", "FURY", "FUSE", "FUSS", "GAFF", "GAGE", "GAIL", "GAIN", "GAIT", + "GALA", "GALE", "GALL", "GALT", "GAME", "GANG", "GARB", "GARY", "GASH", "GATE", "GAUL", "GAUR", "GAVE", "GAWK", + "GEAR", "GELD", "GENE", "GENT", "GERM", "GETS", "GIBE", "GIFT", "GILD", "GILL", "GILT", "GINA", "GIRD", "GIRL", + "GIST", "GIVE", "GLAD", "GLEE", "GLEN", "GLIB", "GLOB", "GLOM", "GLOW", "GLUE", "GLUM", "GLUT", "GOAD", "GOAL", + "GOAT", "GOER", "GOES", "GOLD", "GOLF", "GONE", "GONG", "GOOD", "GOOF", "GORE", "GORY", "GOSH", "GOUT", "GOWN", + "GRAB", "GRAD", "GRAY", "GREG", "GREW", "GREY", "GRID", "GRIM", "GRIN", "GRIT", "GROW", "GRUB", "GULF", "GULL", + "GUNK", "GURU", "GUSH", "GUST", "GWEN", "GWYN", "HAAG", "HAAS", "HACK", "HAIL", "HAIR", "HALE", "HALF", "HALL", + "HALO", "HALT", "HAND", "HANG", "HANK", "HANS", "HARD", "HARK", "HARM", "HART", "HASH", "HAST", "HATE", "HATH", + "HAUL", "HAVE", "HAWK", "HAYS", "HEAD", "HEAL", "HEAR", "HEAT", "HEBE", "HECK", "HEED", "HEEL", "HEFT", "HELD", + "HELL", "HELM", "HERB", "HERD", "HERE", "HERO", "HERS", "HESS", "HEWN", "HICK", "HIDE", "HIGH", "HIKE", "HILL", + "HILT", "HIND", "HINT", "HIRE", "HISS", "HIVE", "HOBO", "HOCK", "HOFF", "HOLD", "HOLE", "HOLM", "HOLT", "HOME", + "HONE", "HONK", "HOOD", "HOOF", "HOOK", "HOOT", "HORN", "HOSE", "HOST", "HOUR", "HOVE", "HOWE", "HOWL", "HOYT", + "HUCK", "HUED", "HUFF", "HUGE", "HUGH", "HUGO", "HULK", "HULL", "HUNK", "HUNT", "HURD", "HURL", "HURT", "HUSH", + "HYDE", "HYMN", "IBIS", "ICON", "IDEA", "IDLE", "IFFY", "INCA", "INCH", "INTO", "IONS", "IOTA", "IOWA", "IRIS", + "IRMA", "IRON", "ISLE", "ITCH", "ITEM", "IVAN", "JACK", "JADE", "JAIL", "JAKE", "JANE", "JAVA", "JEAN", "JEFF", + "JERK", "JESS", "JEST", "JIBE", "JILL", "JILT", "JIVE", "JOAN", "JOBS", "JOCK", "JOEL", "JOEY", "JOHN", "JOIN", + "JOKE", "JOLT", "JOVE", "JUDD", "JUDE", "JUDO", "JUDY", "JUJU", "JUKE", "JULY", "JUNE", "JUNK", "JUNO", "JURY", + "JUST", "JUTE", "KAHN", "KALE", "KANE", "KANT", "KARL", "KATE", "KEEL", "KEEN", "KENO", "KENT", "KERN", "KERR", + "KEYS", "KICK", "KILL", "KIND", "KING", "KIRK", "KISS", "KITE", "KLAN", "KNEE", "KNEW", "KNIT", "KNOB", "KNOT", + "KNOW", "KOCH", "KONG", "KUDO", "KURD", "KURT", "KYLE", "LACE", "LACK", "LACY", "LADY", "LAID", "LAIN", "LAIR", + "LAKE", "LAMB", "LAME", "LAND", "LANE", "LANG", "LARD", "LARK", "LASS", "LAST", "LATE", "LAUD", "LAVA", "LAWN", + "LAWS", "LAYS", "LEAD", "LEAF", "LEAK", "LEAN", "LEAR", "LEEK", "LEER", "LEFT", "LEND", "LENS", "LENT", "LEON", + "LESK", "LESS", "LEST", "LETS", "LIAR", "LICE", "LICK", "LIED", "LIEN", "LIES", "LIEU", "LIFE", "LIFT", "LIKE", + "LILA", "LILT", "LILY", "LIMA", "LIMB", "LIME", "LIND", "LINE", "LINK", "LINT", "LION", "LISA", "LIST", "LIVE", + "LOAD", "LOAF", "LOAM", "LOAN", "LOCK", "LOFT", "LOGE", "LOIS", "LOLA", "LONE", "LONG", "LOOK", "LOON", "LOOT", + "LORD", "LORE", "LOSE", "LOSS", "LOST", "LOUD", "LOVE", "LOWE", "LUCK", "LUCY", "LUGE", "LUKE", "LULU", "LUND", + "LUNG", "LURA", "LURE", "LURK", "LUSH", "LUST", "LYLE", "LYNN", "LYON", "LYRA", "MACE", "MADE", "MAGI", "MAID", + "MAIL", "MAIN", "MAKE", "MALE", "MALI", "MALL", "MALT", "MANA", "MANN", "MANY", "MARC", "MARE", "MARK", "MARS", + "MART", "MARY", "MASH", "MASK", "MASS", "MAST", "MATE", "MATH", "MAUL", "MAYO", "MEAD", "MEAL", "MEAN", "MEAT", + "MEEK", "MEET", "MELD", "MELT", "MEMO", "MEND", "MENU", "MERT", "MESH", "MESS", "MICE", "MIKE", "MILD", "MILE", + "MILK", "MILL", "MILT", "MIMI", "MIND", "MINE", "MINI", "MINK", "MINT", "MIRE", "MISS", "MIST", "MITE", "MITT", + "MOAN", "MOAT", "MOCK", "MODE", "MOLD", "MOLE", "MOLL", "MOLT", "MONA", "MONK", "MONT", "MOOD", "MOON", "MOOR", + "MOOT", "MORE", "MORN", "MORT", "MOSS", "MOST", "MOTH", "MOVE", "MUCH", "MUCK", "MUDD", "MUFF", "MULE", "MULL", + "MURK", "MUSH", "MUST", "MUTE", "MUTT", "MYRA", "MYTH", "NAGY", "NAIL", "NAIR", "NAME", "NARY", "NASH", "NAVE", + "NAVY", "NEAL", "NEAR", "NEAT", "NECK", "NEED", "NEIL", "NELL", "NEON", "NERO", "NESS", "NEST", "NEWS", "NEWT", + "NIBS", "NICE", "NICK", "NILE", "NINA", "NINE", "NOAH", "NODE", "NOEL", "NOLL", "NONE", "NOOK", "NOON", "NORM", + "NOSE", "NOTE", "NOUN", "NOVA", "NUDE", "NULL", "NUMB", "OATH", "OBEY", "OBOE", "ODIN", "OHIO", "OILY", "OINT", + "OKAY", "OLAF", "OLDY", "OLGA", "OLIN", "OMAN", "OMEN", "OMIT", "ONCE", "ONES", "ONLY", "ONTO", "ONUS", "ORAL", + "ORGY", "OSLO", "OTIS", "OTTO", "OUCH", "OUST", "OUTS", "OVAL", "OVEN", "OVER", "OWLY", "OWNS", "QUAD", "QUIT", + "QUOD", "RACE", "RACK", "RACY", "RAFT", "RAGE", "RAID", "RAIL", "RAIN", "RAKE", "RANK", "RANT", "RARE", "RASH", + "RATE", "RAVE", "RAYS", "READ", "REAL", "REAM", "REAR", "RECK", "REED", "REEF", "REEK", "REEL", "REID", "REIN", + "RENA", "REND", "RENT", "REST", "RICE", "RICH", "RICK", "RIDE", "RIFT", "RILL", "RIME", "RING", "RINK", "RISE", + "RISK", "RITE", "ROAD", "ROAM", "ROAR", "ROBE", "ROCK", "RODE", "ROIL", "ROLL", "ROME", "ROOD", "ROOF", "ROOK", + "ROOM", "ROOT", "ROSA", "ROSE", "ROSS", "ROSY", "ROTH", "ROUT", "ROVE", "ROWE", "ROWS", "RUBE", "RUBY", "RUDE", + "RUDY", "RUIN", "RULE", "RUNG", "RUNS", "RUNT", "RUSE", "RUSH", "RUSK", "RUSS", "RUST", "RUTH", "SACK", "SAFE", + "SAGE", "SAID", "SAIL", "SALE", "SALK", "SALT", "SAME", "SAND", "SANE", "SANG", "SANK", "SARA", "SAUL", "SAVE", + "SAYS", "SCAN", "SCAR", "SCAT", "SCOT", "SEAL", "SEAM", "SEAR", "SEAT", "SEED", "SEEK", "SEEM", "SEEN", "SEES", + "SELF", "SELL", "SEND", "SENT", "SETS", "SEWN", "SHAG", "SHAM", "SHAW", "SHAY", "SHED", "SHIM", "SHIN", "SHOD", + "SHOE", "SHOT", "SHOW", "SHUN", "SHUT", "SICK", "SIDE", "SIFT", "SIGH", "SIGN", "SILK", "SILL", "SILO", "SILT", + "SINE", "SING", "SINK", "SIRE", "SITE", "SITS", "SITU", "SKAT", "SKEW", "SKID", "SKIM", "SKIN", "SKIT", "SLAB", + "SLAM", "SLAT", "SLAY", "SLED", "SLEW", "SLID", "SLIM", "SLIT", "SLOB", "SLOG", "SLOT", "SLOW", "SLUG", "SLUM", + "SLUR", "SMOG", "SMUG", "SNAG", "SNOB", "SNOW", "SNUB", "SNUG", "SOAK", "SOAR", "SOCK", "SODA", "SOFA", "SOFT", + "SOIL", "SOLD", "SOME", "SONG", "SOON", "SOOT", "SORE", "SORT", "SOUL", "SOUR", "SOWN", "STAB", "STAG", "STAN", + "STAR", "STAY", "STEM", "STEW", "STIR", "STOW", "STUB", "STUN", "SUCH", "SUDS", "SUIT", "SULK", "SUMS", "SUNG", + "SUNK", "SURE", "SURF", "SWAB", "SWAG", "SWAM", "SWAN", "SWAT", "SWAY", "SWIM", "SWUM", "TACK", "TACT", "TAIL", + "TAKE", "TALE", "TALK", "TALL", "TANK", "TASK", "TATE", "TAUT", "TEAL", "TEAM", "TEAR", "TECH", "TEEM", "TEEN", + "TEET", "TELL", "TEND", "TENT", "TERM", "TERN", "TESS", "TEST", "THAN", "THAT", "THEE", "THEM", "THEN", "THEY", + "THIN", "THIS", "THUD", "THUG", "TICK", "TIDE", "TIDY", "TIED", "TIER", "TILE", "TILL", "TILT", "TIME", "TINA", + "TINE", "TINT", "TINY", "TIRE", "TOAD", "TOGO", "TOIL", "TOLD", "TOLL", "TONE", "TONG", "TONY", "TOOK", "TOOL", + "TOOT", "TORE", "TORN", "TOTE", "TOUR", "TOUT", "TOWN", "TRAG", "TRAM", "TRAY", "TREE", "TREK", "TRIG", "TRIM", + "TRIO", "TROD", "TROT", "TROY", "TRUE", "TUBA", "TUBE", "TUCK", "TUFT", "TUNA", "TUNE", "TUNG", "TURF", "TURN", + "TUSK", "TWIG", "TWIN", "TWIT", "ULAN", "UNIT", "URGE", "USED", "USER", "USES", "UTAH", "VAIL", "VAIN", "VALE", + "VARY", "VASE", "VAST", "VEAL", "VEDA", "VEIL", "VEIN", "VEND", "VENT", "VERB", "VERY", "VETO", "VICE", "VIEW", + "VINE", "VISE", "VOID", "VOLT", "VOTE", "WACK", "WADE", "WAGE", "WAIL", "WAIT", "WAKE", "WALE", "WALK", "WALL", + "WALT", "WAND", "WANE", "WANG", "WANT", "WARD", "WARM", "WARN", "WART", "WASH", "WAST", "WATS", "WATT", "WAVE", + "WAVY", "WAYS", "WEAK", "WEAL", "WEAN", "WEAR", "WEED", "WEEK", "WEIR", "WELD", "WELL", "WELT", "WENT", "WERE", + "WERT", "WEST", "WHAM", "WHAT", "WHEE", "WHEN", "WHET", "WHOA", "WHOM", "WICK", "WIFE", "WILD", "WILL", "WIND", + "WINE", "WING", "WINK", "WINO", "WIRE", "WISE", "WISH", "WITH", "WOLF", "WONT", "WOOD", "WOOL", "WORD", "WORE", + "WORK", "WORM", "WORN", "WOVE", "WRIT", "WYNN", "YALE", "YANG", "YANK", "YARD", "YARN", "YAWL", "YAWN", "YEAH", + "YEAR", "YELL", "YOGA", "YOKE"}; /* Extract 'length' bits from the char array 's' starting with bit 'start' */ @@ -263,9 +182,7 @@ RFC1751::extract(char const* s, int start, int length) XRPL_ASSERT(length <= 11, "xrpl::RFC1751::extract : maximum length"); XRPL_ASSERT(start >= 0, "xrpl::RFC1751::extract : minimum start"); XRPL_ASSERT(length >= 0, "xrpl::RFC1751::extract : minimum length"); - XRPL_ASSERT( - start + length <= 66, - "xrpl::RFC1751::extract : maximum start + length"); + XRPL_ASSERT(start + length <= 66, "xrpl::RFC1751::extract : maximum start + length"); int const shiftR = 24 - (length + (start % 8)); cl = s[start / 8]; // get components @@ -295,12 +212,9 @@ RFC1751::btoe(std::string& strHuman, std::string const& strData) caBuffer[8] = char(p) << 6; - strHuman = std::string() + s_dictionary[extract(caBuffer, 0, 11)] + " " + - s_dictionary[extract(caBuffer, 11, 11)] + " " + - s_dictionary[extract(caBuffer, 22, 11)] + " " + - s_dictionary[extract(caBuffer, 33, 11)] + " " + - s_dictionary[extract(caBuffer, 44, 11)] + " " + - s_dictionary[extract(caBuffer, 55, 11)]; + strHuman = std::string() + s_dictionary[extract(caBuffer, 0, 11)] + " " + s_dictionary[extract(caBuffer, 11, 11)] + + " " + s_dictionary[extract(caBuffer, 22, 11)] + " " + s_dictionary[extract(caBuffer, 33, 11)] + " " + + s_dictionary[extract(caBuffer, 44, 11)] + " " + s_dictionary[extract(caBuffer, 55, 11)]; } void @@ -315,8 +229,7 @@ RFC1751::insert(char* s, int x, int start, int length) XRPL_ASSERT(length <= 11, "xrpl::RFC1751::insert : maximum length"); XRPL_ASSERT(start >= 0, "xrpl::RFC1751::insert : minimum start"); XRPL_ASSERT(length >= 0, "xrpl::RFC1751::insert : minimum length"); - XRPL_ASSERT( - start + length <= 66, "xrpl::RFC1751::insert : maximum start + length"); + XRPL_ASSERT(start + length <= 66, "xrpl::RFC1751::insert : maximum start + length"); shift = ((8 - ((start + length) % 8)) % 8); y = (long)x << shift; @@ -450,11 +363,7 @@ RFC1751::getKeyFromEnglish(std::string& strKey, std::string const& strHuman) boost::algorithm::trim(strTrimmed); - boost::algorithm::split( - vWords, - strTrimmed, - boost::algorithm::is_space(), - boost::algorithm::token_compress_on); + boost::algorithm::split(vWords, strTrimmed, boost::algorithm::is_space(), boost::algorithm::token_compress_on); rc = 12 == vWords.size() ? 1 : -1; @@ -503,8 +412,7 @@ RFC1751::getWordFromBlob(void const* blob, size_t bytes) hash ^= (hash >> 11); hash += (hash << 15); - return s_dictionary - [hash % (sizeof(s_dictionary) / sizeof(s_dictionary[0]))]; + return s_dictionary[hash % (sizeof(s_dictionary) / sizeof(s_dictionary[0]))]; } } // namespace xrpl diff --git a/src/libxrpl/crypto/csprng.cpp b/src/libxrpl/crypto/csprng.cpp index 5ee1700d7f..7858d4089c 100644 --- a/src/libxrpl/crypto/csprng.cpp +++ b/src/libxrpl/crypto/csprng.cpp @@ -46,10 +46,7 @@ csprng_engine::mix_entropy(void* buffer, std::size_t count) // We add data to the pool, but we conservatively assume that // it contributes no actual entropy. - RAND_add( - entropy.data(), - entropy.size() * sizeof(std::random_device::result_type), - 0); + RAND_add(entropy.data(), entropy.size() * sizeof(std::random_device::result_type), 0); if (buffer != nullptr && count != 0) RAND_add(buffer, count, 0); @@ -65,8 +62,7 @@ csprng_engine::operator()(void* ptr, std::size_t count) std::lock_guard lock(mutex_); #endif - auto const result = - RAND_bytes(reinterpret_cast(ptr), count); + auto const result = RAND_bytes(reinterpret_cast(ptr), count); if (result != 1) Throw("CSPRNG: Insufficient entropy"); diff --git a/src/libxrpl/json/Writer.cpp b/src/libxrpl/json/Writer.cpp index 6da29211ca..be9595b088 100644 --- a/src/libxrpl/json/Writer.cpp +++ b/src/libxrpl/json/Writer.cpp @@ -134,10 +134,7 @@ public: auto t = stack_.top().type; if (t != type) { - check( - false, - "Not an " + - ((type == array ? "array: " : "object: ") + message)); + check(false, "Not an " + ((type == array ? "array: " : "object: ") + message)); } if (stack_.top().isFirst) stack_.top().isFirst = false; diff --git a/src/libxrpl/json/json_reader.cpp b/src/libxrpl/json/json_reader.cpp index ca0b5e5eee..22df530b7e 100644 --- a/src/libxrpl/json/json_reader.cpp +++ b/src/libxrpl/json/json_reader.cpp @@ -104,9 +104,7 @@ Reader::parse(char const* beginDoc, char const* endDoc, Value& root) token.type_ = tokenError; token.start_ = beginDoc; token.end_ = endDoc; - addError( - "A valid JSON document must be either an array or an object value.", - token); + addError("A valid JSON document must be either an array or an object value.", token); return false; } @@ -157,8 +155,7 @@ Reader::readValue(unsigned depth) break; default: - return addError( - "Syntax error: value, object or array expected.", token); + return addError("Syntax error: value, object or array expected.", token); } return successful; @@ -361,10 +358,7 @@ Reader::readNumber() { if (!std::isdigit(static_cast(*current_))) { - auto ret = std::find( - std::begin(extended_tokens), - std::end(extended_tokens), - *current_); + auto ret = std::find(std::begin(extended_tokens), std::end(extended_tokens), *current_); if (ret == std::end(extended_tokens)) break; @@ -429,8 +423,7 @@ Reader::readObject(Token& tokenStart, unsigned depth) if (!readToken(colon) || colon.type_ != tokenMemberSeparator) { - return addErrorAndRecover( - "Missing ':' after object member name", colon, tokenObjectEnd); + return addErrorAndRecover("Missing ':' after object member name", colon, tokenObjectEnd); } // Reject duplicate names @@ -448,13 +441,9 @@ Reader::readObject(Token& tokenStart, unsigned depth) Token comma; if (!readToken(comma) || - (comma.type_ != tokenObjectEnd && - comma.type_ != tokenArraySeparator && comma.type_ != tokenComment)) + (comma.type_ != tokenObjectEnd && comma.type_ != tokenArraySeparator && comma.type_ != tokenComment)) { - return addErrorAndRecover( - "Missing ',' or '}' in object declaration", - comma, - tokenObjectEnd); + return addErrorAndRecover("Missing ',' or '}' in object declaration", comma, tokenObjectEnd); } bool finalizeTokenOk = true; @@ -466,8 +455,7 @@ Reader::readObject(Token& tokenStart, unsigned depth) return true; } - return addErrorAndRecover( - "Missing '}' or object member name", tokenName, tokenObjectEnd); + return addErrorAndRecover("Missing '}' or object member name", tokenName, tokenObjectEnd); } bool @@ -504,16 +492,11 @@ Reader::readArray(Token& tokenStart, unsigned depth) ok = readToken(token); } - bool badTokenType = - (token.type_ != tokenArraySeparator && - token.type_ != tokenArrayEnd); + bool badTokenType = (token.type_ != tokenArraySeparator && token.type_ != tokenArrayEnd); if (!ok || badTokenType) { - return addErrorAndRecover( - "Missing ',' or ']' in array declaration", - token, - tokenArrayEnd); + return addErrorAndRecover("Missing ',' or ']' in array declaration", token, tokenArrayEnd); } if (token.type_ == tokenArrayEnd) @@ -534,19 +517,14 @@ Reader::decodeNumber(Token& token) if (current == token.end_) { - return addError( - "'" + std::string(token.start_, token.end_) + - "' is not a valid number.", - token); + return addError("'" + std::string(token.start_, token.end_) + "' is not a valid number.", token); } // The existing Json integers are 32-bit so using a 64-bit value here avoids // overflows in the conversion code below. std::int64_t value = 0; - static_assert( - sizeof(value) > sizeof(Value::maxUInt), - "The JSON integer overflow logic will need to be reworked."); + static_assert(sizeof(value) > sizeof(Value::maxUInt), "The JSON integer overflow logic will need to be reworked."); while (current < token.end_ && (value <= Value::maxUInt)) { @@ -554,10 +532,7 @@ Reader::decodeNumber(Token& token) if (c < '0' || c > '9') { - return addError( - "'" + std::string(token.start_, token.end_) + - "' is not a number.", - token); + return addError("'" + std::string(token.start_, token.end_) + "' is not a number.", token); } value = (value * 10) + (c - '0'); @@ -566,10 +541,7 @@ Reader::decodeNumber(Token& token) // More tokens left -> input is larger than largest possible return value if (current != token.end_) { - return addError( - "'" + std::string(token.start_, token.end_) + - "' exceeds the allowable range.", - token); + return addError("'" + std::string(token.start_, token.end_) + "' exceeds the allowable range.", token); } if (isNegative) @@ -578,10 +550,7 @@ Reader::decodeNumber(Token& token) if (value < Value::minInt || value > Value::maxInt) { - return addError( - "'" + std::string(token.start_, token.end_) + - "' exceeds the allowable range.", - token); + return addError("'" + std::string(token.start_, token.end_) + "' exceeds the allowable range.", token); } currentValue() = static_cast(value); @@ -590,10 +559,7 @@ Reader::decodeNumber(Token& token) { if (value > Value::maxUInt) { - return addError( - "'" + std::string(token.start_, token.end_) + - "' exceeds the allowable range.", - token); + return addError("'" + std::string(token.start_, token.end_) + "' exceeds the allowable range.", token); } // If it's representable as a signed integer, construct it as one. @@ -637,9 +603,7 @@ Reader::decodeDouble(Token& token) count = sscanf(buffer.c_str(), format, &value); } if (count != 1) - return addError( - "'" + std::string(token.start_, token.end_) + "' is not a number.", - token); + return addError("'" + std::string(token.start_, token.end_) + "' is not a number.", token); currentValue() = value; return true; } @@ -672,8 +636,7 @@ Reader::decodeString(Token& token, std::string& decoded) else if (c == '\\') { if (current == end) - return addError( - "Empty escape sequence in string", token, current); + return addError("Empty escape sequence in string", token, current); Char escape = *current++; @@ -722,8 +685,7 @@ Reader::decodeString(Token& token, std::string& decoded) break; default: - return addError( - "Bad escape sequence in string", token, current); + return addError("Bad escape sequence in string", token, current); } } else @@ -736,11 +698,7 @@ Reader::decodeString(Token& token, std::string& decoded) } bool -Reader::decodeUnicodeCodePoint( - Token& token, - Location& current, - Location end, - unsigned int& unicode) +Reader::decodeUnicodeCodePoint(Token& token, Location& current, Location end, unsigned int& unicode) { if (!decodeUnicodeEscapeSequence(token, current, end, unicode)) return false; @@ -761,8 +719,7 @@ Reader::decodeUnicodeCodePoint( { if (decodeUnicodeEscapeSequence(token, current, end, surrogatePair)) { - unicode = 0x10000 + ((unicode & 0x3FF) << 10) + - (surrogatePair & 0x3FF); + unicode = 0x10000 + ((unicode & 0x3FF) << 10) + (surrogatePair & 0x3FF); } else return false; @@ -779,17 +736,10 @@ Reader::decodeUnicodeCodePoint( } bool -Reader::decodeUnicodeEscapeSequence( - Token& token, - Location& current, - Location end, - unsigned int& unicode) +Reader::decodeUnicodeEscapeSequence(Token& token, Location& current, Location end, unsigned int& unicode) { if (end - current < 4) - return addError( - "Bad unicode escape sequence in string: four digits expected.", - token, - current); + return addError("Bad unicode escape sequence in string: four digits expected.", token, current); unicode = 0; @@ -846,10 +796,7 @@ Reader::recoverFromError(TokenType skipUntilToken) } bool -Reader::addErrorAndRecover( - std::string const& message, - Token& token, - TokenType skipUntilToken) +Reader::addErrorAndRecover(std::string const& message, Token& token, TokenType skipUntilToken) { addError(message, token); return recoverFromError(skipUntilToken); @@ -871,8 +818,7 @@ Reader::getNextChar() } void -Reader::getLocationLineAndColumn(Location location, int& line, int& column) - const +Reader::getLocationLineAndColumn(Location location, int& line, int& column) const { Location current = begin_; Location lastLineStart = current; @@ -907,8 +853,7 @@ Reader::getLocationLineAndColumn(Location location) const { int line, column; getLocationLineAndColumn(location, line, column); - return "Line " + std::to_string(line) + ", Column " + - std::to_string(column); + return "Line " + std::to_string(line) + ", Column " + std::to_string(column); } std::string @@ -916,18 +861,14 @@ Reader::getFormattedErrorMessages() const { std::string formattedMessage; - for (Errors::const_iterator itError = errors_.begin(); - itError != errors_.end(); - ++itError) + for (Errors::const_iterator itError = errors_.begin(); itError != errors_.end(); ++itError) { ErrorInfo const& error = *itError; - formattedMessage += - "* " + getLocationLineAndColumn(error.token_.start_) + "\n"; + formattedMessage += "* " + getLocationLineAndColumn(error.token_.start_) + "\n"; formattedMessage += " " + error.message_ + "\n"; if (error.extra_) - formattedMessage += "See " + - getLocationLineAndColumn(error.extra_) + " for detail.\n"; + formattedMessage += "See " + getLocationLineAndColumn(error.extra_) + " for detail.\n"; } return formattedMessage; diff --git a/src/libxrpl/json/json_value.cpp b/src/libxrpl/json/json_value.cpp index b738774d79..edbbafc1eb 100644 --- a/src/libxrpl/json/json_value.cpp +++ b/src/libxrpl/json/json_value.cpp @@ -33,8 +33,7 @@ public: } char* - duplicateStringValue(char const* value, unsigned int length = unknown) - override + duplicateStringValue(char const* value, unsigned int length = unknown) override { //@todo investigate this old optimization // if ( !value || value[0] == 0 ) @@ -90,21 +89,15 @@ Value::CZString::CZString(int index) : cstr_(0), index_(index) } Value::CZString::CZString(char const* cstr, DuplicationPolicy allocate) - : cstr_( - allocate == duplicate ? valueAllocator()->makeMemberName(cstr) : cstr) - , index_(allocate) + : cstr_(allocate == duplicate ? valueAllocator()->makeMemberName(cstr) : cstr), index_(allocate) { } Value::CZString::CZString(CZString const& other) : cstr_( - other.index_ != noDuplication && other.cstr_ != 0 - ? valueAllocator()->makeMemberName(other.cstr_) - : other.cstr_) - , index_( - other.cstr_ - ? (other.index_ == noDuplication ? noDuplication : duplicate) - : other.index_) + other.index_ != noDuplication && other.cstr_ != 0 ? valueAllocator()->makeMemberName(other.cstr_) + : other.cstr_) + , index_(other.cstr_ ? (other.index_ == noDuplication ? noDuplication : duplicate) : other.index_) { } @@ -221,14 +214,12 @@ Value::Value(char const* value) : type_(stringValue), allocated_(true) Value::Value(xrpl::Number const& value) : type_(stringValue), allocated_(true) { auto const tmp = to_string(value); - value_.string_ = - valueAllocator()->duplicateStringValue(tmp.c_str(), tmp.length()); + value_.string_ = valueAllocator()->duplicateStringValue(tmp.c_str(), tmp.length()); } Value::Value(std::string const& value) : type_(stringValue), allocated_(true) { - value_.string_ = valueAllocator()->duplicateStringValue( - value.c_str(), (unsigned int)value.length()); + value_.string_ = valueAllocator()->duplicateStringValue(value.c_str(), (unsigned int)value.length()); } Value::Value(StaticString const& value) : type_(stringValue), allocated_(false) @@ -256,8 +247,7 @@ Value::Value(Value const& other) : type_(other.type_) case stringValue: if (other.value_.string_) { - value_.string_ = valueAllocator()->duplicateStringValue( - other.value_.string_); + value_.string_ = valueAllocator()->duplicateStringValue(other.value_.string_); allocated_ = true; } else @@ -315,8 +305,7 @@ Value::operator=(Value const& other) return *this; } -Value::Value(Value&& other) noexcept - : value_(other.value_), type_(other.type_), allocated_(other.allocated_) +Value::Value(Value&& other) noexcept : value_(other.value_), type_(other.type_), allocated_(other.allocated_) { other.type_ = nullValue; other.allocated_ = 0; @@ -392,8 +381,7 @@ operator<(Value const& x, Value const& y) case stringValue: return (x.value_.string_ == 0 && y.value_.string_) || - (y.value_.string_ && x.value_.string_ && - strcmp(x.value_.string_, y.value_.string_) < 0); + (y.value_.string_ && x.value_.string_ && strcmp(x.value_.string_, y.value_.string_) < 0); case arrayValue: case objectValue: { @@ -443,13 +431,11 @@ operator==(Value const& x, Value const& y) case stringValue: return x.value_.string_ == y.value_.string_ || - (y.value_.string_ && x.value_.string_ && - !strcmp(x.value_.string_, y.value_.string_)); + (y.value_.string_ && x.value_.string_ && !strcmp(x.value_.string_, y.value_.string_)); case arrayValue: case objectValue: - return x.value_.map_->size() == y.value_.map_->size() && - *x.value_.map_ == *y.value_.map_; + return x.value_.map_->size() == y.value_.map_->size() && *x.value_.map_ == *y.value_.map_; // LCOV_EXCL_START default: @@ -515,15 +501,11 @@ Value::asInt() const return value_.int_; case uintValue: - JSON_ASSERT_MESSAGE( - value_.uint_ < (unsigned)maxInt, - "integer out of signed integer range"); + JSON_ASSERT_MESSAGE(value_.uint_ < (unsigned)maxInt, "integer out of signed integer range"); return value_.uint_; case realValue: - JSON_ASSERT_MESSAGE( - value_.real_ >= minInt && value_.real_ <= maxInt, - "Real out of signed integer range"); + JSON_ASSERT_MESSAGE(value_.real_ >= minInt && value_.real_ <= maxInt, "Real out of signed integer range"); return Int(value_.real_); case booleanValue: @@ -569,13 +551,10 @@ Value::asAbsUInt() const case realValue: { if (value_.real_ < 0) { - JSON_ASSERT_MESSAGE( - -1 * value_.real_ <= maxUInt, - "Real out of unsigned integer range"); + JSON_ASSERT_MESSAGE(-1 * value_.real_ <= maxUInt, "Real out of unsigned integer range"); return UInt(-1 * value_.real_); } - JSON_ASSERT_MESSAGE( - value_.real_ <= maxUInt, "Real out of unsigned integer range"); + JSON_ASSERT_MESSAGE(value_.real_ <= maxUInt, "Real out of unsigned integer range"); return UInt(value_.real_); } @@ -587,13 +566,10 @@ Value::asAbsUInt() const auto const temp = beast::lexicalCastThrow(str); if (temp < 0) { - JSON_ASSERT_MESSAGE( - -1 * temp <= maxUInt, - "String out of unsigned integer range"); + JSON_ASSERT_MESSAGE(-1 * temp <= maxUInt, "String out of unsigned integer range"); return -1 * temp; } - JSON_ASSERT_MESSAGE( - temp <= maxUInt, "String out of unsigned integer range"); + JSON_ASSERT_MESSAGE(temp <= maxUInt, "String out of unsigned integer range"); return temp; } @@ -619,18 +595,14 @@ Value::asUInt() const return 0; case intValue: - JSON_ASSERT_MESSAGE( - value_.int_ >= 0, - "Negative integer can not be converted to unsigned integer"); + JSON_ASSERT_MESSAGE(value_.int_ >= 0, "Negative integer can not be converted to unsigned integer"); return value_.int_; case uintValue: return value_.uint_; case realValue: - JSON_ASSERT_MESSAGE( - value_.real_ >= 0 && value_.real_ <= maxUInt, - "Real out of unsigned integer range"); + JSON_ASSERT_MESSAGE(value_.real_ >= 0 && value_.real_ <= maxUInt, "Real out of unsigned integer range"); return UInt(value_.real_); case booleanValue: @@ -731,45 +703,34 @@ Value::isConvertibleTo(ValueType other) const return true; case intValue: - return (other == nullValue && value_.int_ == 0) || - other == intValue || (other == uintValue && value_.int_ >= 0) || - other == realValue || other == stringValue || + return (other == nullValue && value_.int_ == 0) || other == intValue || + (other == uintValue && value_.int_ >= 0) || other == realValue || other == stringValue || other == booleanValue; case uintValue: return (other == nullValue && value_.uint_ == 0) || - (other == intValue && value_.uint_ <= (unsigned)maxInt) || - other == uintValue || other == realValue || + (other == intValue && value_.uint_ <= (unsigned)maxInt) || other == uintValue || other == realValue || other == stringValue || other == booleanValue; case realValue: return (other == nullValue && value_.real_ == 0.0) || - (other == intValue && value_.real_ >= minInt && - value_.real_ <= maxInt) || - (other == uintValue && value_.real_ >= 0 && - value_.real_ <= maxUInt && - std::fabs(round(value_.real_) - value_.real_) < - std::numeric_limits::epsilon()) || - other == realValue || other == stringValue || - other == booleanValue; + (other == intValue && value_.real_ >= minInt && value_.real_ <= maxInt) || + (other == uintValue && value_.real_ >= 0 && value_.real_ <= maxUInt && + std::fabs(round(value_.real_) - value_.real_) < std::numeric_limits::epsilon()) || + other == realValue || other == stringValue || other == booleanValue; case booleanValue: - return (other == nullValue && value_.bool_ == false) || - other == intValue || other == uintValue || other == realValue || - other == stringValue || other == booleanValue; + return (other == nullValue && value_.bool_ == false) || other == intValue || other == uintValue || + other == realValue || other == stringValue || other == booleanValue; case stringValue: - return other == stringValue || - (other == nullValue && - (!value_.string_ || value_.string_[0] == 0)); + return other == stringValue || (other == nullValue && (!value_.string_ || value_.string_[0] == 0)); case arrayValue: - return other == arrayValue || - (other == nullValue && value_.map_->size() == 0); + return other == arrayValue || (other == nullValue && value_.map_->size() == 0); case objectValue: - return other == objectValue || - (other == nullValue && value_.map_->size() == 0); + return other == objectValue || (other == nullValue && value_.map_->size() == 0); // LCOV_EXCL_START default: @@ -833,9 +794,7 @@ Value::operator bool() const void Value::clear() { - XRPL_ASSERT( - type_ == nullValue || type_ == arrayValue || type_ == objectValue, - "Json::Value::clear : valid type"); + XRPL_ASSERT(type_ == nullValue || type_ == arrayValue || type_ == objectValue, "Json::Value::clear : valid type"); switch (type_) { @@ -852,9 +811,7 @@ Value::clear() Value& Value::operator[](UInt index) { - XRPL_ASSERT( - type_ == nullValue || type_ == arrayValue, - "Json::Value::operator[](UInt) : valid type"); + XRPL_ASSERT(type_ == nullValue || type_ == arrayValue, "Json::Value::operator[](UInt) : valid type"); if (type_ == nullValue) *this = Value(arrayValue); @@ -873,9 +830,7 @@ Value::operator[](UInt index) Value const& Value::operator[](UInt index) const { - XRPL_ASSERT( - type_ == nullValue || type_ == arrayValue, - "Json::Value::operator[](UInt) const : valid type"); + XRPL_ASSERT(type_ == nullValue || type_ == arrayValue, "Json::Value::operator[](UInt) const : valid type"); if (type_ == nullValue) return null; @@ -898,15 +853,12 @@ Value::operator[](char const* key) Value& Value::resolveReference(char const* key, bool isStatic) { - XRPL_ASSERT( - type_ == nullValue || type_ == objectValue, - "Json::Value::resolveReference : valid type"); + XRPL_ASSERT(type_ == nullValue || type_ == objectValue, "Json::Value::resolveReference : valid type"); if (type_ == nullValue) *this = Value(objectValue); - CZString actualKey( - key, isStatic ? CZString::noDuplication : CZString::duplicateOnCopy); + CZString actualKey(key, isStatic ? CZString::noDuplication : CZString::duplicateOnCopy); ObjectValues::iterator it = value_.map_->lower_bound(actualKey); if (it != value_.map_->end() && (*it).first == actualKey) @@ -934,9 +886,7 @@ Value::isValidIndex(UInt index) const Value const& Value::operator[](char const* key) const { - XRPL_ASSERT( - type_ == nullValue || type_ == objectValue, - "Json::Value::operator[](const char*) const : valid type"); + XRPL_ASSERT(type_ == nullValue || type_ == objectValue, "Json::Value::operator[](const char*) const : valid type"); if (type_ == nullValue) return null; @@ -1002,9 +952,7 @@ Value::get(std::string const& key, Value const& defaultValue) const Value Value::removeMember(char const* key) { - XRPL_ASSERT( - type_ == nullValue || type_ == objectValue, - "Json::Value::removeMember : valid type"); + XRPL_ASSERT(type_ == nullValue || type_ == objectValue, "Json::Value::removeMember : valid type"); if (type_ == nullValue) return null; @@ -1051,9 +999,7 @@ Value::isMember(StaticString const& key) const Value::Members Value::getMemberNames() const { - XRPL_ASSERT( - type_ == nullValue || type_ == objectValue, - "Json::Value::getMemberNames : valid type"); + XRPL_ASSERT(type_ == nullValue || type_ == objectValue, "Json::Value::getMemberNames : valid type"); if (type_ == nullValue) return Value::Members(); diff --git a/src/libxrpl/json/json_valueiterator.cpp b/src/libxrpl/json/json_valueiterator.cpp index e9c22ac5f7..90a1ebe44b 100644 --- a/src/libxrpl/json/json_valueiterator.cpp +++ b/src/libxrpl/json/json_valueiterator.cpp @@ -17,9 +17,7 @@ ValueIteratorBase::ValueIteratorBase() : current_(), isNull_(true) { } -ValueIteratorBase::ValueIteratorBase( - Value::ObjectValues::iterator const& current) - : current_(current), isNull_(false) +ValueIteratorBase::ValueIteratorBase(Value::ObjectValues::iterator const& current) : current_(current), isNull_(false) { } @@ -60,8 +58,7 @@ ValueIteratorBase::computeDistance(SelfType const& other) const // return difference_type( std::distance( current_, other.current_ ) ); difference_type myDistance = 0; - for (Value::ObjectValues::iterator it = current_; it != other.current_; - ++it) + for (Value::ObjectValues::iterator it = current_; it != other.current_; ++it) { ++myDistance; } @@ -128,9 +125,7 @@ ValueIteratorBase::memberName() const // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// -ValueConstIterator::ValueConstIterator( - Value::ObjectValues::iterator const& current) - : ValueIteratorBase(current) +ValueConstIterator::ValueConstIterator(Value::ObjectValues::iterator const& current) : ValueIteratorBase(current) { } @@ -149,18 +144,15 @@ ValueConstIterator::operator=(ValueIteratorBase const& other) // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// -ValueIterator::ValueIterator(Value::ObjectValues::iterator const& current) - : ValueIteratorBase(current) +ValueIterator::ValueIterator(Value::ObjectValues::iterator const& current) : ValueIteratorBase(current) { } -ValueIterator::ValueIterator(ValueConstIterator const& other) - : ValueIteratorBase(other) +ValueIterator::ValueIterator(ValueConstIterator const& other) : ValueIteratorBase(other) { } -ValueIterator::ValueIterator(ValueIterator const& other) - : ValueIteratorBase(other) +ValueIterator::ValueIterator(ValueIterator const& other) : ValueIteratorBase(other) { } diff --git a/src/libxrpl/json/json_writer.cpp b/src/libxrpl/json/json_writer.cpp index 2d0756852f..e36cf72b1c 100644 --- a/src/libxrpl/json/json_writer.cpp +++ b/src/libxrpl/json/json_writer.cpp @@ -81,9 +81,8 @@ valueToString(double value) // Print into the buffer. We need not request the alternative representation // that always has a decimal point because JSON doesn't distinguish the // concepts of reals and integers. -#if defined(_MSC_VER) && \ - defined(__STDC_SECURE_LIB__) // Use secure version with visual studio 2005 - // to avoid warning. +#if defined(_MSC_VER) && defined(__STDC_SECURE_LIB__) // Use secure version with visual studio 2005 + // to avoid warning. sprintf_s(buffer, sizeof(buffer), "%.16g", value); #else snprintf(buffer, sizeof(buffer), "%.16g", value); @@ -101,8 +100,7 @@ std::string valueToQuotedString(char const* value) { // Not sure how to handle unicode... - if (strpbrk(value, "\"\\\b\f\n\r\t") == nullptr && - !containsControlCharacter(value)) + if (strpbrk(value, "\"\\\b\f\n\r\t") == nullptr && !containsControlCharacter(value)) return std::string("\"") + value + "\""; // We have to walk value and escape any special characters. @@ -156,8 +154,7 @@ valueToQuotedString(char const* value) if (isControlCharacter(*c)) { std::ostringstream oss; - oss << "\\u" << std::hex << std::uppercase - << std::setfill('0') << std::setw(4) + oss << "\\u" << std::hex << std::uppercase << std::setfill('0') << std::setw(4) << static_cast(*c); result += oss.str(); } @@ -234,9 +231,7 @@ FastWriter::writeValue(Value const& value) Value::Members members(value.getMemberNames()); document_ += "{"; - for (Value::Members::iterator it = members.begin(); - it != members.end(); - ++it) + for (Value::Members::iterator it = members.begin(); it != members.end(); ++it) { std::string const& name = *it; @@ -379,9 +374,7 @@ StyledWriter::writeArrayValue(Value const& value) } else // output on a single line { - XRPL_ASSERT( - childValues_.size() == size, - "Json::StyledWriter::writeArrayValue : child size match"); + XRPL_ASSERT(childValues_.size() == size, "Json::StyledWriter::writeArrayValue : child size match"); document_ += "[ "; for (unsigned index = 0; index < size; ++index) @@ -407,9 +400,7 @@ StyledWriter::isMultilineArray(Value const& value) for (int index = 0; index < size && !isMultiLine; ++index) { Value const& childValue = value[index]; - isMultiLine = isMultiLine || - ((childValue.isArray() || childValue.isObject()) && - childValue.size() > 0); + isMultiLine = isMultiLine || ((childValue.isArray() || childValue.isObject()) && childValue.size() > 0); } if (!isMultiLine) // check if line length > max line length @@ -473,9 +464,7 @@ StyledWriter::indent() void StyledWriter::unindent() { - XRPL_ASSERT( - int(indentString_.size()) >= indentSize_, - "Json::StyledWriter::unindent : maximum indent size"); + XRPL_ASSERT(int(indentString_.size()) >= indentSize_, "Json::StyledWriter::unindent : maximum indent size"); indentString_.resize(indentString_.size() - indentSize_); } @@ -605,9 +594,7 @@ StyledStreamWriter::writeArrayValue(Value const& value) } else // output on a single line { - XRPL_ASSERT( - childValues_.size() == size, - "Json::StyledStreamWriter::writeArrayValue : child size match"); + XRPL_ASSERT(childValues_.size() == size, "Json::StyledStreamWriter::writeArrayValue : child size match"); *document_ << "[ "; for (unsigned index = 0; index < size; ++index) @@ -633,9 +620,7 @@ StyledStreamWriter::isMultilineArray(Value const& value) for (int index = 0; index < size && !isMultiLine; ++index) { Value const& childValue = value[index]; - isMultiLine = isMultiLine || - ((childValue.isArray() || childValue.isObject()) && - childValue.size() > 0); + isMultiLine = isMultiLine || ((childValue.isArray() || childValue.isObject()) && childValue.size() > 0); } if (!isMultiLine) // check if line length > max line length @@ -701,8 +686,7 @@ void StyledStreamWriter::unindent() { XRPL_ASSERT( - indentString_.size() >= indentation_.size(), - "Json::StyledStreamWriter::unindent : maximum indent size"); + indentString_.size() >= indentation_.size(), "Json::StyledStreamWriter::unindent : maximum indent size"); indentString_.resize(indentString_.size() - indentation_.size()); } diff --git a/src/xrpld/app/ledger/AcceptedLedgerTx.cpp b/src/libxrpl/ledger/AcceptedLedgerTx.cpp similarity index 69% rename from src/xrpld/app/ledger/AcceptedLedgerTx.cpp rename to src/libxrpl/ledger/AcceptedLedgerTx.cpp index d57246444f..3f35f7cbc2 100644 --- a/src/xrpld/app/ledger/AcceptedLedgerTx.cpp +++ b/src/libxrpl/ledger/AcceptedLedgerTx.cpp @@ -1,7 +1,7 @@ -#include - #include #include +#include +#include #include #include @@ -11,13 +11,9 @@ AcceptedLedgerTx::AcceptedLedgerTx( std::shared_ptr const& ledger, std::shared_ptr const& txn, std::shared_ptr const& met) - : mTxn(txn) - , mMeta(txn->getTransactionID(), ledger->seq(), *met) - , mAffected(mMeta.getAffectedAccounts()) + : mTxn(txn), mMeta(txn->getTransactionID(), ledger->seq(), *met), mAffected(mMeta.getAffectedAccounts()) { - XRPL_ASSERT( - !ledger->open(), - "xrpl::AcceptedLedgerTx::AcceptedLedgerTx : valid ledger state"); + XRPL_ASSERT(!ledger->open(), "xrpl::AcceptedLedgerTx::AcceptedLedgerTx : valid ledger state"); Serializer s; met->add(s); @@ -46,12 +42,8 @@ AcceptedLedgerTx::AcceptedLedgerTx( // If the offer create is not self funded then add the owner balance if (account != amount.issue().account) { - auto const ownerFunds = accountFunds( - *ledger, - account, - amount, - fhIGNORE_FREEZE, - beast::Journal{beast::Journal::getNullSink()}); + auto const ownerFunds = + accountFunds(*ledger, account, amount, fhIGNORE_FREEZE, beast::Journal{beast::Journal::getNullSink()}); mJson[jss::transaction][jss::owner_funds] = ownerFunds.getText(); } } @@ -60,9 +52,7 @@ AcceptedLedgerTx::AcceptedLedgerTx( std::string AcceptedLedgerTx::getEscMeta() const { - XRPL_ASSERT( - !mRawMeta.empty(), - "xrpl::AcceptedLedgerTx::getEscMeta : metadata is set"); + XRPL_ASSERT(!mRawMeta.empty(), "xrpl::AcceptedLedgerTx::getEscMeta : metadata is set"); return sqlBlobLiteral(mRawMeta); } diff --git a/src/libxrpl/ledger/ApplyStateTable.cpp b/src/libxrpl/ledger/ApplyStateTable.cpp index 94fd9d7273..9892951e15 100644 --- a/src/libxrpl/ledger/ApplyStateTable.cpp +++ b/src/libxrpl/ledger/ApplyStateTable.cpp @@ -65,11 +65,7 @@ ApplyStateTable::visit( switch (item.second.first) { case Action::erase: - func( - item.first, - true, - to.read(keylet::unchecked(item.first)), - item.second.second); + func(item.first, true, to.read(keylet::unchecked(item.first)), item.second.second); break; case Action::insert: @@ -77,11 +73,7 @@ ApplyStateTable::visit( break; case Action::modify: - func( - item.first, - false, - to.read(keylet::unchecked(item.first)), - item.second.second); + func(item.first, false, to.read(keylet::unchecked(item.first)), item.second.second); break; default: @@ -135,9 +127,8 @@ ApplyStateTable::apply( auto curNode = item.second.second; if ((type == &sfModifiedNode) && (*curNode == *origNode)) continue; - std::uint16_t nodeType = curNode - ? curNode->getFieldU16(sfLedgerEntryType) - : origNode->getFieldU16(sfLedgerEntryType); + std::uint16_t nodeType = + curNode ? curNode->getFieldU16(sfLedgerEntryType) : origNode->getFieldU16(sfLedgerEntryType); meta.setAffectedNode(item.first, *type, nodeType); if (type == &sfDeletedNode) { @@ -152,27 +143,23 @@ ApplyStateTable::apply( { // go through the original node for // modified fields saved on modification - if (obj.getFName().shouldMeta(SField::sMD_ChangeOrig) && - !curNode->hasMatchingEntry(obj)) + if (obj.getFName().shouldMeta(SField::sMD_ChangeOrig) && !curNode->hasMatchingEntry(obj)) prevs.emplace_back(obj); } if (!prevs.empty()) - meta.getAffectedNode(item.first) - .emplace_back(std::move(prevs)); + meta.getAffectedNode(item.first).emplace_back(std::move(prevs)); STObject finals(sfFinalFields); for (auto const& obj : *curNode) { // go through the final node for final fields - if (obj.getFName().shouldMeta( - SField::sMD_Always | SField::sMD_DeleteFinal)) + if (obj.getFName().shouldMeta(SField::sMD_Always | SField::sMD_DeleteFinal)) finals.emplace_back(obj); } if (!finals.empty()) - meta.getAffectedNode(item.first) - .emplace_back(std::move(finals)); + meta.getAffectedNode(item.first).emplace_back(std::move(finals)); } else if (type == &sfModifiedNode) { @@ -181,36 +168,31 @@ ApplyStateTable::apply( "xrpl::detail::ApplyStateTable::apply : valid nodes for " "modification"); - if (curNode->isThreadedType( - to.rules())) // thread transaction to node - // item modified + if (curNode->isThreadedType(to.rules())) // thread transaction to node + // item modified threadItem(meta, curNode); STObject prevs(sfPreviousFields); for (auto const& obj : *origNode) { // search the original node for values saved on modify - if (obj.getFName().shouldMeta(SField::sMD_ChangeOrig) && - !curNode->hasMatchingEntry(obj)) + if (obj.getFName().shouldMeta(SField::sMD_ChangeOrig) && !curNode->hasMatchingEntry(obj)) prevs.emplace_back(obj); } if (!prevs.empty()) - meta.getAffectedNode(item.first) - .emplace_back(std::move(prevs)); + meta.getAffectedNode(item.first).emplace_back(std::move(prevs)); STObject finals(sfFinalFields); for (auto const& obj : *curNode) { // search the final node for values saved always - if (obj.getFName().shouldMeta( - SField::sMD_Always | SField::sMD_ChangeNew)) + if (obj.getFName().shouldMeta(SField::sMD_Always | SField::sMD_ChangeNew)) finals.emplace_back(obj); } if (!finals.empty()) - meta.getAffectedNode(item.first) - .emplace_back(std::move(finals)); + meta.getAffectedNode(item.first).emplace_back(std::move(finals)); } else if (type == &sfCreatedNode) // if created, thread to owner(s) { @@ -220,23 +202,19 @@ ApplyStateTable::apply( "creation"); threadOwners(to, meta, curNode, newMod, j); - if (curNode->isThreadedType( - to.rules())) // always thread to self + if (curNode->isThreadedType(to.rules())) // always thread to self threadItem(meta, curNode); STObject news(sfNewFields); for (auto const& obj : *curNode) { // save non-default values - if (!obj.isDefault() && - obj.getFName().shouldMeta( - SField::sMD_Create | SField::sMD_Always)) + if (!obj.isDefault() && obj.getFName().shouldMeta(SField::sMD_Create | SField::sMD_Always)) news.emplace_back(obj); } if (!news.empty()) - meta.getAffectedNode(item.first) - .emplace_back(std::move(news)); + meta.getAffectedNode(item.first).emplace_back(std::move(news)); } else { @@ -298,10 +276,8 @@ ApplyStateTable::exists(ReadView const& base, Keylet const& k) const } auto -ApplyStateTable::succ( - ReadView const& base, - key_type const& key, - std::optional const& last) const -> std::optional +ApplyStateTable::succ(ReadView const& base, key_type const& key, std::optional const& last) const + -> std::optional { std::optional next = key; items_t::const_iterator iter; @@ -416,10 +392,8 @@ void ApplyStateTable::rawErase(ReadView const& base, std::shared_ptr const& sle) { using namespace std; - auto const result = items_.emplace( - piecewise_construct, - forward_as_tuple(sle->key()), - forward_as_tuple(Action::erase, sle)); + auto const result = + items_.emplace(piecewise_construct, forward_as_tuple(sle->key()), forward_as_tuple(Action::erase, sle)); if (result.second) return; auto& item = result.first->second; @@ -447,10 +421,7 @@ ApplyStateTable::insert(ReadView const& base, std::shared_ptr const& sle) { using namespace std; items_.emplace_hint( - iter, - piecewise_construct, - forward_as_tuple(sle->key()), - forward_as_tuple(Action::insert, sle)); + iter, piecewise_construct, forward_as_tuple(sle->key()), forward_as_tuple(Action::insert, sle)); return; } auto& item = iter->second; @@ -477,10 +448,7 @@ ApplyStateTable::replace(ReadView const& base, std::shared_ptr const& sle) { using namespace std; items_.emplace_hint( - iter, - piecewise_construct, - forward_as_tuple(sle->key()), - forward_as_tuple(Action::modify, sle)); + iter, piecewise_construct, forward_as_tuple(sle->key()), forward_as_tuple(Action::modify, sle)); return; } auto& item = iter->second; @@ -564,19 +532,13 @@ ApplyStateTable::threadItem(TxMeta& meta, std::shared_ptr const& sle) } std::shared_ptr -ApplyStateTable::getForMod( - ReadView const& base, - key_type const& key, - Mods& mods, - beast::Journal j) +ApplyStateTable::getForMod(ReadView const& base, key_type const& key, Mods& mods, beast::Journal j) { { auto miter = mods.find(key); if (miter != mods.end()) { - XRPL_ASSERT( - miter->second, - "xrpl::ApplyStateTable::getForMod : non-null result"); + XRPL_ASSERT(miter->second, "xrpl::ApplyStateTable::getForMod : non-null result"); return miter->second; } } @@ -615,12 +577,7 @@ ApplyStateTable::getForMod( } void -ApplyStateTable::threadTx( - ReadView const& base, - TxMeta& meta, - AccountID const& to, - Mods& mods, - beast::Journal j) +ApplyStateTable::threadTx(ReadView const& base, TxMeta& meta, AccountID const& to, Mods& mods, beast::Journal j) { auto const sle = getForMod(base, keylet::account(to).key, mods, j); if (!sle) @@ -632,9 +589,7 @@ ApplyStateTable::threadTx( return; } // threadItem only applied to AccountRoot - XRPL_ASSERT( - sle->isThreadedType(base.rules()), - "xrpl::ApplyStateTable::threadTx : SLE is threaded"); + XRPL_ASSERT(sle->isThreadedType(base.rules()), "xrpl::ApplyStateTable::threadTx : SLE is threaded"); threadItem(meta, sle); } diff --git a/src/libxrpl/ledger/ApplyView.cpp b/src/libxrpl/ledger/ApplyView.cpp index cfdbbbcb4d..fc35ff5119 100644 --- a/src/libxrpl/ledger/ApplyView.cpp +++ b/src/libxrpl/ledger/ApplyView.cpp @@ -110,8 +110,7 @@ insertPage( // Check whether we're out of pages. if (page == 0) return std::nullopt; - if (!view.rules().enabled(fixDirectoryLimit) && - page >= dirNodeMaxPages) // Old pages limit + if (!view.rules().enabled(fixDirectoryLimit) && page >= dirNodeMaxPages) // Old pages limit return std::nullopt; // We are about to create a new node; we'll link it to @@ -134,8 +133,7 @@ insertPage( // it's the default. if (page != 1) node->setFieldU64(sfIndexPrevious, page - 1); - XRPL_ASSERT_PARTS( - !nextPage, "xrpl::directory::insertPage", "nextPage has default value"); + XRPL_ASSERT_PARTS(!nextPage, "xrpl::directory::insertPage", "nextPage has default value"); /* Reserved for future use when directory pages may be inserted in * between two other pages instead of only at the end of the chain. if (nextPage) @@ -164,18 +162,15 @@ ApplyView::dirAdd( return directory::createRoot(*this, directory, key, describe); } - auto [page, node, indexes] = - directory::findPreviousPage(*this, directory, root); + auto [page, node, indexes] = directory::findPreviousPage(*this, directory, root); // If there's space, we use it: if (indexes.size() < dirNodeMaxEntries) { - return directory::insertKey( - *this, node, page, preserveOrder, indexes, key); + return directory::insertKey(*this, node, page, preserveOrder, indexes, key); } - return directory::insertPage( - *this, page, node, 0, root, key, directory, describe); + return directory::insertPage(*this, page, node, 0, root, key, directory, describe); } bool @@ -187,8 +182,7 @@ ApplyView::emptyDirDelete(Keylet const& directory) return false; // Verify that the passed directory node is the directory root. - if (directory.type != ltDIR_NODE || - node->getFieldH256(sfRootIndex) != directory.key) + if (directory.type != ltDIR_NODE || node->getFieldH256(sfRootIndex) != directory.key) { // LCOV_EXCL_START UNREACHABLE("xrpl::ApplyView::emptyDirDelete : invalid node type"); @@ -248,11 +242,7 @@ ApplyView::emptyDirDelete(Keylet const& directory) } bool -ApplyView::dirRemove( - Keylet const& directory, - std::uint64_t page, - uint256 const& key, - bool keepRoot) +ApplyView::dirRemove(Keylet const& directory, std::uint64_t page, uint256 const& key, bool keepRoot) { auto node = peek(keylet::page(directory, page)); @@ -373,8 +363,7 @@ ApplyView::dirRemove( // Check whether the next page is the last page and, if // so, whether it's empty. If it is, delete it. - if (nextPage != rootPage && next->getFieldU64(sfIndexNext) == rootPage && - next->getFieldV256(sfIndexes).empty()) + if (nextPage != rootPage && next->getFieldU64(sfIndexNext) == rootPage && next->getFieldV256(sfIndexes).empty()) { // Since next doesn't point to the root, it // can't be pointing to prev. @@ -409,9 +398,7 @@ ApplyView::dirRemove( } bool -ApplyView::dirDelete( - Keylet const& directory, - std::function const& callback) +ApplyView::dirDelete(Keylet const& directory, std::function const& callback) { std::optional pi; diff --git a/src/libxrpl/ledger/ApplyViewBase.cpp b/src/libxrpl/ledger/ApplyViewBase.cpp index 51abd8e4a6..ecb5180557 100644 --- a/src/libxrpl/ledger/ApplyViewBase.cpp +++ b/src/libxrpl/ledger/ApplyViewBase.cpp @@ -3,8 +3,7 @@ namespace xrpl { namespace detail { -ApplyViewBase::ApplyViewBase(ReadView const* base, ApplyFlags flags) - : flags_(flags), base_(base) +ApplyViewBase::ApplyViewBase(ReadView const* base, ApplyFlags flags) : flags_(flags), base_(base) { } @@ -41,8 +40,7 @@ ApplyViewBase::exists(Keylet const& k) const } auto -ApplyViewBase::succ(key_type const& key, std::optional const& last) - const -> std::optional +ApplyViewBase::succ(key_type const& key, std::optional const& last) const -> std::optional { return items_.succ(*base_, key, last); } @@ -66,8 +64,7 @@ ApplyViewBase::slesEnd() const -> std::unique_ptr } auto -ApplyViewBase::slesUpperBound(uint256 const& key) const - -> std::unique_ptr +ApplyViewBase::slesUpperBound(uint256 const& key) const -> std::unique_ptr { return base_->slesUpperBound(key); } diff --git a/src/libxrpl/ledger/ApplyViewImpl.cpp b/src/libxrpl/ledger/ApplyViewImpl.cpp index b0aeb70228..eca9043db8 100644 --- a/src/libxrpl/ledger/ApplyViewImpl.cpp +++ b/src/libxrpl/ledger/ApplyViewImpl.cpp @@ -2,8 +2,7 @@ namespace xrpl { -ApplyViewImpl::ApplyViewImpl(ReadView const* base, ApplyFlags flags) - : ApplyViewBase(base, flags) +ApplyViewImpl::ApplyViewImpl(ReadView const* base, ApplyFlags flags) : ApplyViewBase(base, flags) { } diff --git a/src/libxrpl/ledger/BookDirs.cpp b/src/libxrpl/ledger/BookDirs.cpp index 6dda4ffe51..03dd0b0e13 100644 --- a/src/libxrpl/ledger/BookDirs.cpp +++ b/src/libxrpl/ledger/BookDirs.cpp @@ -10,8 +10,7 @@ BookDirs::BookDirs(ReadView const& view, Book const& book) , next_quality_(getQualityNext(root_)) , key_(view_->succ(root_, next_quality_).value_or(beast::zero)) { - XRPL_ASSERT( - root_ != beast::zero, "xrpl::BookDirs::BookDirs : nonzero root"); + XRPL_ASSERT(root_ != beast::zero, "xrpl::BookDirs::BookDirs : nonzero root"); if (key_ != beast::zero) { if (!cdirFirst(*view_, key_, sle_, entry_, index_)) @@ -43,12 +42,10 @@ BookDirs::end() const -> BookDirs::const_iterator return BookDirs::const_iterator(*view_, root_, key_); } -beast::Journal BookDirs::const_iterator::j_ = - beast::Journal{beast::Journal::getNullSink()}; +beast::Journal BookDirs::const_iterator::j_ = beast::Journal{beast::Journal::getNullSink()}; bool -BookDirs::const_iterator::operator==( - BookDirs::const_iterator const& other) const +BookDirs::const_iterator::operator==(BookDirs::const_iterator const& other) const { if (view_ == nullptr || other.view_ == nullptr) return false; @@ -57,16 +54,13 @@ BookDirs::const_iterator::operator==( view_ == other.view_ && root_ == other.root_, "xrpl::BookDirs::const_iterator::operator== : views and roots are " "matching"); - return entry_ == other.entry_ && cur_key_ == other.cur_key_ && - index_ == other.index_; + return entry_ == other.entry_ && cur_key_ == other.cur_key_ && index_ == other.index_; } BookDirs::const_iterator::reference BookDirs::const_iterator::operator*() const { - XRPL_ASSERT( - index_ != beast::zero, - "xrpl::BookDirs::const_iterator::operator* : nonzero index"); + XRPL_ASSERT(index_ != beast::zero, "xrpl::BookDirs::const_iterator::operator* : nonzero index"); if (!cache_) cache_ = view_->read(keylet::offer(index_)); return *cache_; @@ -77,14 +71,10 @@ BookDirs::const_iterator::operator++() { using beast::zero; - XRPL_ASSERT( - index_ != zero, - "xrpl::BookDirs::const_iterator::operator++ : nonzero index"); + XRPL_ASSERT(index_ != zero, "xrpl::BookDirs::const_iterator::operator++ : nonzero index"); if (!cdirNext(*view_, cur_key_, sle_, entry_, index_)) { - if (index_ != 0 || - (cur_key_ = - view_->succ(++cur_key_, next_quality_).value_or(zero)) == zero) + if (index_ != 0 || (cur_key_ = view_->succ(++cur_key_, next_quality_).value_or(zero)) == zero) { cur_key_ = key_; entry_ = 0; @@ -107,9 +97,7 @@ BookDirs::const_iterator::operator++() BookDirs::const_iterator BookDirs::const_iterator::operator++(int) { - XRPL_ASSERT( - index_ != beast::zero, - "xrpl::BookDirs::const_iterator::operator++(int) : nonzero index"); + XRPL_ASSERT(index_ != beast::zero, "xrpl::BookDirs::const_iterator::operator++(int) : nonzero index"); const_iterator tmp(*this); ++(*this); return tmp; diff --git a/src/xrpld/app/ledger/BookListeners.cpp b/src/libxrpl/ledger/BookListeners.cpp similarity index 85% rename from src/xrpld/app/ledger/BookListeners.cpp rename to src/libxrpl/ledger/BookListeners.cpp index ebd59c3fcc..9ba25b783a 100644 --- a/src/xrpld/app/ledger/BookListeners.cpp +++ b/src/libxrpl/ledger/BookListeners.cpp @@ -1,4 +1,4 @@ -#include +#include namespace xrpl { @@ -17,9 +17,7 @@ BookListeners::removeSubscriber(std::uint64_t seq) } void -BookListeners::publish( - MultiApiJson const& jvObj, - hash_set& havePublished) +BookListeners::publish(MultiApiJson const& jvObj, hash_set& havePublished) { std::lock_guard sl(mLock); auto it = mListeners.cbegin(); diff --git a/src/libxrpl/ledger/CachedView.cpp b/src/libxrpl/ledger/CachedView.cpp index 19d4baa861..12704d227e 100644 --- a/src/libxrpl/ledger/CachedView.cpp +++ b/src/libxrpl/ledger/CachedView.cpp @@ -38,8 +38,7 @@ CachedViewImpl::read(Keylet const& k) const return base_.read(k); }); // If the sle is null, then a failure must have occurred in base_.read() - XRPL_ASSERT( - sle || baseRead, "xrpl::CachedView::read : null SLE result from base"); + XRPL_ASSERT(sle || baseRead, "xrpl::CachedView::read : null SLE result from base"); if (cacheHit && baseRead) hitsexpired.increment(); else if (cacheHit) diff --git a/src/libxrpl/ledger/CredentialHelpers.cpp b/src/libxrpl/ledger/CredentialHelpers.cpp index 82691238f9..c737d42f07 100644 --- a/src/libxrpl/ledger/CredentialHelpers.cpp +++ b/src/libxrpl/ledger/CredentialHelpers.cpp @@ -9,12 +9,9 @@ namespace xrpl { namespace credentials { bool -checkExpired( - std::shared_ptr const& sleCredential, - NetClock::time_point const& closed) +checkExpired(std::shared_ptr const& sleCredential, NetClock::time_point const& closed) { - std::uint32_t const exp = (*sleCredential)[~sfExpiration].value_or( - std::numeric_limits::max()); + std::uint32_t const exp = (*sleCredential)[~sfExpiration].value_or(std::numeric_limits::max()); std::uint32_t const now = closed.time_since_epoch().count(); return now > exp; } @@ -33,8 +30,7 @@ removeExpired(ApplyView& view, STVector256 const& arr, beast::Journal const j) if (sleCred && checkExpired(sleCred, closeTime)) { - JLOG(j.trace()) - << "Credentials are expired. Cred: " << sleCred->getText(); + JLOG(j.trace()) << "Credentials are expired. Cred: " << sleCred->getText(); // delete expired credentials even if the transaction failed deleteSLE(view, sleCred, j); foundExpired = true; @@ -45,17 +41,12 @@ removeExpired(ApplyView& view, STVector256 const& arr, beast::Journal const j) } TER -deleteSLE( - ApplyView& view, - std::shared_ptr const& sleCredential, - beast::Journal j) +deleteSLE(ApplyView& view, std::shared_ptr const& sleCredential, beast::Journal j) { if (!sleCredential) return tecNO_ENTRY; - auto delSLE = - [&view, &sleCredential, j]( - AccountID const& account, SField const& node, bool isOwner) -> TER { + auto delSLE = [&view, &sleCredential, j](AccountID const& account, SField const& node, bool isOwner) -> TER { auto const sleAccount = view.peek(keylet::account(account)); if (!sleAccount) { @@ -67,8 +58,7 @@ deleteSLE( // Remove object from owner directory std::uint64_t const page = sleCredential->getFieldU64(node); - if (!view.dirRemove( - keylet::ownerDir(account), page, sleCredential->key(), false)) + if (!view.dirRemove(keylet::ownerDir(account), page, sleCredential->key(), false)) { // LCOV_EXCL_START JLOG(j.fatal()) << "Unable to delete Credential from owner."; @@ -112,9 +102,7 @@ checkFields(STTx const& tx, beast::Journal j) auto const& credentials = tx.getFieldV256(sfCredentialIDs); if (credentials.empty() || (credentials.size() > maxCredentialsArraySize)) { - JLOG(j.trace()) - << "Malformed transaction: Credentials array size is invalid: " - << credentials.size(); + JLOG(j.trace()) << "Malformed transaction: Credentials array size is invalid: " << credentials.size(); return temMALFORMED; } @@ -124,8 +112,7 @@ checkFields(STTx const& tx, beast::Journal j) auto [it, ins] = duplicates.insert(cred); if (!ins) { - JLOG(j.trace()) - << "Malformed transaction: duplicates in credentials."; + JLOG(j.trace()) << "Malformed transaction: duplicates in credentials."; return temMALFORMED; } } @@ -134,11 +121,7 @@ checkFields(STTx const& tx, beast::Journal j) } TER -valid( - STTx const& tx, - ReadView const& view, - AccountID const& src, - beast::Journal j) +valid(STTx const& tx, ReadView const& view, AccountID const& src, beast::Journal j) { if (!tx.isFieldPresent(sfCredentialIDs)) return tesSUCCESS; @@ -155,9 +138,7 @@ valid( if (sleCred->getAccountID(sfSubject) != src) { - JLOG(j.trace()) - << "Credential doesn't belong to the source account. Cred: " - << h; + JLOG(j.trace()) << "Credential doesn't belong to the source account. Cred: " << h; return tecBAD_CREDENTIALS; } @@ -187,8 +168,7 @@ validDomain(ReadView const& view, uint256 domainID, AccountID const& subject) { auto const issuer = h.getAccountID(sfIssuer); auto const type = h.getFieldVL(sfCredentialType); - auto const keyletCredential = - keylet::credential(subject, issuer, makeSlice(type)); + auto const keyletCredential = keylet::credential(subject, issuer, makeSlice(type)); auto const sleCredential = view.read(keyletCredential); // We cannot delete expired credentials, that would require ApplyView& @@ -214,10 +194,7 @@ validDomain(ReadView const& view, uint256 domainID, AccountID const& subject) } TER -authorizedDepositPreauth( - ApplyView const& view, - STVector256 const& credIDs, - AccountID const& dst) +authorizedDepositPreauth(ApplyView const& view, STVector256 const& credIDs, AccountID const& dst) { std::set> sorted; std::vector> lifeExtender; @@ -228,8 +205,7 @@ authorizedDepositPreauth( if (!sleCred) // already checked in preclaim return tefINTERNAL; // LCOV_EXCL_LINE - auto [it, ins] = - sorted.emplace((*sleCred)[sfIssuer], (*sleCred)[sfCredentialType]); + auto [it, ins] = sorted.emplace((*sleCred)[sfIssuer], (*sleCred)[sfCredentialType]); if (!ins) return tefINTERNAL; // LCOV_EXCL_LINE lifeExtender.push_back(std::move(sleCred)); @@ -301,11 +277,7 @@ checkArray(STArray const& credentials, unsigned maxSize, beast::Journal j) } // namespace credentials TER -verifyValidDomain( - ApplyView& view, - AccountID const& account, - uint256 domainID, - beast::Journal j) +verifyValidDomain(ApplyView& view, AccountID const& account, uint256 domainID, beast::Journal j) { auto const slePD = view.read(keylet::permissionedDomain(domainID)); if (!slePD) @@ -318,8 +290,7 @@ verifyValidDomain( { auto const issuer = h.getAccountID(sfIssuer); auto const type = h.getFieldVL(sfCredentialType); - auto const keyletCredential = - keylet::credential(account, issuer, makeSlice(type)); + auto const keyletCredential = keylet::credential(account, issuer, makeSlice(type)); if (view.exists(keyletCredential)) credentials.push_back(keyletCredential.key); } @@ -355,8 +326,7 @@ verifyDepositPreauth( bool const credentialsPresent = tx.isFieldPresent(sfCredentialIDs); - if (credentialsPresent && - credentials::removeExpired(view, tx.getFieldV256(sfCredentialIDs), j)) + if (credentialsPresent && credentials::removeExpired(view, tx.getFieldV256(sfCredentialIDs), j)) return tecEXPIRED; if (sleDst && (sleDst->getFlags() & lsfDepositAuth)) @@ -366,8 +336,7 @@ verifyDepositPreauth( if (!view.exists(keylet::depositPreauth(dst, src))) return !credentialsPresent ? tecNO_PERMISSION - : credentials::authorizedDepositPreauth( - view, tx.getFieldV256(sfCredentialIDs), dst); + : credentials::authorizedDepositPreauth(view, tx.getFieldV256(sfCredentialIDs), dst); } } diff --git a/src/libxrpl/ledger/Credit.cpp b/src/libxrpl/ledger/Credit.cpp index 09798cef90..064fcdaf3b 100644 --- a/src/libxrpl/ledger/Credit.cpp +++ b/src/libxrpl/ledger/Credit.cpp @@ -6,11 +6,7 @@ namespace xrpl { STAmount -creditLimit( - ReadView const& view, - AccountID const& account, - AccountID const& issuer, - Currency const& currency) +creditLimit(ReadView const& view, AccountID const& account, AccountID const& issuer, Currency const& currency) { STAmount result(Issue{currency, account}); @@ -18,36 +14,23 @@ creditLimit( if (sleRippleState) { - result = sleRippleState->getFieldAmount( - account < issuer ? sfLowLimit : sfHighLimit); + result = sleRippleState->getFieldAmount(account < issuer ? sfLowLimit : sfHighLimit); result.setIssuer(account); } - XRPL_ASSERT( - result.getIssuer() == account, - "xrpl::creditLimit : result issuer match"); - XRPL_ASSERT( - result.getCurrency() == currency, - "xrpl::creditLimit : result currency match"); + XRPL_ASSERT(result.getIssuer() == account, "xrpl::creditLimit : result issuer match"); + XRPL_ASSERT(result.getCurrency() == currency, "xrpl::creditLimit : result currency match"); return result; } IOUAmount -creditLimit2( - ReadView const& v, - AccountID const& acc, - AccountID const& iss, - Currency const& cur) +creditLimit2(ReadView const& v, AccountID const& acc, AccountID const& iss, Currency const& cur) { return toAmount(creditLimit(v, acc, iss, cur)); } STAmount -creditBalance( - ReadView const& view, - AccountID const& account, - AccountID const& issuer, - Currency const& currency) +creditBalance(ReadView const& view, AccountID const& account, AccountID const& issuer, Currency const& currency) { STAmount result(Issue{currency, account}); @@ -61,12 +44,8 @@ creditBalance( result.setIssuer(account); } - XRPL_ASSERT( - result.getIssuer() == account, - "xrpl::creditBalance : result issuer match"); - XRPL_ASSERT( - result.getCurrency() == currency, - "xrpl::creditBalance : result currency match"); + XRPL_ASSERT(result.getIssuer() == account, "xrpl::creditBalance : result issuer match"); + XRPL_ASSERT(result.getCurrency() == currency, "xrpl::creditBalance : result currency match"); return result; } diff --git a/src/libxrpl/ledger/Dir.cpp b/src/libxrpl/ledger/Dir.cpp index d834216d24..cf0b01aa7f 100644 --- a/src/libxrpl/ledger/Dir.cpp +++ b/src/libxrpl/ledger/Dir.cpp @@ -4,8 +4,7 @@ namespace xrpl { using const_iterator = Dir::const_iterator; -Dir::Dir(ReadView const& view, Keylet const& key) - : view_(&view), root_(key), sle_(view_->read(root_)) +Dir::Dir(ReadView const& view, Keylet const& key) : view_(&view), root_(key), sle_(view_->read(root_)) { if (sle_ != nullptr) indexes_ = &sle_->getFieldV256(sfIndexes); @@ -50,9 +49,7 @@ const_iterator::operator==(const_iterator const& other) const const_iterator::reference const_iterator::operator*() const { - XRPL_ASSERT( - index_ != beast::zero, - "xrpl::const_iterator::operator* : nonzero index"); + XRPL_ASSERT(index_ != beast::zero, "xrpl::const_iterator::operator* : nonzero index"); if (!cache_) cache_ = view_->read(keylet::child(index_)); return *cache_; @@ -61,9 +58,7 @@ const_iterator::operator*() const const_iterator& const_iterator::operator++() { - XRPL_ASSERT( - index_ != beast::zero, - "xrpl::const_iterator::operator++ : nonzero index"); + XRPL_ASSERT(index_ != beast::zero, "xrpl::const_iterator::operator++ : nonzero index"); if (++it_ != std::end(*indexes_)) { index_ = *it_; @@ -77,9 +72,7 @@ const_iterator::operator++() const_iterator const_iterator::operator++(int) { - XRPL_ASSERT( - index_ != beast::zero, - "xrpl::const_iterator::operator++(int) : nonzero index"); + XRPL_ASSERT(index_ != beast::zero, "xrpl::const_iterator::operator++(int) : nonzero index"); const_iterator tmp(*this); ++(*this); return tmp; diff --git a/src/libxrpl/ledger/OpenView.cpp b/src/libxrpl/ledger/OpenView.cpp index 5df3ed7cda..73bd3e16ea 100644 --- a/src/libxrpl/ledger/OpenView.cpp +++ b/src/libxrpl/ledger/OpenView.cpp @@ -10,8 +10,7 @@ private: txs_map::const_iterator iter_; public: - explicit txs_iter_impl(bool metadata, txs_map::const_iterator iter) - : metadata_(metadata), iter_(iter) + explicit txs_iter_impl(bool metadata, txs_map::const_iterator iter) : metadata_(metadata), iter_(iter) { } @@ -57,8 +56,7 @@ public: OpenView::OpenView(OpenView const& rhs) : ReadView(rhs) , TxsRawView(rhs) - , monotonic_resource_{std::make_unique< - boost::container::pmr::monotonic_buffer_resource>(initialBufferSize)} + , monotonic_resource_{std::make_unique(initialBufferSize)} , txs_{rhs.txs_, monotonic_resource_.get()} , rules_{rhs.rules_} , header_{rhs.header_} @@ -67,13 +65,8 @@ OpenView::OpenView(OpenView const& rhs) , hold_{rhs.hold_} , open_{rhs.open_} {}; -OpenView::OpenView( - open_ledger_t, - ReadView const* base, - Rules const& rules, - std::shared_ptr hold) - : monotonic_resource_{std::make_unique< - boost::container::pmr::monotonic_buffer_resource>(initialBufferSize)} +OpenView::OpenView(open_ledger_t, ReadView const* base, Rules const& rules, std::shared_ptr hold) + : monotonic_resource_{std::make_unique(initialBufferSize)} , txs_{monotonic_resource_.get()} , rules_(rules) , header_(base->header()) @@ -88,8 +81,7 @@ OpenView::OpenView( } OpenView::OpenView(ReadView const* base, std::shared_ptr hold) - : monotonic_resource_{std::make_unique< - boost::container::pmr::monotonic_buffer_resource>(initialBufferSize)} + : monotonic_resource_{std::make_unique(initialBufferSize)} , txs_{monotonic_resource_.get()} , rules_(base->rules()) , header_(base->header()) @@ -140,8 +132,7 @@ OpenView::exists(Keylet const& k) const } auto -OpenView::succ(key_type const& key, std::optional const& last) const - -> std::optional +OpenView::succ(key_type const& key, std::optional const& last) const -> std::optional { return items_.succ(*base_, key, last); } @@ -165,8 +156,7 @@ OpenView::slesEnd() const -> std::unique_ptr } auto -OpenView::slesUpperBound(uint256 const& key) const - -> std::unique_ptr +OpenView::slesUpperBound(uint256 const& key) const -> std::unique_ptr { return items_.slesUpperBound(*base_, key); } @@ -199,8 +189,7 @@ OpenView::txRead(key_type const& key) const -> tx_type auto stx = std::make_shared(SerialIter{item.txn->slice()}); decltype(tx_type::second) sto; if (item.meta) - sto = std::make_shared( - SerialIter{item.meta->slice()}, sfMetadata); + sto = std::make_shared(SerialIter{item.meta->slice()}, sfMetadata); else sto = nullptr; return {std::move(stx), std::move(sto)}; @@ -242,10 +231,8 @@ OpenView::rawTxInsert( std::shared_ptr const& txn, std::shared_ptr const& metaData) { - auto const result = txs_.emplace( - std::piecewise_construct, - std::forward_as_tuple(key), - std::forward_as_tuple(txn, metaData)); + auto const result = + txs_.emplace(std::piecewise_construct, std::forward_as_tuple(key), std::forward_as_tuple(txn, metaData)); if (!result.second) LogicError("rawTxInsert: duplicate TX id: " + to_string(key)); } diff --git a/src/libxrpl/ledger/PaymentSandbox.cpp b/src/libxrpl/ledger/PaymentSandbox.cpp index 09600ae623..67492142da 100644 --- a/src/libxrpl/ledger/PaymentSandbox.cpp +++ b/src/libxrpl/ledger/PaymentSandbox.cpp @@ -8,10 +8,7 @@ namespace xrpl { namespace detail { auto -DeferredCredits::makeKey( - AccountID const& a1, - AccountID const& a2, - Currency const& c) -> Key +DeferredCredits::makeKey(AccountID const& a1, AccountID const& a2, Currency const& c) -> Key { if (a1 < a2) return std::make_tuple(a1, a2, c); @@ -26,12 +23,8 @@ DeferredCredits::credit( STAmount const& amount, STAmount const& preCreditSenderBalance) { - XRPL_ASSERT( - sender != receiver, - "xrpl::detail::DeferredCredits::credit : sender is not receiver"); - XRPL_ASSERT( - !amount.negative(), - "xrpl::detail::DeferredCredits::credit : positive amount"); + XRPL_ASSERT(sender != receiver, "xrpl::detail::DeferredCredits::credit : sender is not receiver"); + XRPL_ASSERT(!amount.negative(), "xrpl::detail::DeferredCredits::credit : positive amount"); auto const k = makeKey(sender, receiver, amount.getCurrency()); auto i = credits_.find(k); @@ -66,10 +59,7 @@ DeferredCredits::credit( } void -DeferredCredits::ownerCount( - AccountID const& id, - std::uint32_t cur, - std::uint32_t next) +DeferredCredits::ownerCount(AccountID const& id, std::uint32_t cur, std::uint32_t next) { auto const v = std::max(cur, next); auto r = ownerCounts_.emplace(std::make_pair(id, v)); @@ -91,10 +81,8 @@ DeferredCredits::ownerCount(AccountID const& id) const // Get the adjustments for the balance between main and other. auto -DeferredCredits::adjustments( - AccountID const& main, - AccountID const& other, - Currency const& currency) const -> std::optional +DeferredCredits::adjustments(AccountID const& main, AccountID const& other, Currency const& currency) const + -> std::optional { std::optional result; @@ -107,14 +95,12 @@ DeferredCredits::adjustments( if (main < other) { - result.emplace( - v.highAcctCredits, v.lowAcctCredits, v.lowAcctOrigBalance); + result.emplace(v.highAcctCredits, v.lowAcctCredits, v.lowAcctOrigBalance); return result; } else { - result.emplace( - v.lowAcctCredits, v.highAcctCredits, -v.lowAcctOrigBalance); + result.emplace(v.lowAcctCredits, v.highAcctCredits, -v.lowAcctOrigBalance); return result; } } @@ -150,10 +136,7 @@ DeferredCredits::apply(DeferredCredits& to) } // namespace detail STAmount -PaymentSandbox::balanceHook( - AccountID const& account, - AccountID const& issuer, - STAmount const& amount) const +PaymentSandbox::balanceHook(AccountID const& account, AccountID const& issuer, STAmount const& amount) const { /* There are two algorithms here. The pre-switchover algorithm takes the @@ -200,8 +183,7 @@ PaymentSandbox::balanceHook( } std::uint32_t -PaymentSandbox::ownerCountHook(AccountID const& account, std::uint32_t count) - const +PaymentSandbox::ownerCountHook(AccountID const& account, std::uint32_t count) const { std::uint32_t result = count; for (auto curSB = this; curSB; curSB = curSB->ps_) @@ -223,10 +205,7 @@ PaymentSandbox::creditHook( } void -PaymentSandbox::adjustOwnerCountHook( - AccountID const& account, - std::uint32_t cur, - std::uint32_t next) +PaymentSandbox::adjustOwnerCountHook(AccountID const& account, std::uint32_t cur, std::uint32_t next) { tab_.ownerCount(account, cur, next); } diff --git a/src/libxrpl/ledger/RawStateTable.cpp b/src/libxrpl/ledger/RawStateTable.cpp index b958e94c54..4b5f6837b2 100644 --- a/src/libxrpl/ledger/RawStateTable.cpp +++ b/src/libxrpl/ledger/RawStateTable.cpp @@ -126,8 +126,7 @@ private: void skip() { - while (iter1_ != end1_ && iter1_->second.action == Action::erase && - sle0_->key() == sle1_->key()) + while (iter1_ != end1_ && iter1_->second.action == Action::erase && sle0_->key() == sle1_->key()) { inc1(); inc0(); @@ -166,8 +165,7 @@ RawStateTable::apply(RawView& to) const bool RawStateTable::exists(ReadView const& base, Keylet const& k) const { - XRPL_ASSERT( - k.key.isNonZero(), "xrpl::detail::RawStateTable::exists : nonzero key"); + XRPL_ASSERT(k.key.isNonZero(), "xrpl::detail::RawStateTable::exists : nonzero key"); auto const iter = items_.find(k.key); if (iter == items_.end()) return base.exists(k); @@ -184,10 +182,8 @@ RawStateTable::exists(ReadView const& base, Keylet const& k) const the lower of the two. */ auto -RawStateTable::succ( - ReadView const& base, - key_type const& key, - std::optional const& last) const -> std::optional +RawStateTable::succ(ReadView const& base, key_type const& key, std::optional const& last) const + -> std::optional { std::optional next = key; items_t::const_iterator iter; @@ -223,9 +219,7 @@ RawStateTable::erase(std::shared_ptr const& sle) { // The base invariant is checked during apply auto const result = items_.emplace( - std::piecewise_construct, - std::forward_as_tuple(sle->key()), - std::forward_as_tuple(Action::erase, sle)); + std::piecewise_construct, std::forward_as_tuple(sle->key()), std::forward_as_tuple(Action::erase, sle)); if (result.second) return; auto& item = result.first->second; @@ -248,9 +242,7 @@ void RawStateTable::insert(std::shared_ptr const& sle) { auto const result = items_.emplace( - std::piecewise_construct, - std::forward_as_tuple(sle->key()), - std::forward_as_tuple(Action::insert, sle)); + std::piecewise_construct, std::forward_as_tuple(sle->key()), std::forward_as_tuple(Action::insert, sle)); if (result.second) return; auto& item = result.first->second; @@ -273,9 +265,7 @@ void RawStateTable::replace(std::shared_ptr const& sle) { auto const result = items_.emplace( - std::piecewise_construct, - std::forward_as_tuple(sle->key()), - std::forward_as_tuple(Action::replace, sle)); + std::piecewise_construct, std::forward_as_tuple(sle->key()), std::forward_as_tuple(Action::replace, sle)); if (result.second) return; auto& item = result.first->second; @@ -316,25 +306,20 @@ RawStateTable::destroyXRP(XRPAmount const& fee) std::unique_ptr RawStateTable::slesBegin(ReadView const& base) const { - return std::make_unique( - items_.begin(), items_.end(), base.sles.begin(), base.sles.end()); + return std::make_unique(items_.begin(), items_.end(), base.sles.begin(), base.sles.end()); } std::unique_ptr RawStateTable::slesEnd(ReadView const& base) const { - return std::make_unique( - items_.end(), items_.end(), base.sles.end(), base.sles.end()); + return std::make_unique(items_.end(), items_.end(), base.sles.end(), base.sles.end()); } std::unique_ptr RawStateTable::slesUpperBound(ReadView const& base, uint256 const& key) const { return std::make_unique( - items_.upper_bound(key), - items_.end(), - base.sles.upper_bound(key), - base.sles.end()); + items_.upper_bound(key), items_.end(), base.sles.upper_bound(key), base.sles.end()); } } // namespace detail diff --git a/src/libxrpl/ledger/ReadView.cpp b/src/libxrpl/ledger/ReadView.cpp index e0764d6c81..d6674ba0da 100644 --- a/src/libxrpl/ledger/ReadView.cpp +++ b/src/libxrpl/ledger/ReadView.cpp @@ -53,9 +53,7 @@ makeRulesGivenLedger(DigestAwareReadView const& ledger, Rules const& current) } Rules -makeRulesGivenLedger( - DigestAwareReadView const& ledger, - std::unordered_set> const& presets) +makeRulesGivenLedger(DigestAwareReadView const& ledger, std::unordered_set> const& presets) { Keylet const k = keylet::amendments(); std::optional digest = ledger.digest(k.key); diff --git a/src/libxrpl/ledger/View.cpp b/src/libxrpl/ledger/View.cpp index 16ec23ffab..72df44ec4a 100644 --- a/src/libxrpl/ledger/View.cpp +++ b/src/libxrpl/ledger/View.cpp @@ -27,21 +27,12 @@ namespace detail { template < class V, class N, - class = std::enable_if_t< - std::is_same_v, SLE> && - std::is_base_of_v>> + class = std::enable_if_t, SLE> && std::is_base_of_v>> bool -internalDirNext( - V& view, - uint256 const& root, - std::shared_ptr& page, - unsigned int& index, - uint256& entry) +internalDirNext(V& view, uint256 const& root, std::shared_ptr& page, unsigned int& index, uint256& entry) { auto const& svIndexes = page->getFieldV256(sfIndexes); - XRPL_ASSERT( - index <= svIndexes.size(), - "xrpl::detail::internalDirNext : index inside range"); + XRPL_ASSERT(index <= svIndexes.size(), "xrpl::detail::internalDirNext : index inside range"); if (index >= svIndexes.size()) { @@ -75,16 +66,9 @@ internalDirNext( template < class V, class N, - class = std::enable_if_t< - std::is_same_v, SLE> && - std::is_base_of_v>> + class = std::enable_if_t, SLE> && std::is_base_of_v>> bool -internalDirFirst( - V& view, - uint256 const& root, - std::shared_ptr& page, - unsigned int& index, - uint256& entry) +internalDirFirst(V& view, uint256 const& root, std::shared_ptr& page, unsigned int& index, uint256& entry) { if constexpr (std::is_const_v) page = view.read(keylet::page(root)); @@ -102,23 +86,13 @@ internalDirFirst( } // namespace detail bool -dirFirst( - ApplyView& view, - uint256 const& root, - std::shared_ptr& page, - unsigned int& index, - uint256& entry) +dirFirst(ApplyView& view, uint256 const& root, std::shared_ptr& page, unsigned int& index, uint256& entry) { return detail::internalDirFirst(view, root, page, index, entry); } bool -dirNext( - ApplyView& view, - uint256 const& root, - std::shared_ptr& page, - unsigned int& index, - uint256& entry) +dirNext(ApplyView& view, uint256 const& root, std::shared_ptr& page, unsigned int& index, uint256& entry) { return detail::internalDirNext(view, root, page, index, entry); } @@ -192,11 +166,7 @@ isGlobalFrozen(ReadView const& view, Asset const& asset) } bool -isIndividualFrozen( - ReadView const& view, - AccountID const& account, - Currency const& currency, - AccountID const& issuer) +isIndividualFrozen(ReadView const& view, AccountID const& account, Currency const& currency, AccountID const& issuer) { if (isXRP(currency)) return false; @@ -204,21 +174,16 @@ isIndividualFrozen( { // Check if the issuer froze the line auto const sle = view.read(keylet::line(account, issuer, currency)); - if (sle && - sle->isFlag((issuer > account) ? lsfHighFreeze : lsfLowFreeze)) + if (sle && sle->isFlag((issuer > account) ? lsfHighFreeze : lsfLowFreeze)) return true; } return false; } bool -isIndividualFrozen( - ReadView const& view, - AccountID const& account, - MPTIssue const& mptIssue) +isIndividualFrozen(ReadView const& view, AccountID const& account, MPTIssue const& mptIssue) { - if (auto const sle = - view.read(keylet::mptoken(mptIssue.getMptID(), account))) + if (auto const sle = view.read(keylet::mptoken(mptIssue.getMptID(), account))) return sle->isFlag(lsfMPTLocked); return false; } @@ -226,11 +191,7 @@ isIndividualFrozen( // Can the specified account spend the specified currency issued by // the specified issuer or does the freeze flag prohibit it? bool -isFrozen( - ReadView const& view, - AccountID const& account, - Currency const& currency, - AccountID const& issuer) +isFrozen(ReadView const& view, AccountID const& account, Currency const& currency, AccountID const& issuer) { if (isXRP(currency)) return false; @@ -241,31 +202,21 @@ isFrozen( { // Check if the issuer froze the line sle = view.read(keylet::line(account, issuer, currency)); - if (sle && - sle->isFlag((issuer > account) ? lsfHighFreeze : lsfLowFreeze)) + if (sle && sle->isFlag((issuer > account) ? lsfHighFreeze : lsfLowFreeze)) return true; } return false; } bool -isFrozen( - ReadView const& view, - AccountID const& account, - MPTIssue const& mptIssue, - int depth) +isFrozen(ReadView const& view, AccountID const& account, MPTIssue const& mptIssue, int depth) { - return isGlobalFrozen(view, mptIssue) || - isIndividualFrozen(view, account, mptIssue) || + return isGlobalFrozen(view, mptIssue) || isIndividualFrozen(view, account, mptIssue) || isVaultPseudoAccountFrozen(view, account, mptIssue, depth); } [[nodiscard]] bool -isAnyFrozen( - ReadView const& view, - std::initializer_list const& accounts, - MPTIssue const& mptIssue, - int depth) +isAnyFrozen(ReadView const& view, std::initializer_list const& accounts, MPTIssue const& mptIssue, int depth) { if (isGlobalFrozen(view, mptIssue)) return true; @@ -286,11 +237,7 @@ isAnyFrozen( } bool -isVaultPseudoAccountFrozen( - ReadView const& view, - AccountID const& account, - MPTIssue const& mptShare, - int depth) +isVaultPseudoAccountFrozen(ReadView const& view, AccountID const& account, MPTIssue const& mptShare, int depth) { if (!view.rules().enabled(featureSingleAssetVault)) return false; @@ -298,8 +245,7 @@ isVaultPseudoAccountFrozen( if (depth >= maxAssetCheckDepth) return true; // LCOV_EXCL_LINE - auto const mptIssuance = - view.read(keylet::mptIssuance(mptShare.getMptID())); + auto const mptIssuance = view.read(keylet::mptIssuance(mptShare.getMptID())); if (mptIssuance == nullptr) return false; // zero MPToken won't block deletion of MPTokenIssuance @@ -316,8 +262,7 @@ isVaultPseudoAccountFrozen( if (!mptIssuer->isFieldPresent(sfVaultID)) return false; // not a Vault pseudo-account, common case - auto const vault = - view.read(keylet::vault(mptIssuer->getFieldH256(sfVaultID))); + auto const vault = view.read(keylet::vault(mptIssuer->getFieldH256(sfVaultID))); if (vault == nullptr) { // LCOV_EXCL_START UNREACHABLE("xrpl::isVaultPseudoAccountFrozen : null vault"); @@ -329,11 +274,7 @@ isVaultPseudoAccountFrozen( } bool -isDeepFrozen( - ReadView const& view, - AccountID const& account, - Currency const& currency, - AccountID const& issuer) +isDeepFrozen(ReadView const& view, AccountID const& account, Currency const& currency, AccountID const& issuer) { if (isXRP(currency)) { @@ -355,11 +296,7 @@ isDeepFrozen( } bool -isLPTokenFrozen( - ReadView const& view, - AccountID const& account, - Issue const& asset, - Issue const& asset2) +isLPTokenFrozen(ReadView const& view, AccountID const& account, Issue const& asset, Issue const& asset2) { return isFrozen(view, account, asset.currency, asset.account) || isFrozen(view, account, asset2.currency, asset2.account); @@ -383,8 +320,7 @@ getLineIfUsable( if (zeroIfFrozen == fhZERO_IF_FROZEN) { - if (isFrozen(view, account, currency, issuer) || - isDeepFrozen(view, account, currency, issuer)) + if (isFrozen(view, account, currency, issuer) || isDeepFrozen(view, account, currency, issuer)) { return nullptr; } @@ -400,15 +336,10 @@ getLineIfUsable( } else if (sleIssuer->isFieldPresent(sfAMMID)) { - auto const sleAmm = - view.read(keylet::amm((*sleIssuer)[sfAMMID])); + auto const sleAmm = view.read(keylet::amm((*sleIssuer)[sfAMMID])); if (!sleAmm || - isLPTokenFrozen( - view, - account, - (*sleAmm)[sfAsset].get(), - (*sleAmm)[sfAsset2].get())) + isLPTokenFrozen(view, account, (*sleAmm)[sfAsset].get(), (*sleAmm)[sfAsset2].get())) { return nullptr; } @@ -451,8 +382,8 @@ getTrustLineBalance( amount.clear(Issue{currency, issuer}); } - JLOG(j.trace()) << "getTrustLineBalance:" << " account=" - << to_string(account) << " amount=" << amount.getFullText(); + JLOG(j.trace()) << "getTrustLineBalance:" << " account=" << to_string(account) + << " amount=" << amount.getFullText(); return view.balanceHook(account, issuer, amount); } @@ -477,15 +408,12 @@ accountHolds( if (returnSpendable && account == issuer) // If the account is the issuer, then their limit is effectively // infinite - return STAmount{ - Issue{currency, issuer}, STAmount::cMaxValue, STAmount::cMaxOffset}; + return STAmount{Issue{currency, issuer}, STAmount::cMaxValue, STAmount::cMaxOffset}; // IOU: Return balance on trust line modulo freeze - SLE::const_pointer const sle = - getLineIfUsable(view, account, currency, issuer, zeroIfFrozen, j); + SLE::const_pointer const sle = getLineIfUsable(view, account, currency, issuer, zeroIfFrozen, j); - return getTrustLineBalance( - view, sle, account, currency, issuer, returnSpendable, j); + return getTrustLineBalance(view, sle, account, currency, issuer, returnSpendable, j); } STAmount @@ -497,14 +425,7 @@ accountHolds( beast::Journal j, SpendableHandling includeFullBalance) { - return accountHolds( - view, - account, - issue.currency, - issue.account, - zeroIfFrozen, - j, - includeFullBalance); + return accountHolds(view, account, issue.currency, issue.account, zeroIfFrozen, j, includeFullBalance); } STAmount @@ -523,28 +444,23 @@ accountHolds( { // if the account is the issuer, and the issuance exists, their limit is // the issuance limit minus the outstanding value - auto const issuance = - view.read(keylet::mptIssuance(mptIssue.getMptID())); + auto const issuance = view.read(keylet::mptIssuance(mptIssue.getMptID())); if (!issuance) { return STAmount{mptIssue}; } return STAmount{ - mptIssue, - issuance->at(~sfMaximumAmount).value_or(maxMPTokenAmount) - - issuance->at(sfOutstandingAmount)}; + mptIssue, issuance->at(~sfMaximumAmount).value_or(maxMPTokenAmount) - issuance->at(sfOutstandingAmount)}; } STAmount amount; - auto const sleMpt = - view.read(keylet::mptoken(mptIssue.getMptID(), account)); + auto const sleMpt = view.read(keylet::mptoken(mptIssue.getMptID(), account)); if (!sleMpt) amount.clear(mptIssue); - else if ( - zeroIfFrozen == fhZERO_IF_FROZEN && isFrozen(view, account, mptIssue)) + else if (zeroIfFrozen == fhZERO_IF_FROZEN && isFrozen(view, account, mptIssue)) amount.clear(mptIssue); else { @@ -552,23 +468,18 @@ accountHolds( // Only if auth check is needed, as it needs to do an additional read // operation. Note featureSingleAssetVault will affect error codes. - if (zeroIfUnauthorized == ahZERO_IF_UNAUTHORIZED && - view.rules().enabled(featureSingleAssetVault)) + if (zeroIfUnauthorized == ahZERO_IF_UNAUTHORIZED && view.rules().enabled(featureSingleAssetVault)) { - if (auto const err = - requireAuth(view, mptIssue, account, AuthType::StrongAuth); - !isTesSuccess(err)) + if (auto const err = requireAuth(view, mptIssue, account, AuthType::StrongAuth); !isTesSuccess(err)) amount.clear(mptIssue); } else if (zeroIfUnauthorized == ahZERO_IF_UNAUTHORIZED) { - auto const sleIssuance = - view.read(keylet::mptIssuance(mptIssue.getMptID())); + auto const sleIssuance = view.read(keylet::mptIssuance(mptIssue.getMptID())); // if auth is enabled on the issuance and mpt is not authorized, // clear amount - if (sleIssuance && sleIssuance->isFlag(lsfMPTRequireAuth) && - !sleMpt->isFlag(lsfMPTAuthorized)) + if (sleIssuance && sleIssuance->isFlag(lsfMPTRequireAuth) && !sleMpt->isFlag(lsfMPTAuthorized)) amount.clear(mptIssue); } } @@ -590,19 +501,11 @@ accountHolds( [&](TIss const& value) { if constexpr (std::is_same_v) { - return accountHolds( - view, account, value, zeroIfFrozen, j, includeFullBalance); + return accountHolds(view, account, value, zeroIfFrozen, j, includeFullBalance); } else if constexpr (std::is_same_v) { - return accountHolds( - view, - account, - value, - zeroIfFrozen, - zeroIfUnauthorized, - j, - includeFullBalance); + return accountHolds(view, account, value, zeroIfFrozen, zeroIfUnauthorized, j, includeFullBalance); } }, asset.value()); @@ -619,13 +522,7 @@ accountFunds( if (!saDefault.native() && saDefault.getIssuer() == id) return saDefault; - return accountHolds( - view, - id, - saDefault.getCurrency(), - saDefault.getIssuer(), - freezeHandling, - j); + return accountHolds(view, id, saDefault.getCurrency(), saDefault.getIssuer(), freezeHandling, j); } // Prevent ownerCount from wrapping under error conditions. @@ -649,8 +546,7 @@ confineOwnerCount( { if (id) { - JLOG(j.fatal()) - << "Account " << *id << " owner count exceeds max!"; + JLOG(j.fatal()) << "Account " << *id << " owner count exceeds max!"; } adjusted = std::numeric_limits::max(); } @@ -662,8 +558,7 @@ confineOwnerCount( { if (id) { - JLOG(j.fatal()) - << "Account " << *id << " owner count set below 0!"; + JLOG(j.fatal()) << "Account " << *id << " owner count set below 0!"; } adjusted = 0; XRPL_ASSERT(!id, "xrpl::confineOwnerCount : id is not set"); @@ -673,47 +568,34 @@ confineOwnerCount( } XRPAmount -xrpLiquid( - ReadView const& view, - AccountID const& id, - std::int32_t ownerCountAdj, - beast::Journal j) +xrpLiquid(ReadView const& view, AccountID const& id, std::int32_t ownerCountAdj, beast::Journal j) { auto const sle = view.read(keylet::account(id)); if (sle == nullptr) return beast::zero; // Return balance minus reserve - std::uint32_t const ownerCount = confineOwnerCount( - view.ownerCountHook(id, sle->getFieldU32(sfOwnerCount)), ownerCountAdj); + std::uint32_t const ownerCount = + confineOwnerCount(view.ownerCountHook(id, sle->getFieldU32(sfOwnerCount)), ownerCountAdj); // Pseudo-accounts have no reserve requirement - auto const reserve = isPseudoAccount(sle) - ? XRPAmount{0} - : view.fees().accountReserve(ownerCount); + auto const reserve = isPseudoAccount(sle) ? XRPAmount{0} : view.fees().accountReserve(ownerCount); auto const fullBalance = sle->getFieldAmount(sfBalance); auto const balance = view.balanceHook(id, xrpAccount(), fullBalance); - STAmount const amount = - (balance < reserve) ? STAmount{0} : balance - reserve; + STAmount const amount = (balance < reserve) ? STAmount{0} : balance - reserve; - JLOG(j.trace()) << "accountHolds:" << " account=" << to_string(id) - << " amount=" << amount.getFullText() - << " fullBalance=" << fullBalance.getFullText() - << " balance=" << balance.getFullText() - << " reserve=" << reserve << " ownerCount=" << ownerCount - << " ownerCountAdj=" << ownerCountAdj; + JLOG(j.trace()) << "accountHolds:" << " account=" << to_string(id) << " amount=" << amount.getFullText() + << " fullBalance=" << fullBalance.getFullText() << " balance=" << balance.getFullText() + << " reserve=" << reserve << " ownerCount=" << ownerCount << " ownerCountAdj=" << ownerCountAdj; return amount.xrp(); } void -forEachItem( - ReadView const& view, - Keylet const& root, - std::function const&)> const& f) +forEachItem(ReadView const& view, Keylet const& root, std::function const&)> const& f) { XRPL_ASSERT(root.type == ltDIR_NODE, "xrpl::forEachItem : valid root type"); @@ -745,8 +627,7 @@ forEachItemAfter( unsigned int limit, std::function const&)> const& f) { - XRPL_ASSERT( - root.type == ltDIR_NODE, "xrpl::forEachItemAfter : valid root type"); + XRPL_ASSERT(root.type == ltDIR_NODE, "xrpl::forEachItemAfter : valid root type"); if (root.type != ltDIR_NODE) return false; @@ -831,8 +712,7 @@ transferRate(ReadView const& view, MPTID const& issuanceID) // fee is 0-50,000 (0-50%), rate is 1,000,000,000-2,000,000,000 // For example, if transfer fee is 50% then 10,000 * 50,000 = 500,000 // which represents 50% of 1,000,000,000 - if (auto const sle = view.read(keylet::mptIssuance(issuanceID)); - sle && sle->isFieldPresent(sfTransferFee)) + if (auto const sle = view.read(keylet::mptIssuance(issuanceID)); sle && sle->isFieldPresent(sfTransferFee)) return Rate{1'000'000'000u + 10'000 * sle->getFieldU16(sfTransferFee)}; return parityRate; @@ -852,21 +732,14 @@ transferRate(ReadView const& view, STAmount const& amount) } bool -areCompatible( - ReadView const& validLedger, - ReadView const& testLedger, - beast::Journal::Stream& s, - char const* reason) +areCompatible(ReadView const& validLedger, ReadView const& testLedger, beast::Journal::Stream& s, char const* reason) { bool ret = true; if (validLedger.header().seq < testLedger.header().seq) { // valid -> ... -> test - auto hash = hashOfSeq( - testLedger, - validLedger.header().seq, - beast::Journal{beast::Journal::getNullSink()}); + auto hash = hashOfSeq(testLedger, validLedger.header().seq, beast::Journal{beast::Journal::getNullSink()}); if (hash && (*hash != validLedger.header().hash)) { JLOG(s) << reason << " incompatible with valid ledger"; @@ -879,10 +752,7 @@ areCompatible( else if (validLedger.header().seq > testLedger.header().seq) { // test -> ... -> valid - auto hash = hashOfSeq( - validLedger, - testLedger.header().seq, - beast::Journal{beast::Journal::getNullSink()}); + auto hash = hashOfSeq(validLedger, testLedger.header().seq, beast::Journal{beast::Journal::getNullSink()}); if (hash && (*hash != testLedger.header().hash)) { JLOG(s) << reason << " incompatible preceding ledger"; @@ -904,11 +774,9 @@ areCompatible( if (!ret) { - JLOG(s) << "Val: " << validLedger.header().seq << " " - << to_string(validLedger.header().hash); + JLOG(s) << "Val: " << validLedger.header().seq << " " << to_string(validLedger.header().hash); - JLOG(s) << "New: " << testLedger.header().seq << " " - << to_string(testLedger.header().hash); + JLOG(s) << "New: " << testLedger.header().seq << " " << to_string(testLedger.header().hash); } return ret; @@ -927,10 +795,7 @@ areCompatible( if (testLedger.header().seq > validIndex) { // Ledger we are testing follows last valid ledger - auto hash = hashOfSeq( - testLedger, - validIndex, - beast::Journal{beast::Journal::getNullSink()}); + auto hash = hashOfSeq(testLedger, validIndex, beast::Journal{beast::Journal::getNullSink()}); if (hash && (*hash != validHash)) { JLOG(s) << reason << " incompatible following ledger"; @@ -939,9 +804,7 @@ areCompatible( ret = false; } } - else if ( - (validIndex == testLedger.header().seq) && - (testLedger.header().hash != validHash)) + else if ((validIndex == testLedger.header().seq) && (testLedger.header().hash != validHash)) { JLOG(s) << reason << " incompatible ledger"; @@ -952,8 +815,7 @@ areCompatible( { JLOG(s) << "Val: " << validIndex << " " << to_string(validHash); - JLOG(s) << "New: " << testLedger.header().seq << " " - << to_string(testLedger.header().hash); + JLOG(s) << "New: " << testLedger.header().seq << " " << to_string(testLedger.header().hash); } return ret; @@ -1005,8 +867,7 @@ getMajorityAmendments(ReadView const& view) auto const majorities = sle->getFieldArray(sfMajorities); for (auto const& m : majorities) - ret[m.getFieldH256(sfAmendment)] = - tp(d(m.getFieldU32(sfCloseTime))); + ret[m.getFieldH256(sfAmendment)] = tp(d(m.getFieldU32(sfCloseTime))); } } @@ -1019,8 +880,7 @@ hashOfSeq(ReadView const& ledger, LedgerIndex seq, beast::Journal journal) // Easy cases... if (seq > ledger.seq()) { - JLOG(journal.warn()) - << "Can't get seq " << seq << " from " << ledger.seq() << " future"; + JLOG(journal.warn()) << "Can't get seq " << seq << " from " << ledger.seq() << " future"; return std::nullopt; } if (seq == ledger.seq()) @@ -1035,28 +895,23 @@ hashOfSeq(ReadView const& ledger, LedgerIndex seq, beast::Journal journal) if (hashIndex) { XRPL_ASSERT( - hashIndex->getFieldU32(sfLastLedgerSequence) == - (ledger.seq() - 1), + hashIndex->getFieldU32(sfLastLedgerSequence) == (ledger.seq() - 1), "xrpl::hashOfSeq : matching ledger sequence"); STVector256 vec = hashIndex->getFieldV256(sfHashes); if (vec.size() >= diff) return vec[vec.size() - diff]; - JLOG(journal.warn()) - << "Ledger " << ledger.seq() << " missing hash for " << seq - << " (" << vec.size() << "," << diff << ")"; + JLOG(journal.warn()) << "Ledger " << ledger.seq() << " missing hash for " << seq << " (" << vec.size() + << "," << diff << ")"; } else { - JLOG(journal.warn()) - << "Ledger " << ledger.seq() << ":" << ledger.header().hash - << " missing normal list"; + JLOG(journal.warn()) << "Ledger " << ledger.seq() << ":" << ledger.header().hash << " missing normal list"; } } if ((seq & 0xff) != 0) { - JLOG(journal.debug()) - << "Can't get seq " << seq << " from " << ledger.seq() << " past"; + JLOG(journal.debug()) << "Can't get seq " << seq << " from " << ledger.seq() << " past"; return std::nullopt; } @@ -1066,15 +921,13 @@ hashOfSeq(ReadView const& ledger, LedgerIndex seq, beast::Journal journal) { auto const lastSeq = hashIndex->getFieldU32(sfLastLedgerSequence); XRPL_ASSERT(lastSeq >= seq, "xrpl::hashOfSeq : minimum last ledger"); - XRPL_ASSERT( - (lastSeq & 0xff) == 0, "xrpl::hashOfSeq : valid last ledger"); + XRPL_ASSERT((lastSeq & 0xff) == 0, "xrpl::hashOfSeq : valid last ledger"); auto const diff = (lastSeq - seq) >> 8; STVector256 vec = hashIndex->getFieldV256(sfHashes); if (vec.size() > diff) return vec[vec.size() - diff - 1]; } - JLOG(journal.warn()) << "Can't get seq " << seq << " from " << ledger.seq() - << " error"; + JLOG(journal.warn()) << "Can't get seq " << seq << " from " << ledger.seq() << " error"; return std::nullopt; } @@ -1085,11 +938,7 @@ hashOfSeq(ReadView const& ledger, LedgerIndex seq, beast::Journal journal) //------------------------------------------------------------------------------ void -adjustOwnerCount( - ApplyView& view, - std::shared_ptr const& sle, - std::int32_t amount, - beast::Journal j) +adjustOwnerCount(ApplyView& view, std::shared_ptr const& sle, std::int32_t amount, beast::Journal j) { if (!sle) return; @@ -1105,20 +954,13 @@ adjustOwnerCount( std::function describeOwnerDir(AccountID const& account) { - return [account](std::shared_ptr const& sle) { - (*sle)[sfOwner] = account; - }; + return [account](std::shared_ptr const& sle) { (*sle)[sfOwner] = account; }; } TER -dirLink( - ApplyView& view, - AccountID const& owner, - std::shared_ptr& object, - SF_UINT64 const& node) +dirLink(ApplyView& view, AccountID const& owner, std::shared_ptr& object, SF_UINT64 const& node) { - auto const page = view.dirInsert( - keylet::ownerDir(owner), object->key(), describeOwnerDir(owner)); + auto const page = view.dirInsert(keylet::ownerDir(owner), object->key(), describeOwnerDir(owner)); if (!page) return tecDIR_FULL; // LCOV_EXCL_LINE object->setFieldU64(node, *page); @@ -1133,8 +975,7 @@ pseudoAccountAddress(ReadView const& view, uint256 const& pseudoOwnerKey) for (std::uint16_t i = 0; i < maxAccountAttempts; ++i) { ripesha_hasher rsh; - auto const hash = - sha512Half(i, view.header().parentHash, pseudoOwnerKey); + auto const hash = sha512Half(i, view.header().parentHash, pseudoOwnerKey); rsh(hash.data(), hash.size()); AccountID const ret{static_cast(rsh)}; if (!view.read(keylet::account(ret))) @@ -1176,40 +1017,26 @@ getPseudoAccountFields() } [[nodiscard]] bool -isPseudoAccount( - std::shared_ptr sleAcct, - std::set const& pseudoFieldFilter) +isPseudoAccount(std::shared_ptr sleAcct, std::set const& pseudoFieldFilter) { auto const& fields = getPseudoAccountFields(); // Intentionally use defensive coding here because it's cheap and makes the // semantics of true return value clean. return sleAcct && sleAcct->getType() == ltACCOUNT_ROOT && - std::count_if( - fields.begin(), - fields.end(), - [&sleAcct, &pseudoFieldFilter](SField const* sf) -> bool { - return sleAcct->isFieldPresent(*sf) && - (pseudoFieldFilter.empty() || - pseudoFieldFilter.contains(sf)); - }) > 0; + std::count_if(fields.begin(), fields.end(), [&sleAcct, &pseudoFieldFilter](SField const* sf) -> bool { + return sleAcct->isFieldPresent(*sf) && (pseudoFieldFilter.empty() || pseudoFieldFilter.contains(sf)); + }) > 0; } Expected, TER> -createPseudoAccount( - ApplyView& view, - uint256 const& pseudoOwnerKey, - SField const& ownerField) +createPseudoAccount(ApplyView& view, uint256 const& pseudoOwnerKey, SField const& ownerField) { [[maybe_unused]] auto const& fields = getPseudoAccountFields(); XRPL_ASSERT( std::count_if( - fields.begin(), - fields.end(), - [&ownerField](SField const* sf) -> bool { - return *sf == ownerField; - }) == 1, + fields.begin(), fields.end(), [&ownerField](SField const* sf) -> bool { return *sf == ownerField; }) == 1, "xrpl::createPseudoAccount : valid owner field"); auto const accountId = pseudoAccountAddress(view, pseudoOwnerKey); @@ -1233,8 +1060,7 @@ createPseudoAccount( // Ignore reserves requirement, disable the master key, allow default // rippling, and enable deposit authorization to prevent payments into // pseudo-account. - account->setFieldU32( - sfFlags, lsfDisableMaster | lsfDefaultRipple | lsfDepositAuth); + account->setFieldU32(sfFlags, lsfDisableMaster | lsfDefaultRipple | lsfDepositAuth); // Link the pseudo-account with its owner object. account->setFieldH256(ownerField, pseudoOwnerKey); @@ -1275,10 +1101,7 @@ canAddHolding(ReadView const& view, MPTIssue const& mptIssue) canAddHolding(ReadView const& view, Asset const& asset) { return std::visit( - [&](TIss const& issue) -> TER { - return canAddHolding(view, issue); - }, - asset.value()); + [&](TIss const& issue) -> TER { return canAddHolding(view, issue); }, asset.value()); } [[nodiscard]] TER @@ -1312,11 +1135,7 @@ checkDestinationAndTag(SLE::const_ref toSle, bool hasDestinationTag) * even if `from` is the issuer. */ static TER -withdrawToDestExceedsLimit( - ReadView const& view, - AccountID const& from, - AccountID const& to, - STAmount const& amount) +withdrawToDestExceedsLimit(ReadView const& view, AccountID const& from, AccountID const& to, STAmount const& amount) { auto const& issuer = amount.getIssuer(); if (from == to || to == issuer || isXRP(issuer)) @@ -1383,8 +1202,7 @@ canWithdraw(ReadView const& view, STTx const& tx) auto const from = tx[sfAccount]; auto const to = tx[~sfDestination].value_or(from); - return canWithdraw( - view, from, to, tx[sfAmount], tx.isFieldPresent(sfDestinationTag)); + return canWithdraw(view, from, to, tx[sfAmount], tx.isFieldPresent(sfDestinationTag)); } TER @@ -1401,27 +1219,20 @@ doWithdraw( // Create trust line or MPToken for the receiving account if (dstAcct == senderAcct) { - if (auto const ter = addEmptyHolding( - view, senderAcct, priorBalance, amount.asset(), j); + if (auto const ter = addEmptyHolding(view, senderAcct, priorBalance, amount.asset(), j); !isTesSuccess(ter) && ter != tecDUPLICATE) return ter; } else { auto dstSle = view.peek(keylet::account(dstAcct)); - if (auto err = - verifyDepositPreauth(tx, view, senderAcct, dstAcct, dstSle, j)) + if (auto err = verifyDepositPreauth(tx, view, senderAcct, dstAcct, dstSle, j)) return err; } // Sanity check if (accountHolds( - view, - sourceAcct, - amount.asset(), - FreezeHandling::fhIGNORE_FREEZE, - AuthHandling::ahIGNORE_AUTH, - j) < amount) + view, sourceAcct, amount.asset(), FreezeHandling::fhIGNORE_FREEZE, AuthHandling::ahIGNORE_AUTH, j) < amount) { // LCOV_EXCL_START JLOG(j.error()) << "LoanBrokerCoverWithdraw: negative balance of " @@ -1432,8 +1243,7 @@ doWithdraw( // Move the funds directly from the broker's pseudo-account to the // dstAcct - return accountSend( - view, sourceAcct, dstAcct, amount, j, WaiveTransferFee::Yes); + return accountSend(view, sourceAcct, dstAcct, amount, j, WaiveTransferFee::Yes); } [[nodiscard]] TER @@ -1541,11 +1351,7 @@ authorizeMPToken( if (!sleMpt || (*sleMpt)[sfMPTAmount] != 0) return tecINTERNAL; // LCOV_EXCL_LINE - if (!view.dirRemove( - keylet::ownerDir(account), - (*sleMpt)[sfOwnerNode], - sleMpt->key(), - false)) + if (!view.dirRemove(keylet::ownerDir(account), (*sleMpt)[sfOwnerNode], sleMpt->key(), false)) return tecINTERNAL; // LCOV_EXCL_LINE adjustOwnerCount(view, sleAcct, -1, journal); @@ -1565,8 +1371,7 @@ authorizeMPToken( // items. This is similar to the reserve requirements of trust lines. std::uint32_t const uOwnerCount = sleAcct->getFieldU32(sfOwnerCount); XRPAmount const reserveCreate( - (uOwnerCount < 2) ? XRPAmount(beast::zero) - : view.fees().accountReserve(uOwnerCount + 1)); + (uOwnerCount < 2) ? XRPAmount(beast::zero) : view.fees().accountReserve(uOwnerCount + 1)); if (priorBalance < reserveCreate) return tecINSUFFICIENT_RESERVE; @@ -1576,8 +1381,7 @@ authorizeMPToken( if (!mpt || mpt->getAccountID(sfIssuer) == account) { // LCOV_EXCL_START - UNREACHABLE( - "xrpl::authorizeMPToken : invalid issuance or issuers token"); + UNREACHABLE("xrpl::authorizeMPToken : invalid issuance or issuers token"); if (view.rules().enabled(featureLendingProtocol)) return tecINTERNAL; // LCOV_EXCL_STOP @@ -1652,8 +1456,7 @@ trustCreate( std::uint32_t uQualityOut, beast::Journal j) { - JLOG(j.trace()) << "trustCreate: " << to_string(uSrcAccountID) << ", " - << to_string(uDstAccountID) << ", " + JLOG(j.trace()) << "trustCreate: " << to_string(uSrcAccountID) << ", " << to_string(uDstAccountID) << ", " << saBalance.getFullText(); auto const& uLowAccountID = !bSrcHigh ? uSrcAccountID : uDstAccountID; @@ -1670,18 +1473,14 @@ trustCreate( auto const sleRippleState = std::make_shared(ltRIPPLE_STATE, uIndex); view.insert(sleRippleState); - auto lowNode = view.dirInsert( - keylet::ownerDir(uLowAccountID), - sleRippleState->key(), - describeOwnerDir(uLowAccountID)); + auto lowNode = + view.dirInsert(keylet::ownerDir(uLowAccountID), sleRippleState->key(), describeOwnerDir(uLowAccountID)); if (!lowNode) return tecDIR_FULL; // LCOV_EXCL_LINE - auto highNode = view.dirInsert( - keylet::ownerDir(uHighAccountID), - sleRippleState->key(), - describeOwnerDir(uHighAccountID)); + auto highNode = + view.dirInsert(keylet::ownerDir(uHighAccountID), sleRippleState->key(), describeOwnerDir(uHighAccountID)); if (!highNode) return tecDIR_FULL; // LCOV_EXCL_LINE @@ -1694,11 +1493,9 @@ trustCreate( return tefINTERNAL; // LCOV_EXCL_LINE XRPL_ASSERT( - sleAccount->getAccountID(sfAccount) == - (bSetHigh ? uHighAccountID : uLowAccountID), + sleAccount->getAccountID(sfAccount) == (bSetHigh ? uHighAccountID : uLowAccountID), "xrpl::trustCreate : matching account ID"); - auto const slePeer = - view.peek(keylet::account(bSetHigh ? uLowAccountID : uHighAccountID)); + auto const slePeer = view.peek(keylet::account(bSetHigh ? uLowAccountID : uHighAccountID)); if (!slePeer) return tecNO_TARGET; @@ -1706,20 +1503,16 @@ trustCreate( sleRippleState->setFieldU64(sfLowNode, *lowNode); sleRippleState->setFieldU64(sfHighNode, *highNode); - sleRippleState->setFieldAmount( - bSetHigh ? sfHighLimit : sfLowLimit, saLimit); + sleRippleState->setFieldAmount(bSetHigh ? sfHighLimit : sfLowLimit, saLimit); sleRippleState->setFieldAmount( bSetHigh ? sfLowLimit : sfHighLimit, - STAmount(Issue{ - saBalance.getCurrency(), bSetDst ? uSrcAccountID : uDstAccountID})); + STAmount(Issue{saBalance.getCurrency(), bSetDst ? uSrcAccountID : uDstAccountID})); if (uQualityIn) - sleRippleState->setFieldU32( - bSetHigh ? sfHighQualityIn : sfLowQualityIn, uQualityIn); + sleRippleState->setFieldU32(bSetHigh ? sfHighQualityIn : sfLowQualityIn, uQualityIn); if (uQualityOut) - sleRippleState->setFieldU32( - bSetHigh ? sfHighQualityOut : sfLowQualityOut, uQualityOut); + sleRippleState->setFieldU32(bSetHigh ? sfHighQualityOut : sfLowQualityOut, uQualityOut); std::uint32_t uFlags = bSetHigh ? lsfHighReserve : lsfLowReserve; @@ -1750,21 +1543,15 @@ trustCreate( adjustOwnerCount(view, sleAccount, 1, j); // ONLY: Create ripple balance. - sleRippleState->setFieldAmount( - sfBalance, bSetHigh ? -saBalance : saBalance); + sleRippleState->setFieldAmount(sfBalance, bSetHigh ? -saBalance : saBalance); - view.creditHook( - uSrcAccountID, uDstAccountID, saBalance, saBalance.zeroed()); + view.creditHook(uSrcAccountID, uDstAccountID, saBalance, saBalance.zeroed()); return tesSUCCESS; } [[nodiscard]] TER -removeEmptyHolding( - ApplyView& view, - AccountID const& accountID, - Issue const& issue, - beast::Journal journal) +removeEmptyHolding(ApplyView& view, AccountID const& accountID, Issue const& issue, beast::Journal journal) { if (issue.native()) { @@ -1793,8 +1580,7 @@ removeEmptyHolding( if (line->isFlag(lsfLowReserve)) { // Clear reserve for low account. - auto sleLowAccount = - view.peek(keylet::account(line->at(sfLowLimit)->getIssuer())); + auto sleLowAccount = view.peek(keylet::account(line->at(sfLowLimit)->getIssuer())); if (!sleLowAccount) return tecINTERNAL; // LCOV_EXCL_LINE @@ -1808,8 +1594,7 @@ removeEmptyHolding( if (line->isFlag(lsfHighReserve)) { // Clear reserve for high account. - auto sleHighAccount = - view.peek(keylet::account(line->at(sfHighLimit)->getIssuer())); + auto sleHighAccount = view.peek(keylet::account(line->at(sfHighLimit)->getIssuer())); if (!sleHighAccount) return tecINTERNAL; // LCOV_EXCL_LINE @@ -1820,20 +1605,11 @@ removeEmptyHolding( line->clearFlag(lsfHighReserve); } - return trustDelete( - view, - line, - line->at(sfLowLimit)->getIssuer(), - line->at(sfHighLimit)->getIssuer(), - journal); + return trustDelete(view, line, line->at(sfLowLimit)->getIssuer(), line->at(sfHighLimit)->getIssuer(), journal); } [[nodiscard]] TER -removeEmptyHolding( - ApplyView& view, - AccountID const& accountID, - MPTIssue const& mptIssue, - beast::Journal journal) +removeEmptyHolding(ApplyView& view, AccountID const& accountID, MPTIssue const& mptIssue, beast::Journal journal) { // If the account is the issuer, then no token should exist. MPTs do not // have the legacy ability to create such a situation, but check anyway. If @@ -1874,22 +1650,14 @@ trustDelete( JLOG(j.trace()) << "trustDelete: Deleting ripple line: low"; - if (!view.dirRemove( - keylet::ownerDir(uLowAccountID), - uLowNode, - sleRippleState->key(), - false)) + if (!view.dirRemove(keylet::ownerDir(uLowAccountID), uLowNode, sleRippleState->key(), false)) { return tefBAD_LEDGER; // LCOV_EXCL_LINE } JLOG(j.trace()) << "trustDelete: Deleting ripple line: high"; - if (!view.dirRemove( - keylet::ownerDir(uHighAccountID), - uHighNode, - sleRippleState->key(), - false)) + if (!view.dirRemove(keylet::ownerDir(uHighAccountID), uHighNode, sleRippleState->key(), false)) { return tefBAD_LEDGER; // LCOV_EXCL_LINE } @@ -1911,20 +1679,12 @@ offerDelete(ApplyView& view, std::shared_ptr const& sle, beast::Journal j) // Detect legacy directories. uint256 uDirectory = sle->getFieldH256(sfBookDirectory); - if (!view.dirRemove( - keylet::ownerDir(owner), - sle->getFieldU64(sfOwnerNode), - offerIndex, - false)) + if (!view.dirRemove(keylet::ownerDir(owner), sle->getFieldU64(sfOwnerNode), offerIndex, false)) { return tefBAD_LEDGER; // LCOV_EXCL_LINE } - if (!view.dirRemove( - keylet::page(uDirectory), - sle->getFieldU64(sfBookNode), - offerIndex, - false)) + if (!view.dirRemove(keylet::page(uDirectory), sle->getFieldU64(sfBookNode), offerIndex, false)) { return tefBAD_LEDGER; // LCOV_EXCL_LINE } @@ -1942,8 +1702,7 @@ offerDelete(ApplyView& view, std::shared_ptr const& sle, beast::Journal j) auto const& dirIndex = bookDir.getFieldH256(sfBookDirectory); auto const& dirNode = bookDir.getFieldU64(sfBookNode); - if (!view.dirRemove( - keylet::page(dirIndex), dirNode, offerIndex, false)) + if (!view.dirRemove(keylet::page(dirIndex), dirNode, offerIndex, false)) { return tefBAD_LEDGER; // LCOV_EXCL_LINE } @@ -1980,19 +1739,13 @@ rippleCreditIOU( (void)issuer; // Disallow sending to self. - XRPL_ASSERT( - uSenderID != uReceiverID, - "xrpl::rippleCreditIOU : sender is not receiver"); + XRPL_ASSERT(uSenderID != uReceiverID, "xrpl::rippleCreditIOU : sender is not receiver"); bool const bSenderHigh = uSenderID > uReceiverID; auto const index = keylet::line(uSenderID, uReceiverID, currency); - XRPL_ASSERT( - !isXRP(uSenderID) && uSenderID != noAccount(), - "xrpl::rippleCreditIOU : sender is not XRP"); - XRPL_ASSERT( - !isXRP(uReceiverID) && uReceiverID != noAccount(), - "xrpl::rippleCreditIOU : receiver is not XRP"); + XRPL_ASSERT(!isXRP(uSenderID) && uSenderID != noAccount(), "xrpl::rippleCreditIOU : sender is not XRP"); + XRPL_ASSERT(!isXRP(uReceiverID) && uReceiverID != noAccount(), "xrpl::rippleCreditIOU : receiver is not XRP"); // If the line exists, modify it accordingly. if (auto const sleRippleState = view.peek(index)) @@ -2008,10 +1761,8 @@ rippleCreditIOU( saBalance -= saAmount; - JLOG(j.trace()) << "rippleCreditIOU: " << to_string(uSenderID) << " -> " - << to_string(uReceiverID) - << " : before=" << saBefore.getFullText() - << " amount=" << saAmount.getFullText() + JLOG(j.trace()) << "rippleCreditIOU: " << to_string(uSenderID) << " -> " << to_string(uReceiverID) + << " : before=" << saBefore.getFullText() << " amount=" << saAmount.getFullText() << " after=" << saBalance.getFullText(); std::uint32_t const uFlags(sleRippleState->getFieldU32(sfFlags)); @@ -2025,31 +1776,21 @@ rippleCreditIOU( // Sender is zero or negative. && (uFlags & (!bSenderHigh ? lsfLowReserve : lsfHighReserve)) // Sender reserve is set. - && - static_cast( - uFlags & (!bSenderHigh ? lsfLowNoRipple : lsfHighNoRipple)) != - static_cast( - view.read(keylet::account(uSenderID))->getFlags() & - lsfDefaultRipple) && + && static_cast(uFlags & (!bSenderHigh ? lsfLowNoRipple : lsfHighNoRipple)) != + static_cast(view.read(keylet::account(uSenderID))->getFlags() & lsfDefaultRipple) && !(uFlags & (!bSenderHigh ? lsfLowFreeze : lsfHighFreeze)) && - !sleRippleState->getFieldAmount( - !bSenderHigh ? sfLowLimit : sfHighLimit) + !sleRippleState->getFieldAmount(!bSenderHigh ? sfLowLimit : sfHighLimit) // Sender trust limit is 0. - && !sleRippleState->getFieldU32( - !bSenderHigh ? sfLowQualityIn : sfHighQualityIn) + && !sleRippleState->getFieldU32(!bSenderHigh ? sfLowQualityIn : sfHighQualityIn) // Sender quality in is 0. - && !sleRippleState->getFieldU32( - !bSenderHigh ? sfLowQualityOut : sfHighQualityOut)) + && !sleRippleState->getFieldU32(!bSenderHigh ? sfLowQualityOut : sfHighQualityOut)) // Sender quality out is 0. { // Clear the reserve of the sender, possibly delete the line! - adjustOwnerCount( - view, view.peek(keylet::account(uSenderID)), -1, j); + adjustOwnerCount(view, view.peek(keylet::account(uSenderID)), -1, j); // Clear reserve flag. - sleRippleState->setFieldU32( - sfFlags, - uFlags & (!bSenderHigh ? ~lsfLowReserve : ~lsfHighReserve)); + sleRippleState->setFieldU32(sfFlags, uFlags & (!bSenderHigh ? ~lsfLowReserve : ~lsfHighReserve)); // Balance is zero, receiver reserve is clear. bDelete = !saBalance // Balance is zero. @@ -2067,11 +1808,7 @@ rippleCreditIOU( if (bDelete) { return trustDelete( - view, - sleRippleState, - bSenderHigh ? uReceiverID : uSenderID, - !bSenderHigh ? uReceiverID : uSenderID, - j); + view, sleRippleState, bSenderHigh ? uReceiverID : uSenderID, !bSenderHigh ? uReceiverID : uSenderID, j); } view.update(sleRippleState); @@ -2085,8 +1822,7 @@ rippleCreditIOU( JLOG(j.debug()) << "rippleCreditIOU: " "create line: " - << to_string(uSenderID) << " -> " << to_string(uReceiverID) - << " : " << saAmount.getFullText(); + << to_string(uSenderID) << " -> " << to_string(uReceiverID) << " : " << saAmount.getFullText(); auto const sleAccount = view.peek(keylet::account(uReceiverID)); if (!sleAccount) @@ -2127,18 +1863,13 @@ rippleSendIOU( { auto const& issuer = saAmount.getIssuer(); - XRPL_ASSERT( - !isXRP(uSenderID) && !isXRP(uReceiverID), - "xrpl::rippleSendIOU : neither sender nor receiver is XRP"); - XRPL_ASSERT( - uSenderID != uReceiverID, - "xrpl::rippleSendIOU : sender is not receiver"); + XRPL_ASSERT(!isXRP(uSenderID) && !isXRP(uReceiverID), "xrpl::rippleSendIOU : neither sender nor receiver is XRP"); + XRPL_ASSERT(uSenderID != uReceiverID, "xrpl::rippleSendIOU : sender is not receiver"); if (uSenderID == issuer || uReceiverID == issuer || issuer == noAccount()) { // Direct send: redeeming IOUs and/or sending own IOUs. - auto const ter = - rippleCreditIOU(view, uSenderID, uReceiverID, saAmount, false, j); + auto const ter = rippleCreditIOU(view, uSenderID, uReceiverID, saAmount, false, j); if (ter != tesSUCCESS) return ter; saActual = saAmount; @@ -2149,17 +1880,12 @@ rippleSendIOU( // Calculate the amount to transfer accounting // for any transfer fees if the fee is not waived: - saActual = (waiveFee == WaiveTransferFee::Yes) - ? saAmount - : multiply(saAmount, transferRate(view, issuer)); + saActual = (waiveFee == WaiveTransferFee::Yes) ? saAmount : multiply(saAmount, transferRate(view, issuer)); - JLOG(j.debug()) << "rippleSendIOU> " << to_string(uSenderID) << " - > " - << to_string(uReceiverID) - << " : deliver=" << saAmount.getFullText() - << " cost=" << saActual.getFullText(); + JLOG(j.debug()) << "rippleSendIOU> " << to_string(uSenderID) << " - > " << to_string(uReceiverID) + << " : deliver=" << saAmount.getFullText() << " cost=" << saActual.getFullText(); - TER terResult = - rippleCreditIOU(view, issuer, uReceiverID, saAmount, true, j); + TER terResult = rippleCreditIOU(view, issuer, uReceiverID, saAmount, true, j); if (tesSUCCESS == terResult) terResult = rippleCreditIOU(view, uSenderID, issuer, saActual, true, j); @@ -2182,8 +1908,7 @@ rippleSendMultiIOU( { auto const& issuer = issue.getIssuer(); - XRPL_ASSERT( - !isXRP(senderID), "xrpl::rippleSendMultiIOU : sender is not XRP"); + XRPL_ASSERT(!isXRP(senderID), "xrpl::rippleSendMultiIOU : sender is not XRP"); // These may diverge STAmount takeFromSender{issue}; @@ -2201,15 +1926,12 @@ rippleSendMultiIOU( if (!amount || (senderID == receiverID)) continue; - XRPL_ASSERT( - !isXRP(receiverID), - "xrpl::rippleSendMultiIOU : receiver is not XRP"); + XRPL_ASSERT(!isXRP(receiverID), "xrpl::rippleSendMultiIOU : receiver is not XRP"); if (senderID == issuer || receiverID == issuer || issuer == noAccount()) { // Direct send: redeeming IOUs and/or sending own IOUs. - if (auto const ter = rippleCreditIOU( - view, senderID, receiverID, amount, false, j)) + if (auto const ter = rippleCreditIOU(view, senderID, receiverID, amount, false, j)) return ter; actual += amount; // Do not add amount to takeFromSender, because rippleCreditIOU took @@ -2222,26 +1944,21 @@ rippleSendMultiIOU( // Calculate the amount to transfer accounting // for any transfer fees if the fee is not waived: - STAmount actualSend = (waiveFee == WaiveTransferFee::Yes) - ? amount - : multiply(amount, transferRate(view, issuer)); + STAmount actualSend = + (waiveFee == WaiveTransferFee::Yes) ? amount : multiply(amount, transferRate(view, issuer)); actual += actualSend; takeFromSender += actualSend; - JLOG(j.debug()) << "rippleSendMultiIOU> " << to_string(senderID) - << " - > " << to_string(receiverID) - << " : deliver=" << amount.getFullText() - << " cost=" << actual.getFullText(); + JLOG(j.debug()) << "rippleSendMultiIOU> " << to_string(senderID) << " - > " << to_string(receiverID) + << " : deliver=" << amount.getFullText() << " cost=" << actual.getFullText(); - if (TER const terResult = - rippleCreditIOU(view, issuer, receiverID, amount, true, j)) + if (TER const terResult = rippleCreditIOU(view, issuer, receiverID, amount, true, j)) return terResult; } if (senderID != issuer && takeFromSender) { - if (TER const terResult = rippleCreditIOU( - view, senderID, issuer, takeFromSender, true, j)) + if (TER const terResult = rippleCreditIOU(view, senderID, issuer, takeFromSender, true, j)) return terResult; } @@ -2283,12 +2000,10 @@ accountSendIOU( { STAmount saActual; - JLOG(j.trace()) << "accountSendIOU: " << to_string(uSenderID) << " -> " - << to_string(uReceiverID) << " : " + JLOG(j.trace()) << "accountSendIOU: " << to_string(uSenderID) << " -> " << to_string(uReceiverID) << " : " << saAmount.getFullText(); - return rippleSendIOU( - view, uSenderID, uReceiverID, saAmount, saActual, j, waiveFee); + return rippleSendIOU(view, uSenderID, uReceiverID, saAmount, saActual, j, waiveFee); } /* XRP send which does not check reserve and can do pure adjustment. @@ -2298,12 +2013,8 @@ accountSendIOU( */ TER terResult(tesSUCCESS); - SLE::pointer sender = uSenderID != beast::zero - ? view.peek(keylet::account(uSenderID)) - : SLE::pointer(); - SLE::pointer receiver = uReceiverID != beast::zero - ? view.peek(keylet::account(uReceiverID)) - : SLE::pointer(); + SLE::pointer sender = uSenderID != beast::zero ? view.peek(keylet::account(uSenderID)) : SLE::pointer(); + SLE::pointer receiver = uReceiverID != beast::zero ? view.peek(keylet::account(uReceiverID)) : SLE::pointer(); if (auto stream = j.trace()) { @@ -2316,9 +2027,8 @@ accountSendIOU( if (receiver) receiver_bal = receiver->getFieldAmount(sfBalance).getFullText(); - stream << "accountSendIOU> " << to_string(uSenderID) << " (" - << sender_bal << ") -> " << to_string(uReceiverID) << " (" - << receiver_bal << ") : " << saAmount.getFullText(); + stream << "accountSendIOU> " << to_string(uSenderID) << " (" << sender_bal << ") -> " << to_string(uReceiverID) + << " (" << receiver_bal << ") : " << saAmount.getFullText(); } if (sender) @@ -2328,8 +2038,7 @@ accountSendIOU( // VFALCO Its laborious to have to mutate the // TER based on params everywhere // LCOV_EXCL_START - terResult = view.open() ? TER{telFAILED_PROCESSING} - : TER{tecFAILED_PROCESSING}; + terResult = view.open() ? TER{telFAILED_PROCESSING} : TER{tecFAILED_PROCESSING}; // LCOV_EXCL_STOP } else @@ -2364,9 +2073,8 @@ accountSendIOU( if (receiver) receiver_bal = receiver->getFieldAmount(sfBalance).getFullText(); - stream << "accountSendIOU< " << to_string(uSenderID) << " (" - << sender_bal << ") -> " << to_string(uReceiverID) << " (" - << receiver_bal << ") : " << saAmount.getFullText(); + stream << "accountSendIOU< " << to_string(uSenderID) << " (" << sender_bal << ") -> " << to_string(uReceiverID) + << " (" << receiver_bal << ") : " << saAmount.getFullText(); } return terResult; @@ -2381,19 +2089,14 @@ accountSendMultiIOU( beast::Journal j, WaiveTransferFee waiveFee) { - XRPL_ASSERT_PARTS( - receivers.size() > 1, - "xrpl::accountSendMultiIOU", - "multiple recipients provided"); + XRPL_ASSERT_PARTS(receivers.size() > 1, "xrpl::accountSendMultiIOU", "multiple recipients provided"); if (!issue.native()) { STAmount actual; - JLOG(j.trace()) << "accountSendMultiIOU: " << to_string(senderID) - << " sending " << receivers.size() << " IOUs"; + JLOG(j.trace()) << "accountSendMultiIOU: " << to_string(senderID) << " sending " << receivers.size() << " IOUs"; - return rippleSendMultiIOU( - view, senderID, issue, receivers, actual, j, waiveFee); + return rippleSendMultiIOU(view, senderID, issue, receivers, actual, j, waiveFee); } /* XRP send which does not check reserve and can do pure adjustment. @@ -2402,9 +2105,7 @@ accountSendMultiIOU( * ensure that transfers are balanced. */ - SLE::pointer sender = senderID != beast::zero - ? view.peek(keylet::account(senderID)) - : SLE::pointer(); + SLE::pointer sender = senderID != beast::zero ? view.peek(keylet::account(senderID)) : SLE::pointer(); if (auto stream = j.trace()) { @@ -2413,8 +2114,8 @@ accountSendMultiIOU( if (sender) sender_bal = sender->getFieldAmount(sfBalance).getFullText(); - stream << "accountSendMultiIOU> " << to_string(senderID) << " (" - << sender_bal << ") -> " << receivers.size() << " receivers."; + stream << "accountSendMultiIOU> " << to_string(senderID) << " (" << sender_bal << ") -> " << receivers.size() + << " receivers."; } // Failures return immediately. @@ -2435,21 +2136,17 @@ accountSendMultiIOU( if (!amount || (senderID == receiverID)) continue; - SLE::pointer receiver = receiverID != beast::zero - ? view.peek(keylet::account(receiverID)) - : SLE::pointer(); + SLE::pointer receiver = receiverID != beast::zero ? view.peek(keylet::account(receiverID)) : SLE::pointer(); if (auto stream = j.trace()) { std::string receiver_bal("-"); if (receiver) - receiver_bal = - receiver->getFieldAmount(sfBalance).getFullText(); + receiver_bal = receiver->getFieldAmount(sfBalance).getFullText(); - stream << "accountSendMultiIOU> " << to_string(senderID) << " -> " - << to_string(receiverID) << " (" << receiver_bal - << ") : " << amount.getFullText(); + stream << "accountSendMultiIOU> " << to_string(senderID) << " -> " << to_string(receiverID) << " (" + << receiver_bal << ") : " << amount.getFullText(); } if (receiver) @@ -2470,12 +2167,10 @@ accountSendMultiIOU( std::string receiver_bal("-"); if (receiver) - receiver_bal = - receiver->getFieldAmount(sfBalance).getFullText(); + receiver_bal = receiver->getFieldAmount(sfBalance).getFullText(); - stream << "accountSendMultiIOU< " << to_string(senderID) << " -> " - << to_string(receiverID) << " (" << receiver_bal - << ") : " << amount.getFullText(); + stream << "accountSendMultiIOU< " << to_string(senderID) << " -> " << to_string(receiverID) << " (" + << receiver_bal << ") : " << amount.getFullText(); } } @@ -2504,8 +2199,8 @@ accountSendMultiIOU( if (sender) sender_bal = sender->getFieldAmount(sfBalance).getFullText(); - stream << "accountSendMultiIOU< " << to_string(senderID) << " (" - << sender_bal << ") -> " << receivers.size() << " receivers."; + stream << "accountSendMultiIOU< " << to_string(senderID) << " (" << sender_bal << ") -> " << receivers.size() + << " receivers."; } return tesSUCCESS; } @@ -2582,15 +2277,12 @@ rippleSendMPT( beast::Journal j, WaiveTransferFee waiveFee) { - XRPL_ASSERT( - uSenderID != uReceiverID, - "xrpl::rippleSendMPT : sender is not receiver"); + XRPL_ASSERT(uSenderID != uReceiverID, "xrpl::rippleSendMPT : sender is not receiver"); // Safe to get MPT since rippleSendMPT is only called by accountSendMPT auto const& issuer = saAmount.getIssuer(); - auto const sle = - view.read(keylet::mptIssuance(saAmount.get().getMptID())); + auto const sle = view.read(keylet::mptIssuance(saAmount.get().getMptID())); if (!sle) return tecOBJECT_NOT_FOUND; @@ -2601,17 +2293,13 @@ rippleSendMPT( if (uSenderID == issuer) { auto const sendAmount = saAmount.mpt().value(); - auto const maximumAmount = - sle->at(~sfMaximumAmount).value_or(maxMPTokenAmount); - if (sendAmount > maximumAmount || - sle->getFieldU64(sfOutstandingAmount) > - maximumAmount - sendAmount) + auto const maximumAmount = sle->at(~sfMaximumAmount).value_or(maxMPTokenAmount); + if (sendAmount > maximumAmount || sle->getFieldU64(sfOutstandingAmount) > maximumAmount - sendAmount) return tecPATH_DRY; } // Direct send: redeeming MPTs and/or sending own MPTs. - auto const ter = - rippleCreditMPT(view, uSenderID, uReceiverID, saAmount, j); + auto const ter = rippleCreditMPT(view, uSenderID, uReceiverID, saAmount, j); if (ter != tesSUCCESS) return ter; saActual = saAmount; @@ -2621,18 +2309,12 @@ rippleSendMPT( // Sending 3rd party MPTs: transit. saActual = (waiveFee == WaiveTransferFee::Yes) ? saAmount - : multiply( - saAmount, - transferRate(view, saAmount.get().getMptID())); + : multiply(saAmount, transferRate(view, saAmount.get().getMptID())); - JLOG(j.debug()) << "rippleSendMPT> " << to_string(uSenderID) << " - > " - << to_string(uReceiverID) - << " : deliver=" << saAmount.getFullText() - << " cost=" << saActual.getFullText(); + JLOG(j.debug()) << "rippleSendMPT> " << to_string(uSenderID) << " - > " << to_string(uReceiverID) + << " : deliver=" << saAmount.getFullText() << " cost=" << saActual.getFullText(); - if (auto const terResult = - rippleCreditMPT(view, issuer, uReceiverID, saAmount, j); - terResult != tesSUCCESS) + if (auto const terResult = rippleCreditMPT(view, issuer, uReceiverID, saAmount, j); terResult != tesSUCCESS) return terResult; return rippleCreditMPT(view, uSenderID, issuer, saActual, j); @@ -2687,17 +2369,13 @@ rippleSendMultiMPT( "rippler::rippleSendMultiMPT", "sender == issuer, takeFromSender == zero"); auto const sendAmount = amount.mpt().value(); - auto const maximumAmount = - sle->at(~sfMaximumAmount).value_or(maxMPTokenAmount); - if (sendAmount > maximumAmount || - sle->getFieldU64(sfOutstandingAmount) > - maximumAmount - sendAmount) + auto const maximumAmount = sle->at(~sfMaximumAmount).value_or(maxMPTokenAmount); + if (sendAmount > maximumAmount || sle->getFieldU64(sfOutstandingAmount) > maximumAmount - sendAmount) return tecPATH_DRY; } // Direct send: redeeming MPTs and/or sending own MPTs. - if (auto const ter = - rippleCreditMPT(view, senderID, receiverID, amount, j)) + if (auto const ter = rippleCreditMPT(view, senderID, receiverID, amount, j)) return ter; actual += amount; // Do not add amount to takeFromSender, because rippleCreditMPT took @@ -2709,25 +2387,19 @@ rippleSendMultiMPT( // Sending 3rd party MPTs: transit. STAmount actualSend = (waiveFee == WaiveTransferFee::Yes) ? amount - : multiply( - amount, - transferRate(view, amount.get().getMptID())); + : multiply(amount, transferRate(view, amount.get().getMptID())); actual += actualSend; takeFromSender += actualSend; - JLOG(j.debug()) << "rippleSendMultiMPT> " << to_string(senderID) - << " - > " << to_string(receiverID) - << " : deliver=" << amount.getFullText() - << " cost=" << actualSend.getFullText(); + JLOG(j.debug()) << "rippleSendMultiMPT> " << to_string(senderID) << " - > " << to_string(receiverID) + << " : deliver=" << amount.getFullText() << " cost=" << actualSend.getFullText(); - if (auto const terResult = - rippleCreditMPT(view, issuer, receiverID, amount, j)) + if (auto const terResult = rippleCreditMPT(view, issuer, receiverID, amount, j)) return terResult; } if (senderID != issuer && takeFromSender) { - if (TER const terResult = - rippleCreditMPT(view, senderID, issuer, takeFromSender, j)) + if (TER const terResult = rippleCreditMPT(view, senderID, issuer, takeFromSender, j)) return terResult; } @@ -2743,9 +2415,7 @@ accountSendMPT( beast::Journal j, WaiveTransferFee waiveFee) { - XRPL_ASSERT( - saAmount >= beast::zero && saAmount.holds(), - "xrpl::accountSendMPT : minimum amount and MPT"); + XRPL_ASSERT(saAmount >= beast::zero && saAmount.holds(), "xrpl::accountSendMPT : minimum amount and MPT"); /* If we aren't sending anything or if the sender is the same as the * receiver then we don't need to do anything. @@ -2755,8 +2425,7 @@ accountSendMPT( STAmount saActual{saAmount.asset()}; - return rippleSendMPT( - view, uSenderID, uReceiverID, saAmount, saActual, j, waiveFee); + return rippleSendMPT(view, uSenderID, uReceiverID, saAmount, saActual, j, waiveFee); } static TER @@ -2770,8 +2439,7 @@ accountSendMultiMPT( { STAmount actual; - return rippleSendMultiMPT( - view, senderID, mptIssue, receivers, actual, j, waiveFee); + return rippleSendMultiMPT(view, senderID, mptIssue, receivers, actual, j, waiveFee); } TER @@ -2786,11 +2454,9 @@ accountSend( return std::visit( [&](TIss const& issue) { if constexpr (std::is_same_v) - return accountSendIOU( - view, uSenderID, uReceiverID, saAmount, j, waiveFee); + return accountSendIOU(view, uSenderID, uReceiverID, saAmount, j, waiveFee); else - return accountSendMPT( - view, uSenderID, uReceiverID, saAmount, j, waiveFee); + return accountSendMPT(view, uSenderID, uReceiverID, saAmount, j, waiveFee); }, saAmount.asset().value()); } @@ -2804,18 +2470,13 @@ accountSendMulti( beast::Journal j, WaiveTransferFee waiveFee) { - XRPL_ASSERT_PARTS( - receivers.size() > 1, - "xrpl::accountSendMulti", - "multiple recipients provided"); + XRPL_ASSERT_PARTS(receivers.size() > 1, "xrpl::accountSendMulti", "multiple recipients provided"); return std::visit( [&](TIss const& issue) { if constexpr (std::is_same_v) - return accountSendMultiIOU( - view, senderID, issue, receivers, j, waiveFee); + return accountSendMultiIOU(view, senderID, issue, receivers, j, waiveFee); else - return accountSendMultiMPT( - view, senderID, issue, receivers, j, waiveFee); + return accountSendMultiMPT(view, senderID, issue, receivers, j, waiveFee); }, asset.value()); } @@ -2845,16 +2506,14 @@ updateTrustLine( // Sender is zero or negative. && (flags & (!bSenderHigh ? lsfLowReserve : lsfHighReserve)) // Sender reserve is set. - && static_cast( - flags & (!bSenderHigh ? lsfLowNoRipple : lsfHighNoRipple)) != + && static_cast(flags & (!bSenderHigh ? lsfLowNoRipple : lsfHighNoRipple)) != static_cast(sle->getFlags() & lsfDefaultRipple) && !(flags & (!bSenderHigh ? lsfLowFreeze : lsfHighFreeze)) && !state->getFieldAmount(!bSenderHigh ? sfLowLimit : sfHighLimit) // Sender trust limit is 0. && !state->getFieldU32(!bSenderHigh ? sfLowQualityIn : sfHighQualityIn) // Sender quality in is 0. - && - !state->getFieldU32(!bSenderHigh ? sfLowQualityOut : sfHighQualityOut)) + && !state->getFieldU32(!bSenderHigh ? sfLowQualityOut : sfHighQualityOut)) // Sender quality out is 0. { // VFALCO Where is the line being deleted? @@ -2862,8 +2521,7 @@ updateTrustLine( adjustOwnerCount(view, sle, -1, j); // Clear reserve flag. - state->setFieldU32( - sfFlags, flags & (!bSenderHigh ? ~lsfLowReserve : ~lsfHighReserve)); + state->setFieldU32(sfFlags, flags & (!bSenderHigh ? ~lsfLowReserve : ~lsfHighReserve)); // Balance is zero, receiver reserve is clear. if (!after // Balance is zero. @@ -2874,26 +2532,17 @@ updateTrustLine( } TER -issueIOU( - ApplyView& view, - AccountID const& account, - STAmount const& amount, - Issue const& issue, - beast::Journal j) +issueIOU(ApplyView& view, AccountID const& account, STAmount const& amount, Issue const& issue, beast::Journal j) { - XRPL_ASSERT( - !isXRP(account) && !isXRP(issue.account), - "xrpl::issueIOU : neither account nor issuer is XRP"); + XRPL_ASSERT(!isXRP(account) && !isXRP(issue.account), "xrpl::issueIOU : neither account nor issuer is XRP"); // Consistency check XRPL_ASSERT(issue == amount.issue(), "xrpl::issueIOU : matching issue"); // Can't send to self! - XRPL_ASSERT( - issue.account != account, "xrpl::issueIOU : not issuer account"); + XRPL_ASSERT(issue.account != account, "xrpl::issueIOU : not issuer account"); - JLOG(j.trace()) << "issueIOU: " << to_string(account) << ": " - << amount.getFullText(); + JLOG(j.trace()) << "issueIOU: " << to_string(account) << ": " << amount.getFullText(); bool bSenderHigh = issue.account > account; @@ -2910,14 +2559,8 @@ issueIOU( final_balance -= amount; - auto const must_delete = updateTrustLine( - view, - state, - bSenderHigh, - issue.account, - start_balance, - final_balance, - j); + auto const must_delete = + updateTrustLine(view, state, bSenderHigh, issue.account, start_balance, final_balance, j); view.creditHook(issue.account, account, amount, start_balance); @@ -2930,11 +2573,7 @@ issueIOU( state->setFieldAmount(sfBalance, final_balance); if (must_delete) return trustDelete( - view, - state, - bSenderHigh ? account : issue.account, - bSenderHigh ? issue.account : account, - j); + view, state, bSenderHigh ? account : issue.account, bSenderHigh ? issue.account : account, j); view.update(state); @@ -2974,31 +2613,21 @@ issueIOU( } TER -redeemIOU( - ApplyView& view, - AccountID const& account, - STAmount const& amount, - Issue const& issue, - beast::Journal j) +redeemIOU(ApplyView& view, AccountID const& account, STAmount const& amount, Issue const& issue, beast::Journal j) { - XRPL_ASSERT( - !isXRP(account) && !isXRP(issue.account), - "xrpl::redeemIOU : neither account nor issuer is XRP"); + XRPL_ASSERT(!isXRP(account) && !isXRP(issue.account), "xrpl::redeemIOU : neither account nor issuer is XRP"); // Consistency check XRPL_ASSERT(issue == amount.issue(), "xrpl::redeemIOU : matching issue"); // Can't send to self! - XRPL_ASSERT( - issue.account != account, "xrpl::redeemIOU : not issuer account"); + XRPL_ASSERT(issue.account != account, "xrpl::redeemIOU : not issuer account"); - JLOG(j.trace()) << "redeemIOU: " << to_string(account) << ": " - << amount.getFullText(); + JLOG(j.trace()) << "redeemIOU: " << to_string(account) << ": " << amount.getFullText(); bool bSenderHigh = account > issue.account; - if (auto state = - view.peek(keylet::line(account, issue.account, issue.currency))) + if (auto state = view.peek(keylet::line(account, issue.account, issue.currency))) { STAmount final_balance = state->getFieldAmount(sfBalance); @@ -3009,8 +2638,7 @@ redeemIOU( final_balance -= amount; - auto const must_delete = updateTrustLine( - view, state, bSenderHigh, account, start_balance, final_balance, j); + auto const must_delete = updateTrustLine(view, state, bSenderHigh, account, start_balance, final_balance, j); view.creditHook(account, issue.account, amount, start_balance); @@ -3025,11 +2653,7 @@ redeemIOU( if (must_delete) { return trustDelete( - view, - state, - bSenderHigh ? issue.account : account, - bSenderHigh ? account : issue.account, - j); + view, state, bSenderHigh ? issue.account : account, bSenderHigh ? account : issue.account, j); } view.update(state); @@ -3040,8 +2664,7 @@ redeemIOU( // balance. If it doesn't, then something is very wrong. Don't try // to continue. // LCOV_EXCL_START - JLOG(j.fatal()) << "redeemIOU: " << to_string(account) - << " attempts to redeem " << amount.getFullText() + JLOG(j.fatal()) << "redeemIOU: " << to_string(account) << " attempts to redeem " << amount.getFullText() << " but no trust line exists!"; return tefINTERNAL; @@ -3049,15 +2672,9 @@ redeemIOU( } TER -transferXRP( - ApplyView& view, - AccountID const& from, - AccountID const& to, - STAmount const& amount, - beast::Journal j) +transferXRP(ApplyView& view, AccountID const& from, AccountID const& to, STAmount const& amount, beast::Journal j) { - XRPL_ASSERT( - from != beast::zero, "xrpl::transferXRP : nonzero from account"); + XRPL_ASSERT(from != beast::zero, "xrpl::transferXRP : nonzero from account"); XRPL_ASSERT(to != beast::zero, "xrpl::transferXRP : nonzero to account"); XRPL_ASSERT(from != to, "xrpl::transferXRP : sender is not receiver"); XRPL_ASSERT(amount.native(), "xrpl::transferXRP : amount is XRP"); @@ -3067,8 +2684,7 @@ transferXRP( if (!sender || !receiver) return tefINTERNAL; // LCOV_EXCL_LINE - JLOG(j.trace()) << "transferXRP: " << to_string(from) << " -> " - << to_string(to) << ") : " << amount.getFullText(); + JLOG(j.trace()) << "transferXRP: " << to_string(from) << " -> " << to_string(to) << ") : " << amount.getFullText(); if (sender->getFieldAmount(sfBalance) < amount) { @@ -3076,35 +2692,27 @@ transferXRP( // mutating these TER everywhere // FIXME: this logic should be moved to callers maybe? // LCOV_EXCL_START - return view.open() ? TER{telFAILED_PROCESSING} - : TER{tecFAILED_PROCESSING}; + return view.open() ? TER{telFAILED_PROCESSING} : TER{tecFAILED_PROCESSING}; // LCOV_EXCL_STOP } // Decrement XRP balance. - sender->setFieldAmount( - sfBalance, sender->getFieldAmount(sfBalance) - amount); + sender->setFieldAmount(sfBalance, sender->getFieldAmount(sfBalance) - amount); view.update(sender); - receiver->setFieldAmount( - sfBalance, receiver->getFieldAmount(sfBalance) + amount); + receiver->setFieldAmount(sfBalance, receiver->getFieldAmount(sfBalance) + amount); view.update(receiver); return tesSUCCESS; } TER -requireAuth( - ReadView const& view, - Issue const& issue, - AccountID const& account, - AuthType authType) +requireAuth(ReadView const& view, Issue const& issue, AccountID const& account, AuthType authType) { if (isXRP(issue) || issue.account == account) return tesSUCCESS; - auto const trustLine = - view.read(keylet::line(account, issue.account, issue.currency)); + auto const trustLine = view.read(keylet::line(account, issue.account, issue.currency)); // If account has no line, and this is a strong check, fail if (!trustLine && authType == AuthType::StrongAuth) return tecNO_LINE; @@ -3115,10 +2723,8 @@ requireAuth( issuerAccount && (*issuerAccount)[sfFlags] & lsfRequireAuth) { if (trustLine) - return ((*trustLine)[sfFlags] & - ((account > issue.account) ? lsfLowAuth : lsfHighAuth)) - ? tesSUCCESS - : TER{tecNO_AUTH}; + return ((*trustLine)[sfFlags] & ((account > issue.account) ? lsfLowAuth : lsfHighAuth)) ? tesSUCCESS + : TER{tecNO_AUTH}; return TER{tecNO_LINE}; } @@ -3126,12 +2732,7 @@ requireAuth( } TER -requireAuth( - ReadView const& view, - MPTIssue const& mptIssue, - AccountID const& account, - AuthType authType, - int depth) +requireAuth(ReadView const& view, MPTIssue const& mptIssue, AccountID const& account, AuthType authType, int depth) { auto const mptID = keylet::mptIssuance(mptIssue.getMptID()); auto const sleIssuance = view.read(mptID); @@ -3144,8 +2745,7 @@ requireAuth( if (mptIssuer == account) // Issuer won't have MPToken return tesSUCCESS; - bool const featureSAVEnabled = - view.rules().enabled(featureSingleAssetVault); + bool const featureSAVEnabled = view.rules().enabled(featureSingleAssetVault); if (featureSAVEnabled) { @@ -3159,8 +2759,7 @@ requireAuth( if (sleIssuer->isFieldPresent(sfVaultID)) { - auto const sleVault = - view.read(keylet::vault(sleIssuer->getFieldH256(sfVaultID))); + auto const sleVault = view.read(keylet::vault(sleIssuer->getFieldH256(sfVaultID))); if (!sleVault) return tefINTERNAL; // LCOV_EXCL_LINE @@ -3170,8 +2769,7 @@ requireAuth( if constexpr (std::is_same_v) return requireAuth(view, issue, account, authType); else - return requireAuth( - view, issue, account, authType, depth + 1); + return requireAuth(view, issue, account, authType, depth + 1); }, asset.value()); !isTesSuccess(err)) @@ -3183,8 +2781,7 @@ requireAuth( auto const sleToken = view.read(mptokenID); // if account has no MPToken, fail - if (!sleToken && - (authType == AuthType::StrongAuth || authType == AuthType::Legacy)) + if (!sleToken && (authType == AuthType::StrongAuth || authType == AuthType::Legacy)) return tecNO_AUTH; // Note, this check is not amendment-gated because DomainID will be always @@ -3196,9 +2793,7 @@ requireAuth( sleIssuance->getFieldU32(sfFlags) & lsfMPTRequireAuth, "xrpl::requireAuth : issuance requires authorization"); // ter = tefINTERNAL | tecOBJECT_NOT_FOUND | tecNO_AUTH | tecEXPIRED - if (auto const ter = - credentials::validDomain(view, *maybeDomainID, account); - isTesSuccess(ter)) + if (auto const ter = credentials::validDomain(view, *maybeDomainID, account); isTesSuccess(ter)) return ter; // Note: sleToken might be null else if (!sleToken) return ter; @@ -3214,8 +2809,7 @@ requireAuth( } // mptoken must be authorized if issuance enabled requireAuth - if (sleIssuance->isFlag(lsfMPTRequireAuth) && - (!sleToken || !sleToken->isFlag(lsfMPTAuthorized))) + if (sleIssuance->isFlag(lsfMPTRequireAuth) && (!sleToken || !sleToken->isFlag(lsfMPTAuthorized))) return tecNO_AUTH; return tesSUCCESS; // Note: sleToken might be null @@ -3233,9 +2827,7 @@ enforceMPTokenAuthorization( if (!sleIssuance) return tefINTERNAL; // LCOV_EXCL_LINE - XRPL_ASSERT( - sleIssuance->isFlag(lsfMPTRequireAuth), - "xrpl::enforceMPTokenAuthorization : authorization required"); + XRPL_ASSERT(sleIssuance->isFlag(lsfMPTRequireAuth), "xrpl::enforceMPTokenAuthorization : authorization required"); if (account == sleIssuance->at(sfIssuer)) return tefINTERNAL; // LCOV_EXCL_LINE @@ -3280,8 +2872,7 @@ enforceMPTokenAuthorization( // We found an MPToken, but sfDomainID is not set, so this is a classic // MPToken which requires authorization by the token issuer. XRPL_ASSERT( - sleToken != nullptr && !maybeDomainID.has_value(), - "xrpl::enforceMPTokenAuthorization : found MPToken"); + sleToken != nullptr && !maybeDomainID.has_value(), "xrpl::enforceMPTokenAuthorization : found MPToken"); if (sleToken->isFlag(lsfMPTAuthorized)) return tesSUCCESS; @@ -3291,9 +2882,7 @@ enforceMPTokenAuthorization( { // Found an MPToken, authorized by the domain. Ignore authorization flag // lsfMPTAuthorized because it is meaningless. Return tesSUCCESS - XRPL_ASSERT( - maybeDomainID.has_value(), - "xrpl::enforceMPTokenAuthorization : found MPToken for domain"); + XRPL_ASSERT(maybeDomainID.has_value(), "xrpl::enforceMPTokenAuthorization : found MPToken for domain"); return tesSUCCESS; } else if (authorizedByDomain) @@ -3316,18 +2905,13 @@ enforceMPTokenAuthorization( } // LCOV_EXCL_START - UNREACHABLE( - "xrpl::enforceMPTokenAuthorization : condition list is incomplete"); + UNREACHABLE("xrpl::enforceMPTokenAuthorization : condition list is incomplete"); return tefINTERNAL; // LCOV_EXCL_STOP } TER -canTransfer( - ReadView const& view, - MPTIssue const& mptIssue, - AccountID const& from, - AccountID const& to) +canTransfer(ReadView const& view, MPTIssue const& mptIssue, AccountID const& from, AccountID const& to) { auto const mptID = keylet::mptIssuance(mptIssue.getMptID()); auto const sleIssuance = view.read(mptID); @@ -3343,11 +2927,7 @@ canTransfer( } [[nodiscard]] TER -canTransfer( - ReadView const& view, - Issue const& issue, - AccountID const& from, - AccountID const& to) +canTransfer(ReadView const& view, Issue const& issue, AccountID const& from, AccountID const& to) { if (issue.native()) return tesSUCCESS; @@ -3392,8 +2972,7 @@ cleanupOnAccountDelete( uint256 dirEntry{beast::zero}; std::uint32_t deleted = 0; - if (view.exists(ownerDirKeylet) && - dirFirst(view, ownerDirKeylet.key, sleDirNode, uDirEntry, dirEntry)) + if (view.exists(ownerDirKeylet) && dirFirst(view, ownerDirKeylet.key, sleDirNode, uDirEntry, dirEntry)) { do { @@ -3406,16 +2985,13 @@ cleanupOnAccountDelete( { // Directory node has an invalid index. Bail out. // LCOV_EXCL_START - JLOG(j.fatal()) - << "DeleteAccount: Directory node in ledger " << view.seq() - << " has index to object that is missing: " - << to_string(dirEntry); + JLOG(j.fatal()) << "DeleteAccount: Directory node in ledger " << view.seq() + << " has index to object that is missing: " << to_string(dirEntry); return tefBAD_LEDGER; // LCOV_EXCL_STOP } - LedgerEntryType const nodeType{safe_cast( - sleItem->getFieldU16(sfLedgerEntryType))}; + LedgerEntryType const nodeType{safe_cast(sleItem->getFieldU16(sfLedgerEntryType))}; // Deleter handles the details of specific account-owned object // deletion @@ -3439,22 +3015,18 @@ cleanupOnAccountDelete( // // 3. So we verify that uDirEntry is indeed 'it'+1. Then we jam it // back to 'it' to "un-invalidate" the iterator. - XRPL_ASSERT( - uDirEntry >= 1, - "xrpl::cleanupOnAccountDelete : minimum dir entries"); + XRPL_ASSERT(uDirEntry >= 1, "xrpl::cleanupOnAccountDelete : minimum dir entries"); if (uDirEntry == 0) { // LCOV_EXCL_START - JLOG(j.error()) - << "DeleteAccount iterator re-validation failed."; + JLOG(j.error()) << "DeleteAccount iterator re-validation failed."; return tefBAD_LEDGER; // LCOV_EXCL_STOP } if (skipEntry == SkipEntry::No) uDirEntry--; - } while ( - dirNext(view, ownerDirKeylet.key, sleDirNode, uDirEntry, dirEntry)); + } while (dirNext(view, ownerDirKeylet.key, sleDirNode, uDirEntry, dirEntry)); } return tesSUCCESS; @@ -3471,8 +3043,7 @@ deleteAMMTrustLine( return tecINTERNAL; // LCOV_EXCL_LINE auto const& [low, high] = std::minmax( - sleState->getFieldAmount(sfLowLimit).getIssuer(), - sleState->getFieldAmount(sfHighLimit).getIssuer()); + sleState->getFieldAmount(sfLowLimit).getIssuer(), sleState->getFieldAmount(sfHighLimit).getIssuer()); auto sleLow = view.peek(keylet::account(low)); auto sleHigh = view.peek(keylet::account(high)); if (!sleLow || !sleHigh) @@ -3493,11 +3064,9 @@ deleteAMMTrustLine( if (ammAccountID && (low != *ammAccountID && high != *ammAccountID)) return terNO_AMM; - if (auto const ter = trustDelete(view, sleState, low, high, j); - ter != tesSUCCESS) + if (auto const ter = trustDelete(view, sleState, low, high, j); ter != tesSUCCESS) { - JLOG(j.error()) - << "deleteAMMTrustLine: failed to delete the trustline."; + JLOG(j.error()) << "deleteAMMTrustLine: failed to delete the trustline."; return ter; } @@ -3523,15 +3092,12 @@ rippleCredit( [&](TIss const& issue) { if constexpr (std::is_same_v) { - return rippleCreditIOU( - view, uSenderID, uReceiverID, saAmount, bCheckIssuer, j); + return rippleCreditIOU(view, uSenderID, uReceiverID, saAmount, bCheckIssuer, j); } else { - XRPL_ASSERT( - !bCheckIssuer, "xrpl::rippleCredit : not checking issuer"); - return rippleCreditMPT( - view, uSenderID, uReceiverID, saAmount, j); + XRPL_ASSERT(!bCheckIssuer, "xrpl::rippleCredit : not checking issuer"); + return rippleCreditMPT(view, uSenderID, uReceiverID, saAmount, j); } }, saAmount.asset().value()); @@ -3543,22 +3109,15 @@ assetsToSharesDeposit( std::shared_ptr const& issuance, STAmount const& assets) { - XRPL_ASSERT( - !assets.negative(), - "xrpl::assetsToSharesDeposit : non-negative assets"); - XRPL_ASSERT( - assets.asset() == vault->at(sfAsset), - "xrpl::assetsToSharesDeposit : assets and vault match"); + XRPL_ASSERT(!assets.negative(), "xrpl::assetsToSharesDeposit : non-negative assets"); + XRPL_ASSERT(assets.asset() == vault->at(sfAsset), "xrpl::assetsToSharesDeposit : assets and vault match"); if (assets.negative() || assets.asset() != vault->at(sfAsset)) return std::nullopt; // LCOV_EXCL_LINE Number const assetTotal = vault->at(sfAssetsTotal); STAmount shares{vault->at(sfShareMPTID)}; if (assetTotal == 0) - return STAmount{ - shares.asset(), - Number(assets.mantissa(), assets.exponent() + vault->at(sfScale)) - .truncate()}; + return STAmount{shares.asset(), Number(assets.mantissa(), assets.exponent() + vault->at(sfScale)).truncate()}; Number const shareTotal = issuance->at(sfOutstandingAmount); shares = ((shareTotal * assets) / assetTotal).truncate(); @@ -3571,23 +3130,15 @@ sharesToAssetsDeposit( std::shared_ptr const& issuance, STAmount const& shares) { - XRPL_ASSERT( - !shares.negative(), - "xrpl::sharesToAssetsDeposit : non-negative shares"); - XRPL_ASSERT( - shares.asset() == vault->at(sfShareMPTID), - "xrpl::sharesToAssetsDeposit : shares and vault match"); + XRPL_ASSERT(!shares.negative(), "xrpl::sharesToAssetsDeposit : non-negative shares"); + XRPL_ASSERT(shares.asset() == vault->at(sfShareMPTID), "xrpl::sharesToAssetsDeposit : shares and vault match"); if (shares.negative() || shares.asset() != vault->at(sfShareMPTID)) return std::nullopt; // LCOV_EXCL_LINE Number const assetTotal = vault->at(sfAssetsTotal); STAmount assets{vault->at(sfAsset)}; if (assetTotal == 0) - return STAmount{ - assets.asset(), - shares.mantissa(), - shares.exponent() - vault->at(sfScale), - false}; + return STAmount{assets.asset(), shares.mantissa(), shares.exponent() - vault->at(sfScale), false}; Number const shareTotal = issuance->at(sfOutstandingAmount); assets = (assetTotal * shares) / shareTotal; @@ -3601,12 +3152,8 @@ assetsToSharesWithdraw( STAmount const& assets, TruncateShares truncate) { - XRPL_ASSERT( - !assets.negative(), - "xrpl::assetsToSharesDeposit : non-negative assets"); - XRPL_ASSERT( - assets.asset() == vault->at(sfAsset), - "xrpl::assetsToSharesWithdraw : assets and vault match"); + XRPL_ASSERT(!assets.negative(), "xrpl::assetsToSharesDeposit : non-negative assets"); + XRPL_ASSERT(assets.asset() == vault->at(sfAsset), "xrpl::assetsToSharesWithdraw : assets and vault match"); if (assets.negative() || assets.asset() != vault->at(sfAsset)) return std::nullopt; // LCOV_EXCL_LINE @@ -3629,12 +3176,8 @@ sharesToAssetsWithdraw( std::shared_ptr const& issuance, STAmount const& shares) { - XRPL_ASSERT( - !shares.negative(), - "xrpl::sharesToAssetsDeposit : non-negative shares"); - XRPL_ASSERT( - shares.asset() == vault->at(sfShareMPTID), - "xrpl::sharesToAssetsWithdraw : shares and vault match"); + XRPL_ASSERT(!shares.negative(), "xrpl::sharesToAssetsDeposit : non-negative shares"); + XRPL_ASSERT(shares.asset() == vault->at(sfShareMPTID), "xrpl::sharesToAssetsWithdraw : shares and vault match"); if (shares.negative() || shares.asset() != vault->at(sfShareMPTID)) return std::nullopt; // LCOV_EXCL_LINE @@ -3649,26 +3192,20 @@ sharesToAssetsWithdraw( } TER -rippleLockEscrowMPT( - ApplyView& view, - AccountID const& sender, - STAmount const& amount, - beast::Journal j) +rippleLockEscrowMPT(ApplyView& view, AccountID const& sender, STAmount const& amount, beast::Journal j) { auto const mptIssue = amount.get(); auto const mptID = keylet::mptIssuance(mptIssue.getMptID()); auto sleIssuance = view.peek(mptID); if (!sleIssuance) { // LCOV_EXCL_START - JLOG(j.error()) << "rippleLockEscrowMPT: MPT issuance not found for " - << mptIssue.getMptID(); + JLOG(j.error()) << "rippleLockEscrowMPT: MPT issuance not found for " << mptIssue.getMptID(); return tecOBJECT_NOT_FOUND; } // LCOV_EXCL_STOP if (amount.getIssuer() == sender) { // LCOV_EXCL_START - JLOG(j.error()) - << "rippleLockEscrowMPT: sender is the issuer, cannot lock MPTs."; + JLOG(j.error()) << "rippleLockEscrowMPT: sender is the issuer, cannot lock MPTs."; return tecINTERNAL; } // LCOV_EXCL_STOP @@ -3679,8 +3216,7 @@ rippleLockEscrowMPT( auto sle = view.peek(mptokenID); if (!sle) { // LCOV_EXCL_START - JLOG(j.error()) - << "rippleLockEscrowMPT: MPToken not found for " << sender; + JLOG(j.error()) << "rippleLockEscrowMPT: MPToken not found for " << sender; return tecOBJECT_NOT_FOUND; } // LCOV_EXCL_STOP @@ -3690,9 +3226,8 @@ rippleLockEscrowMPT( // Underflow check for subtraction if (!canSubtract(STAmount(mptIssue, amt), STAmount(mptIssue, pay))) { // LCOV_EXCL_START - JLOG(j.error()) - << "rippleLockEscrowMPT: insufficient MPTAmount for " - << to_string(sender) << ": " << amt << " < " << pay; + JLOG(j.error()) << "rippleLockEscrowMPT: insufficient MPTAmount for " << to_string(sender) << ": " << amt + << " < " << pay; return tecINTERNAL; } // LCOV_EXCL_STOP @@ -3703,9 +3238,8 @@ rippleLockEscrowMPT( if (!canAdd(STAmount(mptIssue, locked), STAmount(mptIssue, pay))) { // LCOV_EXCL_START - JLOG(j.error()) - << "rippleLockEscrowMPT: overflow on locked amount for " - << to_string(sender) << ": " << locked << " + " << pay; + JLOG(j.error()) << "rippleLockEscrowMPT: overflow on locked amount for " << to_string(sender) << ": " + << locked << " + " << pay; return tecINTERNAL; } // LCOV_EXCL_STOP @@ -3720,18 +3254,15 @@ rippleLockEscrowMPT( // 1. Increase the Issuance EscrowedAmount // 2. DO NOT change the Issuance OutstandingAmount { - uint64_t const issuanceEscrowed = - (*sleIssuance)[~sfLockedAmount].value_or(0); + uint64_t const issuanceEscrowed = (*sleIssuance)[~sfLockedAmount].value_or(0); auto const pay = amount.mpt().value(); // Overflow check for addition - if (!canAdd( - STAmount(mptIssue, issuanceEscrowed), STAmount(mptIssue, pay))) + if (!canAdd(STAmount(mptIssue, issuanceEscrowed), STAmount(mptIssue, pay))) { // LCOV_EXCL_START JLOG(j.error()) << "rippleLockEscrowMPT: overflow on issuance " "locked amount for " - << mptIssue.getMptID() << ": " << issuanceEscrowed - << " + " << pay; + << mptIssue.getMptID() << ": " << issuanceEscrowed << " + " << pay; return tecINTERNAL; } // LCOV_EXCL_STOP @@ -3755,9 +3286,7 @@ rippleUnlockEscrowMPT( beast::Journal j) { if (!view.rules().enabled(fixTokenEscrowV1)) - XRPL_ASSERT( - netAmount == grossAmount, - "xrpl::rippleUnlockEscrowMPT : netAmount == grossAmount"); + XRPL_ASSERT(netAmount == grossAmount, "xrpl::rippleUnlockEscrowMPT : netAmount == grossAmount"); auto const& issuer = netAmount.getIssuer(); auto const& mptIssue = netAmount.get(); @@ -3765,8 +3294,7 @@ rippleUnlockEscrowMPT( auto sleIssuance = view.peek(mptID); if (!sleIssuance) { // LCOV_EXCL_START - JLOG(j.error()) << "rippleUnlockEscrowMPT: MPT issuance not found for " - << mptIssue.getMptID(); + JLOG(j.error()) << "rippleUnlockEscrowMPT: MPT issuance not found for " << mptIssue.getMptID(); return tecOBJECT_NOT_FOUND; } // LCOV_EXCL_STOP @@ -3774,9 +3302,7 @@ rippleUnlockEscrowMPT( { if (!sleIssuance->isFieldPresent(sfLockedAmount)) { // LCOV_EXCL_START - JLOG(j.error()) - << "rippleUnlockEscrowMPT: no locked amount in issuance for " - << mptIssue.getMptID(); + JLOG(j.error()) << "rippleUnlockEscrowMPT: no locked amount in issuance for " << mptIssue.getMptID(); return tecINTERNAL; } // LCOV_EXCL_STOP @@ -3784,12 +3310,10 @@ rippleUnlockEscrowMPT( auto const redeem = grossAmount.mpt().value(); // Underflow check for subtraction - if (!canSubtract( - STAmount(mptIssue, locked), STAmount(mptIssue, redeem))) + if (!canSubtract(STAmount(mptIssue, locked), STAmount(mptIssue, redeem))) { // LCOV_EXCL_START - JLOG(j.error()) - << "rippleUnlockEscrowMPT: insufficient locked amount for " - << mptIssue.getMptID() << ": " << locked << " < " << redeem; + JLOG(j.error()) << "rippleUnlockEscrowMPT: insufficient locked amount for " << mptIssue.getMptID() << ": " + << locked << " < " << redeem; return tecINTERNAL; } // LCOV_EXCL_STOP @@ -3808,8 +3332,7 @@ rippleUnlockEscrowMPT( auto sle = view.peek(mptokenID); if (!sle) { // LCOV_EXCL_START - JLOG(j.error()) - << "rippleUnlockEscrowMPT: MPToken not found for " << receiver; + JLOG(j.error()) << "rippleUnlockEscrowMPT: MPToken not found for " << receiver; return tecOBJECT_NOT_FOUND; } // LCOV_EXCL_STOP @@ -3819,9 +3342,8 @@ rippleUnlockEscrowMPT( // Overflow check for addition if (!canAdd(STAmount(mptIssue, current), STAmount(mptIssue, delta))) { // LCOV_EXCL_START - JLOG(j.error()) - << "rippleUnlockEscrowMPT: overflow on MPTAmount for " - << to_string(receiver) << ": " << current << " + " << delta; + JLOG(j.error()) << "rippleUnlockEscrowMPT: overflow on MPTAmount for " << to_string(receiver) << ": " + << current << " + " << delta; return tecINTERNAL; } // LCOV_EXCL_STOP @@ -3835,13 +3357,10 @@ rippleUnlockEscrowMPT( auto const redeem = netAmount.mpt().value(); // Underflow check for subtraction - if (!canSubtract( - STAmount(mptIssue, outstanding), STAmount(mptIssue, redeem))) + if (!canSubtract(STAmount(mptIssue, outstanding), STAmount(mptIssue, redeem))) { // LCOV_EXCL_START - JLOG(j.error()) - << "rippleUnlockEscrowMPT: insufficient outstanding amount for " - << mptIssue.getMptID() << ": " << outstanding << " < " - << redeem; + JLOG(j.error()) << "rippleUnlockEscrowMPT: insufficient outstanding amount for " << mptIssue.getMptID() + << ": " << outstanding << " < " << redeem; return tecINTERNAL; } // LCOV_EXCL_STOP @@ -3862,16 +3381,13 @@ rippleUnlockEscrowMPT( auto sle = view.peek(mptokenID); if (!sle) { // LCOV_EXCL_START - JLOG(j.error()) - << "rippleUnlockEscrowMPT: MPToken not found for " << sender; + JLOG(j.error()) << "rippleUnlockEscrowMPT: MPToken not found for " << sender; return tecOBJECT_NOT_FOUND; } // LCOV_EXCL_STOP if (!sle->isFieldPresent(sfLockedAmount)) { // LCOV_EXCL_START - JLOG(j.error()) - << "rippleUnlockEscrowMPT: no locked amount in MPToken for " - << to_string(sender); + JLOG(j.error()) << "rippleUnlockEscrowMPT: no locked amount in MPToken for " << to_string(sender); return tecINTERNAL; } // LCOV_EXCL_STOP @@ -3881,9 +3397,8 @@ rippleUnlockEscrowMPT( // Underflow check for subtraction if (!canSubtract(STAmount(mptIssue, locked), STAmount(mptIssue, delta))) { // LCOV_EXCL_START - JLOG(j.error()) - << "rippleUnlockEscrowMPT: insufficient locked amount for " - << to_string(sender) << ": " << locked << " < " << delta; + JLOG(j.error()) << "rippleUnlockEscrowMPT: insufficient locked amount for " << to_string(sender) << ": " + << locked << " < " << delta; return tecINTERNAL; } // LCOV_EXCL_STOP @@ -3904,12 +3419,10 @@ rippleUnlockEscrowMPT( { auto const outstanding = sleIssuance->getFieldU64(sfOutstandingAmount); // Underflow check for subtraction - if (!canSubtract( - STAmount(mptIssue, outstanding), STAmount(mptIssue, diff))) + if (!canSubtract(STAmount(mptIssue, outstanding), STAmount(mptIssue, diff))) { // LCOV_EXCL_START - JLOG(j.error()) - << "rippleUnlockEscrowMPT: insufficient outstanding amount for " - << mptIssue.getMptID() << ": " << outstanding << " < " << diff; + JLOG(j.error()) << "rippleUnlockEscrowMPT: insufficient outstanding amount for " << mptIssue.getMptID() + << ": " << outstanding << " < " << diff; return tecINTERNAL; } // LCOV_EXCL_STOP diff --git a/src/libxrpl/net/HTTPClient.cpp b/src/libxrpl/net/HTTPClient.cpp index 6057d81a1e..e5a1196cb0 100644 --- a/src/libxrpl/net/HTTPClient.cpp +++ b/src/libxrpl/net/HTTPClient.cpp @@ -32,8 +32,7 @@ HTTPClient::initializeSSLContext( // //------------------------------------------------------------------------------ -class HTTPClientImp : public std::enable_shared_from_this, - public HTTPClient +class HTTPClientImp : public std::enable_shared_from_this, public HTTPClient { public: HTTPClientImp( @@ -54,10 +53,7 @@ public: //-------------------------------------------------------------------------- void - makeGet( - std::string const& strPath, - boost::asio::streambuf& sb, - std::string const& strHost) + makeGet(std::string const& strPath, boost::asio::streambuf& sb, std::string const& strHost) { std::ostream osRequest(&sb); @@ -76,13 +72,10 @@ public: request( bool bSSL, std::deque deqSites, - std::function< - void(boost::asio::streambuf& sb, std::string const& strHost)> build, + std::function build, std::chrono::seconds timeout, - std::function complete) + std::function + complete) { mSSL = bSSL; mDeqSites = deqSites; @@ -100,10 +93,8 @@ public: std::deque deqSites, std::string const& strPath, std::chrono::seconds timeout, - std::function complete) + std::function + complete) { mComplete = complete; mTimeout = timeout; @@ -112,11 +103,7 @@ public: bSSL, deqSites, std::bind( - &HTTPClientImp::makeGet, - shared_from_this(), - strPath, - std::placeholders::_1, - std::placeholders::_2), + &HTTPClientImp::makeGet, shared_from_this(), strPath, std::placeholders::_1, std::placeholders::_2), timeout, complete); } @@ -129,9 +116,7 @@ public: JLOG(j_.trace()) << "Fetch: " << mDeqSites[0]; auto query = std::make_shared( - mDeqSites[0], - std::to_string(mPort), - boost::asio::ip::resolver_query_base::numeric_service); + mDeqSites[0], std::to_string(mPort), boost::asio::ip::resolver_query_base::numeric_service); mQuery = query; try @@ -143,10 +128,7 @@ public: mShutdown = e.code(); JLOG(j_.trace()) << "expires_after: " << mShutdown.message(); - mDeadline.async_wait(std::bind( - &HTTPClientImp::handleDeadline, - shared_from_this(), - std::placeholders::_1)); + mDeadline.async_wait(std::bind(&HTTPClientImp::handleDeadline, shared_from_this(), std::placeholders::_1)); } if (!mShutdown) @@ -158,10 +140,7 @@ public: mQuery->port, mQuery->flags, std::bind( - &HTTPClientImp::handleResolve, - shared_from_this(), - std::placeholders::_1, - std::placeholders::_2)); + &HTTPClientImp::handleResolve, shared_from_this(), std::placeholders::_1, std::placeholders::_2)); } if (mShutdown) @@ -180,8 +159,7 @@ public: } else if (ecResult) { - JLOG(j_.trace()) << "Deadline error: " << mDeqSites[0] << ": " - << ecResult.message(); + JLOG(j_.trace()) << "Deadline error: " << mDeqSites[0] << ": " << ecResult.message(); // Can't do anything sound. abort(); @@ -192,18 +170,14 @@ public: // Mark us as shutting down. // XXX Use our own error code. - mShutdown = boost::system::error_code{ - boost::system::errc::bad_address, - boost::system::system_category()}; + mShutdown = boost::system::error_code{boost::system::errc::bad_address, boost::system::system_category()}; // Cancel any resolving. mResolver.cancel(); // Stop the transaction. - mSocket.async_shutdown(std::bind( - &HTTPClientImp::handleShutdown, - shared_from_this(), - std::placeholders::_1)); + mSocket.async_shutdown( + std::bind(&HTTPClientImp::handleShutdown, shared_from_this(), std::placeholders::_1)); } } @@ -212,27 +186,21 @@ public: { if (ecResult) { - JLOG(j_.trace()) << "Shutdown error: " << mDeqSites[0] << ": " - << ecResult.message(); + JLOG(j_.trace()) << "Shutdown error: " << mDeqSites[0] << ": " << ecResult.message(); } } void - handleResolve( - boost::system::error_code const& ecResult, - boost::asio::ip::tcp::resolver::results_type result) + handleResolve(boost::system::error_code const& ecResult, boost::asio::ip::tcp::resolver::results_type result) { if (!mShutdown) { - mShutdown = ecResult ? ecResult - : httpClientSSLContext->preConnectVerify( - mSocket.SSLSocket(), mDeqSites[0]); + mShutdown = ecResult ? ecResult : httpClientSSLContext->preConnectVerify(mSocket.SSLSocket(), mDeqSites[0]); } if (mShutdown) { - JLOG(j_.trace()) << "Resolve error: " << mDeqSites[0] << ": " - << mShutdown.message(); + JLOG(j_.trace()) << "Resolve error: " << mDeqSites[0] << ": " << mShutdown.message(); invokeComplete(mShutdown); } @@ -243,10 +211,7 @@ public: boost::asio::async_connect( mSocket.lowest_layer(), result, - std::bind( - &HTTPClientImp::handleConnect, - shared_from_this(), - std::placeholders::_1)); + std::bind(&HTTPClientImp::handleConnect, shared_from_this(), std::placeholders::_1)); } } @@ -265,13 +230,11 @@ public: { JLOG(j_.trace()) << "Connected."; - mShutdown = httpClientSSLContext->postConnectVerify( - mSocket.SSLSocket(), mDeqSites[0]); + mShutdown = httpClientSSLContext->postConnectVerify(mSocket.SSLSocket(), mDeqSites[0]); if (mShutdown) { - JLOG(j_.trace()) << "postConnectVerify: " << mDeqSites[0] - << ": " << mShutdown.message(); + JLOG(j_.trace()) << "postConnectVerify: " << mDeqSites[0] << ": " << mShutdown.message(); } } @@ -283,10 +246,7 @@ public: { mSocket.async_handshake( AutoSocket::ssl_socket::client, - std::bind( - &HTTPClientImp::handleRequest, - shared_from_this(), - std::placeholders::_1)); + std::bind(&HTTPClientImp::handleRequest, shared_from_this(), std::placeholders::_1)); } else { @@ -315,17 +275,12 @@ public: mSocket.async_write( mRequest, std::bind( - &HTTPClientImp::handleWrite, - shared_from_this(), - std::placeholders::_1, - std::placeholders::_2)); + &HTTPClientImp::handleWrite, shared_from_this(), std::placeholders::_1, std::placeholders::_2)); } } void - handleWrite( - boost::system::error_code const& ecResult, - std::size_t bytes_transferred) + handleWrite(boost::system::error_code const& ecResult, std::size_t bytes_transferred) { if (!mShutdown) mShutdown = ecResult; @@ -344,27 +299,18 @@ public: mHeader, "\r\n\r\n", std::bind( - &HTTPClientImp::handleHeader, - shared_from_this(), - std::placeholders::_1, - std::placeholders::_2)); + &HTTPClientImp::handleHeader, shared_from_this(), std::placeholders::_1, std::placeholders::_2)); } } void - handleHeader( - boost::system::error_code const& ecResult, - std::size_t bytes_transferred) + handleHeader(boost::system::error_code const& ecResult, std::size_t bytes_transferred) { - std::string strHeader{ - {std::istreambuf_iterator(&mHeader)}, - std::istreambuf_iterator()}; + std::string strHeader{{std::istreambuf_iterator(&mHeader)}, std::istreambuf_iterator()}; JLOG(j_.trace()) << "Header: \"" << strHeader << "\""; - static boost::regex reStatus{ - "\\`HTTP/1\\S+ (\\d{3}) .*\\'"}; // HTTP/1.1 200 OK - static boost::regex reSize{ - "\\`.*\\r\\nContent-Length:\\s+([0-9]+).*\\'", boost::regex::icase}; + static boost::regex reStatus{"\\`HTTP/1\\S+ (\\d{3}) .*\\'"}; // HTTP/1.1 200 OK + static boost::regex reSize{"\\`.*\\r\\nContent-Length:\\s+([0-9]+).*\\'", boost::regex::icase}; static boost::regex reBody{"\\`.*\\r\\n\\r\\n(.*)\\'"}; boost::smatch smMatch; @@ -373,9 +319,8 @@ public: { // XXX Use our own error code. JLOG(j_.trace()) << "No status code"; - invokeComplete(boost::system::error_code{ - boost::system::errc::bad_address, - boost::system::system_category()}); + invokeComplete( + boost::system::error_code{boost::system::errc::bad_address, boost::system::system_category()}); return; } @@ -386,17 +331,15 @@ public: std::size_t const responseSize = [&] { if (boost::regex_match(strHeader, smMatch, reSize)) - return beast::lexicalCast( - std::string(smMatch[1]), maxResponseSize_); + return beast::lexicalCast(std::string(smMatch[1]), maxResponseSize_); return maxResponseSize_; }(); if (responseSize > maxResponseSize_) { JLOG(j_.trace()) << "Response field too large"; - invokeComplete(boost::system::error_code{ - boost::system::errc::value_too_large, - boost::system::system_category()}); + invokeComplete( + boost::system::error_code{boost::system::errc::value_too_large, boost::system::system_category()}); return; } @@ -416,17 +359,12 @@ public: mResponse.prepare(responseSize - mBody.size()), boost::asio::transfer_all(), std::bind( - &HTTPClientImp::handleData, - shared_from_this(), - std::placeholders::_1, - std::placeholders::_2)); + &HTTPClientImp::handleData, shared_from_this(), std::placeholders::_1, std::placeholders::_2)); } } void - handleData( - boost::system::error_code const& ecResult, - std::size_t bytes_transferred) + handleData(boost::system::error_code const& ecResult, std::size_t bytes_transferred) { if (!mShutdown) mShutdown = ecResult; @@ -446,9 +384,7 @@ public: else { mResponse.commit(bytes_transferred); - std::string strBody{ - {std::istreambuf_iterator(&mResponse)}, - std::istreambuf_iterator()}; + std::string strBody{{std::istreambuf_iterator(&mResponse)}, std::istreambuf_iterator()}; invokeComplete(ecResult, mStatus, mBody + strBody); } } @@ -456,10 +392,7 @@ public: // Call cancel the deadline timer and invoke the completion routine. void - invokeComplete( - boost::system::error_code const& ecResult, - int iStatus = 0, - std::string const& strData = "") + invokeComplete(boost::system::error_code const& ecResult, int iStatus = 0, std::string const& strData = "") { boost::system::error_code ecCancel; try @@ -468,13 +401,11 @@ public: } catch (boost::system::system_error const& e) { - JLOG(j_.trace()) - << "invokeComplete: Deadline cancel error: " << e.what(); + JLOG(j_.trace()) << "invokeComplete: Deadline cancel error: " << e.what(); ecCancel = e.code(); } - JLOG(j_.debug()) << "invokeComplete: Deadline popping: " - << mDeqSites.size(); + JLOG(j_.debug()) << "invokeComplete: Deadline popping: " << mDeqSites.size(); if (!mDeqSites.empty()) { @@ -488,8 +419,7 @@ public: // ecResult: !0 = had an error, last entry // iStatus: result, if no error // strData: data, if no error - bAgain = mComplete && - mComplete(ecResult ? ecResult : ecCancel, iStatus, strData); + bAgain = mComplete && mComplete(ecResult ? ecResult : ecCancel, iStatus, strData); } if (!mDeqSites.empty() && bAgain) @@ -520,13 +450,8 @@ private: unsigned short const mPort; std::size_t const maxResponseSize_; int mStatus; - std::function - mBuild; - std::function - mComplete; + std::function mBuild; + std::function mComplete; boost::asio::basic_waitable_timer mDeadline; @@ -549,14 +474,10 @@ HTTPClient::get( std::string const& strPath, std::size_t responseMax, std::chrono::seconds timeout, - std::function complete, + std::function complete, beast::Journal& j) { - auto client = - std::make_shared(io_context, port, responseMax, j); + auto client = std::make_shared(io_context, port, responseMax, j); client->get(bSSL, deqSites, strPath, timeout, complete); } @@ -569,16 +490,12 @@ HTTPClient::get( std::string const& strPath, std::size_t responseMax, std::chrono::seconds timeout, - std::function complete, + std::function complete, beast::Journal& j) { std::deque deqSites(1, strSite); - auto client = - std::make_shared(io_context, port, responseMax, j); + auto client = std::make_shared(io_context, port, responseMax, j); client->get(bSSL, deqSites, strPath, timeout, complete); } @@ -588,20 +505,15 @@ HTTPClient::request( boost::asio::io_context& io_context, std::string strSite, unsigned short const port, - std::function - setRequest, + std::function setRequest, std::size_t responseMax, std::chrono::seconds timeout, - std::function complete, + std::function complete, beast::Journal& j) { std::deque deqSites(1, strSite); - auto client = - std::make_shared(io_context, port, responseMax, j); + auto client = std::make_shared(io_context, port, responseMax, j); client->request(bSSL, deqSites, setRequest, timeout, complete); } diff --git a/src/libxrpl/net/RegisterSSLCerts.cpp b/src/libxrpl/net/RegisterSSLCerts.cpp index a1321e4c61..a15472969e 100644 --- a/src/libxrpl/net/RegisterSSLCerts.cpp +++ b/src/libxrpl/net/RegisterSSLCerts.cpp @@ -16,36 +16,28 @@ namespace xrpl { void -registerSSLCerts( - boost::asio::ssl::context& ctx, - boost::system::error_code& ec, - beast::Journal j) +registerSSLCerts(boost::asio::ssl::context& ctx, boost::system::error_code& ec, beast::Journal j) { #if BOOST_OS_WINDOWS auto certStoreDelete = [](void* h) { if (h != nullptr) CertCloseStore(h, 0); }; - std::unique_ptr hStore{ - CertOpenSystemStore(0, "ROOT"), certStoreDelete}; + std::unique_ptr hStore{CertOpenSystemStore(0, "ROOT"), certStoreDelete}; if (!hStore) { - ec = boost::system::error_code( - GetLastError(), boost::system::system_category()); + ec = boost::system::error_code(GetLastError(), boost::system::system_category()); return; } ERR_clear_error(); - std::unique_ptr store{ - X509_STORE_new(), X509_STORE_free}; + std::unique_ptr store{X509_STORE_new(), X509_STORE_free}; if (!store) { - ec = boost::system::error_code( - static_cast(::ERR_get_error()), - boost::asio::error::get_ssl_category()); + ec = boost::system::error_code(static_cast(::ERR_get_error()), boost::asio::error::get_ssl_category()); return; } @@ -58,8 +50,7 @@ registerSSLCerts( }; PCCERT_CONTEXT pContext = NULL; - while ((pContext = CertEnumCertificatesInStore(hStore.get(), pContext)) != - NULL) + while ((pContext = CertEnumCertificatesInStore(hStore.get(), pContext)) != NULL) { unsigned char const* pbCertEncoded = pContext->pbCertEncoded; std::unique_ptr x509{ diff --git a/src/libxrpl/nodestore/BatchWriter.cpp b/src/libxrpl/nodestore/BatchWriter.cpp index 3ce7900480..73213fe3ba 100644 --- a/src/libxrpl/nodestore/BatchWriter.cpp +++ b/src/libxrpl/nodestore/BatchWriter.cpp @@ -4,10 +4,7 @@ namespace xrpl { namespace NodeStore { BatchWriter::BatchWriter(Callback& callback, Scheduler& scheduler) - : m_callback(callback) - , m_scheduler(scheduler) - , mWriteLoad(0) - , mWritePending(false) + : m_callback(callback), m_scheduler(scheduler), mWriteLoad(0), mWritePending(false) { mWriteSet.reserve(batchWritePreallocationSize); } @@ -64,9 +61,7 @@ BatchWriter::writeBatch() std::lock_guard sl(mWriteMutex); mWriteSet.swap(set); - XRPL_ASSERT( - mWriteSet.empty(), - "xrpl::NodeStore::BatchWriter::writeBatch : writes not set"); + XRPL_ASSERT(mWriteSet.empty(), "xrpl::NodeStore::BatchWriter::writeBatch : writes not set"); mWriteLoad = set.size(); if (set.empty()) @@ -85,8 +80,8 @@ BatchWriter::writeBatch() m_callback.writeBatch(set); - report.elapsed = std::chrono::duration_cast( - std::chrono::steady_clock::now() - before); + report.elapsed = + std::chrono::duration_cast(std::chrono::steady_clock::now() - before); m_scheduler.onBatchWrite(report); } diff --git a/src/libxrpl/nodestore/Database.cpp b/src/libxrpl/nodestore/Database.cpp index 9ea25785ff..f393bf27c9 100644 --- a/src/libxrpl/nodestore/Database.cpp +++ b/src/libxrpl/nodestore/Database.cpp @@ -10,21 +10,14 @@ namespace xrpl { namespace NodeStore { -Database::Database( - Scheduler& scheduler, - int readThreads, - Section const& config, - beast::Journal journal) +Database::Database(Scheduler& scheduler, int readThreads, Section const& config, beast::Journal journal) : j_(journal) , scheduler_(scheduler) - , earliestLedgerSeq_( - get(config, "earliest_seq", XRP_LEDGER_EARLIEST_SEQ)) + , earliestLedgerSeq_(get(config, "earliest_seq", XRP_LEDGER_EARLIEST_SEQ)) , requestBundle_(get(config, "rq_bundle", 4)) , readThreads_(std::max(1, readThreads)) { - XRPL_ASSERT( - readThreads, - "xrpl::NodeStore::Database::Database : nonzero threads input"); + XRPL_ASSERT(readThreads, "xrpl::NodeStore::Database::Database : nonzero threads input"); if (earliestLedgerSeq_ < 1) Throw("Invalid earliest_seq"); @@ -38,8 +31,7 @@ Database::Database( [this](int i) { runningThreads_++; - beast::setCurrentThreadName( - "db prefetch #" + std::to_string(i)); + beast::setCurrentThreadName("db prefetch #" + std::to_string(i)); decltype(read_) read; @@ -63,9 +55,7 @@ Database::Database( // extract multiple object at a time to minimize the // overhead of acquiring the mutex. - for (int cnt = 0; - !read_.empty() && cnt != requestBundle_; - ++cnt) + for (int cnt = 0; !read_.empty() && cnt != requestBundle_; ++cnt) read.insert(read_.extract(read_.begin())); } @@ -80,8 +70,7 @@ Database::Database( auto const& data = it->second; auto const seqn = data[0].first; - auto obj = - fetchNodeObject(hash, seqn, FetchType::async); + auto obj = fetchNodeObject(hash, seqn, FetchType::async); // This could be further optimized: if there are // multiple requests for sequence numbers mapping to @@ -93,8 +82,7 @@ Database::Database( req.second( (seqn == req.first) || isSameDB(req.first, seqn) ? obj - : fetchNodeObject( - hash, req.first, FetchType::async)); + : fetchNodeObject(hash, req.first, FetchType::async)); } } @@ -148,16 +136,12 @@ Database::stop() while (readThreads_.load() != 0) { - XRPL_ASSERT( - steady_clock::now() - start < 30s, - "xrpl::NodeStore::Database::stop : maximum stop duration"); + XRPL_ASSERT(steady_clock::now() - start < 30s, "xrpl::NodeStore::Database::stop : maximum stop duration"); std::this_thread::yield(); } JLOG(j_.debug()) << "Stop request completed in " - << duration_cast( - steady_clock::now() - start) - .count() + << duration_cast(steady_clock::now() - start).count() << " milliseconds"; } @@ -188,8 +172,7 @@ Database::importInternal(Backend& dstBackend, Database& srcDB) } catch (std::exception const& e) { - JLOG(j_.error()) << "Exception caught in function " << fname - << ". Error: " << e.what(); + JLOG(j_.error()) << "Exception caught in function " << fname << ". Error: " << e.what(); return; } @@ -201,9 +184,7 @@ Database::importInternal(Backend& dstBackend, Database& srcDB) }; srcDB.for_each([&](std::shared_ptr nodeObject) { - XRPL_ASSERT( - nodeObject, - "xrpl::NodeStore::Database::importInternal : non-null node"); + XRPL_ASSERT(nodeObject, "xrpl::NodeStore::Database::importInternal : non-null node"); if (!nodeObject) // This should never happen return; @@ -218,11 +199,7 @@ Database::importInternal(Backend& dstBackend, Database& srcDB) // Perform a fetch and report the time it took std::shared_ptr -Database::fetchNodeObject( - uint256 const& hash, - std::uint32_t ledgerSeq, - FetchType fetchType, - bool duplicate) +Database::fetchNodeObject(uint256 const& hash, std::uint32_t ledgerSeq, FetchType fetchType, bool duplicate) { FetchReport fetchReport(fetchType); @@ -247,9 +224,7 @@ Database::fetchNodeObject( void Database::getCountsJson(Json::Value& obj) { - XRPL_ASSERT( - obj.isObject(), - "xrpl::NodeStore::Database::getCountsJson : valid input type"); + XRPL_ASSERT(obj.isObject(), "xrpl::NodeStore::Database::getCountsJson : valid input type"); { std::unique_lock lock(readLock_); diff --git a/src/libxrpl/nodestore/DatabaseNodeImp.cpp b/src/libxrpl/nodestore/DatabaseNodeImp.cpp index 0578351e58..11152a2027 100644 --- a/src/libxrpl/nodestore/DatabaseNodeImp.cpp +++ b/src/libxrpl/nodestore/DatabaseNodeImp.cpp @@ -4,24 +4,12 @@ namespace xrpl { namespace NodeStore { void -DatabaseNodeImp::store( - NodeObjectType type, - Blob&& data, - uint256 const& hash, - std::uint32_t) +DatabaseNodeImp::store(NodeObjectType type, Blob&& data, uint256 const& hash, std::uint32_t) { storeStats(1, data.size()); auto obj = NodeObject::createObject(type, std::move(data), hash); backend_->store(obj); - if (cache_) - { - // After the store, replace a negative cache entry if there is one - cache_->canonicalize( - hash, obj, [](std::shared_ptr const& n) { - return n->getType() == hotDUMMY; - }); - } } void @@ -30,90 +18,36 @@ DatabaseNodeImp::asyncFetch( std::uint32_t ledgerSeq, std::function const&)>&& callback) { - if (cache_) - { - std::shared_ptr obj = cache_->fetch(hash); - if (obj) - { - callback(obj->getType() == hotDUMMY ? nullptr : obj); - return; - } - } Database::asyncFetch(hash, ledgerSeq, std::move(callback)); } -void -DatabaseNodeImp::sweep() -{ - if (cache_) - cache_->sweep(); -} - std::shared_ptr -DatabaseNodeImp::fetchNodeObject( - uint256 const& hash, - std::uint32_t, - FetchReport& fetchReport, - bool duplicate) +DatabaseNodeImp::fetchNodeObject(uint256 const& hash, std::uint32_t, FetchReport& fetchReport, bool duplicate) { - std::shared_ptr nodeObject = - cache_ ? cache_->fetch(hash) : nullptr; + std::shared_ptr nodeObject = nullptr; + Status status; - if (!nodeObject) + try { - JLOG(j_.trace()) << "fetchNodeObject " << hash << ": record not " - << (cache_ ? "cached" : "found"); - - Status status; - - try - { - status = backend_->fetch(hash.data(), &nodeObject); - } - catch (std::exception const& e) - { - JLOG(j_.fatal()) - << "fetchNodeObject " << hash - << ": Exception fetching from backend: " << e.what(); - Rethrow(); - } - - switch (status) - { - case ok: - if (cache_) - { - if (nodeObject) - cache_->canonicalize_replace_client(hash, nodeObject); - else - { - auto notFound = - NodeObject::createObject(hotDUMMY, {}, hash); - cache_->canonicalize_replace_client(hash, notFound); - if (notFound->getType() != hotDUMMY) - nodeObject = notFound; - } - } - break; - case notFound: - break; - case dataCorrupt: - JLOG(j_.fatal()) << "fetchNodeObject " << hash - << ": nodestore data is corrupted"; - break; - default: - JLOG(j_.warn()) - << "fetchNodeObject " << hash - << ": backend returns unknown result " << status; - break; - } + status = backend_->fetch(hash.data(), &nodeObject); } - else + catch (std::exception const& e) { - JLOG(j_.trace()) << "fetchNodeObject " << hash - << ": record found in cache"; - if (nodeObject->getType() == hotDUMMY) - nodeObject.reset(); + JLOG(j_.fatal()) << "fetchNodeObject " << hash << ": Exception fetching from backend: " << e.what(); + Rethrow(); + } + + switch (status) + { + case ok: + case notFound: + break; + case dataCorrupt: + JLOG(j_.fatal()) << "fetchNodeObject " << hash << ": nodestore data is corrupted"; + break; + default: + JLOG(j_.warn()) << "fetchNodeObject " << hash << ": backend returns unknown result " << status; + break; } if (nodeObject) @@ -125,71 +59,36 @@ DatabaseNodeImp::fetchNodeObject( std::vector> DatabaseNodeImp::fetchBatch(std::vector const& hashes) { - std::vector> results{hashes.size()}; using namespace std::chrono; auto const before = steady_clock::now(); - std::unordered_map indexMap; - std::vector cacheMisses; - uint64_t hits = 0; - uint64_t fetches = 0; + + std::vector batch{}; + batch.reserve(hashes.size()); for (size_t i = 0; i < hashes.size(); ++i) { auto const& hash = hashes[i]; - // See if the object already exists in the cache - auto nObj = cache_ ? cache_->fetch(hash) : nullptr; - ++fetches; - if (!nObj) - { - // Try the database - indexMap[&hash] = i; - cacheMisses.push_back(&hash); - } - else - { - results[i] = nObj->getType() == hotDUMMY ? nullptr : nObj; - // It was in the cache. - ++hits; - } + batch.push_back(&hash); } - JLOG(j_.debug()) << "fetchBatch - cache hits = " - << (hashes.size() - cacheMisses.size()) - << " - cache misses = " << cacheMisses.size(); - auto dbResults = backend_->fetchBatch(cacheMisses).first; - - for (size_t i = 0; i < dbResults.size(); ++i) + // Get the node objects that match the hashes from the backend. To protect + // against the backends returning fewer or more results than expected, the + // container is resized to the number of hashes. + auto results = backend_->fetchBatch(batch).first; + XRPL_ASSERT( + results.size() == hashes.size() || results.empty(), + "number of output objects either matches number of input hashes or is empty"); + results.resize(hashes.size()); + for (size_t i = 0; i < results.size(); ++i) { - auto nObj = std::move(dbResults[i]); - size_t index = indexMap[cacheMisses[i]]; - auto const& hash = hashes[index]; - - if (nObj) + if (!results[i]) { - // Ensure all threads get the same object - if (cache_) - cache_->canonicalize_replace_client(hash, nObj); + JLOG(j_.error()) << "fetchBatch - " + << "record not found in db. hash = " << strHex(hashes[i]); } - else - { - JLOG(j_.error()) - << "fetchBatch - " - << "record not found in db or cache. hash = " << strHex(hash); - if (cache_) - { - auto notFound = NodeObject::createObject(hotDUMMY, {}, hash); - cache_->canonicalize_replace_client(hash, notFound); - if (notFound->getType() != hotDUMMY) - nObj = std::move(notFound); - } - } - results[index] = std::move(nObj); } - auto fetchDurationUs = - std::chrono::duration_cast( - steady_clock::now() - before) - .count(); - updateFetchMetrics(fetches, hits, fetchDurationUs); + auto fetchDurationUs = std::chrono::duration_cast(steady_clock::now() - before).count(); + updateFetchMetrics(hashes.size(), 0, fetchDurationUs); return results; } diff --git a/src/libxrpl/nodestore/DatabaseRotatingImp.cpp b/src/libxrpl/nodestore/DatabaseRotatingImp.cpp index f51771f023..f25b9d068e 100644 --- a/src/libxrpl/nodestore/DatabaseRotatingImp.cpp +++ b/src/libxrpl/nodestore/DatabaseRotatingImp.cpp @@ -23,9 +23,7 @@ DatabaseRotatingImp::DatabaseRotatingImp( void DatabaseRotatingImp::rotate( std::unique_ptr&& newBackend, - std::function const& f) + std::function const& f) { // Pass these two names to the callback function std::string const newWritableBackendName = newBackend->getName(); @@ -82,11 +80,7 @@ DatabaseRotatingImp::sync() } void -DatabaseRotatingImp::store( - NodeObjectType type, - Blob&& data, - uint256 const& hash, - std::uint32_t) +DatabaseRotatingImp::store(NodeObjectType type, Blob&& data, uint256 const& hash, std::uint32_t) { auto nObj = NodeObject::createObject(type, std::move(data), hash); @@ -99,18 +93,8 @@ DatabaseRotatingImp::store( storeStats(1, nObj->getData().size()); } -void -DatabaseRotatingImp::sweep() -{ - // nothing to do -} - std::shared_ptr -DatabaseRotatingImp::fetchNodeObject( - uint256 const& hash, - std::uint32_t, - FetchReport& fetchReport, - bool duplicate) +DatabaseRotatingImp::fetchNodeObject(uint256 const& hash, std::uint32_t, FetchReport& fetchReport, bool duplicate) { auto fetch = [&](std::shared_ptr const& backend) { Status status; @@ -176,8 +160,7 @@ DatabaseRotatingImp::fetchNodeObject( } void -DatabaseRotatingImp::for_each( - std::function)> f) +DatabaseRotatingImp::for_each(std::function)> f) { auto [writable, archive] = [&] { std::lock_guard lock(mutex_); diff --git a/src/libxrpl/nodestore/DecodedBlob.cpp b/src/libxrpl/nodestore/DecodedBlob.cpp index e3d54fae78..ad704cb84e 100644 --- a/src/libxrpl/nodestore/DecodedBlob.cpp +++ b/src/libxrpl/nodestore/DecodedBlob.cpp @@ -54,9 +54,7 @@ DecodedBlob::DecodedBlob(void const* key, void const* value, int valueBytes) std::shared_ptr DecodedBlob::createObject() { - XRPL_ASSERT( - m_success, - "xrpl::NodeStore::DecodedBlob::createObject : valid object type"); + XRPL_ASSERT(m_success, "xrpl::NodeStore::DecodedBlob::createObject : valid object type"); std::shared_ptr object; @@ -64,8 +62,7 @@ DecodedBlob::createObject() { Blob data(m_objectData, m_objectData + m_dataBytes); - object = NodeObject::createObject( - m_objectType, std::move(data), uint256::fromVoid(m_key)); + object = NodeObject::createObject(m_objectType, std::move(data), uint256::fromVoid(m_key)); } return object; diff --git a/src/libxrpl/nodestore/ManagerImp.cpp b/src/libxrpl/nodestore/ManagerImp.cpp index 58accd4108..9d78097aae 100644 --- a/src/libxrpl/nodestore/ManagerImp.cpp +++ b/src/libxrpl/nodestore/ManagerImp.cpp @@ -44,11 +44,7 @@ ManagerImp::ManagerImp() } std::unique_ptr -ManagerImp::make_Backend( - Section const& parameters, - std::size_t burstSize, - Scheduler& scheduler, - beast::Journal journal) +ManagerImp::make_Backend(Section const& parameters, std::size_t burstSize, Scheduler& scheduler, beast::Journal journal) { std::string const type{get(parameters, "type")}; if (type.empty()) @@ -60,8 +56,7 @@ ManagerImp::make_Backend( missing_backend(); } - return factory->createInstance( - NodeObject::keyBytes, parameters, burstSize, scheduler, journal); + return factory->createInstance(NodeObject::keyBytes, parameters, burstSize, scheduler, journal); } std::unique_ptr @@ -74,8 +69,7 @@ ManagerImp::make_Database( { auto backend{make_Backend(config, burstSize, scheduler, journal)}; backend->open(); - return std::make_unique( - scheduler, readThreads, std::move(backend), config, journal); + return std::make_unique(scheduler, readThreads, std::move(backend), config, journal); } void @@ -90,12 +84,8 @@ ManagerImp::erase(Factory& factory) { std::lock_guard _(mutex_); auto const iter = - std::find_if(list_.begin(), list_.end(), [&factory](Factory* other) { - return other == &factory; - }); - XRPL_ASSERT( - iter != list_.end(), - "xrpl::NodeStore::ManagerImp::erase : valid input"); + std::find_if(list_.begin(), list_.end(), [&factory](Factory* other) { return other == &factory; }); + XRPL_ASSERT(iter != list_.end(), "xrpl::NodeStore::ManagerImp::erase : valid input"); list_.erase(iter); } @@ -103,10 +93,8 @@ Factory* ManagerImp::find(std::string const& name) { std::lock_guard _(mutex_); - auto const iter = - std::find_if(list_.begin(), list_.end(), [&name](Factory* other) { - return boost::iequals(name, other->getName()); - }); + auto const iter = std::find_if( + list_.begin(), list_.end(), [&name](Factory* other) { return boost::iequals(name, other->getName()); }); if (iter == list_.end()) return nullptr; return *iter; diff --git a/src/libxrpl/nodestore/NodeObject.cpp b/src/libxrpl/nodestore/NodeObject.cpp index 3758862e18..2e40989e7c 100644 --- a/src/libxrpl/nodestore/NodeObject.cpp +++ b/src/libxrpl/nodestore/NodeObject.cpp @@ -6,11 +6,7 @@ namespace xrpl { //------------------------------------------------------------------------------ -NodeObject::NodeObject( - NodeObjectType type, - Blob&& data, - uint256 const& hash, - PrivateAccess) +NodeObject::NodeObject(NodeObjectType type, Blob&& data, uint256 const& hash, PrivateAccess) : mType(type), mHash(hash), mData(std::move(data)) { } @@ -18,8 +14,7 @@ NodeObject::NodeObject( std::shared_ptr NodeObject::createObject(NodeObjectType type, Blob&& data, uint256 const& hash) { - return std::make_shared( - type, std::move(data), hash, PrivateAccess()); + return std::make_shared(type, std::move(data), hash, PrivateAccess()); } NodeObjectType diff --git a/src/libxrpl/nodestore/backend/MemoryFactory.cpp b/src/libxrpl/nodestore/backend/MemoryFactory.cpp index 923ae95ebb..3cb8fb7f5e 100644 --- a/src/libxrpl/nodestore/backend/MemoryFactory.cpp +++ b/src/libxrpl/nodestore/backend/MemoryFactory.cpp @@ -46,8 +46,7 @@ public: open(std::string const& path) { std::lock_guard _(mutex_); - auto const result = map_.emplace( - std::piecewise_construct, std::make_tuple(path), std::make_tuple()); + auto const result = map_.emplace(std::piecewise_construct, std::make_tuple(path), std::make_tuple()); MemoryDB& db = result.first->second; if (db.open) Throw("already open"); @@ -76,10 +75,7 @@ private: MemoryDB* db_{nullptr}; public: - MemoryBackend( - size_t keyBytes, - Section const& keyValues, - beast::Journal journal) + MemoryBackend(size_t keyBytes, Section const& keyValues, beast::Journal journal) : name_(get(keyValues, "path")), journal_(journal) { boost::ignore_unused(journal_); // Keep unused journal_ just in case. @@ -121,8 +117,7 @@ public: Status fetch(void const* key, std::shared_ptr* pObject) override { - XRPL_ASSERT( - db_, "xrpl::NodeStore::MemoryBackend::fetch : non-null database"); + XRPL_ASSERT(db_, "xrpl::NodeStore::MemoryBackend::fetch : non-null database"); uint256 const hash(uint256::fromVoid(key)); std::lock_guard _(db_->mutex); @@ -158,8 +153,7 @@ public: void store(std::shared_ptr const& object) override { - XRPL_ASSERT( - db_, "xrpl::NodeStore::MemoryBackend::store : non-null database"); + XRPL_ASSERT(db_, "xrpl::NodeStore::MemoryBackend::store : non-null database"); std::lock_guard _(db_->mutex); db_->table.emplace(object->getHash(), object); } @@ -179,9 +173,7 @@ public: void for_each(std::function)> f) override { - XRPL_ASSERT( - db_, - "xrpl::NodeStore::MemoryBackend::for_each : non-null database"); + XRPL_ASSERT(db_, "xrpl::NodeStore::MemoryBackend::for_each : non-null database"); for (auto const& e : db_->table) f(e.second); } diff --git a/src/libxrpl/nodestore/backend/NuDBFactory.cpp b/src/libxrpl/nodestore/backend/NuDBFactory.cpp index 71a5811162..eb3ccb3181 100644 --- a/src/libxrpl/nodestore/backend/NuDBFactory.cpp +++ b/src/libxrpl/nodestore/backend/NuDBFactory.cpp @@ -53,8 +53,7 @@ public: , scheduler_(scheduler) { if (name_.empty()) - Throw( - "nodestore: Missing path in NuDB backend"); + Throw("nodestore: Missing path in NuDB backend"); } NuDBBackend( @@ -74,8 +73,7 @@ public: , scheduler_(scheduler) { if (name_.empty()) - Throw( - "nodestore: Missing path in NuDB backend"); + Throw("nodestore: Missing path in NuDB backend"); } ~NuDBBackend() override @@ -105,8 +103,7 @@ public: } void - open(bool createIfMissing, uint64_t appType, uint64_t uid, uint64_t salt) - override + open(bool createIfMissing, uint64_t appType, uint64_t uid, uint64_t salt) override { using namespace boost::filesystem; if (db_.is_open()) @@ -127,17 +124,7 @@ public: if (createIfMissing) { create_directories(folder); - nudb::create( - dp, - kp, - lp, - appType, - uid, - salt, - keyBytes_, - blockSize_, - 0.50, - ec); + nudb::create(dp, kp, lp, appType, uid, salt, keyBytes_, blockSize_, 0.50, ec); if (ec == nudb::errc::file_exists) ec = {}; if (ec) @@ -183,8 +170,7 @@ public: boost::filesystem::remove_all(name_, ec); if (ec) { - JLOG(j_.fatal()) << "Filesystem remove_all of " << name_ - << " failed with: " << ec.message(); + JLOG(j_.fatal()) << "Filesystem remove_all of " << name_ << " failed with: " << ec.message(); } } } @@ -255,8 +241,8 @@ public: report.writeCount = 1; auto const start = std::chrono::steady_clock::now(); do_insert(no); - report.elapsed = std::chrono::duration_cast( - std::chrono::steady_clock::now() - start); + report.elapsed = + std::chrono::duration_cast(std::chrono::steady_clock::now() - start); scheduler_.onBatchWrite(report); } @@ -268,8 +254,8 @@ public: auto const start = std::chrono::steady_clock::now(); for (auto const& e : batch) do_insert(e); - report.elapsed = std::chrono::duration_cast( - std::chrono::steady_clock::now() - start); + report.elapsed = + std::chrono::duration_cast(std::chrono::steady_clock::now() - start); scheduler_.onBatchWrite(report); } @@ -291,11 +277,7 @@ public: Throw(ec); nudb::visit( dp, - [&](void const* key, - std::size_t key_bytes, - void const* data, - std::size_t size, - nudb::error_code&) { + [&](void const* key, std::size_t key_bytes, void const* data, std::size_t size, nudb::error_code&) { nudb::detail::buffer bf; auto const result = nodeobject_decompress(data, size, bf); DecodedBlob decoded(key, result.first, result.second); @@ -354,17 +336,13 @@ public: private: static std::size_t - parseBlockSize( - std::string const& name, - Section const& keyValues, - beast::Journal journal) + parseBlockSize(std::string const& name, Section const& keyValues, beast::Journal journal) { using namespace boost::filesystem; auto const folder = path(name); auto const kp = (folder / "nudb.key").string(); - std::size_t const defaultSize = - nudb::block_size(kp); // Default 4K from NuDB + std::size_t const defaultSize = nudb::block_size(kp); // Default 4K from NuDB std::size_t blockSize = defaultSize; std::string blockSizeStr; @@ -375,29 +353,23 @@ private: try { - std::size_t const parsedBlockSize = - beast::lexicalCastThrow(blockSizeStr); + std::size_t const parsedBlockSize = beast::lexicalCastThrow(blockSizeStr); // Validate: must be power of 2 between 4K and 32K - if (parsedBlockSize < 4096 || parsedBlockSize > 32768 || - (parsedBlockSize & (parsedBlockSize - 1)) != 0) + if (parsedBlockSize < 4096 || parsedBlockSize > 32768 || (parsedBlockSize & (parsedBlockSize - 1)) != 0) { std::stringstream s; - s << "Invalid nudb_block_size: " << parsedBlockSize - << ". Must be power of 2 between 4096 and 32768."; + s << "Invalid nudb_block_size: " << parsedBlockSize << ". Must be power of 2 between 4096 and 32768."; Throw(s.str()); } - JLOG(journal.info()) - << "Using custom NuDB block size: " << parsedBlockSize - << " bytes"; + JLOG(journal.info()) << "Using custom NuDB block size: " << parsedBlockSize << " bytes"; return parsedBlockSize; } catch (std::exception const& e) { std::stringstream s; - s << "Invalid nudb_block_size value: " << blockSizeStr - << ". Error: " << e.what(); + s << "Invalid nudb_block_size value: " << blockSizeStr << ". Error: " << e.what(); Throw(s.str()); } } @@ -430,8 +402,7 @@ public: Scheduler& scheduler, beast::Journal journal) override { - return std::make_unique( - keyBytes, keyValues, burstSize, scheduler, journal); + return std::make_unique(keyBytes, keyValues, burstSize, scheduler, journal); } std::unique_ptr @@ -443,8 +414,7 @@ public: nudb::context& context, beast::Journal journal) override { - return std::make_unique( - keyBytes, keyValues, burstSize, scheduler, context, journal); + return std::make_unique(keyBytes, keyValues, burstSize, scheduler, context, journal); } }; diff --git a/src/libxrpl/nodestore/backend/NullFactory.cpp b/src/libxrpl/nodestore/backend/NullFactory.cpp index ffe1eb931f..4ecca46a9a 100644 --- a/src/libxrpl/nodestore/backend/NullFactory.cpp +++ b/src/libxrpl/nodestore/backend/NullFactory.cpp @@ -108,12 +108,7 @@ public: } std::unique_ptr - createInstance( - size_t, - Section const&, - std::size_t, - Scheduler&, - beast::Journal) override + createInstance(size_t, Section const&, std::size_t, Scheduler&, beast::Journal) override { return std::make_unique(); } diff --git a/src/libxrpl/nodestore/backend/RocksDBFactory.cpp b/src/libxrpl/nodestore/backend/RocksDBFactory.cpp index 97d5484554..a35f737528 100644 --- a/src/libxrpl/nodestore/backend/RocksDBFactory.cpp +++ b/src/libxrpl/nodestore/backend/RocksDBFactory.cpp @@ -81,10 +81,7 @@ public: Scheduler& scheduler, beast::Journal journal, RocksDBEnv* env) - : m_deletePath(false) - , m_journal(journal) - , m_keyBytes(keyBytes) - , m_batch(*this, scheduler) + : m_deletePath(false), m_journal(journal), m_keyBytes(keyBytes), m_batch(*this, scheduler) { if (!get_if_exists(keyValues, "path", m_name)) Throw("Missing path in RocksDBFactory backend"); @@ -92,8 +89,7 @@ public: rocksdb::BlockBasedTableOptions table_options; m_options.env = env; - bool hard_set = - keyValues.exists("hard_set") && get(keyValues, "hard_set"); + bool hard_set = keyValues.exists("hard_set") && get(keyValues, "hard_set"); if (keyValues.exists("cache_mb")) { @@ -107,10 +103,8 @@ public: if (auto const v = get(keyValues, "filter_bits")) { - bool const filter_blocks = !keyValues.exists("filter_full") || - (get(keyValues, "filter_full") == 0); - table_options.filter_policy.reset( - rocksdb::NewBloomFilterPolicy(v, filter_blocks)); + bool const filter_blocks = !keyValues.exists("filter_full") || (get(keyValues, "filter_full") == 0); + table_options.filter_policy.reset(rocksdb::NewBloomFilterPolicy(v, filter_blocks)); } if (get_if_exists(keyValues, "open_files", m_options.max_open_files)) @@ -129,25 +123,21 @@ public: file_size_mb = 256; m_options.target_file_size_base = megabytes(file_size_mb); - m_options.max_bytes_for_level_base = - 5 * m_options.target_file_size_base; + m_options.max_bytes_for_level_base = 5 * m_options.target_file_size_base; m_options.write_buffer_size = 2 * m_options.target_file_size_base; } - get_if_exists( - keyValues, "file_size_mult", m_options.target_file_size_multiplier); + get_if_exists(keyValues, "file_size_mult", m_options.target_file_size_multiplier); if (keyValues.exists("bg_threads")) { - m_options.env->SetBackgroundThreads( - get(keyValues, "bg_threads"), rocksdb::Env::LOW); + m_options.env->SetBackgroundThreads(get(keyValues, "bg_threads"), rocksdb::Env::LOW); } if (keyValues.exists("high_threads")) { auto const highThreads = get(keyValues, "high_threads"); - m_options.env->SetBackgroundThreads( - highThreads, rocksdb::Env::HIGH); + m_options.env->SetBackgroundThreads(highThreads, rocksdb::Env::HIGH); // If we have high-priority threads, presumably we want to // use them for background flushes @@ -159,8 +149,7 @@ public: get_if_exists(keyValues, "block_size", table_options.block_size); - if (keyValues.exists("universal_compaction") && - (get(keyValues, "universal_compaction") != 0)) + if (keyValues.exists("universal_compaction") && (get(keyValues, "universal_compaction") != 0)) { m_options.compaction_style = rocksdb::kCompactionStyleUniversal; m_options.min_write_buffer_number_to_merge = 2; @@ -172,26 +161,18 @@ public: { rocksdb::ConfigOptions config_options; auto const s = rocksdb::GetBlockBasedTableOptionsFromString( - config_options, - table_options, - get(keyValues, "bbt_options"), - &table_options); + config_options, table_options, get(keyValues, "bbt_options"), &table_options); if (!s.ok()) - Throw( - std::string("Unable to set RocksDB bbt_options: ") + - s.ToString()); + Throw(std::string("Unable to set RocksDB bbt_options: ") + s.ToString()); } m_options.table_factory.reset(NewBlockBasedTableFactory(table_options)); if (keyValues.exists("options")) { - auto const s = rocksdb::GetOptionsFromString( - m_options, get(keyValues, "options"), &m_options); + auto const s = rocksdb::GetOptionsFromString(m_options, get(keyValues, "options"), &m_options); if (!s.ok()) - Throw( - std::string("Unable to set RocksDB options: ") + - s.ToString()); + Throw(std::string("Unable to set RocksDB options: ") + s.ToString()); } std::string s1, s2; @@ -223,9 +204,7 @@ public: m_options.create_if_missing = createIfMissing; rocksdb::Status status = rocksdb::DB::Open(m_options, m_name, &db); if (!status.ok() || !db) - Throw( - std::string("Unable to open/create RocksDB: ") + - status.ToString()); + Throw(std::string("Unable to open/create RocksDB: ") + status.ToString()); m_db.reset(db); } @@ -260,8 +239,7 @@ public: Status fetch(void const* key, std::shared_ptr* pObject) override { - XRPL_ASSERT( - m_db, "xrpl::NodeStore::RocksDBBackend::fetch : non-null database"); + XRPL_ASSERT(m_db, "xrpl::NodeStore::RocksDBBackend::fetch : non-null database"); pObject->reset(); Status status(ok); @@ -300,8 +278,7 @@ public: } else { - status = - Status(customCode + unsafe_cast(getStatus.code())); + status = Status(customCode + unsafe_cast(getStatus.code())); JLOG(m_journal.error()) << getStatus.ToString(); } @@ -348,12 +325,8 @@ public: EncodedBlob encoded(e); wb.Put( - rocksdb::Slice( - reinterpret_cast(encoded.getKey()), - m_keyBytes), - rocksdb::Slice( - reinterpret_cast(encoded.getData()), - encoded.getSize())); + rocksdb::Slice(reinterpret_cast(encoded.getKey()), m_keyBytes), + rocksdb::Slice(reinterpret_cast(encoded.getData()), encoded.getSize())); } rocksdb::WriteOptions const options; @@ -372,9 +345,7 @@ public: void for_each(std::function)> f) override { - XRPL_ASSERT( - m_db, - "xrpl::NodeStore::RocksDBBackend::for_each : non-null database"); + XRPL_ASSERT(m_db, "xrpl::NodeStore::RocksDBBackend::for_each : non-null database"); rocksdb::ReadOptions const options; std::unique_ptr it(m_db->NewIterator(options)); @@ -383,8 +354,7 @@ public: { if (it->key().size() == m_keyBytes) { - DecodedBlob decoded( - it->key().data(), it->value().data(), it->value().size()); + DecodedBlob decoded(it->key().data(), it->value().data(), it->value().size()); if (decoded.wasOk()) { @@ -393,16 +363,14 @@ public: else { // Uh oh, corrupted data! - JLOG(m_journal.fatal()) - << "Corrupt NodeObject #" << it->key().ToString(true); + JLOG(m_journal.fatal()) << "Corrupt NodeObject #" << it->key().ToString(true); } } else { // VFALCO NOTE What does it mean to find an // incorrectly sized key? Corruption? - JLOG(m_journal.fatal()) - << "Bad key size = " << it->key().size(); + JLOG(m_journal.fatal()) << "Bad key size = " << it->key().size(); } } } @@ -457,15 +425,10 @@ public: } std::unique_ptr - createInstance( - size_t keyBytes, - Section const& keyValues, - std::size_t, - Scheduler& scheduler, - beast::Journal journal) override + createInstance(size_t keyBytes, Section const& keyValues, std::size_t, Scheduler& scheduler, beast::Journal journal) + override { - return std::make_unique( - keyBytes, keyValues, scheduler, journal, &m_env); + return std::make_unique(keyBytes, keyValues, scheduler, journal, &m_env); } }; diff --git a/src/libxrpl/protocol/AMMCore.cpp b/src/libxrpl/protocol/AMMCore.cpp index 71ce6ea98e..bb83be2724 100644 --- a/src/libxrpl/protocol/AMMCore.cpp +++ b/src/libxrpl/protocol/AMMCore.cpp @@ -29,24 +29,18 @@ ammLPTCurrency(Currency const& cur1, Currency const& cur2) auto const hash = sha512Half(minC, maxC); Currency currency; *currency.begin() = AMMCurrencyCode; - std::copy( - hash.begin(), hash.begin() + currency.size() - 1, currency.begin() + 1); + std::copy(hash.begin(), hash.begin() + currency.size() - 1, currency.begin() + 1); return currency; } Issue -ammLPTIssue( - Currency const& cur1, - Currency const& cur2, - AccountID const& ammAccountID) +ammLPTIssue(Currency const& cur1, Currency const& cur2, AccountID const& ammAccountID) { return Issue(ammLPTCurrency(cur1, cur2), ammAccountID); } NotTEC -invalidAMMAsset( - Issue const& issue, - std::optional> const& pair) +invalidAMMAsset(Issue const& issue, std::optional> const& pair) { if (badCurrency() == issue.currency) return temBAD_CURRENCY; @@ -58,10 +52,7 @@ invalidAMMAsset( } NotTEC -invalidAMMAssetPair( - Issue const& issue1, - Issue const& issue2, - std::optional> const& pair) +invalidAMMAssetPair(Issue const& issue1, Issue const& issue2, std::optional> const& pair) { if (issue1 == issue2) return temBAD_AMM_TOKENS; @@ -73,10 +64,7 @@ invalidAMMAssetPair( } NotTEC -invalidAMMAmount( - STAmount const& amount, - std::optional> const& pair, - bool validZero) +invalidAMMAmount(STAmount const& amount, std::optional> const& pair, bool validZero) { if (auto const res = invalidAMMAsset(amount.issue(), pair)) return res; @@ -91,13 +79,10 @@ ammAuctionTimeSlot(std::uint64_t current, STObject const& auctionSlot) // It should be impossible for expiration to be < TOTAL_TIME_SLOT_SECS, // but check just to be safe auto const expiration = auctionSlot[sfExpiration]; - XRPL_ASSERT( - expiration >= TOTAL_TIME_SLOT_SECS, - "xrpl::ammAuctionTimeSlot : minimum expiration"); + XRPL_ASSERT(expiration >= TOTAL_TIME_SLOT_SECS, "xrpl::ammAuctionTimeSlot : minimum expiration"); if (expiration >= TOTAL_TIME_SLOT_SECS) { - if (auto const start = expiration - TOTAL_TIME_SLOT_SECS; - current >= start) + if (auto const start = expiration - TOTAL_TIME_SLOT_SECS; current >= start) { if (auto const diff = current - start; diff < TOTAL_TIME_SLOT_SECS) return diff / AUCTION_SLOT_INTERVAL_DURATION; diff --git a/src/libxrpl/protocol/AccountID.cpp b/src/libxrpl/protocol/AccountID.cpp index 779018613f..4edbf5c0e7 100644 --- a/src/libxrpl/protocol/AccountID.cpp +++ b/src/libxrpl/protocol/AccountID.cpp @@ -63,12 +63,9 @@ public: return cache_[index].encoding; } - auto ret = - encodeBase58Token(TokenType::AccountID, id.data(), id.size()); + auto ret = encodeBase58Token(TokenType::AccountID, id.data(), id.size()); - XRPL_ASSERT( - ret.size() <= 38, - "xrpl::detail::AccountIdCache : maximum result size"); + XRPL_ASSERT(ret.size() <= 38, "xrpl::detail::AccountIdCache : maximum result size"); { std::lock_guard lock(sl); diff --git a/src/libxrpl/protocol/Asset.cpp b/src/libxrpl/protocol/Asset.cpp index 1a4a94f744..0076da6570 100644 --- a/src/libxrpl/protocol/Asset.cpp +++ b/src/libxrpl/protocol/Asset.cpp @@ -16,9 +16,7 @@ namespace xrpl { AccountID const& Asset::getIssuer() const { - return std::visit( - [&](auto&& issue) -> AccountID const& { return issue.getIssuer(); }, - issue_); + return std::visit([&](auto&& issue) -> AccountID const& { return issue.getIssuer(); }, issue_); } std::string @@ -42,8 +40,7 @@ Asset::operator()(Number const& number) const std::string to_string(Asset const& asset) { - return std::visit( - [&](auto const& issue) { return to_string(issue); }, asset.value()); + return std::visit([&](auto const& issue) { return to_string(issue); }, asset.value()); } bool @@ -58,8 +55,7 @@ Asset assetFromJson(Json::Value const& v) { if (!v.isMember(jss::currency) && !v.isMember(jss::mpt_issuance_id)) - Throw( - "assetFromJson must contain currency or mpt_issuance_id"); + Throw("assetFromJson must contain currency or mpt_issuance_id"); if (v.isMember(jss::currency)) return issueFromJson(v); diff --git a/src/libxrpl/protocol/Book.cpp b/src/libxrpl/protocol/Book.cpp index d26aaf3384..59ad739c11 100644 --- a/src/libxrpl/protocol/Book.cpp +++ b/src/libxrpl/protocol/Book.cpp @@ -9,8 +9,7 @@ namespace xrpl { bool isConsistent(Book const& book) { - return isConsistent(book.in) && isConsistent(book.out) && - book.in != book.out; + return isConsistent(book.in) && isConsistent(book.out) && book.in != book.out; } std::string diff --git a/src/libxrpl/protocol/BuildInfo.cpp b/src/libxrpl/protocol/BuildInfo.cpp index b5e2354165..c86ef17449 100644 --- a/src/libxrpl/protocol/BuildInfo.cpp +++ b/src/libxrpl/protocol/BuildInfo.cpp @@ -67,10 +67,8 @@ getFullVersionString() return value; } -static constexpr std::uint64_t implementationVersionIdentifier = - 0x183B'0000'0000'0000LLU; -static constexpr std::uint64_t implementationVersionIdentifierMask = - 0xFFFF'0000'0000'0000LLU; +static constexpr std::uint64_t implementationVersionIdentifier = 0x183B'0000'0000'0000LLU; +static constexpr std::uint64_t implementationVersionIdentifierMask = 0xFFFF'0000'0000'0000LLU; std::uint64_t encodeSoftwareVersion(char const* const versionStr) @@ -109,9 +107,7 @@ encodeSoftwareVersion(char const* const versionStr) if (prefix != identifier.substr(0, prefix.length())) return 0; - if (!beast::lexicalCastChecked( - ret, - std::string(identifier.substr(prefix.length())))) + if (!beast::lexicalCastChecked(ret, std::string(identifier.substr(prefix.length())))) return 0; if (std::clamp(ret, lok, hik) != ret) @@ -147,8 +143,7 @@ getEncodedVersion() bool isRippledVersion(std::uint64_t version) { - return (version & implementationVersionIdentifierMask) == - implementationVersionIdentifier; + return (version & implementationVersionIdentifierMask) == implementationVersionIdentifier; } bool diff --git a/src/libxrpl/protocol/ErrorCodes.cpp b/src/libxrpl/protocol/ErrorCodes.cpp index d78ff594e1..33ec869db6 100644 --- a/src/libxrpl/protocol/ErrorCodes.cpp +++ b/src/libxrpl/protocol/ErrorCodes.cpp @@ -221,9 +221,7 @@ error_code_http_status(error_code_i code) std::string rpcErrorString(Json::Value const& jv) { - XRPL_ASSERT( - RPC::contains_error(jv), - "xrpl::RPC::rpcErrorString : input contains an error"); + XRPL_ASSERT(RPC::contains_error(jv), "xrpl::RPC::rpcErrorString : input contains an error"); return jv[jss::error].asString() + jv[jss::error_message].asString(); } diff --git a/src/libxrpl/protocol/Feature.cpp b/src/libxrpl/protocol/Feature.cpp index dc4fd105b5..834341f8d6 100644 --- a/src/libxrpl/protocol/Feature.cpp +++ b/src/libxrpl/protocol/Feature.cpp @@ -70,8 +70,7 @@ class FeatureCollections uint256 feature; Feature() = delete; - explicit Feature(std::string const& name_, uint256 const& feature_) - : name(name_), feature(feature_) + explicit Feature(std::string const& name_, uint256 const& feature_) : name(name_), feature(feature_) { } @@ -91,21 +90,18 @@ class FeatureCollections // Intermediate types to help with readability template - using feature_hashed_unique = boost::multi_index::hashed_unique< - boost::multi_index::tag, - boost::multi_index::member>; + using feature_hashed_unique = boost::multi_index:: + hashed_unique, boost::multi_index::member>; // Intermediate types to help with readability using feature_indexing = boost::multi_index::indexed_by< - boost::multi_index::random_access< - boost::multi_index::tag>, + boost::multi_index::random_access>, feature_hashed_unique, feature_hashed_unique>; // This multi_index_container provides access to the features collection by // name, index, and uint256 feature identifier - boost::multi_index::multi_index_container - features; + boost::multi_index::multi_index_container features; std::map all; std::map supported; std::size_t upVotes = 0; @@ -152,10 +148,7 @@ public: getRegisteredFeature(std::string const& name) const; uint256 - registerFeature( - std::string const& name, - Supported support, - VoteBehavior vote); + registerFeature(std::string const& name, Supported support, VoteBehavior vote); /** Tell FeatureCollections when registration is complete. */ bool @@ -211,9 +204,7 @@ FeatureCollections::FeatureCollections() std::optional FeatureCollections::getRegisteredFeature(std::string const& name) const { - XRPL_ASSERT( - readOnly.load(), - "xrpl::FeatureCollections::getRegisteredFeature : startup completed"); + XRPL_ASSERT(readOnly.load(), "xrpl::FeatureCollections::getRegisteredFeature : startup completed"); Feature const* feature = getByName(name); if (feature) return feature->feature; @@ -228,10 +219,7 @@ check(bool condition, char const* logicErrorMessage) } uint256 -FeatureCollections::registerFeature( - std::string const& name, - Supported support, - VoteBehavior vote) +FeatureCollections::registerFeature(std::string const& name, Supported support, VoteBehavior vote) { check(!readOnly, "Attempting to register a feature after startup."); check( @@ -240,9 +228,7 @@ FeatureCollections::registerFeature( Feature const* i = getByName(name); if (!i) { - check( - features.size() < detail::numFeatures, - "More features defined than allocated."); + check(features.size() < detail::numFeatures, "More features defined than allocated."); auto const f = sha512Half(Slice(name.data(), name.size())); @@ -251,8 +237,7 @@ FeatureCollections::registerFeature( auto const getAmendmentSupport = [=]() { if (vote == VoteBehavior::Obsolete) return AmendmentSupport::Retired; - return support == Supported::yes ? AmendmentSupport::Supported - : AmendmentSupport::Unsupported; + return support == Supported::yes ? AmendmentSupport::Supported : AmendmentSupport::Unsupported; }; all.emplace(name, getAmendmentSupport()); @@ -265,15 +250,9 @@ FeatureCollections::registerFeature( else ++downVotes; } - check( - upVotes + downVotes == supported.size(), - "Feature counting logic broke"); - check( - supported.size() <= features.size(), - "More supported features than defined features"); - check( - features.size() == all.size(), - "The 'all' features list is populated incorrectly"); + check(upVotes + downVotes == supported.size(), "Feature counting logic broke"); + check(supported.size() <= features.size(), "More supported features than defined features"); + check(features.size() == all.size(), "The 'all' features list is populated incorrectly"); return f; } else @@ -292,9 +271,7 @@ FeatureCollections::registrationIsDone() size_t FeatureCollections::featureToBitsetIndex(uint256 const& f) const { - XRPL_ASSERT( - readOnly.load(), - "xrpl::FeatureCollections::featureToBitsetIndex : startup completed"); + XRPL_ASSERT(readOnly.load(), "xrpl::FeatureCollections::featureToBitsetIndex : startup completed"); Feature const* feature = getByFeature(f); if (!feature) @@ -306,9 +283,7 @@ FeatureCollections::featureToBitsetIndex(uint256 const& f) const uint256 const& FeatureCollections::bitsetIndexToFeature(size_t i) const { - XRPL_ASSERT( - readOnly.load(), - "xrpl::FeatureCollections::bitsetIndexToFeature : startup completed"); + XRPL_ASSERT(readOnly.load(), "xrpl::FeatureCollections::bitsetIndexToFeature : startup completed"); Feature const& feature = getByIndex(i); return feature.feature; } @@ -316,9 +291,7 @@ FeatureCollections::bitsetIndexToFeature(size_t i) const std::string FeatureCollections::featureToName(uint256 const& f) const { - XRPL_ASSERT( - readOnly.load(), - "xrpl::FeatureCollections::featureToName : startup completed"); + XRPL_ASSERT(readOnly.load(), "xrpl::FeatureCollections::featureToName : startup completed"); Feature const* feature = getByFeature(f); return feature ? feature->name : to_string(f); } @@ -416,10 +389,8 @@ featureToName(uint256 const& f) #pragma push_macro("XRPL_RETIRE_FIX") #undef XRPL_RETIRE_FIX -#define XRPL_FEATURE(name, supported, vote) \ - uint256 const feature##name = registerFeature(#name, supported, vote); -#define XRPL_FIX(name, supported, vote) \ - uint256 const fix##name = registerFeature("fix" #name, supported, vote); +#define XRPL_FEATURE(name, supported, vote) uint256 const feature##name = registerFeature(#name, supported, vote); +#define XRPL_FIX(name, supported, vote) uint256 const fix##name = registerFeature("fix" #name, supported, vote); // clang-format off #define XRPL_RETIRE_FEATURE(name) \ @@ -449,7 +420,6 @@ featureToName(uint256 const& f) // // Use initialization of one final static variable to set // featureCollections::readOnly. -[[maybe_unused]] static bool const readOnlySet = - featureCollections.registrationIsDone(); +[[maybe_unused]] static bool const readOnlySet = featureCollections.registrationIsDone(); } // namespace xrpl diff --git a/src/libxrpl/protocol/IOUAmount.cpp b/src/libxrpl/protocol/IOUAmount.cpp index 297c2bac12..cfad753edc 100644 --- a/src/libxrpl/protocol/IOUAmount.cpp +++ b/src/libxrpl/protocol/IOUAmount.cpp @@ -57,8 +57,7 @@ IOUAmount::fromNumber(Number const& number) // Need to create a default IOUAmount and assign directly so it doesn't try // to normalize, which calls fromNumber IOUAmount result{}; - std::tie(result.mantissa_, result.exponent_) = - number.normalizeToRange(minMantissa, maxMantissa); + std::tie(result.mantissa_, result.exponent_) = number.normalizeToRange(minMantissa, maxMantissa); return result; } @@ -182,11 +181,7 @@ to_string(IOUAmount const& amount) } IOUAmount -mulRatio( - IOUAmount const& amt, - std::uint32_t num, - std::uint32_t den, - bool roundUp) +mulRatio(IOUAmount const& amt, std::uint32_t num, std::uint32_t den, bool roundUp) { using namespace boost::multiprecision; @@ -213,8 +208,7 @@ mulRatio( static auto log10Floor = [](uint128_t const& v) { // Find the index of the first element >= the requested element, the // index is the log of the element in the log table. - auto const l = - std::lower_bound(powerTable.begin(), powerTable.end(), v); + auto const l = std::lower_bound(powerTable.begin(), powerTable.end(), v); int index = std::distance(powerTable.begin(), l); // If we're not equal, subtract to get the floor if (*l != v) @@ -226,20 +220,17 @@ mulRatio( static auto log10Ceil = [](uint128_t const& v) { // Find the index of the first element >= the requested element, the // index is the log of the element in the log table. - auto const l = - std::lower_bound(powerTable.begin(), powerTable.end(), v); + auto const l = std::lower_bound(powerTable.begin(), powerTable.end(), v); return int(std::distance(powerTable.begin(), l)); }; - static auto const fl64 = - log10Floor(std::numeric_limits::max()); + static auto const fl64 = log10Floor(std::numeric_limits::max()); bool const neg = amt.mantissa() < 0; uint128_t const den128(den); // a 32 value * a 64 bit value and stored in a 128 bit value. This will // never overflow - uint128_t const mul = - uint128_t(neg ? -amt.mantissa() : amt.mantissa()) * uint128_t(num); + uint128_t const mul = uint128_t(neg ? -amt.mantissa() : amt.mantissa()) * uint128_t(num); auto low = mul / den128; uint128_t rem(mul - low * den128); diff --git a/src/libxrpl/protocol/Indexes.cpp b/src/libxrpl/protocol/Indexes.cpp index 0bdfeefc4d..33c836eab6 100644 --- a/src/libxrpl/protocol/Indexes.cpp +++ b/src/libxrpl/protocol/Indexes.cpp @@ -99,19 +99,15 @@ getBookBase(Book const& book) { XRPL_ASSERT(isConsistent(book), "xrpl::getBookBase : input is consistent"); - auto const index = book.domain ? indexHash( - LedgerNameSpace::BOOK_DIR, - book.in.currency, - book.out.currency, - book.in.account, - book.out.account, - *(book.domain)) - : indexHash( - LedgerNameSpace::BOOK_DIR, - book.in.currency, - book.out.currency, - book.in.account, - book.out.account); + auto const index = book.domain + ? indexHash( + LedgerNameSpace::BOOK_DIR, + book.in.currency, + book.out.currency, + book.in.account, + book.out.account, + *(book.domain)) + : indexHash(LedgerNameSpace::BOOK_DIR, book.in.currency, book.out.currency, book.in.account, book.out.account); // Return with quality 0. auto k = keylet::quality({ltDIR_NODE, index}, 0); @@ -122,8 +118,7 @@ getBookBase(Book const& book) uint256 getQualityNext(uint256 const& uBase) { - static constexpr uint256 nextQuality( - "0000000000000000000000000000000000000000000000010000000000000000"); + static constexpr uint256 nextQuality("0000000000000000000000000000000000000000000000010000000000000000"); return uBase + nextQuality; } @@ -137,8 +132,7 @@ getQuality(uint256 const& uBase) uint256 getTicketIndex(AccountID const& account, std::uint32_t ticketSeq) { - return indexHash( - LedgerNameSpace::TICKET, account, std::uint32_t(ticketSeq)); + return indexHash(LedgerNameSpace::TICKET, account, std::uint32_t(ticketSeq)); } uint256 @@ -177,8 +171,7 @@ child(uint256 const& key) noexcept Keylet const& skip() noexcept { - static Keylet const ret{ - ltLEDGER_HASHES, indexHash(LedgerNameSpace::SKIP_LIST)}; + static Keylet const ret{ltLEDGER_HASHES, indexHash(LedgerNameSpace::SKIP_LIST)}; return ret; } @@ -187,32 +180,27 @@ skip(LedgerIndex ledger) noexcept { return { ltLEDGER_HASHES, - indexHash( - LedgerNameSpace::SKIP_LIST, - std::uint32_t(static_cast(ledger) >> 16))}; + indexHash(LedgerNameSpace::SKIP_LIST, std::uint32_t(static_cast(ledger) >> 16))}; } Keylet const& amendments() noexcept { - static Keylet const ret{ - ltAMENDMENTS, indexHash(LedgerNameSpace::AMENDMENTS)}; + static Keylet const ret{ltAMENDMENTS, indexHash(LedgerNameSpace::AMENDMENTS)}; return ret; } Keylet const& fees() noexcept { - static Keylet const ret{ - ltFEE_SETTINGS, indexHash(LedgerNameSpace::FEE_SETTINGS)}; + static Keylet const ret{ltFEE_SETTINGS, indexHash(LedgerNameSpace::FEE_SETTINGS)}; return ret; } Keylet const& negativeUNL() noexcept { - static Keylet const ret{ - ltNEGATIVE_UNL, indexHash(LedgerNameSpace::NEGATIVE_UNL)}; + static Keylet const ret{ltNEGATIVE_UNL, indexHash(LedgerNameSpace::NEGATIVE_UNL)}; return ret; } @@ -223,10 +211,7 @@ book_t::operator()(Book const& b) const } Keylet -line( - AccountID const& id0, - AccountID const& id1, - Currency const& currency) noexcept +line(AccountID const& id0, AccountID const& id1, Currency const& currency) noexcept { // There is code in SetTrust that calls us with id0 == id1, to allow users // to locate and delete such "weird" trustlines. If we remove that code, we @@ -243,13 +228,7 @@ line( // two accounts (smallest then largest) and hash them in that order: auto const accounts = std::minmax(id0, id1); - return { - ltRIPPLE_STATE, - indexHash( - LedgerNameSpace::TRUST_LINE, - accounts.first, - accounts.second, - currency)}; + return {ltRIPPLE_STATE, indexHash(LedgerNameSpace::TRUST_LINE, accounts.first, accounts.second, currency)}; } Keylet @@ -261,8 +240,7 @@ offer(AccountID const& id, std::uint32_t seq) noexcept Keylet quality(Keylet const& k, std::uint64_t q) noexcept { - XRPL_ASSERT( - k.type == ltDIR_NODE, "xrpl::keylet::quality : valid input type"); + XRPL_ASSERT(k.type == ltDIR_NODE, "xrpl::keylet::quality : valid input type"); // Indexes are stored in big endian format: they print as hex as stored. // Most significant bytes are first and the least significant bytes @@ -280,9 +258,7 @@ quality(Keylet const& k, std::uint64_t q) noexcept Keylet next_t::operator()(Keylet const& k) const { - XRPL_ASSERT( - k.type == ltDIR_NODE, - "xrpl::keylet::next_t::operator() : valid input type"); + XRPL_ASSERT(k.type == ltDIR_NODE, "xrpl::keylet::next_t::operator() : valid input type"); return {ltDIR_NODE, getQualityNext(k.key)}; } @@ -304,8 +280,7 @@ ticket_t::operator()(AccountID const& id, SeqProxy ticketSeq) const static Keylet signers(AccountID const& account, std::uint32_t page) noexcept { - return { - ltSIGNER_LIST, indexHash(LedgerNameSpace::SIGNER_LIST, account, page)}; + return {ltSIGNER_LIST, indexHash(LedgerNameSpace::SIGNER_LIST, account, page)}; } Keylet @@ -323,25 +298,19 @@ check(AccountID const& id, std::uint32_t seq) noexcept Keylet depositPreauth(AccountID const& owner, AccountID const& preauthorized) noexcept { - return { - ltDEPOSIT_PREAUTH, - indexHash(LedgerNameSpace::DEPOSIT_PREAUTH, owner, preauthorized)}; + return {ltDEPOSIT_PREAUTH, indexHash(LedgerNameSpace::DEPOSIT_PREAUTH, owner, preauthorized)}; } // Credentials should be sorted here, use credentials::makeSorted Keylet -depositPreauth( - AccountID const& owner, - std::set> const& authCreds) noexcept +depositPreauth(AccountID const& owner, std::set> const& authCreds) noexcept { std::vector hashes; hashes.reserve(authCreds.size()); for (auto const& o : authCreds) hashes.emplace_back(sha512Half(o.first, o.second)); - return { - ltDEPOSIT_PREAUTH, - indexHash(LedgerNameSpace::DEPOSIT_PREAUTH_CREDENTIALS, owner, hashes)}; + return {ltDEPOSIT_PREAUTH, indexHash(LedgerNameSpace::DEPOSIT_PREAUTH_CREDENTIALS, owner, hashes)}; } //------------------------------------------------------------------------------ @@ -376,9 +345,7 @@ escrow(AccountID const& src, std::uint32_t seq) noexcept Keylet payChan(AccountID const& src, AccountID const& dst, std::uint32_t seq) noexcept { - return { - ltPAYCHAN, - indexHash(LedgerNameSpace::XRP_PAYMENT_CHANNEL, src, dst, seq)}; + return {ltPAYCHAN, indexHash(LedgerNameSpace::XRP_PAYMENT_CHANNEL, src, dst, seq)}; } Keylet @@ -400,16 +367,14 @@ nftpage_max(AccountID const& owner) Keylet nftpage(Keylet const& k, uint256 const& token) { - XRPL_ASSERT( - k.type == ltNFTOKEN_PAGE, "xrpl::keylet::nftpage : valid input type"); + XRPL_ASSERT(k.type == ltNFTOKEN_PAGE, "xrpl::keylet::nftpage : valid input type"); return {ltNFTOKEN_PAGE, (k.key & ~nft::pageMask) + (token & nft::pageMask)}; } Keylet nftoffer(AccountID const& owner, std::uint32_t seq) { - return { - ltNFTOKEN_OFFER, indexHash(LedgerNameSpace::NFTOKEN_OFFER, owner, seq)}; + return {ltNFTOKEN_OFFER, indexHash(LedgerNameSpace::NFTOKEN_OFFER, owner, seq)}; } Keylet @@ -427,14 +392,8 @@ nft_sells(uint256 const& id) noexcept Keylet amm(Asset const& issue1, Asset const& issue2) noexcept { - auto const& [minI, maxI] = - std::minmax(issue1.get(), issue2.get()); - return amm(indexHash( - LedgerNameSpace::AMM, - minI.account, - minI.currency, - maxI.account, - maxI.currency)); + auto const& [minI, maxI] = std::minmax(issue1.get(), issue2.get()); + return amm(indexHash(LedgerNameSpace::AMM, minI.account, minI.currency, maxI.account, maxI.currency)); } Keylet @@ -446,9 +405,7 @@ amm(uint256 const& id) noexcept Keylet delegate(AccountID const& account, AccountID const& authorizedAccount) noexcept { - return { - ltDELEGATE, - indexHash(LedgerNameSpace::DELEGATE, account, authorizedAccount)}; + return {ltDELEGATE, indexHash(LedgerNameSpace::DELEGATE, account, authorizedAccount)}; } Keylet @@ -458,10 +415,7 @@ bridge(STXChainBridge const& bridge, STXChainBridge::ChainType chainType) // there can only be one bridge per lockingChainCurrency. On the issuing // chain there can only be one bridge per issuingChainCurrency. auto const& issue = bridge.issue(chainType); - return { - ltBRIDGE, - indexHash( - LedgerNameSpace::BRIDGE, bridge.door(chainType), issue.currency)}; + return {ltBRIDGE, indexHash(LedgerNameSpace::BRIDGE, bridge.door(chainType), issue.currency)}; } Keylet @@ -513,9 +467,7 @@ mptIssuance(std::uint32_t seq, AccountID const& issuer) noexcept Keylet mptIssuance(MPTID const& issuanceID) noexcept { - return { - ltMPTOKEN_ISSUANCE, - indexHash(LedgerNameSpace::MPTOKEN_ISSUANCE, issuanceID)}; + return {ltMPTOKEN_ISSUANCE, indexHash(LedgerNameSpace::MPTOKEN_ISSUANCE, issuanceID)}; } Keylet @@ -527,19 +479,13 @@ mptoken(MPTID const& issuanceID, AccountID const& holder) noexcept Keylet mptoken(uint256 const& issuanceKey, AccountID const& holder) noexcept { - return { - ltMPTOKEN, indexHash(LedgerNameSpace::MPTOKEN, issuanceKey, holder)}; + return {ltMPTOKEN, indexHash(LedgerNameSpace::MPTOKEN, issuanceKey, holder)}; } Keylet -credential( - AccountID const& subject, - AccountID const& issuer, - Slice const& credType) noexcept +credential(AccountID const& subject, AccountID const& issuer, Slice const& credType) noexcept { - return { - ltCREDENTIAL, - indexHash(LedgerNameSpace::CREDENTIAL, subject, issuer, credType)}; + return {ltCREDENTIAL, indexHash(LedgerNameSpace::CREDENTIAL, subject, issuer, credType)}; } Keylet @@ -563,9 +509,7 @@ loan(uint256 const& loanBrokerID, std::uint32_t loanSeq) noexcept Keylet permissionedDomain(AccountID const& account, std::uint32_t seq) noexcept { - return { - ltPERMISSIONED_DOMAIN, - indexHash(LedgerNameSpace::PERMISSIONED_DOMAIN, account, seq)}; + return {ltPERMISSIONED_DOMAIN, indexHash(LedgerNameSpace::PERMISSIONED_DOMAIN, account, seq)}; } Keylet diff --git a/src/libxrpl/protocol/InnerObjectFormats.cpp b/src/libxrpl/protocol/InnerObjectFormats.cpp index 3eb73e7c9b..8139ef0f55 100644 --- a/src/libxrpl/protocol/InnerObjectFormats.cpp +++ b/src/libxrpl/protocol/InnerObjectFormats.cpp @@ -136,9 +136,7 @@ InnerObjectFormats::InnerObjectFormats() {sfCredentialType, soeREQUIRED}, }); - add(sfPermission.jsonName.c_str(), - sfPermission.getCode(), - {{sfPermissionValue, soeREQUIRED}}); + add(sfPermission.jsonName.c_str(), sfPermission.getCode(), {{sfPermissionValue, soeREQUIRED}}); add(sfBatchSigner.jsonName.c_str(), sfBatchSigner.getCode(), diff --git a/src/libxrpl/protocol/Issue.cpp b/src/libxrpl/protocol/Issue.cpp index ca5bf35e8b..f540b52050 100644 --- a/src/libxrpl/protocol/Issue.cpp +++ b/src/libxrpl/protocol/Issue.cpp @@ -83,14 +83,12 @@ issueFromJson(Json::Value const& v) { if (!v.isObject()) { - Throw( - "issueFromJson can only be specified with an 'object' Json value"); + Throw("issueFromJson can only be specified with an 'object' Json value"); } if (v.isMember(jss::mpt_issuance_id)) { - Throw( - "issueFromJson, Issue should not have mpt_issuance_id"); + Throw("issueFromJson, Issue should not have mpt_issuance_id"); } Json::Value const curStr = v[jss::currency]; @@ -98,8 +96,7 @@ issueFromJson(Json::Value const& v) if (!curStr.isString()) { - Throw( - "issueFromJson currency must be a string Json value"); + Throw("issueFromJson currency must be a string Json value"); } auto const currency = to_currency(curStr.asString()); diff --git a/src/libxrpl/protocol/Keylet.cpp b/src/libxrpl/protocol/Keylet.cpp index 2c65bb9ed4..18bd76440a 100644 --- a/src/libxrpl/protocol/Keylet.cpp +++ b/src/libxrpl/protocol/Keylet.cpp @@ -8,9 +8,7 @@ namespace xrpl { bool Keylet::check(STLedgerEntry const& sle) const { - XRPL_ASSERT( - sle.getType() != ltANY || sle.getType() != ltCHILD, - "xrpl::Keylet::check : valid input type"); + XRPL_ASSERT(sle.getType() != ltANY || sle.getType() != ltCHILD, "xrpl::Keylet::check : valid input type"); if (type == ltANY) return true; diff --git a/src/libxrpl/protocol/LedgerFormats.cpp b/src/libxrpl/protocol/LedgerFormats.cpp index 2056cfab7b..8d9a24f741 100644 --- a/src/libxrpl/protocol/LedgerFormats.cpp +++ b/src/libxrpl/protocol/LedgerFormats.cpp @@ -22,8 +22,7 @@ LedgerFormats::LedgerFormats() #undef LEDGER_ENTRY #define UNWRAP(...) __VA_ARGS__ -#define LEDGER_ENTRY(tag, value, name, rpcName, fields) \ - add(jss::name, tag, UNWRAP fields, commonFields); +#define LEDGER_ENTRY(tag, value, name, rpcName, fields) add(jss::name, tag, UNWRAP fields, commonFields); #include diff --git a/src/libxrpl/protocol/LedgerHeader.cpp b/src/libxrpl/protocol/LedgerHeader.cpp index 5258bdbc22..270833c6fa 100644 --- a/src/libxrpl/protocol/LedgerHeader.cpp +++ b/src/libxrpl/protocol/LedgerHeader.cpp @@ -34,8 +34,7 @@ deserializeHeader(Slice data, bool hasHash) header.parentHash = sit.get256(); header.txHash = sit.get256(); header.accountHash = sit.get256(); - header.parentCloseTime = - NetClock::time_point{NetClock::duration{sit.get32()}}; + header.parentCloseTime = NetClock::time_point{NetClock::duration{sit.get32()}}; header.closeTime = NetClock::time_point{NetClock::duration{sit.get32()}}; header.closeTimeResolution = NetClock::duration{sit.get8()}; header.closeFlags = sit.get8(); diff --git a/src/libxrpl/protocol/MPTIssue.cpp b/src/libxrpl/protocol/MPTIssue.cpp index c92ac60b73..9673d6071f 100644 --- a/src/libxrpl/protocol/MPTIssue.cpp +++ b/src/libxrpl/protocol/MPTIssue.cpp @@ -23,8 +23,7 @@ MPTIssue::getIssuer() const // MPTID is concatenation of sequence + account static_assert(sizeof(MPTID) == (sizeof(std::uint32_t) + sizeof(AccountID))); // copy from id skipping the sequence - AccountID const* account = reinterpret_cast( - mptID_.data() + sizeof(std::uint32_t)); + AccountID const* account = reinterpret_cast(mptID_.data() + sizeof(std::uint32_t)); return *account; } @@ -67,16 +66,14 @@ mptIssueFromJson(Json::Value const& v) if (v.isMember(jss::currency) || v.isMember(jss::issuer)) { - Throw( - "mptIssueFromJson, MPTIssue should not have currency or issuer"); + Throw("mptIssueFromJson, MPTIssue should not have currency or issuer"); } Json::Value const& idStr = v[jss::mpt_issuance_id]; if (!idStr.isString()) { - Throw( - "mptIssueFromJson MPTID must be a string Json value"); + Throw("mptIssueFromJson MPTID must be a string Json value"); } MPTID id; diff --git a/src/libxrpl/protocol/NFTokenID.cpp b/src/libxrpl/protocol/NFTokenID.cpp index 64fadce3c9..deed26360a 100644 --- a/src/libxrpl/protocol/NFTokenID.cpp +++ b/src/libxrpl/protocol/NFTokenID.cpp @@ -20,16 +20,13 @@ namespace xrpl { bool -canHaveNFTokenID( - std::shared_ptr const& serializedTx, - TxMeta const& transactionMeta) +canHaveNFTokenID(std::shared_ptr const& serializedTx, TxMeta const& transactionMeta) { if (!serializedTx) return false; TxType const tt = serializedTx->getTxnType(); - if (tt != ttNFTOKEN_MINT && tt != ttNFTOKEN_ACCEPT_OFFER && - tt != ttNFTOKEN_CANCEL_OFFER) + if (tt != ttNFTOKEN_MINT && tt != ttNFTOKEN_ACCEPT_OFFER && tt != ttNFTOKEN_CANCEL_OFFER) return false; // if the transaction failed nothing could have been delivered. @@ -56,14 +53,9 @@ getNFTokenIDFromPage(TxMeta const& transactionMeta) SField const& fName = node.getFName(); if (fName == sfCreatedNode) { - STArray const& toAddPrevNFTs = node.peekAtField(sfNewFields) - .downcast() - .getFieldArray(sfNFTokens); + STArray const& toAddPrevNFTs = node.peekAtField(sfNewFields).downcast().getFieldArray(sfNFTokens); std::transform( - toAddPrevNFTs.begin(), - toAddPrevNFTs.end(), - std::back_inserter(finalIDs), - [](STObject const& nft) { + toAddPrevNFTs.begin(), toAddPrevNFTs.end(), std::back_inserter(finalIDs), [](STObject const& nft) { return nft.getFieldH256(sfNFTokenID); }); } @@ -78,29 +70,20 @@ getNFTokenIDFromPage(TxMeta const& transactionMeta) // However, there will always be NFTs listed in the final fields, // as rippled outputs all fields in final fields even if they were // not changed. - STObject const& previousFields = - node.peekAtField(sfPreviousFields).downcast(); + STObject const& previousFields = node.peekAtField(sfPreviousFields).downcast(); if (!previousFields.isFieldPresent(sfNFTokens)) continue; - STArray const& toAddPrevNFTs = - previousFields.getFieldArray(sfNFTokens); + STArray const& toAddPrevNFTs = previousFields.getFieldArray(sfNFTokens); std::transform( - toAddPrevNFTs.begin(), - toAddPrevNFTs.end(), - std::back_inserter(prevIDs), - [](STObject const& nft) { + toAddPrevNFTs.begin(), toAddPrevNFTs.end(), std::back_inserter(prevIDs), [](STObject const& nft) { return nft.getFieldH256(sfNFTokenID); }); - STArray const& toAddFinalNFTs = node.peekAtField(sfFinalFields) - .downcast() - .getFieldArray(sfNFTokens); + STArray const& toAddFinalNFTs = + node.peekAtField(sfFinalFields).downcast().getFieldArray(sfNFTokens); std::transform( - toAddFinalNFTs.begin(), - toAddFinalNFTs.end(), - std::back_inserter(finalIDs), - [](STObject const& nft) { + toAddFinalNFTs.begin(), toAddFinalNFTs.end(), std::back_inserter(finalIDs), [](STObject const& nft) { return nft.getFieldH256(sfNFTokenID); }); } @@ -113,8 +96,7 @@ getNFTokenIDFromPage(TxMeta const& transactionMeta) // Find the first NFT ID that doesn't match. We're looking for an // added NFT, so the one we want will be the mismatch in finalIDs. - auto const diff = std::mismatch( - finalIDs.begin(), finalIDs.end(), prevIDs.begin(), prevIDs.end()); + auto const diff = std::mismatch(finalIDs.begin(), finalIDs.end(), prevIDs.begin(), prevIDs.end()); // There should always be a difference so the returned finalIDs // iterator should never be end(). But better safe than sorry. @@ -130,30 +112,22 @@ getNFTokenIDFromDeletedOffer(TxMeta const& transactionMeta) std::vector tokenIDResult; for (STObject const& node : transactionMeta.getNodes()) { - if (node.getFieldU16(sfLedgerEntryType) != ltNFTOKEN_OFFER || - node.getFName() != sfDeletedNode) + if (node.getFieldU16(sfLedgerEntryType) != ltNFTOKEN_OFFER || node.getFName() != sfDeletedNode) continue; - auto const& toAddNFT = node.peekAtField(sfFinalFields) - .downcast() - .getFieldH256(sfNFTokenID); + auto const& toAddNFT = node.peekAtField(sfFinalFields).downcast().getFieldH256(sfNFTokenID); tokenIDResult.push_back(toAddNFT); } // Deduplicate the NFT IDs because multiple offers could affect the same NFT // and hence we would get duplicate NFT IDs sort(tokenIDResult.begin(), tokenIDResult.end()); - tokenIDResult.erase( - unique(tokenIDResult.begin(), tokenIDResult.end()), - tokenIDResult.end()); + tokenIDResult.erase(unique(tokenIDResult.begin(), tokenIDResult.end()), tokenIDResult.end()); return tokenIDResult; } void -insertNFTokenID( - Json::Value& response, - std::shared_ptr const& transaction, - TxMeta const& transactionMeta) +insertNFTokenID(Json::Value& response, std::shared_ptr const& transaction, TxMeta const& transactionMeta) { if (!canHaveNFTokenID(transaction, transactionMeta)) return; @@ -167,16 +141,14 @@ insertNFTokenID( } else if (type == ttNFTOKEN_ACCEPT_OFFER) { - std::vector result = - getNFTokenIDFromDeletedOffer(transactionMeta); + std::vector result = getNFTokenIDFromDeletedOffer(transactionMeta); if (result.size() > 0) response[jss::nftoken_id] = to_string(result.front()); } else if (type == ttNFTOKEN_CANCEL_OFFER) { - std::vector result = - getNFTokenIDFromDeletedOffer(transactionMeta); + std::vector result = getNFTokenIDFromDeletedOffer(transactionMeta); response[jss::nftoken_ids] = Json::Value(Json::arrayValue); for (auto const& nftID : result) diff --git a/src/libxrpl/protocol/NFTokenOfferID.cpp b/src/libxrpl/protocol/NFTokenOfferID.cpp index b1a08081c0..bbd67d710c 100644 --- a/src/libxrpl/protocol/NFTokenOfferID.cpp +++ b/src/libxrpl/protocol/NFTokenOfferID.cpp @@ -16,16 +16,13 @@ namespace xrpl { bool -canHaveNFTokenOfferID( - std::shared_ptr const& serializedTx, - TxMeta const& transactionMeta) +canHaveNFTokenOfferID(std::shared_ptr const& serializedTx, TxMeta const& transactionMeta) { if (!serializedTx) return false; TxType const tt = serializedTx->getTxnType(); - if (!(tt == ttNFTOKEN_MINT && serializedTx->isFieldPresent(sfAmount)) && - tt != ttNFTOKEN_CREATE_OFFER) + if (!(tt == ttNFTOKEN_MINT && serializedTx->isFieldPresent(sfAmount)) && tt != ttNFTOKEN_CREATE_OFFER) return false; // if the transaction failed nothing could have been delivered. @@ -40,8 +37,7 @@ getOfferIDFromCreatedOffer(TxMeta const& transactionMeta) { for (STObject const& node : transactionMeta.getNodes()) { - if (node.getFieldU16(sfLedgerEntryType) != ltNFTOKEN_OFFER || - node.getFName() != sfCreatedNode) + if (node.getFieldU16(sfLedgerEntryType) != ltNFTOKEN_OFFER || node.getFName() != sfCreatedNode) continue; return node.getFieldH256(sfLedgerIndex); diff --git a/src/libxrpl/protocol/Permissions.cpp b/src/libxrpl/protocol/Permissions.cpp index 082a1792a4..7e592fdc7f 100644 --- a/src/libxrpl/protocol/Permissions.cpp +++ b/src/libxrpl/protocol/Permissions.cpp @@ -11,8 +11,7 @@ Permission::Permission() #pragma push_macro("TRANSACTION") #undef TRANSACTION -#define TRANSACTION(tag, value, name, delegable, amendment, ...) \ - {value, amendment}, +#define TRANSACTION(tag, value, name, delegable, amendment, ...) {value, amendment}, #include @@ -91,8 +90,7 @@ Permission::getPermissionName(std::uint32_t const value) const // not a granular permission, check if it maps to a transaction type auto const txType = permissionToTxType(value); - if (auto const* item = TxFormats::getInstance().findByType(txType); - item != nullptr) + if (auto const* item = TxFormats::getInstance().findByType(txType); item != nullptr) return item->getName(); return std::nullopt; @@ -132,9 +130,7 @@ std::optional> const Permission::getTxFeature(TxType txType) const { auto const txFeaturesIt = txFeatureMap_.find(txType); - XRPL_ASSERT( - txFeaturesIt != txFeatureMap_.end(), - "xrpl::Permissions::getTxFeature : tx exists in txFeatureMap_"); + XRPL_ASSERT(txFeaturesIt != txFeatureMap_.end(), "xrpl::Permissions::getTxFeature : tx exists in txFeatureMap_"); if (txFeaturesIt->second == uint256{}) return std::nullopt; @@ -142,12 +138,9 @@ Permission::getTxFeature(TxType txType) const } bool -Permission::isDelegable( - std::uint32_t const& permissionValue, - Rules const& rules) const +Permission::isDelegable(std::uint32_t const& permissionValue, Rules const& rules) const { - auto const granularPermission = - getGranularName(static_cast(permissionValue)); + auto const granularPermission = getGranularName(static_cast(permissionValue)); if (granularPermission) // granular permissions are always allowed to be delegated return true; @@ -159,15 +152,12 @@ Permission::isDelegable( return false; auto const txFeaturesIt = txFeatureMap_.find(txType); - XRPL_ASSERT( - txFeaturesIt != txFeatureMap_.end(), - "xrpl::Permissions::isDelegable : tx exists in txFeatureMap_"); + XRPL_ASSERT(txFeaturesIt != txFeatureMap_.end(), "xrpl::Permissions::isDelegable : tx exists in txFeatureMap_"); // Delegation is only allowed if the required amendment for the transaction // is enabled. For transactions that do not require an amendment, delegation // is always allowed. - if (txFeaturesIt->second != uint256{} && - !rules.enabled(txFeaturesIt->second)) + if (txFeaturesIt->second != uint256{} && !rules.enabled(txFeaturesIt->second)) return false; if (it->second == Delegation::notDelegable) diff --git a/src/libxrpl/protocol/PublicKey.cpp b/src/libxrpl/protocol/PublicKey.cpp index 2dcf484adc..b336b2d4b5 100644 --- a/src/libxrpl/protocol/PublicKey.cpp +++ b/src/libxrpl/protocol/PublicKey.cpp @@ -109,16 +109,11 @@ sliceToHex(Slice const& slice) std::optional ecdsaCanonicality(Slice const& sig) { - using uint264 = - boost::multiprecision::number>; + using uint264 = boost::multiprecision::number< + boost::multiprecision:: + cpp_int_backend<264, 264, boost::multiprecision::signed_magnitude, boost::multiprecision::unchecked, void>>; - static uint264 const G( - "0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"); + static uint264 const G("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"); // The format of a signature should be: // <30> [ <02> ] [ <02> ] @@ -155,9 +150,8 @@ ed25519Canonical(Slice const& sig) return false; // Big-endian Order, the Ed25519 subgroup order std::uint8_t const Order[] = { - 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x14, 0xDE, 0xF9, 0xDE, 0xA2, 0xF7, - 0x9C, 0xD6, 0x58, 0x12, 0x63, 0x1A, 0x5C, 0xF5, 0xD3, 0xED, + 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x14, 0xDE, 0xF9, 0xDE, 0xA2, 0xF7, 0x9C, 0xD6, 0x58, 0x12, 0x63, 0x1A, 0x5C, 0xF5, 0xD3, 0xED, }; // Take the second half of signature // and byte-reverse it to big-endian. @@ -216,19 +210,14 @@ publicKeyType(Slice const& slice) } bool -verifyDigest( - PublicKey const& publicKey, - uint256 const& digest, - Slice const& sig, - bool mustBeFullyCanonical) noexcept +verifyDigest(PublicKey const& publicKey, uint256 const& digest, Slice const& sig, bool mustBeFullyCanonical) noexcept { if (publicKeyType(publicKey) != KeyType::secp256k1) LogicError("sign: secp256k1 required for digest signing"); auto const canonicality = ecdsaCanonicality(sig); if (!canonicality) return false; - if (mustBeFullyCanonical && - (*canonicality != ECDSACanonicality::fullyCanonical)) + if (mustBeFullyCanonical && (*canonicality != ECDSACanonicality::fullyCanonical)) return false; secp256k1_pubkey pubkey_imp; @@ -241,28 +230,19 @@ verifyDigest( secp256k1_ecdsa_signature sig_imp; if (secp256k1_ecdsa_signature_parse_der( - secp256k1Context(), - &sig_imp, - reinterpret_cast(sig.data()), - sig.size()) != 1) + secp256k1Context(), &sig_imp, reinterpret_cast(sig.data()), sig.size()) != 1) return false; if (*canonicality != ECDSACanonicality::fullyCanonical) { secp256k1_ecdsa_signature sig_norm; - if (secp256k1_ecdsa_signature_normalize( - secp256k1Context(), &sig_norm, &sig_imp) != 1) + if (secp256k1_ecdsa_signature_normalize(secp256k1Context(), &sig_norm, &sig_imp) != 1) return false; return secp256k1_ecdsa_verify( - secp256k1Context(), - &sig_norm, - reinterpret_cast(digest.data()), - &pubkey_imp) == 1; + secp256k1Context(), &sig_norm, reinterpret_cast(digest.data()), &pubkey_imp) == + 1; } return secp256k1_ecdsa_verify( - secp256k1Context(), - &sig_imp, - reinterpret_cast(digest.data()), - &pubkey_imp) == 1; + secp256k1Context(), &sig_imp, reinterpret_cast(digest.data()), &pubkey_imp) == 1; } bool @@ -283,9 +263,7 @@ verify(PublicKey const& publicKey, Slice const& m, Slice const& sig) noexcept // byte to distinguish them from secp256k1 keys // so when verifying the signature, we need to // first strip that prefix. - return ed25519_sign_open( - m.data(), m.size(), publicKey.data() + 1, sig.data()) == - 0; + return ed25519_sign_open(m.data(), m.size(), publicKey.data() + 1, sig.data()) == 0; } } return false; diff --git a/src/libxrpl/protocol/Quality.cpp b/src/libxrpl/protocol/Quality.cpp index cd56f237fc..fda0ac2e1e 100644 --- a/src/libxrpl/protocol/Quality.cpp +++ b/src/libxrpl/protocol/Quality.cpp @@ -13,8 +13,7 @@ Quality::Quality(std::uint64_t value) : m_value(value) { } -Quality::Quality(Amounts const& amount) - : m_value(getRate(amount.out, amount.in)) +Quality::Quality(Amounts const& amount) : m_value(getRate(amount.out, amount.in)) { } @@ -37,9 +36,7 @@ Quality::operator++(int) Quality& Quality::operator--() { - XRPL_ASSERT( - m_value < std::numeric_limits::max(), - "xrpl::Quality::operator--() : maximum value"); + XRPL_ASSERT(m_value < std::numeric_limits::max(), "xrpl::Quality::operator--() : maximum value"); ++m_value; return *this; } @@ -52,25 +49,17 @@ Quality::operator--(int) return prev; } -template +template static Amounts -ceil_in_impl( - Amounts const& amount, - STAmount const& limit, - bool roundUp, - Quality const& quality) +ceil_in_impl(Amounts const& amount, STAmount const& limit, bool roundUp, Quality const& quality) { if (amount.in > limit) { - Amounts result( - limit, - DivRoundFunc(limit, quality.rate(), amount.out.asset(), roundUp)); + Amounts result(limit, DivRoundFunc(limit, quality.rate(), amount.out.asset(), roundUp)); // Clamp out if (result.out > amount.out) result.out = amount.out; - XRPL_ASSERT( - result.in == limit, "xrpl::ceil_in_impl : result matches limit"); + XRPL_ASSERT(result.in == limit, "xrpl::ceil_in_impl : result matches limit"); return result; } XRPL_ASSERT(amount.in <= limit, "xrpl::ceil_in_impl : result inside limit"); @@ -84,37 +73,25 @@ Quality::ceil_in(Amounts const& amount, STAmount const& limit) const } Amounts -Quality::ceil_in_strict( - Amounts const& amount, - STAmount const& limit, - bool roundUp) const +Quality::ceil_in_strict(Amounts const& amount, STAmount const& limit, bool roundUp) const { return ceil_in_impl(amount, limit, roundUp, *this); } -template +template static Amounts -ceil_out_impl( - Amounts const& amount, - STAmount const& limit, - bool roundUp, - Quality const& quality) +ceil_out_impl(Amounts const& amount, STAmount const& limit, bool roundUp, Quality const& quality) { if (amount.out > limit) { - Amounts result( - MulRoundFunc(limit, quality.rate(), amount.in.asset(), roundUp), - limit); + Amounts result(MulRoundFunc(limit, quality.rate(), amount.in.asset(), roundUp), limit); // Clamp in if (result.in > amount.in) result.in = amount.in; - XRPL_ASSERT( - result.out == limit, "xrpl::ceil_out_impl : result matches limit"); + XRPL_ASSERT(result.out == limit, "xrpl::ceil_out_impl : result matches limit"); return result; } - XRPL_ASSERT( - amount.out <= limit, "xrpl::ceil_out_impl : result inside limit"); + XRPL_ASSERT(amount.out <= limit, "xrpl::ceil_out_impl : result inside limit"); return amount; } @@ -125,10 +102,7 @@ Quality::ceil_out(Amounts const& amount, STAmount const& limit) const } Amounts -Quality::ceil_out_strict( - Amounts const& amount, - STAmount const& limit, - bool roundUp) const +Quality::ceil_out_strict(Amounts const& amount, STAmount const& limit, bool roundUp) const { return ceil_out_impl(amount, limit, roundUp, *this); } @@ -137,22 +111,17 @@ Quality composed_quality(Quality const& lhs, Quality const& rhs) { STAmount const lhs_rate(lhs.rate()); - XRPL_ASSERT( - lhs_rate != beast::zero, "xrpl::composed_quality : nonzero left input"); + XRPL_ASSERT(lhs_rate != beast::zero, "xrpl::composed_quality : nonzero left input"); STAmount const rhs_rate(rhs.rate()); - XRPL_ASSERT( - rhs_rate != beast::zero, - "xrpl::composed_quality : nonzero right input"); + XRPL_ASSERT(rhs_rate != beast::zero, "xrpl::composed_quality : nonzero right input"); STAmount const rate(mulRound(lhs_rate, rhs_rate, lhs_rate.asset(), true)); std::uint64_t const stored_exponent(rate.exponent() + 100); std::uint64_t const stored_mantissa(rate.mantissa()); - XRPL_ASSERT( - (stored_exponent > 0) && (stored_exponent <= 255), - "xrpl::composed_quality : valid exponent"); + XRPL_ASSERT((stored_exponent > 0) && (stored_exponent <= 255), "xrpl::composed_quality : valid exponent"); return Quality((stored_exponent << (64 - 8)) | stored_mantissa); } diff --git a/src/libxrpl/protocol/QualityFunction.cpp b/src/libxrpl/protocol/QualityFunction.cpp index b254e1af86..db004bf478 100644 --- a/src/libxrpl/protocol/QualityFunction.cpp +++ b/src/libxrpl/protocol/QualityFunction.cpp @@ -9,10 +9,7 @@ namespace xrpl { -QualityFunction::QualityFunction( - Quality const& quality, - QualityFunction::CLOBLikeTag) - : m_(0), b_(0), quality_(quality) +QualityFunction::QualityFunction(Quality const& quality, QualityFunction::CLOBLikeTag) : m_(0), b_(0), quality_(quality) { if (quality.rate() <= beast::zero) Throw("QualityFunction quality rate is 0."); diff --git a/src/libxrpl/protocol/Rate2.cpp b/src/libxrpl/protocol/Rate2.cpp index 511b28cc67..490474fdb1 100644 --- a/src/libxrpl/protocol/Rate2.cpp +++ b/src/libxrpl/protocol/Rate2.cpp @@ -53,14 +53,9 @@ multiplyRound(STAmount const& amount, Rate const& rate, bool roundUp) } STAmount -multiplyRound( - STAmount const& amount, - Rate const& rate, - Asset const& asset, - bool roundUp) +multiplyRound(STAmount const& amount, Rate const& rate, Asset const& asset, bool roundUp) { - XRPL_ASSERT( - rate.value, "xrpl::nft::multiplyRound(Issue) : nonzero rate input"); + XRPL_ASSERT(rate.value, "xrpl::nft::multiplyRound(Issue) : nonzero rate input"); if (rate == parityRate) { @@ -93,14 +88,9 @@ divideRound(STAmount const& amount, Rate const& rate, bool roundUp) } STAmount -divideRound( - STAmount const& amount, - Rate const& rate, - Asset const& asset, - bool roundUp) +divideRound(STAmount const& amount, Rate const& rate, Asset const& asset, bool roundUp) { - XRPL_ASSERT( - rate.value, "xrpl::nft::divideRound(Issue) : nonzero rate input"); + XRPL_ASSERT(rate.value, "xrpl::nft::divideRound(Issue) : nonzero rate input"); if (rate == parityRate) return amount; diff --git a/src/libxrpl/protocol/Rules.cpp b/src/libxrpl/protocol/Rules.cpp index 3710322699..e649b15ea2 100644 --- a/src/libxrpl/protocol/Rules.cpp +++ b/src/libxrpl/protocol/Rules.cpp @@ -39,11 +39,8 @@ setCurrentTransactionRules(std::optional r) // Make global changes associated with the rules before the value is moved. // Push the appropriate setting, instead of having the class pull every time // the value is needed. That could get expensive fast. - bool enableLargeNumbers = !r || - (r->enabled(featureSingleAssetVault) || - r->enabled(featureLendingProtocol)); - Number::setMantissaScale( - enableLargeNumbers ? MantissaRange::large : MantissaRange::small); + bool enableLargeNumbers = !r || (r->enabled(featureSingleAssetVault) || r->enabled(featureLendingProtocol)); + Number::setMantissaScale(enableLargeNumbers ? MantissaRange::large : MantissaRange::small); *getCurrentTransactionRulesRef() = std::move(r); } @@ -56,8 +53,7 @@ private: std::unordered_set> const& presets_; public: - explicit Impl(std::unordered_set> const& presets) - : presets_(presets) + explicit Impl(std::unordered_set> const& presets) : presets_(presets) { } @@ -100,8 +96,7 @@ public: } }; -Rules::Rules(std::unordered_set> const& presets) - : impl_(std::make_shared(presets)) +Rules::Rules(std::unordered_set> const& presets) : impl_(std::make_shared(presets)) { } @@ -130,9 +125,7 @@ Rules::enabled(uint256 const& feature) const bool Rules::operator==(Rules const& other) const { - XRPL_ASSERT( - impl_ && other.impl_, - "xrpl::Rules::operator==(Rules) const : both initialized"); + XRPL_ASSERT(impl_ && other.impl_, "xrpl::Rules::operator==(Rules) const : both initialized"); if (impl_.get() == other.impl_.get()) return true; return *impl_ == *other.impl_; diff --git a/src/libxrpl/protocol/SField.cpp b/src/libxrpl/protocol/SField.cpp index 54402ea6e2..c04c82f2bc 100644 --- a/src/libxrpl/protocol/SField.cpp +++ b/src/libxrpl/protocol/SField.cpp @@ -22,8 +22,7 @@ static SField::private_access_tag_t access; template template -TypedField::TypedField(private_access_tag_t pat, Args&&... args) - : SField(pat, std::forward(args)...) +TypedField::TypedField(private_access_tag_t pat, Args&&... args) : SField(pat, std::forward(args)...) { } @@ -37,19 +36,10 @@ TypedField::TypedField(private_access_tag_t pat, Args&&... args) #undef TYPED_SFIELD #define UNTYPED_SFIELD(sfName, stiSuffix, fieldValue, ...) \ - SField const sfName( \ - access, \ - STI_##stiSuffix, \ - fieldValue, \ - std::string_view(#sfName).substr(2).data(), \ - ##__VA_ARGS__); + SField const sfName(access, STI_##stiSuffix, fieldValue, std::string_view(#sfName).substr(2).data(), ##__VA_ARGS__); #define TYPED_SFIELD(sfName, stiSuffix, fieldValue, ...) \ SF_##stiSuffix const sfName( \ - access, \ - STI_##stiSuffix, \ - fieldValue, \ - std::string_view(#sfName).substr(2).data(), \ - ##__VA_ARGS__); + access, STI_##stiSuffix, fieldValue, std::string_view(#sfName).substr(2).data(), ##__VA_ARGS__); // SFields which, for historical reasons, do not follow naming conventions. SField const sfInvalid(access, -1, ""); @@ -66,13 +56,7 @@ SField const sfIndex(access, STI_UINT256, 258, "index"); #undef UNTYPED_SFIELD #pragma pop_macro("UNTYPED_SFIELD") -SField::SField( - private_access_tag_t, - SerializedTypeID tid, - int fv, - char const* fn, - int meta, - IsSigning signing) +SField::SField(private_access_tag_t, SerializedTypeID tid, int fv, char const* fn, int meta, IsSigning signing) : fieldCode(field_code(tid, fv)) , fieldType(tid) , fieldValue(fv) @@ -83,11 +67,9 @@ SField::SField( , jsonName(fieldName.c_str()) { XRPL_ASSERT( - !knownCodeToField.contains(fieldCode), - "xrpl::SField::SField(tid,fv,fn,meta,signing) : fieldCode is unique"); + !knownCodeToField.contains(fieldCode), "xrpl::SField::SField(tid,fv,fn,meta,signing) : fieldCode is unique"); XRPL_ASSERT( - !knownNameToField.contains(fieldName), - "xrpl::SField::SField(tid,fv,fn,meta,signing) : fieldName is unique"); + !knownNameToField.contains(fieldName), "xrpl::SField::SField(tid,fv,fn,meta,signing) : fieldName is unique"); knownCodeToField[fieldCode] = this; knownNameToField[fieldName] = this; } @@ -102,12 +84,8 @@ SField::SField(private_access_tag_t, int fc, char const* fn) , signingField(IsSigning::yes) , jsonName(fieldName.c_str()) { - XRPL_ASSERT( - !knownCodeToField.contains(fieldCode), - "xrpl::SField::SField(fc,fn) : fieldCode is unique"); - XRPL_ASSERT( - !knownNameToField.contains(fieldName), - "xrpl::SField::SField(fc,fn) : fieldName is unique"); + XRPL_ASSERT(!knownCodeToField.contains(fieldCode), "xrpl::SField::SField(fc,fn) : fieldCode is unique"); + XRPL_ASSERT(!knownNameToField.contains(fieldName), "xrpl::SField::SField(fc,fn) : fieldName is unique"); knownCodeToField[fieldCode] = this; knownNameToField[fieldName] = this; } diff --git a/src/libxrpl/protocol/SOTemplate.cpp b/src/libxrpl/protocol/SOTemplate.cpp index 46edf98710..23d086f493 100644 --- a/src/libxrpl/protocol/SOTemplate.cpp +++ b/src/libxrpl/protocol/SOTemplate.cpp @@ -8,9 +8,7 @@ namespace xrpl { -SOTemplate::SOTemplate( - std::initializer_list uniqueFields, - std::initializer_list commonFields) +SOTemplate::SOTemplate(std::initializer_list uniqueFields, std::initializer_list commonFields) : indices_(SField::getNumFields() + 1, -1) // Unmapped indices == -1 { // Add all SOElements. diff --git a/src/libxrpl/protocol/STAccount.cpp b/src/libxrpl/protocol/STAccount.cpp index 728fb25f6c..b85341daf3 100644 --- a/src/libxrpl/protocol/STAccount.cpp +++ b/src/libxrpl/protocol/STAccount.cpp @@ -20,8 +20,7 @@ STAccount::STAccount() : STBase(), value_(beast::zero), default_(true) { } -STAccount::STAccount(SField const& n) - : STBase(n), value_(beast::zero), default_(true) +STAccount::STAccount(SField const& n) : STBase(n), value_(beast::zero), default_(true) { } @@ -42,13 +41,11 @@ STAccount::STAccount(SField const& n, Buffer&& v) : STAccount(n) memcpy(value_.begin(), v.data(), uint160::bytes); } -STAccount::STAccount(SerialIter& sit, SField const& name) - : STAccount(name, sit.getVLBuffer()) +STAccount::STAccount(SerialIter& sit, SField const& name) : STAccount(name, sit.getVLBuffer()) { } -STAccount::STAccount(SField const& n, AccountID const& v) - : STBase(n), value_(v), default_(false) +STAccount::STAccount(SField const& n, AccountID const& v) : STBase(n), value_(v), default_(false) { } @@ -73,11 +70,8 @@ STAccount::getSType() const void STAccount::add(Serializer& s) const { - XRPL_ASSERT( - getFName().isBinary(), "xrpl::STAccount::add : field is binary"); - XRPL_ASSERT( - getFName().fieldType == STI_ACCOUNT, - "xrpl::STAccount::add : valid field type"); + XRPL_ASSERT(getFName().isBinary(), "xrpl::STAccount::add : field is binary"); + XRPL_ASSERT(getFName().fieldType == STI_ACCOUNT, "xrpl::STAccount::add : valid field type"); // Preserve the serialization behavior of an STBlob: // o If we are default (all zeros) serialize as an empty blob. diff --git a/src/libxrpl/protocol/STAmount.cpp b/src/libxrpl/protocol/STAmount.cpp index ec60971e63..b7c33bb907 100644 --- a/src/libxrpl/protocol/STAmount.cpp +++ b/src/libxrpl/protocol/STAmount.cpp @@ -61,14 +61,11 @@ getInt64Value(STAmount const& amount, bool valid, char const* error) { if (!valid) Throw(error); - XRPL_ASSERT( - amount.exponent() == 0, "xrpl::getInt64Value : exponent is zero"); + XRPL_ASSERT(amount.exponent() == 0, "xrpl::getInt64Value : exponent is zero"); auto ret = static_cast(amount.mantissa()); - XRPL_ASSERT( - static_cast(ret) == amount.mantissa(), - "xrpl::getInt64Value : mantissa must roundtrip"); + XRPL_ASSERT(static_cast(ret) == amount.mantissa(), "xrpl::getInt64Value : mantissa must roundtrip"); if (amount.negative()) ret = -ret; @@ -85,21 +82,21 @@ getSNValue(STAmount const& amount) static std::int64_t getMPTValue(STAmount const& amount) { - return getInt64Value( - amount, amount.holds(), "amount is not MPT!"); + return getInt64Value(amount, amount.holds(), "amount is not MPT!"); } static bool areComparable(STAmount const& v1, STAmount const& v2) { if (v1.holds() && v2.holds()) - return v1.native() == v2.native() && - v1.get().currency == v2.get().currency; + return v1.native() == v2.native() && v1.get().currency == v2.get().currency; if (v1.holds() && v2.holds()) return v1.get() == v2.get(); return false; } +static_assert(INITIAL_XRP.drops() == STAmount::cMaxNativeN); + STAmount::STAmount(SerialIter& sit, SField const& name) : STBase(name) { std::uint64_t value = sit.get64(); @@ -158,8 +155,7 @@ STAmount::STAmount(SerialIter& sit, SField const& name) : STBase(name) bool isNegative = (offset & 256) == 0; offset = (offset & 255) - 97; // center the range - if (value < cMinValue || value > cMaxValue || offset < cMinOffset || - offset > cMaxOffset) + if (value < cMinValue || value > cMaxValue || offset < cMinOffset || offset > cMaxOffset) { Throw("invalid currency value"); } @@ -182,18 +178,13 @@ STAmount::STAmount(SerialIter& sit, SField const& name) : STBase(name) canonicalize(); } -STAmount::STAmount(SField const& name, std::int64_t mantissa) - : STBase(name), mAsset(xrpIssue()), mOffset(0) +STAmount::STAmount(SField const& name, std::int64_t mantissa) : STBase(name), mAsset(xrpIssue()), mOffset(0) { set(mantissa); } STAmount::STAmount(SField const& name, std::uint64_t mantissa, bool negative) - : STBase(name) - , mAsset(xrpIssue()) - , mValue(mantissa) - , mOffset(0) - , mIsNegative(negative) + : STBase(name), mAsset(xrpIssue()), mValue(mantissa), mOffset(0), mIsNegative(negative) { XRPL_ASSERT( mValue <= std::numeric_limits::max(), @@ -202,11 +193,7 @@ STAmount::STAmount(SField const& name, std::uint64_t mantissa, bool negative) } STAmount::STAmount(SField const& name, STAmount const& from) - : STBase(name) - , mAsset(from.mAsset) - , mValue(from.mValue) - , mOffset(from.mOffset) - , mIsNegative(from.mIsNegative) + : STBase(name), mAsset(from.mAsset), mValue(from.mValue), mOffset(from.mOffset), mIsNegative(from.mIsNegative) { XRPL_ASSERT( mValue <= std::numeric_limits::max(), @@ -217,10 +204,7 @@ STAmount::STAmount(SField const& name, STAmount const& from) //------------------------------------------------------------------------------ STAmount::STAmount(std::uint64_t mantissa, bool negative) - : mAsset(xrpIssue()) - , mValue(mantissa) - , mOffset(0) - , mIsNegative(mantissa != 0 && negative) + : mAsset(xrpIssue()), mValue(mantissa), mOffset(0), mIsNegative(mantissa != 0 && negative) { XRPL_ASSERT( mValue <= std::numeric_limits::max(), @@ -228,8 +212,7 @@ STAmount::STAmount(std::uint64_t mantissa, bool negative) "input"); } -STAmount::STAmount(XRPAmount const& amount) - : mAsset(xrpIssue()), mOffset(0), mIsNegative(amount < beast::zero) +STAmount::STAmount(XRPAmount const& amount) : mAsset(xrpIssue()), mOffset(0), mIsNegative(amount < beast::zero) { if (mIsNegative) mValue = unsafe_cast(-amount.drops()); @@ -266,8 +249,7 @@ XRPAmount STAmount::xrp() const { if (!native()) - Throw( - "Cannot return non-native STAmount as XRPAmount"); + Throw("Cannot return non-native STAmount as XRPAmount"); auto drops = static_cast(mValue); XRPL_ASSERT(mOffset == 0, "xrpl::STAmount::xrp : amount is canonical"); @@ -311,9 +293,7 @@ STAmount::mpt() const STAmount& STAmount::operator=(IOUAmount const& iou) { - XRPL_ASSERT( - integral() == false, - "xrpl::STAmount::operator=(IOUAmount) : is not integral"); + XRPL_ASSERT(integral() == false, "xrpl::STAmount::operator=(IOUAmount) : is not integral"); mOffset = iou.exponent(); mIsNegative = iou < beast::zero; if (mIsNegative) @@ -326,8 +306,7 @@ STAmount::operator=(IOUAmount const& iou) STAmount& STAmount::operator=(Number const& number) { - if (!getCurrentTransactionRules() || - isFeatureEnabled(featureSingleAssetVault) || + if (!getCurrentTransactionRules() || isFeatureEnabled(featureSingleAssetVault) || isFeatureEnabled(featureLendingProtocol)) { *this = fromNumber(mAsset, number); @@ -375,12 +354,7 @@ operator+(STAmount const& v1, STAmount const& v2) if (v1 == beast::zero) { // Result must be in terms of v1 currency and issuer. - return { - v1.getFName(), - v1.asset(), - v2.mantissa(), - v2.exponent(), - v2.negative()}; + return {v1.getFName(), v1.asset(), v2.mantissa(), v2.exponent(), v2.negative()}; } if (v1.native()) @@ -426,15 +400,9 @@ operator+(STAmount const& v1, STAmount const& v2) return {v1.getFName(), v1.asset()}; if (fv >= 0) - return STAmount{ - v1.getFName(), - v1.asset(), - static_cast(fv), - ov1, - false}; + return STAmount{v1.getFName(), v1.asset(), static_cast(fv), ov1, false}; - return STAmount{ - v1.getFName(), v1.asset(), static_cast(-fv), ov1, true}; + return STAmount{v1.getFName(), v1.asset(), static_cast(-fv), ov1, true}; } STAmount @@ -472,9 +440,7 @@ getRate(STAmount const& offerOut, STAmount const& offerIn) STAmount r = divide(offerIn, offerOut, noIssue()); if (r == beast::zero) // offer is too good return 0; - XRPL_ASSERT( - (r.exponent() >= -100) && (r.exponent() <= 155), - "xrpl::getRate : exponent inside range"); + XRPL_ASSERT((r.exponent() >= -100) && (r.exponent() <= 155), "xrpl::getRate : exponent inside range"); std::uint64_t ret = r.exponent() + 100; return (ret << (64 - 8)) | r.mantissa(); } @@ -521,12 +487,8 @@ canAdd(STAmount const& a, STAmount const& b) XRPAmount A = a.xrp(); XRPAmount B = b.xrp(); - if ((B > XRPAmount{0} && - A > XRPAmount{std::numeric_limits::max()} - - B) || - (B < XRPAmount{0} && - A < XRPAmount{std::numeric_limits::min()} - - B)) + if ((B > XRPAmount{0} && A > XRPAmount{std::numeric_limits::max()} - B) || + (B < XRPAmount{0} && A < XRPAmount{std::numeric_limits::min()} - B)) { return false; } @@ -540,8 +502,7 @@ canAdd(STAmount const& a, STAmount const& b) static STAmount const maxLoss{IOUAmount{1, -4}, noIssue()}; STAmount lhs = divide((a - b) + b, a, noIssue()) - one; STAmount rhs = divide((b - a) + a, b, noIssue()) - one; - return ((rhs.negative() ? -rhs : rhs) + - (lhs.negative() ? -lhs : lhs)) <= maxLoss; + return ((rhs.negative() ? -rhs : rhs) + (lhs.negative() ? -lhs : lhs)) <= maxLoss; } // MPT (overflow & underflow check) @@ -549,12 +510,8 @@ canAdd(STAmount const& a, STAmount const& b) { MPTAmount A = a.mpt(); MPTAmount B = b.mpt(); - if ((B > MPTAmount{0} && - A > MPTAmount{std::numeric_limits::max()} - - B) || - (B < MPTAmount{0} && - A < MPTAmount{std::numeric_limits::min()} - - B)) + if ((B > MPTAmount{0} && A > MPTAmount{std::numeric_limits::max()} - B) || + (B < MPTAmount{0} && A < MPTAmount{std::numeric_limits::min()} - B)) { return false; } @@ -605,9 +562,7 @@ canSubtract(STAmount const& a, STAmount const& b) return false; // Check for overflow - if (B < XRPAmount{0} && - A > XRPAmount{std::numeric_limits::max()} + - B) + if (B < XRPAmount{0} && A > XRPAmount{std::numeric_limits::max()} + B) return false; return true; @@ -630,9 +585,7 @@ canSubtract(STAmount const& a, STAmount const& b) return false; // Overflow check - if (B < MPTAmount{0} && - A > MPTAmount{std::numeric_limits::max()} + - B) + if (B < MPTAmount{0} && A > MPTAmount{std::numeric_limits::max()} + B) return false; return true; } @@ -695,8 +648,7 @@ STAmount::getText() const if (mIsNegative) ret.append(1, '-'); - bool const scientific( - (mOffset != 0) && ((mOffset < -25) || (mOffset > -5))); + bool const scientific((mOffset != 0) && ((mOffset < -25) || (mOffset > -5))); if (native() || mAsset.holds() || scientific) { @@ -735,8 +687,7 @@ STAmount::getText() const if (std::distance(pre_from, pre_to) > pad_prefix) pre_from += pad_prefix; - XRPL_ASSERT( - post_to >= post_from, "xrpl::STAmount::getText : first distance check"); + XRPL_ASSERT(post_to >= post_from, "xrpl::STAmount::getText : first distance check"); pre_from = std::find_if(pre_from, pre_to, [](char c) { return c != '0'; }); @@ -745,15 +696,11 @@ STAmount::getText() const if (std::distance(post_from, post_to) > pad_suffix) post_to -= pad_suffix; - XRPL_ASSERT( - post_to >= post_from, - "xrpl::STAmount::getText : second distance check"); + XRPL_ASSERT(post_to >= post_from, "xrpl::STAmount::getText : second distance check"); - post_to = std::find_if( - std::make_reverse_iterator(post_to), - std::make_reverse_iterator(post_from), - [](char c) { return c != '0'; }) - .base(); + post_to = std::find_if(std::make_reverse_iterator(post_to), std::make_reverse_iterator(post_from), [](char c) { + return c != '0'; + }).base(); // Assemble the output: if (pre_from == pre_to) @@ -804,14 +751,9 @@ STAmount::add(Serializer& s) const if (*this == beast::zero) s.add64(cIssuedCurrency); else if (mIsNegative) // 512 = not native - s.add64( - mValue | - (static_cast(mOffset + 512 + 97) << (64 - 10))); + s.add64(mValue | (static_cast(mOffset + 512 + 97) << (64 - 10))); else // 256 = positive - s.add64( - mValue | - (static_cast(mOffset + 512 + 256 + 97) - << (64 - 10))); + s.add64(mValue | (static_cast(mOffset + 512 + 256 + 97) << (64 - 10))); s.addBitString(mAsset.get().currency); s.addBitString(mAsset.get().account); } @@ -899,8 +841,7 @@ STAmount::canonicalize() // N.B. do not move the overflow check to after the // multiplication if (native() && mValue > cMaxNativeN) - Throw( - "Native currency amount out of range"); + Throw("Native currency amount out of range"); else if (!native() && mValue > maxMPTokenAmount) Throw("MPT amount out of range"); @@ -962,9 +903,7 @@ STAmount::canonicalize() XRPL_ASSERT( (mValue == 0) || ((mOffset >= cMinOffset) && (mOffset <= cMaxOffset)), "xrpl::STAmount::canonicalize : offset inside range"); - XRPL_ASSERT( - (mValue != 0) || (mOffset != -100), - "xrpl::STAmount::canonicalize : value or offset set"); + XRPL_ASSERT((mValue != 0) || (mOffset != -100), "xrpl::STAmount::canonicalize : value or offset set"); } void @@ -1001,8 +940,7 @@ amountFromString(Asset const& asset, std::string const& amount) { auto const parts = partsFromString(amount); if ((asset.native() || asset.holds()) && parts.exponent < 0) - Throw( - "XRP and MPT must be specified as integral amount."); + Throw("XRP and MPT must be specified as integral amount."); return {asset, parts.mantissa, parts.exponent, parts.negative}; } @@ -1018,8 +956,7 @@ amountFromJson(SField const& name, Json::Value const& v) if (v.isNull()) { - Throw( - "XRP may not be specified with a null Json value"); + Throw("XRP may not be specified with a null Json value"); } else if (v.isObject()) { @@ -1066,8 +1003,7 @@ amountFromJson(SField const& name, Json::Value const& v) value = v; } - bool const native = !currencyOrMPTID.isString() || - currencyOrMPTID.asString().empty() || + bool const native = !currencyOrMPTID.isString() || currencyOrMPTID.asString().empty() || (currencyOrMPTID.asString() == systemCurrencyCode()); if (native) @@ -1091,8 +1027,7 @@ amountFromJson(SField const& name, Json::Value const& v) Issue issue; if (!to_currency(issue.currency, currencyOrMPTID.asString())) Throw("invalid currency"); - if (!issuer.isString() || - !to_issuer(issue.account, issuer.asString())) + if (!issuer.isString() || !to_issuer(issue.account, issuer.asString())) Throw("invalid issuer"); if (issue.native()) Throw("invalid issuer"); @@ -1123,8 +1058,7 @@ amountFromJson(SField const& name, Json::Value const& v) parts = partsFromString(value.asString()); // Can't specify XRP or MPT using fractional representation if ((asset.native() || asset.holds()) && parts.exponent < 0) - Throw( - "XRP and MPT must be specified as integral amount."); + Throw("XRP and MPT must be specified as integral amount."); } else { @@ -1144,8 +1078,7 @@ amountFromJsonNoThrow(STAmount& result, Json::Value const& jvSource) } catch (std::exception const& e) { - JLOG(debugLog().warn()) - << "amountFromJsonNoThrow: caught: " << e.what(); + JLOG(debugLog().warn()) << "amountFromJsonNoThrow: caught: " << e.what(); } return false; } @@ -1159,16 +1092,15 @@ amountFromJsonNoThrow(STAmount& result, Json::Value const& jvSource) bool operator==(STAmount const& lhs, STAmount const& rhs) { - return areComparable(lhs, rhs) && lhs.negative() == rhs.negative() && - lhs.exponent() == rhs.exponent() && lhs.mantissa() == rhs.mantissa(); + return areComparable(lhs, rhs) && lhs.negative() == rhs.negative() && lhs.exponent() == rhs.exponent() && + lhs.mantissa() == rhs.mantissa(); } bool operator<(STAmount const& lhs, STAmount const& rhs) { if (!areComparable(lhs, rhs)) - Throw( - "Can't compare amounts that are't comparable!"); + Throw("Can't compare amounts that are't comparable!"); if (lhs.negative() != rhs.negative()) return lhs.negative(); @@ -1204,12 +1136,7 @@ operator-(STAmount const& value) if (value.mantissa() == 0) return value; return STAmount( - value.getFName(), - value.asset(), - value.mantissa(), - value.exponent(), - !value.negative(), - STAmount::unchecked{}); + value.getFName(), value.asset(), value.mantissa(), value.exponent(), !value.negative(), STAmount::unchecked{}); } //------------------------------------------------------------------------------ @@ -1221,10 +1148,7 @@ operator-(STAmount const& value) // Calculate (a * b) / c when all three values are 64-bit // without loss of precision: static std::uint64_t -muldiv( - std::uint64_t multiplier, - std::uint64_t multiplicand, - std::uint64_t divisor) +muldiv(std::uint64_t multiplier, std::uint64_t multiplicand, std::uint64_t divisor) { boost::multiprecision::uint128_t ret; @@ -1234,19 +1158,15 @@ muldiv( if (ret > std::numeric_limits::max()) { Throw( - "overflow: (" + std::to_string(multiplier) + " * " + - std::to_string(multiplicand) + ") / " + std::to_string(divisor)); + "overflow: (" + std::to_string(multiplier) + " * " + std::to_string(multiplicand) + ") / " + + std::to_string(divisor)); } return static_cast(ret); } static std::uint64_t -muldiv_round( - std::uint64_t multiplier, - std::uint64_t multiplicand, - std::uint64_t divisor, - std::uint64_t rounding) +muldiv_round(std::uint64_t multiplier, std::uint64_t multiplicand, std::uint64_t divisor, std::uint64_t rounding) { boost::multiprecision::uint128_t ret; @@ -1257,9 +1177,8 @@ muldiv_round( if (ret > std::numeric_limits::max()) { Throw( - "overflow: ((" + std::to_string(multiplier) + " * " + - std::to_string(multiplicand) + ") + " + std::to_string(rounding) + - ") / " + std::to_string(divisor)); + "overflow: ((" + std::to_string(multiplier) + " * " + std::to_string(multiplicand) + ") + " + + std::to_string(rounding) + ") / " + std::to_string(divisor)); } return static_cast(ret); @@ -1304,10 +1223,7 @@ divide(STAmount const& num, STAmount const& den, Asset const& asset) // 10^32 to 10^33) followed by a division, so the result // is in the range of 10^16 to 10^15. return STAmount( - asset, - muldiv(numVal, tenTo17, denVal) + 5, - numOffset - denOffset - 17, - num.negative() != den.negative()); + asset, muldiv(numVal, tenTo17, denVal) + 5, numOffset - denOffset - 17, num.negative() != den.negative()); } STAmount @@ -1376,11 +1292,7 @@ multiply(STAmount const& v1, STAmount const& v2, Asset const& asset) // and 10^16), so their product is in the 10^30 to 10^32 // range. Dividing their product by 10^14 maintains the // precision, by scaling the result to 10^16 to 10^18. - return STAmount( - asset, - muldiv(value1, value2, tenTo14) + 7, - offset1 + offset2 + 14, - v1.negative() != v2.negative()); + return STAmount(asset, muldiv(value1, value2, tenTo14) + 7, offset1 + offset2 + 14, v1.negative() != v2.negative()); } // This is the legacy version of canonicalizeRound. It's been in use @@ -1443,11 +1355,7 @@ canonicalizeRound(bool native, std::uint64_t& value, int& offset, bool) // rounding decisions. canonicalizeRoundStrict() tracks all of the bits in // the value being rounded. static void -canonicalizeRoundStrict( - bool native, - std::uint64_t& value, - int& offset, - bool roundUp) +canonicalizeRoundStrict(bool native, std::uint64_t& value, int& offset, bool roundUp) { if (native) { @@ -1465,8 +1373,7 @@ canonicalizeRoundStrict( value = newValue; ++offset; } - value += - (hadRemainder && roundUp) ? 10 : 9; // Add before last divide + value += (hadRemainder && roundUp) ? 10 : 9; // Add before last divide value /= 10; ++offset; } @@ -1485,10 +1392,7 @@ canonicalizeRoundStrict( } STAmount -roundToScale( - STAmount const& value, - std::int32_t scale, - Number::rounding_mode rounding) +roundToScale(STAmount const& value, std::int32_t scale, Number::rounding_mode rounding) { // Nothing to do for integral types. if (value.integral()) @@ -1504,8 +1408,7 @@ roundToScale( if (value.exponent() >= scale) return value; - STAmount const referenceValue{ - value.asset(), STAmount::cMinValue, scale, value.negative()}; + STAmount const referenceValue{value.asset(), STAmount::cMinValue, scale, value.negative()}; NumberRoundModeGuard mg(rounding); // With an IOU, the the result of addition will be truncated to the @@ -1538,15 +1441,9 @@ public: // // We might need to use NumberRoundModeGuard. Allow the caller // to pass either that or a replacement as a template parameter. -template < - void (*CanonicalizeFunc)(bool, std::uint64_t&, int&, bool), - typename MightSaveRound> +template static STAmount -mulRoundImpl( - STAmount const& v1, - STAmount const& v2, - Asset const& asset, - bool roundUp) +mulRoundImpl(STAmount const& v1, STAmount const& v2, Asset const& asset, bool roundUp) { if (v1 == beast::zero || v2 == beast::zero) return {asset}; @@ -1612,8 +1509,7 @@ mulRoundImpl( // If the we're rounding up, we want to round up away // from zero, and if we're rounding down, truncation // is implicit. - std::uint64_t amount = muldiv_round( - value1, value2, tenTo14, (resultNegative != roundUp) ? tenTo14m1 : 0); + std::uint64_t amount = muldiv_round(value1, value2, tenTo14, (resultNegative != roundUp) ? tenTo14m1 : 0); int offset = offset1 + offset2 + 14; if (resultNegative != roundUp) @@ -1647,36 +1543,22 @@ mulRoundImpl( } STAmount -mulRound( - STAmount const& v1, - STAmount const& v2, - Asset const& asset, - bool roundUp) +mulRound(STAmount const& v1, STAmount const& v2, Asset const& asset, bool roundUp) { - return mulRoundImpl( - v1, v2, asset, roundUp); + return mulRoundImpl(v1, v2, asset, roundUp); } STAmount -mulRoundStrict( - STAmount const& v1, - STAmount const& v2, - Asset const& asset, - bool roundUp) +mulRoundStrict(STAmount const& v1, STAmount const& v2, Asset const& asset, bool roundUp) { - return mulRoundImpl( - v1, v2, asset, roundUp); + return mulRoundImpl(v1, v2, asset, roundUp); } // We might need to use NumberRoundModeGuard. Allow the caller // to pass either that or a replacement as a template parameter. template static STAmount -divRoundImpl( - STAmount const& num, - STAmount const& den, - Asset const& asset, - bool roundUp) +divRoundImpl(STAmount const& num, STAmount const& den, Asset const& asset, bool roundUp) { if (den == beast::zero) Throw("division by zero"); @@ -1715,22 +1597,19 @@ divRoundImpl( // // We round away from zero if we're rounding up or // truncate if we're rounding down. - std::uint64_t amount = muldiv_round( - numVal, tenTo17, denVal, (resultNegative != roundUp) ? denVal - 1 : 0); + std::uint64_t amount = muldiv_round(numVal, tenTo17, denVal, (resultNegative != roundUp) ? denVal - 1 : 0); int offset = numOffset - denOffset - 17; if (resultNegative != roundUp) - canonicalizeRound( - asset.native() || asset.holds(), amount, offset, roundUp); + canonicalizeRound(asset.native() || asset.holds(), amount, offset, roundUp); STAmount result = [&]() { // If appropriate, tell Number the rounding mode we are using. // Note that "roundUp == true" actually means "round away from zero". // Otherwise round toward zero. using enum Number::rounding_mode; - MightSaveRound const savedRound( - roundUp ^ resultNegative ? upward : downward); + MightSaveRound const savedRound(roundUp ^ resultNegative ? upward : downward); return STAmount(asset, amount, offset, resultNegative); }(); @@ -1754,21 +1633,13 @@ divRoundImpl( } STAmount -divRound( - STAmount const& num, - STAmount const& den, - Asset const& asset, - bool roundUp) +divRound(STAmount const& num, STAmount const& den, Asset const& asset, bool roundUp) { return divRoundImpl(num, den, asset, roundUp); } STAmount -divRoundStrict( - STAmount const& num, - STAmount const& den, - Asset const& asset, - bool roundUp) +divRoundStrict(STAmount const& num, STAmount const& den, Asset const& asset, bool roundUp) { return divRoundImpl(num, den, asset, roundUp); } diff --git a/src/libxrpl/protocol/STArray.cpp b/src/libxrpl/protocol/STArray.cpp index de1e6905c6..8e7827cccc 100644 --- a/src/libxrpl/protocol/STArray.cpp +++ b/src/libxrpl/protocol/STArray.cpp @@ -14,8 +14,7 @@ namespace xrpl { -STArray::STArray(STArray&& other) - : STBase(other.getFName()), v_(std::move(other.v_)) +STArray::STArray(STArray&& other) : STBase(other.getFName()), v_(std::move(other.v_)) { } @@ -53,8 +52,7 @@ STArray::STArray(SerialIter& sit, SField const& f, int depth) : STBase(f) if ((type == STI_OBJECT) && (field == 1)) { - JLOG(debugLog().error()) - << "Encountered array with end of object marker"; + JLOG(debugLog().error()) << "Encountered array with end of object marker"; Throw("Illegal terminator in array"); } @@ -62,8 +60,7 @@ STArray::STArray(SerialIter& sit, SField const& f, int depth) : STBase(f) if (fn.isInvalid()) { - JLOG(debugLog().error()) - << "Unknown field: " << type << "/" << field; + JLOG(debugLog().error()) << "Unknown field: " << type << "/" << field; Throw("Unknown field"); } diff --git a/src/libxrpl/protocol/STBase.cpp b/src/libxrpl/protocol/STBase.cpp index d3faf090eb..f6b1dcec58 100644 --- a/src/libxrpl/protocol/STBase.cpp +++ b/src/libxrpl/protocol/STBase.cpp @@ -101,9 +101,7 @@ STBase::add(Serializer& s) const bool STBase::isEquivalent(STBase const& t) const { - XRPL_ASSERT( - getSType() == STI_NOTPRESENT, - "xrpl::STBase::isEquivalent : type not present"); + XRPL_ASSERT(getSType() == STI_NOTPRESENT, "xrpl::STBase::isEquivalent : type not present"); return t.getSType() == STI_NOTPRESENT; } @@ -129,8 +127,7 @@ STBase::getFName() const void STBase::addFieldID(Serializer& s) const { - XRPL_ASSERT( - fName->isBinary(), "xrpl::STBase::addFieldID : field is binary"); + XRPL_ASSERT(fName->isBinary(), "xrpl::STBase::addFieldID : field is binary"); s.addFieldID(fName->fieldType, fName->fieldValue); } diff --git a/src/libxrpl/protocol/STBlob.cpp b/src/libxrpl/protocol/STBlob.cpp index 65670a6a9f..1a9dae7771 100644 --- a/src/libxrpl/protocol/STBlob.cpp +++ b/src/libxrpl/protocol/STBlob.cpp @@ -11,8 +11,7 @@ namespace xrpl { -STBlob::STBlob(SerialIter& st, SField const& name) - : STBase(name), value_(st.getVLBuffer()) +STBlob::STBlob(SerialIter& st, SField const& name) : STBase(name), value_(st.getVLBuffer()) { } @@ -45,8 +44,7 @@ STBlob::add(Serializer& s) const { XRPL_ASSERT(getFName().isBinary(), "xrpl::STBlob::add : field is binary"); XRPL_ASSERT( - (getFName().fieldType == STI_VL) || - (getFName().fieldType == STI_ACCOUNT), + (getFName().fieldType == STI_VL) || (getFName().fieldType == STI_ACCOUNT), "xrpl::STBlob::add : valid field type"); s.addVL(value_.data(), value_.size()); } diff --git a/src/libxrpl/protocol/STCurrency.cpp b/src/libxrpl/protocol/STCurrency.cpp index d4c10b48d3..cfbbe509c6 100644 --- a/src/libxrpl/protocol/STCurrency.cpp +++ b/src/libxrpl/protocol/STCurrency.cpp @@ -23,8 +23,7 @@ STCurrency::STCurrency(SerialIter& sit, SField const& name) : STBase{name} currency_ = sit.get160(); } -STCurrency::STCurrency(SField const& name, Currency const& currency) - : STBase{name}, currency_{currency} +STCurrency::STCurrency(SField const& name, Currency const& currency) : STBase{name}, currency_{currency} { } @@ -88,15 +87,13 @@ currencyFromJson(SField const& name, Json::Value const& v) { if (!v.isString()) { - Throw( - "currencyFromJson currency must be a string Json value"); + Throw("currencyFromJson currency must be a string Json value"); } auto const currency = to_currency(v.asString()); if (currency == badCurrency() || currency == noCurrency()) { - Throw( - "currencyFromJson currency must be a valid currency"); + Throw("currencyFromJson currency must be a valid currency"); } return STCurrency{name, currency}; diff --git a/src/libxrpl/protocol/STInteger.cpp b/src/libxrpl/protocol/STInteger.cpp index e701fc4203..ae7b3ff279 100644 --- a/src/libxrpl/protocol/STInteger.cpp +++ b/src/libxrpl/protocol/STInteger.cpp @@ -20,8 +20,7 @@ namespace xrpl { template <> -STInteger::STInteger(SerialIter& sit, SField const& name) - : STInteger(name, sit.get8()) +STInteger::STInteger(SerialIter& sit, SField const& name) : STInteger(name, sit.get8()) { } @@ -44,8 +43,7 @@ STUInt8::getText() const return human; // LCOV_EXCL_START - JLOG(debugLog().error()) - << "Unknown result code in metadata: " << value_; + JLOG(debugLog().error()) << "Unknown result code in metadata: " << value_; // LCOV_EXCL_STOP } @@ -64,8 +62,7 @@ STUInt8::getJson(JsonOptions) const return token; // LCOV_EXCL_START - JLOG(debugLog().error()) - << "Unknown result code in metadata: " << value_; + JLOG(debugLog().error()) << "Unknown result code in metadata: " << value_; // LCOV_EXCL_STOP } @@ -75,8 +72,7 @@ STUInt8::getJson(JsonOptions) const //------------------------------------------------------------------------------ template <> -STInteger::STInteger(SerialIter& sit, SField const& name) - : STInteger(name, sit.get16()) +STInteger::STInteger(SerialIter& sit, SField const& name) : STInteger(name, sit.get16()) { } @@ -93,8 +89,7 @@ STUInt16::getText() const { if (getFName() == sfLedgerEntryType) { - auto item = LedgerFormats::getInstance().findByType( - safe_cast(value_)); + auto item = LedgerFormats::getInstance().findByType(safe_cast(value_)); if (item != nullptr) return item->getName(); @@ -102,8 +97,7 @@ STUInt16::getText() const if (getFName() == sfTransactionType) { - auto item = - TxFormats::getInstance().findByType(safe_cast(value_)); + auto item = TxFormats::getInstance().findByType(safe_cast(value_)); if (item != nullptr) return item->getName(); @@ -118,8 +112,7 @@ STUInt16::getJson(JsonOptions) const { if (getFName() == sfLedgerEntryType) { - auto item = LedgerFormats::getInstance().findByType( - safe_cast(value_)); + auto item = LedgerFormats::getInstance().findByType(safe_cast(value_)); if (item != nullptr) return item->getName(); @@ -127,8 +120,7 @@ STUInt16::getJson(JsonOptions) const if (getFName() == sfTransactionType) { - auto item = - TxFormats::getInstance().findByType(safe_cast(value_)); + auto item = TxFormats::getInstance().findByType(safe_cast(value_)); if (item != nullptr) return item->getName(); @@ -140,8 +132,7 @@ STUInt16::getJson(JsonOptions) const //------------------------------------------------------------------------------ template <> -STInteger::STInteger(SerialIter& sit, SField const& name) - : STInteger(name, sit.get32()) +STInteger::STInteger(SerialIter& sit, SField const& name) : STInteger(name, sit.get32()) { } @@ -158,8 +149,7 @@ STUInt32::getText() const { if (getFName() == sfPermissionValue) { - auto const permissionName = - Permission::getInstance().getPermissionName(value_); + auto const permissionName = Permission::getInstance().getPermissionName(value_); if (permissionName) return *permissionName; } @@ -172,8 +162,7 @@ STUInt32::getJson(JsonOptions) const { if (getFName() == sfPermissionValue) { - auto const permissionName = - Permission::getInstance().getPermissionName(value_); + auto const permissionName = Permission::getInstance().getPermissionName(value_); if (permissionName) return *permissionName; } @@ -184,8 +173,7 @@ STUInt32::getJson(JsonOptions) const //------------------------------------------------------------------------------ template <> -STInteger::STInteger(SerialIter& sit, SField const& name) - : STInteger(name, sit.get64()) +STInteger::STInteger(SerialIter& sit, SField const& name) : STInteger(name, sit.get64()) { } @@ -208,16 +196,10 @@ Json::Value STUInt64::getJson(JsonOptions) const { auto convertToString = [](uint64_t const value, int const base) { - XRPL_ASSERT( - base == 10 || base == 16, - "xrpl::STUInt64::getJson : base 10 or 16"); - std::string str( - base == 10 ? 20 : 16, 0); // Allocate space depending on base - auto ret = - std::to_chars(str.data(), str.data() + str.size(), value, base); - XRPL_ASSERT( - ret.ec == std::errc(), - "xrpl::STUInt64::getJson : to_chars succeeded"); + XRPL_ASSERT(base == 10 || base == 16, "xrpl::STUInt64::getJson : base 10 or 16"); + std::string str(base == 10 ? 20 : 16, 0); // Allocate space depending on base + auto ret = std::to_chars(str.data(), str.data() + str.size(), value, base); + XRPL_ASSERT(ret.ec == std::errc(), "xrpl::STUInt64::getJson : to_chars succeeded"); str.resize(std::distance(str.data(), ret.ptr)); return str; }; @@ -233,8 +215,7 @@ STUInt64::getJson(JsonOptions) const //------------------------------------------------------------------------------ template <> -STInteger::STInteger(SerialIter& sit, SField const& name) - : STInteger(name, sit.get32()) +STInteger::STInteger(SerialIter& sit, SField const& name) : STInteger(name, sit.get32()) { } diff --git a/src/libxrpl/protocol/STIssue.cpp b/src/libxrpl/protocol/STIssue.cpp index 213c8b7962..627c61fc58 100644 --- a/src/libxrpl/protocol/STIssue.cpp +++ b/src/libxrpl/protocol/STIssue.cpp @@ -44,13 +44,9 @@ STIssue::STIssue(SerialIter& sit, SField const& name) : STBase{name} { MPTID mptID; std::uint32_t sequence = sit.get32(); - static_assert( - MPTID::size() == sizeof(sequence) + sizeof(currencyOrAccount)); + static_assert(MPTID::size() == sizeof(sequence) + sizeof(currencyOrAccount)); memcpy(mptID.data(), &sequence, sizeof(sequence)); - memcpy( - mptID.data() + sizeof(sequence), - currencyOrAccount.data(), - sizeof(currencyOrAccount)); + memcpy(mptID.data() + sizeof(sequence), currencyOrAccount.data(), sizeof(currencyOrAccount)); MPTIssue issue{mptID}; asset_ = issue; } @@ -60,8 +56,7 @@ STIssue::STIssue(SerialIter& sit, SField const& name) : STBase{name} issue.currency = currencyOrAccount; issue.account = account; if (!isConsistent(issue)) - Throw( - "invalid issue: currency and account native mismatch"); + Throw("invalid issue: currency and account native mismatch"); asset_ = issue; } } diff --git a/src/libxrpl/protocol/STLedgerEntry.cpp b/src/libxrpl/protocol/STLedgerEntry.cpp index 8ee3669a24..d73da2eb3a 100644 --- a/src/libxrpl/protocol/STLedgerEntry.cpp +++ b/src/libxrpl/protocol/STLedgerEntry.cpp @@ -28,30 +28,26 @@ namespace xrpl { -STLedgerEntry::STLedgerEntry(Keylet const& k) - : STObject(sfLedgerEntry), key_(k.key), type_(k.type) +STLedgerEntry::STLedgerEntry(Keylet const& k) : STObject(sfLedgerEntry), key_(k.key), type_(k.type) { auto const format = LedgerFormats::getInstance().findByType(type_); if (format == nullptr) Throw( - "Attempt to create a SLE of unknown type " + - std::to_string(safe_cast(k.type))); + "Attempt to create a SLE of unknown type " + std::to_string(safe_cast(k.type))); set(format->getSOTemplate()); setFieldU16(sfLedgerEntryType, static_cast(type_)); } -STLedgerEntry::STLedgerEntry(SerialIter& sit, uint256 const& index) - : STObject(sfLedgerEntry), key_(index) +STLedgerEntry::STLedgerEntry(SerialIter& sit, uint256 const& index) : STObject(sfLedgerEntry), key_(index) { set(sit); setSLEType(); } -STLedgerEntry::STLedgerEntry(STObject const& object, uint256 const& index) - : STObject(object), key_(index) +STLedgerEntry::STLedgerEntry(STObject const& object, uint256 const& index) : STObject(object), key_(index) { setSLEType(); } @@ -59,8 +55,7 @@ STLedgerEntry::STLedgerEntry(STObject const& object, uint256 const& index) void STLedgerEntry::setSLEType() { - auto format = LedgerFormats::getInstance().findByType( - safe_cast(getFieldU16(sfLedgerEntryType))); + auto format = LedgerFormats::getInstance().findByType(safe_cast(getFieldU16(sfLedgerEntryType))); if (format == nullptr) Throw("invalid ledger entry type"); @@ -108,8 +103,7 @@ STLedgerEntry::getSType() const std::string STLedgerEntry::getText() const { - return str( - boost::format("{ %s, %s }") % to_string(key_) % STObject::getText()); + return str(boost::format("{ %s, %s }") % to_string(key_) % STObject::getText()); } Json::Value @@ -120,8 +114,7 @@ STLedgerEntry::getJson(JsonOptions options) const ret[jss::index] = to_string(key_); if (getType() == ltMPTOKEN_ISSUANCE) - ret[jss::mpt_issuance_id] = to_string( - makeMptID(getFieldU32(sfSequence), getAccountID(sfIssuer))); + ret[jss::mpt_issuance_id] = to_string(makeMptID(getFieldU32(sfSequence), getAccountID(sfIssuer))); return ret; } @@ -134,19 +127,12 @@ STLedgerEntry::isThreadedType(Rules const& rules) const // Exclude PrevTxnID/PrevTxnLgrSeq if the fixPreviousTxnID amendment is not // enabled and the ledger object type is in the above set bool const excludePrevTxnID = !rules.enabled(fixPreviousTxnID) && - std::count( - newPreviousTxnIDTypes.cbegin(), - newPreviousTxnIDTypes.cend(), - type_); + std::count(newPreviousTxnIDTypes.cbegin(), newPreviousTxnIDTypes.cend(), type_); return !excludePrevTxnID && getFieldIndex(sfPreviousTxnID) != -1; } bool -STLedgerEntry::thread( - uint256 const& txID, - std::uint32_t ledgerSeq, - uint256& prevTxID, - std::uint32_t& prevLedgerID) +STLedgerEntry::thread(uint256 const& txID, std::uint32_t ledgerSeq, uint256& prevTxID, std::uint32_t& prevLedgerID) { uint256 oldPrevTxID = getFieldH256(sfPreviousTxnID); @@ -156,8 +142,7 @@ STLedgerEntry::thread( { // this transaction is already threaded XRPL_ASSERT( - getFieldU32(sfPreviousTxnLgrSeq) == ledgerSeq, - "xrpl::STLedgerEntry::thread : ledger sequence match"); + getFieldU32(sfPreviousTxnLgrSeq) == ledgerSeq, "xrpl::STLedgerEntry::thread : ledger sequence match"); return false; } diff --git a/src/libxrpl/protocol/STNumber.cpp b/src/libxrpl/protocol/STNumber.cpp index 2f2dae7493..a549a0e482 100644 --- a/src/libxrpl/protocol/STNumber.cpp +++ b/src/libxrpl/protocol/STNumber.cpp @@ -20,8 +20,7 @@ namespace xrpl { -STNumber::STNumber(SField const& field, Number const& value) - : STTakesAsset(field), value_(value) +STNumber::STNumber(SField const& field, Number const& value) : STTakesAsset(field), value_(value) { } @@ -51,10 +50,7 @@ STNumber::associateAsset(Asset const& a) { STTakesAsset::associateAsset(a); - XRPL_ASSERT_PARTS( - getFName().shouldMeta(SField::sMD_NeedsAsset), - "STNumber::associateAsset", - "field needs asset"); + XRPL_ASSERT_PARTS(getFName().shouldMeta(SField::sMD_NeedsAsset), "STNumber::associateAsset", "field needs asset"); roundToAsset(a, value_); } @@ -63,9 +59,7 @@ void STNumber::add(Serializer& s) const { XRPL_ASSERT(getFName().isBinary(), "xrpl::STNumber::add : field is binary"); - XRPL_ASSERT( - getFName().fieldType == getSType(), - "xrpl::STNumber::add : field type match"); + XRPL_ASSERT(getFName().fieldType == getSType(), "xrpl::STNumber::add : field type match"); auto value = value_; auto const mantissa = value.mantissa(); @@ -80,10 +74,7 @@ STNumber::add(Serializer& s) const // The number should be rounded to the asset's precision, but round // it here if it has an asset assigned. roundToAsset(*asset_, value); - XRPL_ASSERT_PARTS( - value_ == value, - "xrpl::STNumber::add", - "value is already rounded"); + XRPL_ASSERT_PARTS(value_ == value, "xrpl::STNumber::add", "value is already rounded"); } else { @@ -103,8 +94,7 @@ STNumber::add(Serializer& s) const } XRPL_ASSERT_PARTS( - mantissa <= std::numeric_limits::max() && - mantissa >= std::numeric_limits::min(), + mantissa <= std::numeric_limits::max() && mantissa >= std::numeric_limits::min(), "xrpl::STNumber::add", "mantissa in valid range"); s.add64(mantissa); @@ -138,9 +128,7 @@ STNumber::move(std::size_t n, void* buf) bool STNumber::isEquivalent(STBase const& t) const { - XRPL_ASSERT( - t.getSType() == this->getSType(), - "xrpl::STNumber::isEquivalent : field type match"); + XRPL_ASSERT(t.getSType() == this->getSType(), "xrpl::STNumber::isEquivalent : field type match"); STNumber const& v = dynamic_cast(t); return value_ == v; } @@ -238,29 +226,19 @@ numberFromJson(SField const& field, Json::Value const& value) { parts = partsFromString(value.asString()); - XRPL_ASSERT_PARTS( - !getCurrentTransactionRules(), - "xrpld::numberFromJson", - "Not in a Transactor context"); + XRPL_ASSERT_PARTS(!getCurrentTransactionRules(), "xrpld::numberFromJson", "Not in a Transactor context"); // Number mantissas are much bigger than the allowable parsed values, so // it can't be out of range. static_assert( - std::numeric_limits::max() >= - std::numeric_limits::max()); + std::numeric_limits::max() >= std::numeric_limits::max()); } else { Throw("not a number"); } - return STNumber{ - field, - Number{ - parts.negative, - parts.mantissa, - parts.exponent, - Number::normalized{}}}; + return STNumber{field, Number{parts.negative, parts.mantissa, parts.exponent, Number::normalized{}}}; } } // namespace xrpl diff --git a/src/libxrpl/protocol/STObject.cpp b/src/libxrpl/protocol/STObject.cpp index 6007753ed1..ad5b6fe352 100644 --- a/src/libxrpl/protocol/STObject.cpp +++ b/src/libxrpl/protocol/STObject.cpp @@ -41,8 +41,7 @@ namespace xrpl { -STObject::STObject(STObject&& other) - : STBase(other.getFName()), v_(std::move(other.v_)), mType(other.mType) +STObject::STObject(STObject&& other) : STBase(other.getFName()), v_(std::move(other.v_)), mType(other.mType) { } @@ -55,17 +54,14 @@ STObject::STObject(SOTemplate const& type, SField const& name) : STBase(name) set(type); } -STObject::STObject(SOTemplate const& type, SerialIter& sit, SField const& name) - : STBase(name) +STObject::STObject(SOTemplate const& type, SerialIter& sit, SField const& name) : STBase(name) { v_.reserve(type.size()); set(sit); applyTemplate(type); // May throw } -STObject::STObject(SerialIter& sit, SField const& name, int depth) noexcept( - false) - : STBase(name), mType(nullptr) +STObject::STObject(SerialIter& sit, SField const& name, int depth) noexcept(false) : STBase(name), mType(nullptr) { if (depth > 10) Throw("Maximum nesting depth of STObject exceeded"); @@ -87,8 +83,7 @@ STObject::makeInnerObject(SField const& name) if (!rules || (rules->enabled(fixInnerObjTemplate) && isAMMObj) || (rules->enabled(fixInnerObjTemplate2) && !isAMMObj)) { - if (SOTemplate const* elements = - InnerObjectFormats::getInstance().findSOTemplateBySField(name)) + if (SOTemplate const* elements = InnerObjectFormats::getInstance().findSOTemplateBySField(name)) obj.set(*elements); } return obj; @@ -165,17 +160,13 @@ STObject::applyTemplate(SOTemplate const& type) v.reserve(type.size()); for (auto const& e : type) { - auto const iter = - std::find_if(v_.begin(), v_.end(), [&](detail::STVar const& b) { - return b.get().getFName() == e.sField(); - }); + auto const iter = std::find_if( + v_.begin(), v_.end(), [&](detail::STVar const& b) { return b.get().getFName() == e.sField(); }); if (iter != v_.end()) { if ((e.style() == soeDEFAULT) && iter->get().isDefault()) { - throwFieldErr( - e.sField().fieldName, - "may not be explicitly set to default."); + throwFieldErr(e.sField().fieldName, "may not be explicitly set to default."); } v.emplace_back(std::move(*iter)); v_.erase(iter); @@ -194,8 +185,7 @@ STObject::applyTemplate(SOTemplate const& type) // Anything left over in the object must be discardable if (!e->getFName().isDiscardable()) { - throwFieldErr( - e->getFName().getName(), "found in disallowed location."); + throwFieldErr(e->getFName().getName(), "found in disallowed location."); } } // Swap the template matching data in for the old data, @@ -206,8 +196,7 @@ STObject::applyTemplate(SOTemplate const& type) void STObject::applyTemplateFromSField(SField const& sField) { - SOTemplate const* elements = - InnerObjectFormats::getInstance().findSOTemplateBySField(sField); + SOTemplate const* elements = InnerObjectFormats::getInstance().findSOTemplateBySField(sField); if (elements) applyTemplate(*elements); // May throw } @@ -239,8 +228,7 @@ STObject::set(SerialIter& sit, int depth) if (type == STI_ARRAY && field == 1) { - JLOG(debugLog().error()) - << "Encountered object with embedded end-of-array marker"; + JLOG(debugLog().error()) << "Encountered object with embedded end-of-array marker"; Throw("Illegal end-of-array marker in object"); } @@ -248,8 +236,7 @@ STObject::set(SerialIter& sit, int depth) if (fn.isInvalid()) { - JLOG(debugLog().error()) << "Unknown field: field_type=" << type - << ", field_name=" << field; + JLOG(debugLog().error()) << "Unknown field: field_type=" << type << ", field_name=" << field; Throw("Unknown field"); } @@ -265,10 +252,9 @@ STObject::set(SerialIter& sit, int depth) // duplicate fields. This is a key invariant: auto const sf = getSortedFields(*this, withAllFields); - auto const dup = std::adjacent_find( - sf.cbegin(), sf.cend(), [](STBase const* lhs, STBase const* rhs) { - return lhs->getFName() == rhs->getFName(); - }); + auto const dup = std::adjacent_find(sf.cbegin(), sf.cend(), [](STBase const* lhs, STBase const* rhs) { + return lhs->getFName() == rhs->getFName(); + }); if (dup != sf.cend()) Throw("Duplicate field detected"); @@ -347,29 +333,17 @@ STObject::isEquivalent(STBase const& t) const if (mType != nullptr && v->mType == mType) { - return std::equal( - begin(), - end(), - v->begin(), - v->end(), - [](STBase const& st1, STBase const& st2) { - return (st1.getSType() == st2.getSType()) && - st1.isEquivalent(st2); - }); + return std::equal(begin(), end(), v->begin(), v->end(), [](STBase const& st1, STBase const& st2) { + return (st1.getSType() == st2.getSType()) && st1.isEquivalent(st2); + }); } auto const sf1 = getSortedFields(*this, withAllFields); auto const sf2 = getSortedFields(*v, withAllFields); - return std::equal( - sf1.begin(), - sf1.end(), - sf2.begin(), - sf2.end(), - [](STBase const* st1, STBase const* st2) { - return (st1->getSType() == st2->getSType()) && - st1->isEquivalent(*st2); - }); + return std::equal(sf1.begin(), sf1.end(), sf2.begin(), sf2.end(), [](STBase const* st1, STBase const* st2) { + return (st1->getSType() == st2->getSType()) && st1->isEquivalent(*st2); + }); } uint256 @@ -580,6 +554,12 @@ STObject::delField(int index) v_.erase(v_.begin() + index); } +SOEStyle +STObject::getStyle(SField const& field) const +{ + return mType ? mType->style(field) : soeINVALID; +} + unsigned char STObject::getFieldU8(SField const& field) const { @@ -891,8 +871,7 @@ STObject::add(Serializer& s, WhichFields whichFields) const { // Depending on whichFields, signing fields are either serialized or // not. Then fields are added to the Serializer sorted by fieldCode. - std::vector const fields{ - getSortedFields(*this, whichFields)}; + std::vector const fields{getSortedFields(*this, whichFields)}; // insert sorted for (STBase const* const field : fields) @@ -902,8 +881,7 @@ STObject::add(Serializer& s, WhichFields whichFields) const // must be OBJECT, or the object cannot be deserialized SerializedTypeID const sType{field->getSType()}; XRPL_ASSERT( - (sType != STI_OBJECT) || - (field->getFName().fieldType == STI_OBJECT), + (sType != STI_OBJECT) || (field->getFName().fieldType == STI_OBJECT), "xrpl::STObject::add : valid field type"); field->addFieldID(s); field->add(s); @@ -922,8 +900,7 @@ STObject::getSortedFields(STObject const& objToSort, WhichFields whichFields) for (detail::STVar const& elem : objToSort.v_) { STBase const& base = elem.get(); - if ((base.getSType() != STI_NOTPRESENT) && - base.getFName().shouldInclude(whichFields)) + if ((base.getSType() != STI_NOTPRESENT) && base.getFName().shouldInclude(whichFields)) { sf.push_back(&base); } diff --git a/src/libxrpl/protocol/STParsedJSON.cpp b/src/libxrpl/protocol/STParsedJSON.cpp index 34c8b70e45..878f6c3605 100644 --- a/src/libxrpl/protocol/STParsedJSON.cpp +++ b/src/libxrpl/protocol/STParsedJSON.cpp @@ -45,9 +45,8 @@ namespace xrpl { namespace STParsedJSONDetail { template -constexpr std:: - enable_if_t::value && std::is_signed::value, U> - to_unsigned(S value) +constexpr std::enable_if_t::value && std::is_signed::value, U> +to_unsigned(S value) { if (value < 0 || std::numeric_limits::max() < value) Throw("Value out of range"); @@ -55,9 +54,8 @@ constexpr std:: } template -constexpr std:: - enable_if_t::value && std::is_unsigned::value, U1> - to_unsigned(U2 value) +constexpr std::enable_if_t::value && std::is_unsigned::value, U1> +to_unsigned(U2 value) { if (std::numeric_limits::max() < value) Throw("Value out of range"); @@ -77,9 +75,7 @@ make_name(std::string const& object, std::string const& field) static inline Json::Value not_an_object(std::string const& object, std::string const& field) { - return RPC::make_error( - rpcINVALID_PARAMS, - "Field '" + make_name(object, field) + "' is not a JSON object."); + return RPC::make_error(rpcINVALID_PARAMS, "Field '" + make_name(object, field) + "' is not a JSON object."); } static inline Json::Value @@ -91,40 +87,31 @@ not_an_object(std::string const& object) static inline Json::Value not_an_array(std::string const& object) { - return RPC::make_error( - rpcINVALID_PARAMS, "Field '" + object + "' is not a JSON array."); + return RPC::make_error(rpcINVALID_PARAMS, "Field '" + object + "' is not a JSON array."); } static inline Json::Value unknown_field(std::string const& object, std::string const& field) { - return RPC::make_error( - rpcINVALID_PARAMS, - "Field '" + make_name(object, field) + "' is unknown."); + return RPC::make_error(rpcINVALID_PARAMS, "Field '" + make_name(object, field) + "' is unknown."); } static inline Json::Value out_of_range(std::string const& object, std::string const& field) { - return RPC::make_error( - rpcINVALID_PARAMS, - "Field '" + make_name(object, field) + "' is out of range."); + return RPC::make_error(rpcINVALID_PARAMS, "Field '" + make_name(object, field) + "' is out of range."); } static inline Json::Value bad_type(std::string const& object, std::string const& field) { - return RPC::make_error( - rpcINVALID_PARAMS, - "Field '" + make_name(object, field) + "' has bad type."); + return RPC::make_error(rpcINVALID_PARAMS, "Field '" + make_name(object, field) + "' has bad type."); } static inline Json::Value invalid_data(std::string const& object, std::string const& field) { - return RPC::make_error( - rpcINVALID_PARAMS, - "Field '" + make_name(object, field) + "' has invalid data."); + return RPC::make_error(rpcINVALID_PARAMS, "Field '" + make_name(object, field) + "' has invalid data."); } static inline Json::Value @@ -136,25 +123,19 @@ invalid_data(std::string const& object) static inline Json::Value array_expected(std::string const& object, std::string const& field) { - return RPC::make_error( - rpcINVALID_PARAMS, - "Field '" + make_name(object, field) + "' must be a JSON array."); + return RPC::make_error(rpcINVALID_PARAMS, "Field '" + make_name(object, field) + "' must be a JSON array."); } static inline Json::Value string_expected(std::string const& object, std::string const& field) { - return RPC::make_error( - rpcINVALID_PARAMS, - "Field '" + make_name(object, field) + "' must be a string."); + return RPC::make_error(rpcINVALID_PARAMS, "Field '" + make_name(object, field) + "' must be a string."); } static inline Json::Value too_deep(std::string const& object) { - return RPC::make_error( - rpcINVALID_PARAMS, - "Field '" + object + "' exceeds nesting depth limit."); + return RPC::make_error(rpcINVALID_PARAMS, "Field '" + object + "' exceeds nesting depth limit."); } static inline Json::Value @@ -162,17 +143,14 @@ singleton_expected(std::string const& object, unsigned int index) { return RPC::make_error( rpcINVALID_PARAMS, - "Field '" + object + "[" + std::to_string(index) + - "]' must be an object with a single key/object value."); + "Field '" + object + "[" + std::to_string(index) + "]' must be an object with a single key/object value."); } static inline Json::Value template_mismatch(SField const& sField) { return RPC::make_error( - rpcINVALID_PARAMS, - "Object '" + sField.getName() + - "' contents did not meet requirements for that type."); + rpcINVALID_PARAMS, "Object '" + sField.getName() + "' contents did not meet requirements for that type."); } static inline Json::Value @@ -202,21 +180,15 @@ parseUnsigned( if (value.isString()) { ret = detail::make_stvar( - field, - safe_cast( - beast::lexicalCastThrow(value.asString()))); + field, safe_cast(beast::lexicalCastThrow(value.asString()))); } else if (value.isInt()) { - ret = detail::make_stvar( - field, - to_unsigned(value.asInt())); + ret = detail::make_stvar(field, to_unsigned(value.asInt())); } else if (value.isUInt()) { - ret = detail::make_stvar( - field, - to_unsigned(value.asUInt())); + ret = detail::make_stvar(field, to_unsigned(value.asUInt())); } else { @@ -251,17 +223,14 @@ parseUint16( { std::string const strValue = value.asString(); - if (!strValue.empty() && - ((strValue[0] < '0') || (strValue[0] > '9'))) + if (!strValue.empty() && ((strValue[0] < '0') || (strValue[0] > '9'))) { if (field == sfTransactionType) { ret = detail::make_stvar( field, safe_cast( - static_cast( - TxFormats::getInstance().findTypeByName( - strValue)))); + static_cast(TxFormats::getInstance().findTypeByName(strValue)))); if (*name == sfGeneric) name = &sfTransaction; @@ -271,9 +240,7 @@ parseUint16( ret = detail::make_stvar( field, safe_cast( - static_cast( - LedgerFormats::getInstance().findTypeByName( - strValue)))); + static_cast(LedgerFormats::getInstance().findTypeByName(strValue)))); if (*name == sfGeneric) name = &sfLedgerEntry; @@ -286,8 +253,7 @@ parseUint16( } } if (!ret) - return parseUnsigned( - field, json_name, fieldName, name, value, error); + return parseUnsigned(field, json_name, fieldName, name, value, error); } catch (std::exception const&) { @@ -317,33 +283,26 @@ parseUint32( if (field == sfPermissionValue) { std::string const strValue = value.asString(); - auto const granularPermission = - Permission::getInstance().getGranularValue(strValue); + auto const granularPermission = Permission::getInstance().getGranularValue(strValue); if (granularPermission) { - ret = detail::make_stvar( - field, *granularPermission); + ret = detail::make_stvar(field, *granularPermission); } else { - auto const& txType = - TxFormats::getInstance().findTypeByName(strValue); - ret = detail::make_stvar( - field, - Permission::getInstance().txToPermissionType(txType)); + auto const& txType = TxFormats::getInstance().findTypeByName(strValue); + ret = detail::make_stvar(field, Permission::getInstance().txToPermissionType(txType)); } } else { ret = detail::make_stvar( field, - safe_cast( - beast::lexicalCastThrow(value.asString()))); + safe_cast(beast::lexicalCastThrow(value.asString()))); } } if (!ret) - return parseUnsigned( - field, json_name, fieldName, name, value, error); + return parseUnsigned(field, json_name, fieldName, name, value, error); } catch (std::exception const&) { @@ -382,31 +341,25 @@ parseLeaf( case STI_UINT8: try { - constexpr auto minValue = - std::numeric_limits::min(); - constexpr auto maxValue = - std::numeric_limits::max(); + constexpr auto minValue = std::numeric_limits::min(); + constexpr auto maxValue = std::numeric_limits::max(); if (value.isString()) { std::string const strValue = value.asString(); - if (!strValue.empty() && - ((strValue[0] < '0') || (strValue[0] > '9'))) + if (!strValue.empty() && ((strValue[0] < '0') || (strValue[0] > '9'))) { if (field == sfTransactionResult) { auto ter = transCode(strValue); - if (!ter || TERtoInt(*ter) < minValue || - TERtoInt(*ter) > maxValue) + if (!ter || TERtoInt(*ter) < minValue || TERtoInt(*ter) > maxValue) { error = out_of_range(json_name, fieldName); return ret; } - ret = detail::make_stvar( - field, - static_cast(TERtoInt(*ter))); + ret = detail::make_stvar(field, static_cast(TERtoInt(*ter))); } else { @@ -416,9 +369,7 @@ parseLeaf( } else { - ret = detail::make_stvar( - field, - beast::lexicalCastThrow(strValue)); + ret = detail::make_stvar(field, beast::lexicalCastThrow(strValue)); } } else if (value.isInt()) @@ -429,8 +380,7 @@ parseLeaf( return ret; } - ret = detail::make_stvar( - field, static_cast(value.asInt())); + ret = detail::make_stvar(field, static_cast(value.asInt())); } else if (value.isUInt()) { @@ -440,8 +390,7 @@ parseLeaf( return ret; } - ret = detail::make_stvar( - field, static_cast(value.asUInt())); + ret = detail::make_stvar(field, static_cast(value.asUInt())); } else { @@ -457,16 +406,14 @@ parseLeaf( break; case STI_UINT16: - ret = parseUint16( - field, json_name, fieldName, name, value, error); + ret = parseUint16(field, json_name, fieldName, name, value, error); if (!ret) return ret; break; case STI_UINT32: - ret = parseUint32( - field, json_name, fieldName, name, value, error); + ret = parseUint32(field, json_name, fieldName, name, value, error); if (!ret) return ret; @@ -481,15 +428,10 @@ parseLeaf( std::uint64_t val; - bool const useBase10 = - field.shouldMeta(SField::sMD_BaseTen); + bool const useBase10 = field.shouldMeta(SField::sMD_BaseTen); // if the field is amount, serialize as base 10 - auto [p, ec] = std::from_chars( - str.data(), - str.data() + str.size(), - val, - useBase10 ? 10 : 16); + auto [p, ec] = std::from_chars(str.data(), str.data() + str.size(), val, useBase10 ? 10 : 16); if (ec != std::errc() || (p != str.data() + str.size())) Throw("invalid data"); @@ -498,13 +440,11 @@ parseLeaf( } else if (value.isInt()) { - ret = detail::make_stvar( - field, to_unsigned(value.asInt())); + ret = detail::make_stvar(field, to_unsigned(value.asInt())); } else if (value.isUInt()) { - ret = detail::make_stvar( - field, safe_cast(value.asUInt())); + ret = detail::make_stvar(field, safe_cast(value.asUInt())); } else { @@ -621,32 +561,25 @@ parseLeaf( { if (value.isString()) { - ret = detail::make_stvar( - field, - beast::lexicalCastThrow( - value.asString())); + ret = detail::make_stvar(field, beast::lexicalCastThrow(value.asString())); } else if (value.isInt()) { // future-proofing - a static assert failure if the JSON // library ever supports larger ints // In such case, we will need additional bounds checks here - static_assert( - std::is_same_v); + static_assert(std::is_same_v); ret = detail::make_stvar(field, value.asInt()); } else if (value.isUInt()) { auto const uintValue = value.asUInt(); - if (uintValue > - static_cast( - std::numeric_limits::max())) + if (uintValue > static_cast(std::numeric_limits::max())) { error = out_of_range(json_name, fieldName); return ret; } - ret = detail::make_stvar( - field, static_cast(uintValue)); + ret = detail::make_stvar(field, static_cast(uintValue)); } else { @@ -673,8 +606,7 @@ parseLeaf( { if (auto vBlob = strUnHex(value.asString())) { - ret = detail::make_stvar( - field, vBlob->data(), vBlob->size()); + ret = detail::make_stvar(field, vBlob->data(), vBlob->size()); } else { @@ -692,8 +624,7 @@ parseLeaf( case STI_AMOUNT: try { - ret = - detail::make_stvar(amountFromJson(field, value)); + ret = detail::make_stvar(amountFromJson(field, value)); } catch (std::exception const&) { @@ -706,8 +637,7 @@ parseLeaf( case STI_NUMBER: try { - ret = - detail::make_stvar(numberFromJson(field, value)); + ret = detail::make_stvar(numberFromJson(field, value)); } catch (std::exception const&) { @@ -771,8 +701,7 @@ parseLeaf( { std::stringstream ss; ss << fieldName << "[" << i << "][" << j << "]"; - std::string const element_name( - json_name + "." + ss.str()); + std::string const element_name(json_name + "." + ss.str()); // each element in this path has some combination of // account, currency, or issuer @@ -803,8 +732,7 @@ parseLeaf( // human account id if (!account.isString()) { - error = - string_expected(element_name, "account"); + error = string_expected(element_name, "account"); return ret; } @@ -812,12 +740,10 @@ parseLeaf( // we set it, otherwise, we assume it's an AccountID if (!uAccount.parseHex(account.asString())) { - auto const a = - parseBase58(account.asString()); + auto const a = parseBase58(account.asString()); if (!a) { - error = - invalid_data(element_name, "account"); + error = invalid_data(element_name, "account"); return ret; } uAccount = *a; @@ -829,8 +755,7 @@ parseLeaf( // human currency if (!currency.isString()) { - error = - string_expected(element_name, "currency"); + error = string_expected(element_name, "currency"); return ret; } @@ -838,11 +763,9 @@ parseLeaf( if (!uCurrency.parseHex(currency.asString())) { - if (!to_currency( - uCurrency, currency.asString())) + if (!to_currency(uCurrency, currency.asString())) { - error = - invalid_data(element_name, "currency"); + error = invalid_data(element_name, "currency"); return ret; } } @@ -859,20 +782,17 @@ parseLeaf( if (!uIssuer.parseHex(issuer.asString())) { - auto const a = - parseBase58(issuer.asString()); + auto const a = parseBase58(issuer.asString()); if (!a) { - error = - invalid_data(element_name, "issuer"); + error = invalid_data(element_name, "issuer"); return ret; } uIssuer = *a; } } - p.emplace_back( - uAccount, uCurrency, uIssuer, hasCurrency); + p.emplace_back(uAccount, uCurrency, uIssuer, hasCurrency); } tail.push_back(p); @@ -930,8 +850,7 @@ parseLeaf( case STI_XCHAIN_BRIDGE: try { - ret = detail::make_stvar( - STXChainBridge(field, value)); + ret = detail::make_stvar(STXChainBridge(field, value)); } catch (std::exception const&) { @@ -943,8 +862,7 @@ parseLeaf( case STI_CURRENCY: try { - ret = detail::make_stvar( - currencyFromJson(field, value)); + ret = detail::make_stvar(currencyFromJson(field, value)); } catch (std::exception const&) { @@ -965,20 +883,10 @@ static int const maxDepth = 64; // Forward declaration since parseObject() and parseArray() call each other. static std::optional -parseArray( - std::string const& json_name, - Json::Value const& json, - SField const& inName, - int depth, - Json::Value& error); +parseArray(std::string const& json_name, Json::Value const& json, SField const& inName, int depth, Json::Value& error); static std::optional -parseObject( - std::string const& json_name, - Json::Value const& json, - SField const& inName, - int depth, - Json::Value& error) +parseObject(std::string const& json_name, Json::Value const& json, SField const& inName, int depth, Json::Value& error) { if (!json.isObjectOrNull()) { @@ -1023,12 +931,7 @@ parseObject( try { - auto ret = parseObject( - json_name + "." + fieldName, - value, - field, - depth + 1, - error); + auto ret = parseObject(json_name + "." + fieldName, value, field, depth + 1, error); if (!ret) return std::nullopt; data.emplace_back(std::move(*ret)); @@ -1045,12 +948,7 @@ parseObject( case STI_ARRAY: try { - auto array = parseArray( - json_name + "." + fieldName, - value, - field, - depth + 1, - error); + auto array = parseArray(json_name + "." + fieldName, value, field, depth + 1, error); if (!array.has_value()) return std::nullopt; data.emplace_back(std::move(*array)); @@ -1065,8 +963,7 @@ parseObject( // Everything else (types that don't recurse). default: { - auto leaf = - parseLeaf(json_name, fieldName, &inName, value, error); + auto leaf = parseLeaf(json_name, fieldName, &inName, value, error); if (!leaf) return std::nullopt; @@ -1096,12 +993,7 @@ parseObject( } static std::optional -parseArray( - std::string const& json_name, - Json::Value const& json, - SField const& inName, - int depth, - Json::Value& error) +parseArray(std::string const& json_name, Json::Value const& json, SField const& inName, int depth, Json::Value& error) { if (!json.isArrayOrNull()) { @@ -1149,13 +1041,11 @@ parseArray( std::stringstream ss; ss << json_name << "." << "[" << i << "]." << objectName; - auto ret = parseObject( - ss.str(), objectFields, nameField, depth + 1, error); + auto ret = parseObject(ss.str(), objectFields, nameField, depth + 1, error); if (!ret) { std::string errMsg = error["error_message"].asString(); - error["error_message"] = - "Error at '" + ss.str() + "'. " + errMsg; + error["error_message"] = "Error at '" + ss.str() + "'. " + errMsg; return std::nullopt; } @@ -1182,9 +1072,7 @@ parseArray( //------------------------------------------------------------------------------ -STParsedJSONObject::STParsedJSONObject( - std::string const& name, - Json::Value const& json) +STParsedJSONObject::STParsedJSONObject(std::string const& name, Json::Value const& json) { using namespace STParsedJSONDetail; object = parseObject(name, json, sfGeneric, 0, error); diff --git a/src/libxrpl/protocol/STPathSet.cpp b/src/libxrpl/protocol/STPathSet.cpp index 631fd51d8a..060f5c4d7c 100644 --- a/src/libxrpl/protocol/STPathSet.cpp +++ b/src/libxrpl/protocol/STPathSet.cpp @@ -47,8 +47,7 @@ STPathSet::STPathSet(SerialIter& sit, SField const& name) : STBase(name) { int iType = sit.get8(); - if (iType == STPathElement::typeNone || - iType == STPathElement::typeBoundary) + if (iType == STPathElement::typeNone || iType == STPathElement::typeBoundary) { if (path.empty()) { @@ -64,8 +63,7 @@ STPathSet::STPathSet(SerialIter& sit, SField const& name) : STBase(name) } else if (iType & ~STPathElement::typeAll) { - JLOG(debugLog().error()) - << "Bad path element " << iType << " in pathset"; + JLOG(debugLog().error()) << "Bad path element " << iType << " in pathset"; Throw("bad path element"); } else @@ -139,15 +137,11 @@ STPathSet::isDefault() const } bool -STPath::hasSeen( - AccountID const& account, - Currency const& currency, - AccountID const& issuer) const +STPath::hasSeen(AccountID const& account, Currency const& currency, AccountID const& issuer) const { for (auto& p : mPath) { - if (p.getAccountID() == account && p.getCurrency() == currency && - p.getIssuerID() == issuer) + if (p.getAccountID() == account && p.getCurrency() == currency && p.getIssuerID() == issuer) return true; } @@ -200,11 +194,8 @@ STPathSet::getSType() const void STPathSet::add(Serializer& s) const { - XRPL_ASSERT( - getFName().isBinary(), "xrpl::STPathSet::add : field is binary"); - XRPL_ASSERT( - getFName().fieldType == STI_PATHSET, - "xrpl::STPathSet::add : valid field type"); + XRPL_ASSERT(getFName().isBinary(), "xrpl::STPathSet::add : field is binary"); + XRPL_ASSERT(getFName().fieldType == STI_PATHSET, "xrpl::STPathSet::add : valid field type"); bool first = true; for (auto const& spPath : value) diff --git a/src/libxrpl/protocol/STTakesAsset.cpp b/src/libxrpl/protocol/STTakesAsset.cpp index d43e7b04a1..ba57f4f2a8 100644 --- a/src/libxrpl/protocol/STTakesAsset.cpp +++ b/src/libxrpl/protocol/STTakesAsset.cpp @@ -18,10 +18,22 @@ associateAsset(SLE& sle, Asset const& asset) // If the field is not set or present, skip it. if (type == STI_NOTPRESENT) continue; + // If the type doesn't downcast, then the flag shouldn't be on the // SField auto& ta = entry.downcast(); + auto const style = sle.getStyle(ta.getFName()); + XRPL_ASSERT_PARTS(style != soeINVALID, "xrpl::associateAsset", "valid template element style"); + + XRPL_ASSERT_PARTS(style != soeDEFAULT || !ta.isDefault(), "xrpl::associateAsset", "non-default value"); ta.associateAsset(asset); + + // associateAsset in derived classes may change the underlying + // value, but it won't know anything about how the value relates to + // the SLE. If the template element is soeDEFAULT, and the value + // changed to the default value, remove the field. + if (style == soeDEFAULT && ta.isDefault()) + sle.makeFieldAbsent(field); } } } diff --git a/src/libxrpl/protocol/STTx.cpp b/src/libxrpl/protocol/STTx.cpp index 6640468bd4..5dea8be56d 100644 --- a/src/libxrpl/protocol/STTx.cpp +++ b/src/libxrpl/protocol/STTx.cpp @@ -61,8 +61,7 @@ getTxFormat(TxType type) if (format == nullptr) { Throw( - "Invalid transaction type " + - std::to_string(safe_cast>(type))); + "Invalid transaction type " + std::to_string(safe_cast>(type))); } return format; @@ -91,8 +90,7 @@ STTx::STTx(SerialIter& sit) : STObject(sfTransaction) tid_ = getHash(HashPrefix::transactionID); } -STTx::STTx(TxType type, std::function assembler) - : STObject(sfTransaction) +STTx::STTx(TxType type, std::function assembler) : STObject(sfTransaction) { auto format = getTxFormat(type); @@ -148,9 +146,7 @@ STTx::getMentionedAccounts() const { if (auto sacc = dynamic_cast(&it)) { - XRPL_ASSERT( - !sacc->isDefault(), - "xrpl::STTx::getMentionedAccounts : account is set"); + XRPL_ASSERT(!sacc->isDefault(), "xrpl::STTx::getMentionedAccounts : account is set"); if (!sacc->isDefault()) list.insert(sacc->value()); } @@ -246,8 +242,7 @@ STTx::checkSign(Rules const& rules, STObject const& sigObject) const // multi-signing. Otherwise we're single-signing. Blob const& signingPubKey = sigObject.getFieldVL(sfSigningPubKey); - return signingPubKey.empty() ? checkMultiSign(rules, sigObject) - : checkSingleSign(sigObject); + return signingPubKey.empty() ? checkMultiSign(rules, sigObject) : checkSingleSign(sigObject); } catch (std::exception const&) { @@ -275,9 +270,7 @@ STTx::checkBatchSign(Rules const& rules) const { try { - XRPL_ASSERT( - getTxnType() == ttBATCH, - "STTx::checkBatchSign : not a batch transaction"); + XRPL_ASSERT(getTxnType() == ttBATCH, "STTx::checkBatchSign : not a batch transaction"); if (getTxnType() != ttBATCH) { JLOG(debugLog().fatal()) << "not a batch transaction"; @@ -287,9 +280,8 @@ STTx::checkBatchSign(Rules const& rules) const for (auto const& signer : signers) { Blob const& signingPubKey = signer.getFieldVL(sfSigningPubKey); - auto const result = signingPubKey.empty() - ? checkBatchMultiSign(signer, rules) - : checkBatchSingleSign(signer); + auto const result = + signingPubKey.empty() ? checkBatchMultiSign(signer, rules) : checkBatchSingleSign(signer); if (!result) return result; @@ -298,8 +290,7 @@ STTx::checkBatchSign(Rules const& rules) const } catch (std::exception const& e) { - JLOG(debugLog().error()) - << "Batch signature check failed: " << e.what(); + JLOG(debugLog().error()) << "Batch signature check failed: " << e.what(); } return Unexpected("Internal batch signature check failure."); } @@ -354,8 +345,7 @@ STTx::getMetaSQLInsertReplaceHeader() } std::string -STTx::getMetaSQL(std::uint32_t inLedger, std::string const& escapedMetaData) - const +STTx::getMetaSQL(std::uint32_t inLedger, std::string const& escapedMetaData) const { Serializer s; add(s); @@ -364,22 +354,16 @@ STTx::getMetaSQL(std::uint32_t inLedger, std::string const& escapedMetaData) // VFALCO This could be a free function elsewhere std::string -STTx::getMetaSQL( - Serializer rawTxn, - std::uint32_t inLedger, - char status, - std::string const& escapedMetaData) const +STTx::getMetaSQL(Serializer rawTxn, std::uint32_t inLedger, char status, std::string const& escapedMetaData) const { - static boost::format bfTrans( - "('%s', '%s', '%s', '%d', '%d', '%c', %s, %s)"); + static boost::format bfTrans("('%s', '%s', '%s', '%d', '%d', '%c', %s, %s)"); std::string rTxn = sqlBlobLiteral(rawTxn.peekData()); auto format = TxFormats::getInstance().findByType(tx_type_); XRPL_ASSERT(format, "xrpl::STTx::getMetaSQL : non-null type format"); return str( - boost::format(bfTrans) % to_string(getTransactionID()) % - format->getName() % toBase58(getAccountID(sfAccount)) % + boost::format(bfTrans) % to_string(getTransactionID()) % format->getName() % toBase58(getAccountID(sfAccount)) % getFieldU32(sfSequence) % inLedger % status % rTxn % escapedMetaData); } @@ -399,8 +383,7 @@ singleSignHelper(STObject const& sigObject, Slice const& data) if (publicKeyType(makeSlice(spk))) { Blob const signature = sigObject.getFieldVL(sfTxnSignature); - validSig = - verify(PublicKey(makeSlice(spk)), data, makeSlice(signature)); + validSig = verify(PublicKey(makeSlice(spk)), data, makeSlice(signature)); } } catch (std::exception const&) @@ -449,8 +432,7 @@ multiSignHelper( STArray const& signers{sigObject.getFieldArray(sfSigners)}; // There are well known bounds that the number of signers must be within. - if (signers.size() < STTx::minMultiSigners || - signers.size() > STTx::maxMultiSigners) + if (signers.size() < STTx::minMultiSigners || signers.size() > STTx::maxMultiSigners) return Unexpected("Invalid Signers array size."); // Signers must be in sorted order by AccountID. @@ -486,10 +468,7 @@ multiSignHelper( if (publicKeyType(makeSlice(spk))) { Blob const signature = signer.getFieldVL(sfTxnSignature); - validSig = verify( - PublicKey(makeSlice(spk)), - makeMsg(accountID).slice(), - makeSlice(signature)); + validSig = verify(PublicKey(makeSlice(spk)), makeMsg(accountID).slice(), makeSlice(signature)); } } catch (std::exception const& e) @@ -500,8 +479,7 @@ multiSignHelper( } if (!validSig) return Unexpected( - std::string("Invalid signature on account ") + - toBase58(accountID) + errorWhat.value_or("") + "."); + std::string("Invalid signature on account ") + toBase58(accountID) + errorWhat.value_or("") + "."); } // All signatures verified. return {}; @@ -531,9 +509,7 @@ STTx::checkMultiSign(Rules const& rules, STObject const& sigObject) const { // Used inside the loop in multiSignHelper to enforce that // the account owner may not multisign for themselves. - auto const txnAccountID = &sigObject != this - ? std::nullopt - : std::optional(getAccountID(sfAccount)); + auto const txnAccountID = &sigObject != this ? std::nullopt : std::optional(getAccountID(sfAccount)); // We can ease the computational load inside the loop a bit by // pre-constructing part of the data that we hash. Fill a Serializer @@ -568,12 +544,8 @@ STTx::checkMultiSign(Rules const& rules, STObject const& sigObject) const std::vector const& STTx::getBatchTransactionIDs() const { - XRPL_ASSERT( - getTxnType() == ttBATCH, - "STTx::getBatchTransactionIDs : not a batch transaction"); - XRPL_ASSERT( - getFieldArray(sfRawTransactions).size() != 0, - "STTx::getBatchTransactionIDs : empty raw transactions"); + XRPL_ASSERT(getTxnType() == ttBATCH, "STTx::getBatchTransactionIDs : not a batch transaction"); + XRPL_ASSERT(getFieldArray(sfRawTransactions).size() != 0, "STTx::getBatchTransactionIDs : empty raw transactions"); // The list of inner ids is built once, then reused on subsequent calls. // After the list is built, it must always have the same size as the array @@ -626,8 +598,7 @@ isMemoOkay(STObject const& st, std::string& reason) { auto const& name = memoElement.getFName(); - if (name != sfMemoType && name != sfMemoData && - name != sfMemoFormat) + if (name != sfMemoType && name != sfMemoData && name != sfMemoFormat) { reason = "A memo may contain only MemoType, MemoData or " @@ -703,18 +674,15 @@ invalidMPTAmountInTx(STObject const& tx) auto const txType = tx[~sfTransactionType]; if (!txType) return false; - if (auto const* item = - TxFormats::getInstance().findByType(safe_cast(*txType))) + if (auto const* item = TxFormats::getInstance().findByType(safe_cast(*txType))) { for (auto const& e : item->getSOTemplate()) { if (tx.isFieldPresent(e.sField()) && e.supportMPT() != soeMPTNone) { if (auto const& field = tx.peekAtField(e.sField()); - (field.getSType() == STI_AMOUNT && - static_cast(field).holds()) || - (field.getSType() == STI_ISSUE && - static_cast(field).holds())) + (field.getSType() == STI_AMOUNT && static_cast(field).holds()) || + (field.getSType() == STI_ISSUE && static_cast(field).holds())) { if (e.supportMPT() != soeMPTSupported) return true; @@ -731,8 +699,7 @@ isRawTransactionOkay(STObject const& st, std::string& reason) if (!st.isFieldPresent(sfRawTransactions)) return true; - if (st.isFieldPresent(sfBatchSigners) && - st.getFieldArray(sfBatchSigners).size() > maxBatchTxCount) + if (st.isFieldPresent(sfBatchSigners) && st.getFieldArray(sfBatchSigners).size() > maxBatchTxCount) { reason = "Batch Signers array exceeds max entries."; return false; @@ -748,8 +715,7 @@ isRawTransactionOkay(STObject const& st, std::string& reason) { try { - TxType const tt = - safe_cast(raw.getFieldU16(sfTransactionType)); + TxType const tt = safe_cast(raw.getFieldU16(sfTransactionType)); if (tt == ttBATCH) { reason = "Raw Transactions may not contain batch transactions."; diff --git a/src/libxrpl/protocol/STValidation.cpp b/src/libxrpl/protocol/STValidation.cpp index f6f89d43e9..2bea078809 100644 --- a/src/libxrpl/protocol/STValidation.cpp +++ b/src/libxrpl/protocol/STValidation.cpp @@ -100,14 +100,10 @@ STValidation::isValid() const noexcept if (!valid_) { XRPL_ASSERT( - publicKeyType(getSignerPublic()) == KeyType::secp256k1, - "xrpl::STValidation::isValid : valid key type"); + publicKeyType(getSignerPublic()) == KeyType::secp256k1, "xrpl::STValidation::isValid : valid key type"); valid_ = verifyDigest( - getSignerPublic(), - getSigningHash(), - makeSlice(getFieldVL(sfSignature)), - getFlags() & vfFullyCanonicalSig); + getSignerPublic(), getSigningHash(), makeSlice(getFieldVL(sfSignature)), getFlags() & vfFullyCanonicalSig); } return valid_.value(); diff --git a/src/libxrpl/protocol/STVar.cpp b/src/libxrpl/protocol/STVar.cpp index e0df5d51a9..d77aabc312 100644 --- a/src/libxrpl/protocol/STVar.cpp +++ b/src/libxrpl/protocol/STVar.cpp @@ -93,8 +93,7 @@ STVar::STVar(defaultObject_t, SField const& name) : STVar(name.fieldType, name) { } -STVar::STVar(nonPresentObject_t, SField const& name) - : STVar(STI_NOTPRESENT, name) +STVar::STVar(nonPresentObject_t, SField const& name) : STVar(STI_NOTPRESENT, name) { } @@ -130,22 +129,17 @@ void STVar::constructST(SerializedTypeID id, int depth, Args&&... args) { auto constructWithDepth = [&]() { - if constexpr (std::is_same_v< - std::tuple...>, - std::tuple>) + if constexpr (std::is_same_v...>, std::tuple>) { construct(std::forward(args)...); } - else if constexpr (std::is_same_v< - std::tuple...>, - std::tuple>) + else if constexpr (std::is_same_v...>, std::tuple>) { construct(std::forward(args)..., depth); } else { - constexpr bool alwaysFalse = - !std::is_same_v, std::tuple>; + constexpr bool alwaysFalse = !std::is_same_v, std::tuple>; static_assert(alwaysFalse, "Invalid STVar constructor arguments"); } }; @@ -154,8 +148,7 @@ STVar::constructST(SerializedTypeID id, int depth, Args&&... args) { case STI_NOTPRESENT: { // Last argument is always SField - SField const& field = - std::get(std::forward_as_tuple(args...)); + SField const& field = std::get(std::forward_as_tuple(args...)); construct(field); return; } diff --git a/src/libxrpl/protocol/STVector256.cpp b/src/libxrpl/protocol/STVector256.cpp index 17b4895b62..312184dcc0 100644 --- a/src/libxrpl/protocol/STVector256.cpp +++ b/src/libxrpl/protocol/STVector256.cpp @@ -19,9 +19,7 @@ STVector256::STVector256(SerialIter& sit, SField const& name) : STBase(name) auto const slice = sit.getSlice(sit.getVLDataLength()); if (slice.size() % uint256::size() != 0) - Throw( - "Bad serialization for STVector256: " + - std::to_string(slice.size())); + Throw("Bad serialization for STVector256: " + std::to_string(slice.size())); auto const cnt = slice.size() / uint256::size(); @@ -58,11 +56,8 @@ STVector256::isDefault() const void STVector256::add(Serializer& s) const { - XRPL_ASSERT( - getFName().isBinary(), "xrpl::STVector256::add : field is binary"); - XRPL_ASSERT( - getFName().fieldType == STI_VECTOR256, - "xrpl::STVector256::add : valid field type"); + XRPL_ASSERT(getFName().isBinary(), "xrpl::STVector256::add : field is binary"); + XRPL_ASSERT(getFName().fieldType == STI_VECTOR256, "xrpl::STVector256::add : valid field type"); s.addVL(mValue.begin(), mValue.end(), mValue.size() * (256 / 8)); } diff --git a/src/libxrpl/protocol/STXChainBridge.cpp b/src/libxrpl/protocol/STXChainBridge.cpp index 413094b0cd..ed79c28f29 100644 --- a/src/libxrpl/protocol/STXChainBridge.cpp +++ b/src/libxrpl/protocol/STXChainBridge.cpp @@ -50,30 +50,25 @@ STXChainBridge::STXChainBridge(STObject const& o) { } -STXChainBridge::STXChainBridge(Json::Value const& v) - : STXChainBridge{sfXChainBridge, v} +STXChainBridge::STXChainBridge(Json::Value const& v) : STXChainBridge{sfXChainBridge, v} { } -STXChainBridge::STXChainBridge(SField const& name, Json::Value const& v) - : STBase{name} +STXChainBridge::STXChainBridge(SField const& name, Json::Value const& v) : STBase{name} { if (!v.isObject()) { - Throw( - "STXChainBridge can only be specified with a 'object' Json value"); + Throw("STXChainBridge can only be specified with a 'object' Json value"); } auto checkExtra = [](Json::Value const& v) { - static auto const bridgeJson = - xrpl::STXChainBridge().getJson(xrpl::JsonOptions::none); + static auto const bridgeJson = xrpl::STXChainBridge().getJson(xrpl::JsonOptions::none); for (auto it = v.begin(); it != v.end(); ++it) { std::string const name = it.memberName(); if (!bridgeJson.isMember(name)) { - Throw( - "STXChainBridge extra field detected: " + name); + Throw("STXChainBridge extra field detected: " + name); } } return true; @@ -87,36 +82,28 @@ STXChainBridge::STXChainBridge(SField const& name, Json::Value const& v) if (!lockingChainDoorStr.isString()) { - Throw( - "STXChainBridge LockingChainDoor must be a string Json value"); + Throw("STXChainBridge LockingChainDoor must be a string Json value"); } if (!issuingChainDoorStr.isString()) { - Throw( - "STXChainBridge IssuingChainDoor must be a string Json value"); + Throw("STXChainBridge IssuingChainDoor must be a string Json value"); } - auto const lockingChainDoor = - parseBase58(lockingChainDoorStr.asString()); - auto const issuingChainDoor = - parseBase58(issuingChainDoorStr.asString()); + auto const lockingChainDoor = parseBase58(lockingChainDoorStr.asString()); + auto const issuingChainDoor = parseBase58(issuingChainDoorStr.asString()); if (!lockingChainDoor) { - Throw( - "STXChainBridge LockingChainDoor must be a valid account"); + Throw("STXChainBridge LockingChainDoor must be a valid account"); } if (!issuingChainDoor) { - Throw( - "STXChainBridge IssuingChainDoor must be a valid account"); + Throw("STXChainBridge IssuingChainDoor must be a valid account"); } lockingChainDoor_ = STAccount{sfLockingChainDoor, *lockingChainDoor}; - lockingChainIssue_ = - STIssue{sfLockingChainIssue, issueFromJson(lockingChainIssue)}; + lockingChainIssue_ = STIssue{sfLockingChainIssue, issueFromJson(lockingChainIssue)}; issuingChainDoor_ = STAccount{sfIssuingChainDoor, *issuingChainDoor}; - issuingChainIssue_ = - STIssue{sfIssuingChainIssue, issueFromJson(issuingChainIssue)}; + issuingChainIssue_ = STIssue{sfIssuingChainIssue, issueFromJson(issuingChainIssue)}; } STXChainBridge::STXChainBridge(SerialIter& sit, SField const& name) @@ -152,11 +139,10 @@ std::string STXChainBridge::getText() const { return str( - boost::format("{ %s = %s, %s = %s, %s = %s, %s = %s }") % - sfLockingChainDoor.getName() % lockingChainDoor_.getText() % - sfLockingChainIssue.getName() % lockingChainIssue_.getText() % - sfIssuingChainDoor.getName() % issuingChainDoor_.getText() % - sfIssuingChainIssue.getName() % issuingChainIssue_.getText()); + boost::format("{ %s = %s, %s = %s, %s = %s, %s = %s }") % sfLockingChainDoor.getName() % + lockingChainDoor_.getText() % sfLockingChainIssue.getName() % lockingChainIssue_.getText() % + sfIssuingChainDoor.getName() % issuingChainDoor_.getText() % sfIssuingChainIssue.getName() % + issuingChainIssue_.getText()); } STObject @@ -186,8 +172,8 @@ STXChainBridge::isEquivalent(STBase const& t) const bool STXChainBridge::isDefault() const { - return lockingChainDoor_.isDefault() && lockingChainIssue_.isDefault() && - issuingChainDoor_.isDefault() && issuingChainIssue_.isDefault(); + return lockingChainDoor_.isDefault() && lockingChainIssue_.isDefault() && issuingChainDoor_.isDefault() && + issuingChainIssue_.isDefault(); } std::unique_ptr diff --git a/src/libxrpl/protocol/SecretKey.cpp b/src/libxrpl/protocol/SecretKey.cpp index 2507269407..ee112b9072 100644 --- a/src/libxrpl/protocol/SecretKey.cpp +++ b/src/libxrpl/protocol/SecretKey.cpp @@ -156,22 +156,16 @@ private: } public: - explicit Generator(Seed const& seed) - : root_(deriveDeterministicRootKey(seed)) + explicit Generator(Seed const& seed) : root_(deriveDeterministicRootKey(seed)) { secp256k1_pubkey pubkey; - if (secp256k1_ec_pubkey_create( - secp256k1Context(), &pubkey, root_.data()) != 1) + if (secp256k1_ec_pubkey_create(secp256k1Context(), &pubkey, root_.data()) != 1) LogicError("derivePublicKey: secp256k1_ec_pubkey_create failed"); auto len = generator_.size(); if (secp256k1_ec_pubkey_serialize( - secp256k1Context(), - generator_.data(), - &len, - &pubkey, - SECP256K1_EC_COMPRESSED) != 1) + secp256k1Context(), generator_.data(), &len, &pubkey, SECP256K1_EC_COMPRESSED) != 1) LogicError("derivePublicKey: secp256k1_ec_pubkey_serialize failed"); } @@ -189,8 +183,7 @@ public: auto gsk = [this, tweak = calculateTweak(ordinal)]() { auto rpk = root_; - if (secp256k1_ec_seckey_tweak_add( - secp256k1Context(), rpk.data(), tweak.data()) == 1) + if (secp256k1_ec_seckey_tweak_add(secp256k1Context(), rpk.data(), tweak.data()) == 1) { SecretKey sk{Slice{rpk.data(), rpk.size()}}; secure_erase(rpk.data(), rpk.size()); @@ -225,8 +218,7 @@ signDigest(PublicKey const& pk, SecretKey const& sk, uint256 const& digest) unsigned char sig[72]; size_t len = sizeof(sig); - if (secp256k1_ecdsa_signature_serialize_der( - secp256k1Context(), sig, &len, &sig_imp) != 1) + if (secp256k1_ecdsa_signature_serialize_der(secp256k1Context(), sig, &len, &sig_imp) != 1) LogicError("sign: secp256k1_ecdsa_signature_serialize_der failed"); return Buffer{sig, len}; @@ -242,8 +234,7 @@ sign(PublicKey const& pk, SecretKey const& sk, Slice const& m) { case KeyType::ed25519: { Buffer b(64); - ed25519_sign( - m.data(), m.size(), sk.data(), pk.data() + 1, b.data()); + ed25519_sign(m.data(), m.size(), sk.data(), pk.data() + 1, b.data()); return b; } case KeyType::secp256k1: { @@ -263,10 +254,8 @@ sign(PublicKey const& pk, SecretKey const& sk, Slice const& m) unsigned char sig[72]; size_t len = sizeof(sig); - if (secp256k1_ecdsa_signature_serialize_der( - secp256k1Context(), sig, &len, &sig_imp) != 1) - LogicError( - "sign: secp256k1_ecdsa_signature_serialize_der failed"); + if (secp256k1_ecdsa_signature_serialize_der(secp256k1Context(), sig, &len, &sig_imp) != 1) + LogicError("sign: secp256k1_ecdsa_signature_serialize_der failed"); return Buffer{sig, len}; } @@ -315,22 +304,14 @@ derivePublicKey(KeyType type, SecretKey const& sk) case KeyType::secp256k1: { secp256k1_pubkey pubkey_imp; if (secp256k1_ec_pubkey_create( - secp256k1Context(), - &pubkey_imp, - reinterpret_cast(sk.data())) != 1) - LogicError( - "derivePublicKey: secp256k1_ec_pubkey_create failed"); + secp256k1Context(), &pubkey_imp, reinterpret_cast(sk.data())) != 1) + LogicError("derivePublicKey: secp256k1_ec_pubkey_create failed"); unsigned char pubkey[33]; std::size_t len = sizeof(pubkey); - if (secp256k1_ec_pubkey_serialize( - secp256k1Context(), - pubkey, - &len, - &pubkey_imp, - SECP256K1_EC_COMPRESSED) != 1) - LogicError( - "derivePublicKey: secp256k1_ec_pubkey_serialize failed"); + if (secp256k1_ec_pubkey_serialize(secp256k1Context(), pubkey, &len, &pubkey_imp, SECP256K1_EC_COMPRESSED) != + 1) + LogicError("derivePublicKey: secp256k1_ec_pubkey_serialize failed"); return PublicKey{Slice{pubkey, len}}; } diff --git a/src/libxrpl/protocol/Seed.cpp b/src/libxrpl/protocol/Seed.cpp index 18e89ef6ca..2629d08439 100644 --- a/src/libxrpl/protocol/Seed.cpp +++ b/src/libxrpl/protocol/Seed.cpp @@ -80,10 +80,8 @@ parseGenericSeed(std::string const& str, bool rfc1751) if (str.empty()) return std::nullopt; - if (parseBase58(str) || - parseBase58(TokenType::NodePublic, str) || - parseBase58(TokenType::AccountPublic, str) || - parseBase58(TokenType::NodePrivate, str) || + if (parseBase58(str) || parseBase58(TokenType::NodePublic, str) || + parseBase58(TokenType::AccountPublic, str) || parseBase58(TokenType::NodePrivate, str) || parseBase58(TokenType::AccountSecret, str)) { return std::nullopt; diff --git a/src/libxrpl/protocol/Serializer.cpp b/src/libxrpl/protocol/Serializer.cpp index e6c1e6967f..bb3eb17ae3 100644 --- a/src/libxrpl/protocol/Serializer.cpp +++ b/src/libxrpl/protocol/Serializer.cpp @@ -34,8 +34,7 @@ Serializer::add32(HashPrefix p) { // This should never trigger; the size & type of a hash prefix are // integral parts of the protocol and unlikely to ever change. - static_assert( - std::is_same_v>); + static_assert(std::is_same_v>); return add32(safe_cast(p)); } @@ -108,8 +107,7 @@ Serializer::addFieldID(int type, int name) { int ret = mData.size(); XRPL_ASSERT( - (type > 0) && (type < 256) && (name > 0) && (name < 256), - "xrpl::Serializer::addFieldID : inputs inside range"); + (type > 0) && (type < 256) && (name > 0) && (name < 256), "xrpl::Serializer::addFieldID : inputs inside range"); if (type < 16) { @@ -179,8 +177,7 @@ Serializer::addVL(Blob const& vector) int ret = addEncoded(vector.size()); addRaw(vector); XRPL_ASSERT( - mData.size() == - (ret + vector.size() + encodeLengthLength(vector.size())), + mData.size() == (ret + vector.size() + encodeLengthLength(vector.size())), "xrpl::Serializer::addVL : size matches expected"); return ret; } @@ -369,8 +366,7 @@ SerialIter::get32() p_ += 4; used_ += 4; remain_ -= 4; - return (std::uint64_t(t[0]) << 24) + (std::uint64_t(t[1]) << 16) + - (std::uint64_t(t[2]) << 8) + std::uint64_t(t[3]); + return (std::uint64_t(t[0]) << 24) + (std::uint64_t(t[1]) << 16) + (std::uint64_t(t[2]) << 8) + std::uint64_t(t[3]); } std::uint64_t @@ -382,9 +378,8 @@ SerialIter::get64() p_ += 8; used_ += 8; remain_ -= 8; - return (std::uint64_t(t[0]) << 56) + (std::uint64_t(t[1]) << 48) + - (std::uint64_t(t[2]) << 40) + (std::uint64_t(t[3]) << 32) + - (std::uint64_t(t[4]) << 24) + (std::uint64_t(t[5]) << 16) + + return (std::uint64_t(t[0]) << 56) + (std::uint64_t(t[1]) << 48) + (std::uint64_t(t[2]) << 40) + + (std::uint64_t(t[3]) << 32) + (std::uint64_t(t[4]) << 24) + (std::uint64_t(t[5]) << 16) + (std::uint64_t(t[6]) << 8) + std::uint64_t(t[7]); } @@ -424,8 +419,7 @@ SerialIter::getFieldID(int& type, int& name) // uncommon type type = get8(); if (type < 16) - Throw( - "gFID: uncommon type out of range " + std::to_string(type)); + Throw("gFID: uncommon type out of range " + std::to_string(type)); } if (name == 0) @@ -433,8 +427,7 @@ SerialIter::getFieldID(int& type, int& name) // uncommon name name = get8(); if (name < 16) - Throw( - "gFID: uncommon name out of range " + std::to_string(name)); + Throw("gFID: uncommon name out of range " + std::to_string(name)); } } @@ -443,8 +436,7 @@ template T SerialIter::getRawHelper(int size) { - static_assert( - std::is_same::value || std::is_same::value, ""); + static_assert(std::is_same::value || std::is_same::value, ""); if (remain_ < size) Throw("invalid SerialIter getRaw"); T result(size); @@ -485,8 +477,7 @@ SerialIter::getVLDataLength() } else { - XRPL_ASSERT( - lenLen == 3, "xrpl::SerialIter::getVLDataLength : lenLen is 3"); + XRPL_ASSERT(lenLen == 3, "xrpl::SerialIter::getVLDataLength : lenLen is 3"); int b2 = get8(); int b3 = get8(); datLen = Serializer::decodeVLLength(b1, b2, b3); diff --git a/src/libxrpl/protocol/Sign.cpp b/src/libxrpl/protocol/Sign.cpp index 9edd2bbfa4..fe18941940 100644 --- a/src/libxrpl/protocol/Sign.cpp +++ b/src/libxrpl/protocol/Sign.cpp @@ -12,12 +12,7 @@ namespace xrpl { void -sign( - STObject& st, - HashPrefix const& prefix, - KeyType type, - SecretKey const& sk, - SF_VL const& sigField) +sign(STObject& st, HashPrefix const& prefix, KeyType type, SecretKey const& sk, SF_VL const& sigField) { Serializer ss; ss.add32(prefix); @@ -26,11 +21,7 @@ sign( } bool -verify( - STObject const& st, - HashPrefix const& prefix, - PublicKey const& pk, - SF_VL const& sigField) +verify(STObject const& st, HashPrefix const& prefix, PublicKey const& pk, SF_VL const& sigField) { auto const sig = get(st, sigField); if (!sig) @@ -38,8 +29,7 @@ verify( Serializer ss; ss.add32(prefix); st.addWithoutSigningFields(ss); - return verify( - pk, Slice(ss.data(), ss.size()), Slice(sig->data(), sig->size())); + return verify(pk, Slice(ss.data(), ss.size()), Slice(sig->data(), sig->size())); } // Questions regarding buildMultiSigningData: diff --git a/src/libxrpl/protocol/TER.cpp b/src/libxrpl/protocol/TER.cpp index 6871cf5700..723bbae505 100644 --- a/src/libxrpl/protocol/TER.cpp +++ b/src/libxrpl/protocol/TER.cpp @@ -10,9 +10,7 @@ namespace xrpl { -std::unordered_map< - TERUnderlyingType, - std::pair> const& +std::unordered_map> const& transResults() { // clang-format off @@ -265,11 +263,9 @@ transCode(std::string const& token) static auto const results = [] { auto& byTer = transResults(); auto range = boost::make_iterator_range(byTer.begin(), byTer.end()); - auto tRange = boost::adaptors::transform(range, [](auto const& r) { - return std::make_pair(r.second.first, r.first); - }); - std::unordered_map const byToken( - tRange.begin(), tRange.end()); + auto tRange = + boost::adaptors::transform(range, [](auto const& r) { return std::make_pair(r.second.first, r.first); }); + std::unordered_map const byToken(tRange.begin(), tRange.end()); return byToken; }(); diff --git a/src/libxrpl/protocol/TxFormats.cpp b/src/libxrpl/protocol/TxFormats.cpp index c725c1da69..00a560de1b 100644 --- a/src/libxrpl/protocol/TxFormats.cpp +++ b/src/libxrpl/protocol/TxFormats.cpp @@ -36,8 +36,7 @@ TxFormats::TxFormats() #undef TRANSACTION #define UNWRAP(...) __VA_ARGS__ -#define TRANSACTION( \ - tag, value, name, delegable, amendment, privileges, fields) \ +#define TRANSACTION(tag, value, name, delegable, amendment, privileges, fields) \ add(jss::name, tag, UNWRAP fields, commonFields); #include diff --git a/src/libxrpl/protocol/TxMeta.cpp b/src/libxrpl/protocol/TxMeta.cpp index f0077c7f92..62e62a9b5c 100644 --- a/src/libxrpl/protocol/TxMeta.cpp +++ b/src/libxrpl/protocol/TxMeta.cpp @@ -21,17 +21,13 @@ namespace xrpl { TxMeta::TxMeta(uint256 const& txid, std::uint32_t ledger, STObject const& obj) - : transactionID_(txid) - , ledgerSeq_(ledger) - , nodes_(obj.getFieldArray(sfAffectedNodes)) + : transactionID_(txid), ledgerSeq_(ledger), nodes_(obj.getFieldArray(sfAffectedNodes)) { result_ = obj.getFieldU8(sfTransactionResult); index_ = obj.getFieldU32(sfTransactionIndex); - auto affectedNodes = - dynamic_cast(obj.peekAtPField(sfAffectedNodes)); - XRPL_ASSERT( - affectedNodes, "xrpl::TxMeta::TxMeta(STObject) : type cast succeeded"); + auto affectedNodes = dynamic_cast(obj.peekAtPField(sfAffectedNodes)); + XRPL_ASSERT(affectedNodes, "xrpl::TxMeta::TxMeta(STObject) : type cast succeeded"); if (affectedNodes) nodes_ = *affectedNodes; @@ -62,10 +58,7 @@ TxMeta::TxMeta(uint256 const& transactionID, std::uint32_t ledger) } void -TxMeta::setAffectedNode( - uint256 const& node, - SField const& type, - std::uint16_t nodeType) +TxMeta::setAffectedNode(uint256 const& node, SField const& type, std::uint16_t nodeType) { // make sure the node exists and force its type for (auto& n : nodes_) @@ -81,9 +74,7 @@ TxMeta::setAffectedNode( nodes_.push_back(STObject(type)); STObject& obj = nodes_.back(); - XRPL_ASSERT( - obj.getFName() == type, - "xrpl::TxMeta::setAffectedNode : field type match"); + XRPL_ASSERT(obj.getFName() == type, "xrpl::TxMeta::setAffectedNode : field type match"); obj.setFieldH256(sfLedgerIndex, node); obj.setFieldU16(sfLedgerEntryType, nodeType); } @@ -98,33 +89,25 @@ TxMeta::getAffectedAccounts() const // Meta#getAffectedAccounts for (auto const& node : nodes_) { - int index = node.getFieldIndex( - (node.getFName() == sfCreatedNode) ? sfNewFields : sfFinalFields); + int index = node.getFieldIndex((node.getFName() == sfCreatedNode) ? sfNewFields : sfFinalFields); if (index != -1) { - auto const* inner = - dynamic_cast(&node.peekAtIndex(index)); - XRPL_ASSERT( - inner, - "xrpl::getAffectedAccounts : STObject type cast succeeded"); + auto const* inner = dynamic_cast(&node.peekAtIndex(index)); + XRPL_ASSERT(inner, "xrpl::getAffectedAccounts : STObject type cast succeeded"); if (inner) { for (auto const& field : *inner) { if (auto sa = dynamic_cast(&field)) { - XRPL_ASSERT( - !sa->isDefault(), - "xrpl::getAffectedAccounts : account is set"); + XRPL_ASSERT(!sa->isDefault(), "xrpl::getAffectedAccounts : account is set"); if (!sa->isDefault()) list.insert(sa->value()); } else if ( - (field.getFName() == sfLowLimit) || - (field.getFName() == sfHighLimit) || - (field.getFName() == sfTakerPays) || - (field.getFName() == sfTakerGets)) + (field.getFName() == sfLowLimit) || (field.getFName() == sfHighLimit) || + (field.getFName() == sfTakerPays) || (field.getFName() == sfTakerGets)) { auto lim = dynamic_cast(&field); XRPL_ASSERT( @@ -142,8 +125,7 @@ TxMeta::getAffectedAccounts() const } else if (field.getFName() == sfMPTokenIssuanceID) { - auto mptID = - dynamic_cast const*>(&field); + auto mptID = dynamic_cast const*>(&field); if (mptID != nullptr) { auto issuer = MPTIssue(mptID->value()).getIssuer(); @@ -172,9 +154,7 @@ TxMeta::getAffectedNode(SLE::ref node, SField const& type) nodes_.push_back(STObject(type)); STObject& obj = nodes_.back(); - XRPL_ASSERT( - obj.getFName() == type, - "xrpl::TxMeta::getAffectedNode(SLE::ref) : field type match"); + XRPL_ASSERT(obj.getFName() == type, "xrpl::TxMeta::getAffectedNode(SLE::ref) : field type match"); obj.setFieldH256(sfLedgerIndex, index); obj.setFieldU16(sfLedgerEntryType, node->getFieldU16(sfLedgerEntryType)); @@ -218,9 +198,7 @@ TxMeta::addRaw(Serializer& s, TER result, std::uint32_t index) { result_ = TERtoInt(result); index_ = index; - XRPL_ASSERT( - (result_ == 0) || ((result_ > 100) && (result_ <= 255)), - "xrpl::TxMeta::addRaw : valid TER input"); + XRPL_ASSERT((result_ == 0) || ((result_ > 100) && (result_ <= 255)), "xrpl::TxMeta::addRaw : valid TER input"); nodes_.sort([](STObject const& o1, STObject const& o2) { return o1.getFieldH256(sfLedgerIndex) < o2.getFieldH256(sfLedgerIndex); diff --git a/src/libxrpl/protocol/UintTypes.cpp b/src/libxrpl/protocol/UintTypes.cpp index 6c799397ee..ca29147989 100644 --- a/src/libxrpl/protocol/UintTypes.cpp +++ b/src/libxrpl/protocol/UintTypes.cpp @@ -40,19 +40,16 @@ to_string(Currency const& currency) if (currency == noCurrency()) return "1"; - static constexpr Currency sIsoBits( - "FFFFFFFFFFFFFFFFFFFFFFFF000000FFFFFFFFFF"); + static constexpr Currency sIsoBits("FFFFFFFFFFFFFFFFFFFFFFFF000000FFFFFFFFFF"); if ((currency & sIsoBits).isZero()) { std::string const iso( - currency.data() + detail::isoCodeOffset, - currency.data() + detail::isoCodeOffset + detail::isoCodeLength); + currency.data() + detail::isoCodeOffset, currency.data() + detail::isoCodeOffset + detail::isoCodeLength); // Specifying the system currency code using ISO-style representation // is not allowed. - if ((iso != systemCurrencyCode()) && - (iso.find_first_not_of(detail::isoCharSet) == std::string::npos)) + if ((iso != systemCurrencyCode()) && (iso.find_first_not_of(detail::isoCharSet) == std::string::npos)) { return iso; } @@ -78,8 +75,7 @@ to_currency(Currency& currency, std::string const& code) currency = beast::zero; - std::copy( - code.begin(), code.end(), currency.begin() + detail::isoCodeOffset); + std::copy(code.begin(), code.end(), currency.begin() + detail::isoCodeOffset); return true; } diff --git a/src/libxrpl/protocol/XChainAttestations.cpp b/src/libxrpl/protocol/XChainAttestations.cpp index 89771b63b0..5f109ea272 100644 --- a/src/libxrpl/protocol/XChainAttestations.cpp +++ b/src/libxrpl/protocol/XChainAttestations.cpp @@ -44,9 +44,7 @@ AttestationBase::AttestationBase( } bool -AttestationBase::equalHelper( - AttestationBase const& lhs, - AttestationBase const& rhs) +AttestationBase::equalHelper(AttestationBase const& lhs, AttestationBase const& rhs) { return std::tie( lhs.attestationSignerAccount, @@ -67,16 +65,10 @@ AttestationBase::equalHelper( } bool -AttestationBase::sameEventHelper( - AttestationBase const& lhs, - AttestationBase const& rhs) +AttestationBase::sameEventHelper(AttestationBase const& lhs, AttestationBase const& rhs) { - return std::tie( - lhs.sendingAccount, - lhs.sendingAmount, - lhs.wasLockingChainSend) == - std::tie( - rhs.sendingAccount, rhs.sendingAmount, rhs.wasLockingChainSend); + return std::tie(lhs.sendingAccount, lhs.sendingAmount, lhs.wasLockingChainSend) == + std::tie(rhs.sendingAccount, rhs.sendingAmount, rhs.wasLockingChainSend); } bool @@ -98,9 +90,7 @@ AttestationBase::AttestationBase(STObject const& o) } AttestationBase::AttestationBase(Json::Value const& v) - : attestationSignerAccount{Json::getOrThrow( - v, - sfAttestationSignerAccount)} + : attestationSignerAccount{Json::getOrThrow(v, sfAttestationSignerAccount)} , publicKey{Json::getOrThrow(v, sfPublicKey)} , signature{Json::getOrThrow(v, sfSignature)} , sendingAccount{Json::getOrThrow(v, sfAccount)} @@ -177,8 +167,7 @@ AttestationClaim::AttestationClaim(STObject const& o) } AttestationClaim::AttestationClaim(Json::Value const& v) - : AttestationBase{v} - , claimID{Json::getOrThrow(v, sfXChainClaimID)} + : AttestationBase{v}, claimID{Json::getOrThrow(v, sfXChainClaimID)} { if (v.isMember(sfDestination.getJsonName())) dst = Json::getOrThrow(v, sfDestination); @@ -187,8 +176,7 @@ AttestationClaim::AttestationClaim(Json::Value const& v) STObject AttestationClaim::toSTObject() const { - STObject o = - STObject::makeInnerObject(sfXChainClaimAttestationCollectionElement); + STObject o = STObject::makeInnerObject(sfXChainClaimAttestationCollectionElement); addHelper(o); o[sfXChainClaimID] = claimID; if (dst) @@ -227,13 +215,7 @@ std::vector AttestationClaim::message(STXChainBridge const& bridge) const { return AttestationClaim::message( - bridge, - sendingAccount, - sendingAmount, - rewardAccount, - wasLockingChainSend, - claimID, - dst); + bridge, sendingAccount, sendingAmount, rewardAccount, wasLockingChainSend, claimID, dst); } bool @@ -245,15 +227,13 @@ AttestationClaim::validAmounts() const bool AttestationClaim::sameEvent(AttestationClaim const& rhs) const { - return AttestationClaim::sameEventHelper(*this, rhs) && - tie(claimID, dst) == tie(rhs.claimID, rhs.dst); + return AttestationClaim::sameEventHelper(*this, rhs) && tie(claimID, dst) == tie(rhs.claimID, rhs.dst); } bool operator==(AttestationClaim const& lhs, AttestationClaim const& rhs) { - return AttestationClaim::equalHelper(lhs, rhs) && - tie(lhs.claimID, lhs.dst) == tie(rhs.claimID, rhs.dst); + return AttestationClaim::equalHelper(lhs, rhs) && tie(lhs.claimID, lhs.dst) == tie(rhs.claimID, rhs.dst); } AttestationCreateAccount::AttestationCreateAccount(STObject const& o) @@ -266,9 +246,7 @@ AttestationCreateAccount::AttestationCreateAccount(STObject const& o) AttestationCreateAccount::AttestationCreateAccount(Json::Value const& v) : AttestationBase{v} - , createCount{Json::getOrThrow( - v, - sfXChainAccountCreateCount)} + , createCount{Json::getOrThrow(v, sfXChainAccountCreateCount)} , toCreate{Json::getOrThrow(v, sfDestination)} , rewardAmount{Json::getOrThrow(v, sfSignatureReward)} { @@ -330,8 +308,7 @@ AttestationCreateAccount::AttestationCreateAccount( STObject AttestationCreateAccount::toSTObject() const { - STObject o = STObject::makeInnerObject( - sfXChainCreateAccountAttestationCollectionElement); + STObject o = STObject::makeInnerObject(sfXChainCreateAccountAttestationCollectionElement); addHelper(o); o[sfXChainAccountCreateCount] = createCount; @@ -373,14 +350,7 @@ std::vector AttestationCreateAccount::message(STXChainBridge const& bridge) const { return AttestationCreateAccount::message( - bridge, - sendingAccount, - sendingAmount, - rewardAmount, - rewardAccount, - wasLockingChainSend, - createCount, - toCreate); + bridge, sendingAccount, sendingAmount, rewardAmount, rewardAccount, wasLockingChainSend, createCount, toCreate); } bool @@ -393,14 +363,11 @@ bool AttestationCreateAccount::sameEvent(AttestationCreateAccount const& rhs) const { return AttestationCreateAccount::sameEventHelper(*this, rhs) && - std::tie(createCount, toCreate, rewardAmount) == - std::tie(rhs.createCount, rhs.toCreate, rhs.rewardAmount); + std::tie(createCount, toCreate, rewardAmount) == std::tie(rhs.createCount, rhs.toCreate, rhs.rewardAmount); } bool -operator==( - AttestationCreateAccount const& lhs, - AttestationCreateAccount const& rhs) +operator==(AttestationCreateAccount const& lhs, AttestationCreateAccount const& rhs) { return AttestationCreateAccount::equalHelper(lhs, rhs) && std::tie(lhs.createCount, lhs.toCreate, lhs.rewardAmount) == @@ -410,8 +377,7 @@ operator==( } // namespace Attestations SField const& XChainClaimAttestation::ArrayFieldName{sfXChainClaimAttestations}; -SField const& XChainCreateAccountAttestation::ArrayFieldName{ - sfXChainCreateAccountAttestations}; +SField const& XChainCreateAccountAttestation::ArrayFieldName{sfXChainCreateAccountAttestations}; XChainClaimAttestation::XChainClaimAttestation( AccountID const& keyAccount_, @@ -468,8 +434,7 @@ XChainClaimAttestation::XChainClaimAttestation(Json::Value const& v) dst = Json::getOrThrow(v, sfDestination); }; -XChainClaimAttestation::XChainClaimAttestation( - XChainClaimAttestation::TSignedAttestation const& claimAtt) +XChainClaimAttestation::XChainClaimAttestation(XChainClaimAttestation::TSignedAttestation const& claimAtt) : XChainClaimAttestation{ claimAtt.attestationSignerAccount, claimAtt.publicKey, @@ -484,12 +449,10 @@ STObject XChainClaimAttestation::toSTObject() const { STObject o = STObject::makeInnerObject(sfXChainClaimProofSig); - o[sfAttestationSignerAccount] = - STAccount{sfAttestationSignerAccount, keyAccount}; + o[sfAttestationSignerAccount] = STAccount{sfAttestationSignerAccount, keyAccount}; o[sfPublicKey] = publicKey; o[sfAmount] = STAmount{sfAmount, amount}; - o[sfAttestationRewardAccount] = - STAccount{sfAttestationRewardAccount, rewardAccount}; + o[sfAttestationRewardAccount] = STAccount{sfAttestationRewardAccount, rewardAccount}; o[sfWasLockingChainSend] = wasLockingChainSend; if (dst) o[sfDestination] = STAccount{sfDestination, *dst}; @@ -499,36 +462,19 @@ XChainClaimAttestation::toSTObject() const bool operator==(XChainClaimAttestation const& lhs, XChainClaimAttestation const& rhs) { - return std::tie( - lhs.keyAccount, - lhs.publicKey, - lhs.amount, - lhs.rewardAccount, - lhs.wasLockingChainSend, - lhs.dst) == - std::tie( - rhs.keyAccount, - rhs.publicKey, - rhs.amount, - rhs.rewardAccount, - rhs.wasLockingChainSend, - rhs.dst); + return std::tie(lhs.keyAccount, lhs.publicKey, lhs.amount, lhs.rewardAccount, lhs.wasLockingChainSend, lhs.dst) == + std::tie(rhs.keyAccount, rhs.publicKey, rhs.amount, rhs.rewardAccount, rhs.wasLockingChainSend, rhs.dst); } -XChainClaimAttestation::MatchFields::MatchFields( - XChainClaimAttestation::TSignedAttestation const& att) - : amount{att.sendingAmount} - , wasLockingChainSend{att.wasLockingChainSend} - , dst{att.dst} +XChainClaimAttestation::MatchFields::MatchFields(XChainClaimAttestation::TSignedAttestation const& att) + : amount{att.sendingAmount}, wasLockingChainSend{att.wasLockingChainSend}, dst{att.dst} { } AttestationMatch -XChainClaimAttestation::match( - XChainClaimAttestation::MatchFields const& rhs) const +XChainClaimAttestation::match(XChainClaimAttestation::MatchFields const& rhs) const { - if (std::tie(amount, wasLockingChainSend) != - std::tie(rhs.amount, rhs.wasLockingChainSend)) + if (std::tie(amount, wasLockingChainSend) != std::tie(rhs.amount, rhs.wasLockingChainSend)) return AttestationMatch::nonDstMismatch; if (dst != rhs.dst) return AttestationMatch::matchExceptDst; @@ -555,8 +501,7 @@ XChainCreateAccountAttestation::XChainCreateAccountAttestation( { } -XChainCreateAccountAttestation::XChainCreateAccountAttestation( - STObject const& o) +XChainCreateAccountAttestation::XChainCreateAccountAttestation(STObject const& o) : XChainCreateAccountAttestation{ o[sfAttestationSignerAccount], PublicKey{o[sfPublicKey]}, @@ -566,8 +511,7 @@ XChainCreateAccountAttestation::XChainCreateAccountAttestation( o[sfWasLockingChainSend] != 0, o[sfDestination]} {}; -XChainCreateAccountAttestation ::XChainCreateAccountAttestation( - Json::Value const& v) +XChainCreateAccountAttestation ::XChainCreateAccountAttestation(Json::Value const& v) : XChainCreateAccountAttestation{ Json::getOrThrow(v, sfAttestationSignerAccount), Json::getOrThrow(v, sfPublicKey), @@ -597,21 +541,18 @@ XChainCreateAccountAttestation::toSTObject() const { STObject o = STObject::makeInnerObject(sfXChainCreateAccountProofSig); - o[sfAttestationSignerAccount] = - STAccount{sfAttestationSignerAccount, keyAccount}; + o[sfAttestationSignerAccount] = STAccount{sfAttestationSignerAccount, keyAccount}; o[sfPublicKey] = publicKey; o[sfAmount] = STAmount{sfAmount, amount}; o[sfSignatureReward] = STAmount{sfSignatureReward, rewardAmount}; - o[sfAttestationRewardAccount] = - STAccount{sfAttestationRewardAccount, rewardAccount}; + o[sfAttestationRewardAccount] = STAccount{sfAttestationRewardAccount, rewardAccount}; o[sfWasLockingChainSend] = wasLockingChainSend; o[sfDestination] = STAccount{sfDestination, dst}; return o; } -XChainCreateAccountAttestation::MatchFields::MatchFields( - XChainCreateAccountAttestation::TSignedAttestation const& att) +XChainCreateAccountAttestation::MatchFields::MatchFields(XChainCreateAccountAttestation::TSignedAttestation const& att) : amount{att.sendingAmount} , rewardAmount(att.rewardAmount) , wasLockingChainSend{att.wasLockingChainSend} @@ -620,8 +561,7 @@ XChainCreateAccountAttestation::MatchFields::MatchFields( } AttestationMatch -XChainCreateAccountAttestation::match( - XChainCreateAccountAttestation::MatchFields const& rhs) const +XChainCreateAccountAttestation::match(XChainCreateAccountAttestation::MatchFields const& rhs) const { if (std::tie(amount, rewardAmount, wasLockingChainSend) != std::tie(rhs.amount, rhs.rewardAmount, rhs.wasLockingChainSend)) @@ -632,9 +572,7 @@ XChainCreateAccountAttestation::match( } bool -operator==( - XChainCreateAccountAttestation const& lhs, - XChainCreateAccountAttestation const& rhs) +operator==(XChainCreateAccountAttestation const& lhs, XChainCreateAccountAttestation const& rhs) { return std::tie( lhs.keyAccount, @@ -657,8 +595,7 @@ operator==( //------------------------------------------------------------------------------ // template -XChainAttestationsBase::XChainAttestationsBase( - XChainAttestationsBase::AttCollection&& atts) +XChainAttestationsBase::XChainAttestationsBase(XChainAttestationsBase::AttCollection&& atts) : attestations_{std::move(atts)} { } @@ -692,8 +629,7 @@ XChainAttestationsBase::end() } template -XChainAttestationsBase::XChainAttestationsBase( - Json::Value const& v) +XChainAttestationsBase::XChainAttestationsBase(Json::Value const& v) { if (!v.isObject()) { @@ -706,8 +642,7 @@ XChainAttestationsBase::XChainAttestationsBase( auto const jAtts = v[jss::attestations]; if (jAtts.size() > maxAttestations) - Throw( - "XChainAttestationsBase exceeded max number of attestations"); + Throw("XChainAttestationsBase exceeded max number of attestations"); std::vector r; r.reserve(jAtts.size()); @@ -721,8 +656,7 @@ template XChainAttestationsBase::XChainAttestationsBase(STArray const& arr) { if (arr.size() > maxAttestations) - Throw( - "XChainAttestationsBase exceeded max number of attestations"); + Throw("XChainAttestationsBase exceeded max number of attestations"); attestations_.reserve(arr.size()); for (auto const& o : arr) diff --git a/src/libxrpl/protocol/digest.cpp b/src/libxrpl/protocol/digest.cpp index dd4ecd7688..aa5600dde0 100644 --- a/src/libxrpl/protocol/digest.cpp +++ b/src/libxrpl/protocol/digest.cpp @@ -9,18 +9,13 @@ namespace xrpl { openssl_ripemd160_hasher::openssl_ripemd160_hasher() { - static_assert( - sizeof(decltype(openssl_ripemd160_hasher::ctx_)) == - sizeof(RIPEMD160_CTX), - ""); + static_assert(sizeof(decltype(openssl_ripemd160_hasher::ctx_)) == sizeof(RIPEMD160_CTX), ""); auto const ctx = reinterpret_cast(ctx_); RIPEMD160_Init(ctx); } void -openssl_ripemd160_hasher::operator()( - void const* data, - std::size_t size) noexcept +openssl_ripemd160_hasher::operator()(void const* data, std::size_t size) noexcept { auto const ctx = reinterpret_cast(ctx_); RIPEMD160_Update(ctx, data, size); @@ -38,9 +33,7 @@ openssl_ripemd160_hasher::operator result_type() noexcept openssl_sha512_hasher::openssl_sha512_hasher() { - static_assert( - sizeof(decltype(openssl_sha512_hasher::ctx_)) == sizeof(SHA512_CTX), - ""); + static_assert(sizeof(decltype(openssl_sha512_hasher::ctx_)) == sizeof(SHA512_CTX), ""); auto const ctx = reinterpret_cast(ctx_); SHA512_Init(ctx); } @@ -64,9 +57,7 @@ openssl_sha512_hasher::operator result_type() noexcept openssl_sha256_hasher::openssl_sha256_hasher() { - static_assert( - sizeof(decltype(openssl_sha256_hasher::ctx_)) == sizeof(SHA256_CTX), - ""); + static_assert(sizeof(decltype(openssl_sha256_hasher::ctx_)) == sizeof(SHA256_CTX), ""); auto const ctx = reinterpret_cast(ctx_); SHA256_Init(ctx); } diff --git a/src/libxrpl/protocol/tokens.cpp b/src/libxrpl/protocol/tokens.cpp index 420eb56df0..1b73b06380 100644 --- a/src/libxrpl/protocol/tokens.cpp +++ b/src/libxrpl/protocol/tokens.cpp @@ -121,8 +121,7 @@ coefficients sizes greatly speeds up the multi-precision computations. namespace xrpl { -static constexpr char const* alphabetForward = - "rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz"; +static constexpr char const* alphabetForward = "rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz"; static constexpr std::array const alphabetReverse = []() { std::array map{}; @@ -142,11 +141,7 @@ digest(void const* data, std::size_t size) noexcept return static_cast(h); } -template < - class Hasher, - class T, - std::size_t N, - class = std::enable_if_t> +template > static typename Hasher::result_type digest(std::array const& v) { @@ -202,11 +197,7 @@ namespace b58_ref { namespace detail { std::string -encodeBase58( - void const* message, - std::size_t size, - void* temp, - std::size_t temp_size) +encodeBase58(void const* message, std::size_t size, void* temp, std::size_t temp_size) { auto pbegin = reinterpret_cast(message); auto const pend = pbegin + size; @@ -234,8 +225,7 @@ encodeBase58( iter[-1] = carry % 58; carry /= 58; } - XRPL_ASSERT( - carry == 0, "xrpl::b58_ref::detail::encodeBase58 : zero carry"); + XRPL_ASSERT(carry == 0, "xrpl::b58_ref::detail::encodeBase58 : zero carry"); pbegin++; } @@ -285,14 +275,12 @@ decodeBase58(std::string const& s) *iter = carry % 256; carry /= 256; } - XRPL_ASSERT( - carry == 0, "xrpl::b58_ref::detail::decodeBase58 : zero carry"); + XRPL_ASSERT(carry == 0, "xrpl::b58_ref::detail::decodeBase58 : zero carry"); ++psz; --remain; } // Skip leading zeroes in b256. - auto iter = std::find_if( - b256.begin(), b256.end(), [](unsigned char c) { return c != 0; }); + auto iter = std::find_if(b256.begin(), b256.end(), [](unsigned char c) { return c != 0; }); std::string result; result.reserve(zeroes + (b256.end() - iter)); result.assign(zeroes, 0x00); @@ -323,8 +311,7 @@ encodeBase58Token(TokenType type, void const* token, std::size_t size) std::memcpy(buf.data() + 1, token, size); checksum(buf.data() + 1 + size, buf.data(), 1 + size); - return detail::encodeBase58( - buf.data(), expanded, buf.data() + expanded, bufsize - expanded); + return detail::encodeBase58(buf.data(), expanded, buf.data() + expanded, bufsize - expanded); } std::string @@ -367,8 +354,7 @@ b256_to_b58_be(std::span input, std::span out) return Unexpected(TokenCodecErrc::inputTooLarge); }; - auto count_leading_zeros = - [](std::span const& col) -> std::size_t { + auto count_leading_zeros = [](std::span const& col) -> std::size_t { std::size_t count = 0; for (auto const& c : col) { @@ -387,8 +373,7 @@ b256_to_b58_be(std::span input, std::span out) // Allocate enough base 2^64 coeff for encoding 38 bytes // log(2^(38*8),2^64)) ~= 4.75. So 5 coeff are enough std::array base_2_64_coeff_buf{}; - std::span const base_2_64_coeff = - [&]() -> std::span { + std::span const base_2_64_coeff = [&]() -> std::span { // convert input from big endian to native u64, lowest coeff first std::size_t num_coeff = 0; for (int i = 0; i < base_2_64_coeff_buf.size(); ++i) @@ -400,10 +385,8 @@ b256_to_b58_be(std::span input, std::span out) auto const src_i_end = input.size() - i * 8; if (src_i_end >= 8) { - std::memcpy( - &base_2_64_coeff_buf[num_coeff], &input[src_i_end - 8], 8); - boost::endian::big_to_native_inplace( - base_2_64_coeff_buf[num_coeff]); + std::memcpy(&base_2_64_coeff_buf[num_coeff], &input[src_i_end - 8], 8); + boost::endian::big_to_native_inplace(base_2_64_coeff_buf[num_coeff]); } else { @@ -430,8 +413,7 @@ b256_to_b58_be(std::span input, std::span out) while (cur_2_64_end > 0) { base_58_10_coeff[num_58_10_coeffs] = - xrpl::b58_fast::detail::inplace_bigint_div_rem( - base_2_64_coeff.subspan(0, cur_2_64_end), B_58_10); + xrpl::b58_fast::detail::inplace_bigint_div_rem(base_2_64_coeff.subspan(0, cur_2_64_end), B_58_10); num_58_10_coeffs += 1; if (base_2_64_coeff[cur_2_64_end - 1] == 0) { @@ -441,8 +423,7 @@ b256_to_b58_be(std::span input, std::span out) // Translate the result into the alphabet // Put all the zeros at the beginning, then all the values from the output - std::fill( - out.begin(), out.begin() + input_zeros, ::xrpl::alphabetForward[0]); + std::fill(out.begin(), out.begin() + input_zeros, ::xrpl::alphabetForward[0]); // iterate through the base 58^10 coeff // convert to base 58 big endian then @@ -460,8 +441,7 @@ b256_to_b58_be(std::span input, std::span out) { return Unexpected(TokenCodecErrc::inputTooLarge); } - std::array const b58_be = - xrpl::b58_fast::detail::b58_10_to_b58_be(base_58_10_coeff[i]); + std::array const b58_be = xrpl::b58_fast::detail::b58_10_to_b58_be(base_58_10_coeff[i]); std::size_t to_skip = 0; std::span b58_be_s{b58_be.data(), b58_be.size()}; if (skip_zeros) @@ -519,13 +499,10 @@ b58_to_b256_be(std::string_view input, std::span out) // (33 bytes for nodepublic + 1 byte token + 4 bytes checksum) // log(2^(38*8),58^10)) ~= 5.18. So 6 coeff are enough std::array b_58_10_coeff{}; - auto [num_full_coeffs, partial_coeff_len] = - xrpl::b58_fast::detail::div_rem(input.size(), 10); + auto [num_full_coeffs, partial_coeff_len] = xrpl::b58_fast::detail::div_rem(input.size(), 10); auto const num_partial_coeffs = partial_coeff_len ? 1 : 0; auto const num_b_58_10_coeffs = num_full_coeffs + num_partial_coeffs; - XRPL_ASSERT( - num_b_58_10_coeffs <= b_58_10_coeff.size(), - "xrpl::b58_fast::detail::b58_to_b256_be : maximum coeff"); + XRPL_ASSERT(num_b_58_10_coeffs <= b_58_10_coeff.size(), "xrpl::b58_fast::detail::b58_to_b256_be : maximum coeff"); for (unsigned char c : input.substr(0, partial_coeff_len)) { auto cur_val = ::xrpl::alphabetReverse[c]; @@ -562,16 +539,14 @@ b58_to_b256_be(std::string_view input, std::span out) std::uint64_t const c = b_58_10_coeff[i]; { - auto code = xrpl::b58_fast::detail::inplace_bigint_mul( - std::span(&result[0], cur_result_size + 1), B_58_10); + auto code = xrpl::b58_fast::detail::inplace_bigint_mul(std::span(&result[0], cur_result_size + 1), B_58_10); if (code != TokenCodecErrc::success) { return Unexpected(code); } } { - auto code = xrpl::b58_fast::detail::inplace_bigint_add( - std::span(&result[0], cur_result_size + 1), c); + auto code = xrpl::b58_fast::detail::inplace_bigint_add(std::span(&result[0], cur_result_size + 1), c); if (code != TokenCodecErrc::success) { return Unexpected(code); @@ -623,10 +598,7 @@ b58_to_b256_be(std::string_view input, std::span out) } // namespace detail B58Result> -encodeBase58Token( - TokenType token_type, - std::span input, - std::span out) +encodeBase58Token(TokenType token_type, std::span input, std::span out) { constexpr std::size_t tmpBufSize = 128; std::array buf; @@ -654,14 +626,10 @@ encodeBase58Token( // The decoded base 256 value does not include the token type or checksum. // It is an error if the token type or checksum does not match. B58Result> -decodeBase58Token( - TokenType type, - std::string_view s, - std::span outBuf) +decodeBase58Token(TokenType type, std::string_view s, std::span outBuf) { std::array tmpBuf; - auto const decodeResult = - detail::b58_to_b256_be(s, std::span(tmpBuf.data(), tmpBuf.size())); + auto const decodeResult = detail::b58_to_b256_be(s, std::span(tmpBuf.data(), tmpBuf.size())); if (!decodeResult) return decodeResult; @@ -703,10 +671,8 @@ encodeBase58Token(TokenType type, void const* token, std::size_t size) // over-allocation, this function uses 128 (again, over-allocation assuming // 2 base 58 char per byte) sr.resize(128); - std::span outSp( - reinterpret_cast(sr.data()), sr.size()); - std::span inSp( - reinterpret_cast(token), size); + std::span outSp(reinterpret_cast(sr.data()), sr.size()); + std::span inSp(reinterpret_cast(token), size); auto r = b58_fast::encodeBase58Token(type, inSp, outSp); if (!r) return {}; @@ -721,8 +687,7 @@ decodeBase58Token(std::string const& s, TokenType type) // The largest object encoded as base58 is 33 bytes; 64 is plenty (and // there's no benefit making it smaller) sr.resize(64); - std::span outSp( - reinterpret_cast(sr.data()), sr.size()); + std::span outSp(reinterpret_cast(sr.data()), sr.size()); auto r = b58_fast::decodeBase58Token(type, s, outSp); if (!r) return {}; diff --git a/src/libxrpl/rdb/DatabaseCon.cpp b/src/libxrpl/rdb/DatabaseCon.cpp new file mode 100644 index 0000000000..344df85b4a --- /dev/null +++ b/src/libxrpl/rdb/DatabaseCon.cpp @@ -0,0 +1,92 @@ +#include +#include +#include +#include + +#include +#include + +#include +#include + +namespace xrpl { + +class CheckpointersCollection +{ + std::uintptr_t nextId_{0}; + // Mutex protects the CheckpointersCollection + std::mutex mutex_; + // Each checkpointer is given a unique id. All the checkpointers that are + // part of a DatabaseCon are part of this collection. When the DatabaseCon + // is destroyed, its checkpointer is removed from the collection + std::unordered_map> checkpointers_; + +public: + std::shared_ptr + fromId(std::uintptr_t id) + { + std::lock_guard l{mutex_}; + auto it = checkpointers_.find(id); + if (it != checkpointers_.end()) + return it->second; + return {}; + } + + void + erase(std::uintptr_t id) + { + std::lock_guard lock{mutex_}; + checkpointers_.erase(id); + } + + std::shared_ptr + create(std::shared_ptr const& session, JobQueue& jobQueue, Logs& logs) + { + std::lock_guard lock{mutex_}; + auto const id = nextId_++; + auto const r = makeCheckpointer(id, session, jobQueue, logs); + checkpointers_[id] = r; + return r; + } +}; + +CheckpointersCollection checkpointers; + +std::shared_ptr +checkpointerFromId(std::uintptr_t id) +{ + return checkpointers.fromId(id); +} + +DatabaseCon::~DatabaseCon() +{ + if (checkpointer_) + { + checkpointers.erase(checkpointer_->id()); + + std::weak_ptr wk(checkpointer_); + checkpointer_.reset(); + + // The references to our Checkpointer held by 'checkpointer_' and + // 'checkpointers' have been removed, so if the use count is nonzero, a + // checkpoint is currently in progress. Wait for it to end, otherwise + // creating a new DatabaseCon to the same database may fail due to the + // database being locked by our (now old) Checkpointer. + while (wk.use_count()) + { + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + } + } +} + +std::unique_ptr const> DatabaseCon::Setup::globalPragma; + +void +DatabaseCon::setupCheckpointing(JobQueue* q, Logs& l) +{ + if (!q) + Throw("No JobQueue"); + checkpointer_ = checkpointers.create(session_, *q, l); +} + +} // namespace xrpl diff --git a/src/xrpld/core/detail/SociDB.cpp b/src/libxrpl/rdb/SociDB.cpp similarity index 78% rename from src/xrpld/core/detail/SociDB.cpp rename to src/libxrpl/rdb/SociDB.cpp index c04beaff29..2f8c5f1ac6 100644 --- a/src/xrpld/core/detail/SociDB.cpp +++ b/src/libxrpl/rdb/SociDB.cpp @@ -3,12 +3,10 @@ #pragma clang diagnostic ignored "-Wdeprecated" #endif -#include -#include -#include - #include #include +#include +#include #include @@ -23,16 +21,11 @@ static auto checkpointPageCount = 1000; namespace detail { std::string -getSociSqliteInit( - std::string const& name, - std::string const& dir, - std::string const& ext) +getSociSqliteInit(std::string const& name, std::string const& dir, std::string const& ext) { if (name.empty()) { - Throw( - "Sqlite databases must specify a dir and a name. Name: " + name + - " Dir: " + dir); + Throw("Sqlite databases must specify a dir and a name. Name: " + name + " Dir: " + dir); } boost::filesystem::path file(dir); if (is_directory(file)) @@ -50,8 +43,7 @@ getSociInit(BasicConfig const& config, std::string const& dbName) Throw("Unsupported soci backend: " + backendName); auto const path = config.legacy("database_path"); - auto const ext = - dbName == "validators" || dbName == "peerfinder" ? ".sqlite" : ".db"; + auto const ext = dbName == "validators" || dbName == "peerfinder" ? ".sqlite" : ".db"; return detail::getSociSqliteInit(dbName, path, ext); } @@ -61,8 +53,7 @@ DBConfig::DBConfig(std::string const& dbPath) : connectionString_(dbPath) { } -DBConfig::DBConfig(BasicConfig const& config, std::string const& dbName) - : DBConfig(detail::getSociInit(config, dbName)) +DBConfig::DBConfig(BasicConfig const& config, std::string const& dbName) : DBConfig(detail::getSociInit(config, dbName)) { } @@ -85,10 +76,7 @@ open(soci::session& s, BasicConfig const& config, std::string const& dbName) } void -open( - soci::session& s, - std::string const& beName, - std::string const& connectionString) +open(soci::session& s, std::string const& beName, std::string const& connectionString) { if (beName == "sqlite") s.open(soci::sqlite3, connectionString); @@ -115,8 +103,7 @@ getKBUsedAll(soci::session& s) { if (!getConnection(s)) Throw("No connection found."); - return static_cast( - sqlite_api::sqlite3_memory_used() / kilobytes(1)); + return static_cast(sqlite_api::sqlite3_memory_used() / kilobytes(1)); } std::uint32_t @@ -126,8 +113,7 @@ getKBUsedDB(soci::session& s) if (auto conn = getConnection(s)) { int cur = 0, hiw = 0; - sqlite_api::sqlite3_db_status( - conn, SQLITE_DBSTATUS_CACHE_USED, &cur, &hiw, 0); + sqlite_api::sqlite3_db_status(conn, SQLITE_DBSTATUS_CACHE_USED, &cur, &hiw, 0); return cur / kilobytes(1); } Throw(""); @@ -183,21 +169,13 @@ namespace { class WALCheckpointer : public Checkpointer { public: - WALCheckpointer( - std::uintptr_t id, - std::weak_ptr session, - JobQueue& q, - Logs& logs) - : id_(id) - , session_(std::move(session)) - , jobQueue_(q) - , j_(logs.journal("WALCheckpointer")) + WALCheckpointer(std::uintptr_t id, std::weak_ptr session, JobQueue& q, Logs& logs) + : id_(id), session_(std::move(session)), jobQueue_(q), j_(logs.journal("WALCheckpointer")) { if (auto [conn, keepAlive] = getConnection(); conn) { (void)keepAlive; - sqlite_api::sqlite3_wal_hook( - conn, &sqliteWALHook, reinterpret_cast(id_)); + sqlite_api::sqlite3_wal_hook(conn, &sqliteWALHook, reinterpret_cast(id_)); } } @@ -257,8 +235,7 @@ public: return; int log = 0, ckpt = 0; - int ret = sqlite3_wal_checkpoint_v2( - conn, nullptr, SQLITE_CHECKPOINT_PASSIVE, &log, &ckpt); + int ret = sqlite3_wal_checkpoint_v2(conn, nullptr, SQLITE_CHECKPOINT_PASSIVE, &log, &ckpt); auto fname = sqlite3_db_filename(conn, "main"); if (ret != SQLITE_OK) @@ -268,8 +245,7 @@ public: } else { - JLOG(j_.trace()) << "WAL(" << fname << "): frames=" << log - << ", written=" << ckpt; + JLOG(j_.trace()) << "WAL(" << fname << "): frames=" << log << ", written=" << ckpt; } std::lock_guard lock(mutex_); @@ -289,16 +265,11 @@ protected: beast::Journal const j_; static int - sqliteWALHook( - void* cpId, - sqlite_api::sqlite3* conn, - char const* dbName, - int walSize) + sqliteWALHook(void* cpId, sqlite_api::sqlite3* conn, char const* dbName, int walSize) { if (walSize >= checkpointPageCount) { - if (auto checkpointer = - checkpointerFromId(reinterpret_cast(cpId))) + if (auto checkpointer = checkpointerFromId(reinterpret_cast(cpId))) { checkpointer->schedule(); } @@ -314,14 +285,9 @@ protected: } // namespace std::shared_ptr -makeCheckpointer( - std::uintptr_t id, - std::weak_ptr session, - JobQueue& queue, - Logs& logs) +makeCheckpointer(std::uintptr_t id, std::weak_ptr session, JobQueue& queue, Logs& logs) { - return std::make_shared( - id, std::move(session), queue, logs); + return std::make_shared(id, std::move(session), queue, logs); } } // namespace xrpl diff --git a/src/libxrpl/resource/Charge.cpp b/src/libxrpl/resource/Charge.cpp index 1d88526b65..eece5355f0 100644 --- a/src/libxrpl/resource/Charge.cpp +++ b/src/libxrpl/resource/Charge.cpp @@ -8,8 +8,7 @@ namespace xrpl { namespace Resource { -Charge::Charge(value_type cost, std::string const& label) - : m_cost(cost), m_label(label) +Charge::Charge(value_type cost, std::string const& label) : m_cost(cost), m_label(label) { } diff --git a/src/libxrpl/resource/Consumer.cpp b/src/libxrpl/resource/Consumer.cpp index c9d8ea6125..11c23b1044 100644 --- a/src/libxrpl/resource/Consumer.cpp +++ b/src/libxrpl/resource/Consumer.cpp @@ -13,8 +13,7 @@ namespace xrpl { namespace Resource { -Consumer::Consumer(Logic& logic, Entry& entry) - : m_logic(&logic), m_entry(&entry) +Consumer::Consumer(Logic& logic, Entry& entry) : m_logic(&logic), m_entry(&entry) { } @@ -22,8 +21,7 @@ Consumer::Consumer() : m_logic(nullptr), m_entry(nullptr) { } -Consumer::Consumer(Consumer const& other) - : m_logic(other.m_logic), m_entry(nullptr) +Consumer::Consumer(Consumer const& other) : m_logic(other.m_logic), m_entry(nullptr) { if (m_logic && other.m_entry) { @@ -104,8 +102,7 @@ Consumer::warn() bool Consumer::disconnect(beast::Journal const& j) { - XRPL_ASSERT( - m_entry, "xrpl::Resource::Consumer::disconnect : non-null entry"); + XRPL_ASSERT(m_entry, "xrpl::Resource::Consumer::disconnect : non-null entry"); bool const d = m_logic->disconnect(*m_entry); if (d) { diff --git a/src/libxrpl/resource/ResourceManager.cpp b/src/libxrpl/resource/ResourceManager.cpp index 15d31a558e..787ceff768 100644 --- a/src/libxrpl/resource/ResourceManager.cpp +++ b/src/libxrpl/resource/ResourceManager.cpp @@ -36,9 +36,7 @@ private: std::condition_variable cond_; public: - ManagerImp( - beast::insight::Collector::ptr const& collector, - beast::Journal journal) + ManagerImp(beast::insight::Collector::ptr const& collector, beast::Journal journal) : journal_(journal), logic_(collector, stopwatch(), journal) { thread_ = std::thread{&ManagerImp::run, this}; @@ -66,10 +64,7 @@ public: } Consumer - newInboundEndpoint( - beast::IP::Endpoint const& address, - bool const proxy, - std::string_view forwardedFor) override + newInboundEndpoint(beast::IP::Endpoint const& address, bool const proxy, std::string_view forwardedFor) override { if (!proxy) return newInboundEndpoint(address); @@ -78,14 +73,11 @@ public: auto const proxiedIp = boost::asio::ip::make_address(forwardedFor, ec); if (ec) { - journal_.warn() - << "forwarded for (" << forwardedFor << ") from proxy " - << address.to_string() - << " doesn't convert to IP endpoint: " << ec.message(); + journal_.warn() << "forwarded for (" << forwardedFor << ") from proxy " << address.to_string() + << " doesn't convert to IP endpoint: " << ec.message(); return newInboundEndpoint(address); } - return newInboundEndpoint( - beast::IPAddressConversion::from_asio(proxiedIp)); + return newInboundEndpoint(beast::IPAddressConversion::from_asio(proxiedIp)); } Consumer @@ -163,9 +155,7 @@ Manager::~Manager() = default; //------------------------------------------------------------------------------ std::unique_ptr -make_Manager( - beast::insight::Collector::ptr const& collector, - beast::Journal journal) +make_Manager(beast::insight::Collector::ptr const& collector, beast::Journal journal) { return std::make_unique(collector, journal); } diff --git a/src/xrpld/rpc/detail/InfoSub.cpp b/src/libxrpl/server/InfoSub.cpp similarity index 91% rename from src/xrpld/rpc/detail/InfoSub.cpp rename to src/libxrpl/server/InfoSub.cpp index c8917b3327..c413f5d257 100644 --- a/src/xrpld/rpc/detail/InfoSub.cpp +++ b/src/libxrpl/server/InfoSub.cpp @@ -1,4 +1,4 @@ -#include +#include namespace xrpl { @@ -17,8 +17,7 @@ InfoSub::InfoSub(Source& source) : m_source(source), mSeq(assign_id()) { } -InfoSub::InfoSub(Source& source, Consumer consumer) - : m_consumer(consumer), m_source(source), mSeq(assign_id()) +InfoSub::InfoSub(Source& source, Consumer consumer) : m_consumer(consumer), m_source(source), mSeq(assign_id()) { } @@ -125,8 +124,7 @@ InfoSub::setApiVersion(unsigned int apiVersion) unsigned int InfoSub::getApiVersion() const noexcept { - XRPL_ASSERT( - apiVersion_ > 0, "xrpl::InfoSub::getApiVersion : valid API version"); + XRPL_ASSERT(apiVersion_ > 0, "xrpl::InfoSub::getApiVersion : valid API version"); return apiVersion_; } diff --git a/src/libxrpl/server/JSONRPCUtil.cpp b/src/libxrpl/server/JSONRPCUtil.cpp index 845781374d..634bb07850 100644 --- a/src/libxrpl/server/JSONRPCUtil.cpp +++ b/src/libxrpl/server/JSONRPCUtil.cpp @@ -27,20 +27,12 @@ getHTTPHeaderTimestamp() #else gmtime_s(&now_gmt, &now); #endif - strftime( - buffer, - sizeof(buffer), - "Date: %a, %d %b %Y %H:%M:%S +0000\r\n", - &now_gmt); + strftime(buffer, sizeof(buffer), "Date: %a, %d %b %Y %H:%M:%S +0000\r\n", &now_gmt); return std::string(buffer); } void -HTTPReply( - int nStatus, - std::string const& content, - Json::Output const& output, - beast::Journal j) +HTTPReply(int nStatus, std::string const& content, Json::Output const& output, beast::Journal j) { JLOG(j.trace()) << "HTTP Reply " << nStatus << " " << content; diff --git a/src/libxrpl/server/Port.cpp b/src/libxrpl/server/Port.cpp index 03a503e940..389714a40f 100644 --- a/src/libxrpl/server/Port.cpp +++ b/src/libxrpl/server/Port.cpp @@ -26,8 +26,8 @@ namespace xrpl { bool Port::secure() const { - return protocol.count("peer") > 0 || protocol.count("https") > 0 || - protocol.count("wss") > 0 || protocol.count("wss2") > 0; + return protocol.count("peer") > 0 || protocol.count("https") > 0 || protocol.count("wss") > 0 || + protocol.count("wss2") > 0; } std::string @@ -111,8 +111,7 @@ populate( { if (is_unspecified(*addr)) { - nets4.push_back( - boost::asio::ip::make_network_v4("0.0.0.0/0")); + nets4.push_back(boost::asio::ip::make_network_v4("0.0.0.0/0")); nets6.push_back(boost::asio::ip::make_network_v6("::/0")); // No reason to allow more IPs--it would be redundant. break; @@ -164,8 +163,7 @@ populate( if (v4Net != v4Net.canonical()) { log << "The configured subnet " << v4Net.to_string() - << " is not the same as the network address, which is " - << v4Net.canonical().to_string(); + << " is not the same as the network address, which is " << v4Net.canonical().to_string(); Throw(); } nets4.push_back(v4Net); @@ -175,8 +173,7 @@ populate( if (v6Net != v6Net.canonical()) { log << "The configured subnet " << v6Net.to_string() - << " is not the same as the network address, which is " - << v6Net.canonical().to_string(); + << " is not the same as the network address, which is " << v6Net.canonical().to_string(); Throw(); } nets6.push_back(v6Net); @@ -184,8 +181,7 @@ populate( } catch (boost::system::system_error const& e) { - log << "Invalid value '" << ip << "' for key '" << field << "' in [" - << section.name() << "]: " << e.what(); + log << "Invalid value '" << ip << "' for key '" << field << "' in [" << section.name() << "]: " << e.what(); Throw(); } } @@ -205,8 +201,7 @@ parse_Port(ParsedPort& port, Section const& section, std::ostream& log) } catch (std::exception const&) { - log << "Invalid value '" << *optResult << "' for key 'ip' in [" - << section.name() << "]"; + log << "Invalid value '" << *optResult << "' for key 'ip' in [" << section.name() << "]"; Rethrow(); } } @@ -237,8 +232,7 @@ parse_Port(ParsedPort& port, Section const& section, std::ostream& log) auto const optResult = section.get("protocol"); if (optResult) { - for (auto const& s : beast::rfc2616::split_commas( - optResult->begin(), optResult->end())) + for (auto const& s : beast::rfc2616::split_commas(optResult->begin(), optResult->end())) port.protocol.insert(s); } } @@ -250,8 +244,7 @@ parse_Port(ParsedPort& port, Section const& section, std::ostream& log) { try { - port.limit = - safe_cast(beast::lexicalCastThrow(lim)); + port.limit = safe_cast(beast::lexicalCastThrow(lim)); } catch (std::exception const&) { @@ -268,8 +261,7 @@ parse_Port(ParsedPort& port, Section const& section, std::ostream& log) { try { - port.ws_queue_limit = - beast::lexicalCastThrow(*optResult); + port.ws_queue_limit = beast::lexicalCastThrow(*optResult); // Queue must be greater than 0 if (port.ws_queue_limit == 0) @@ -290,12 +282,7 @@ parse_Port(ParsedPort& port, Section const& section, std::ostream& log) } populate(section, "admin", log, port.admin_nets_v4, port.admin_nets_v6); - populate( - section, - "secure_gateway", - log, - port.secure_gateway_nets_v4, - port.secure_gateway_nets_v6); + populate(section, "secure_gateway", log, port.secure_gateway_nets_v4, port.secure_gateway_nets_v6); set(port.user, "user", section); set(port.password, "password", section); @@ -306,16 +293,11 @@ parse_Port(ParsedPort& port, Section const& section, std::ostream& log) set(port.ssl_chain, "ssl_chain", section); set(port.ssl_ciphers, "ssl_ciphers", section); - port.pmd_options.server_enable = - section.value_or("permessage_deflate", true); - port.pmd_options.client_max_window_bits = - section.value_or("client_max_window_bits", 15); - port.pmd_options.server_max_window_bits = - section.value_or("server_max_window_bits", 15); - port.pmd_options.client_no_context_takeover = - section.value_or("client_no_context_takeover", false); - port.pmd_options.server_no_context_takeover = - section.value_or("server_no_context_takeover", false); + port.pmd_options.server_enable = section.value_or("permessage_deflate", true); + port.pmd_options.client_max_window_bits = section.value_or("client_max_window_bits", 15); + port.pmd_options.server_max_window_bits = section.value_or("server_max_window_bits", 15); + port.pmd_options.client_no_context_takeover = section.value_or("client_no_context_takeover", false); + port.pmd_options.server_no_context_takeover = section.value_or("server_no_context_takeover", false); port.pmd_options.compLevel = section.value_or("compress_level", 8); port.pmd_options.memLevel = section.value_or("memory_level", 4); } diff --git a/src/xrpld/app/rdb/detail/State.cpp b/src/libxrpl/server/State.cpp similarity index 81% rename from src/xrpld/app/rdb/detail/State.cpp rename to src/libxrpl/server/State.cpp index 984c8824f2..4e3a1584c2 100644 --- a/src/xrpld/app/rdb/detail/State.cpp +++ b/src/libxrpl/server/State.cpp @@ -1,12 +1,9 @@ -#include +#include namespace xrpl { void -initStateDB( - soci::session& session, - BasicConfig const& config, - std::string const& dbName) +initStateDB(soci::session& session, BasicConfig const& config, std::string const& dbName) { open(session, config, dbName); @@ -28,11 +25,9 @@ initStateDB( { // SOCI requires boost::optional (not std::optional) as the parameter. boost::optional countO; - session << "SELECT COUNT(Key) FROM DbState WHERE Key = 1;", - soci::into(countO); + session << "SELECT COUNT(Key) FROM DbState WHERE Key = 1;", soci::into(countO); if (!countO) - Throw( - "Failed to fetch Key Count from DbState."); + Throw("Failed to fetch Key Count from DbState."); count = *countO; } @@ -44,11 +39,9 @@ initStateDB( { // SOCI requires boost::optional (not std::optional) as the parameter. boost::optional countO; - session << "SELECT COUNT(Key) FROM CanDelete WHERE Key = 1;", - soci::into(countO); + session << "SELECT COUNT(Key) FROM CanDelete WHERE Key = 1;", soci::into(countO); if (!countO) - Throw( - "Failed to fetch Key Count from CanDelete."); + Throw("Failed to fetch Key Count from CanDelete."); count = *countO; } @@ -62,8 +55,7 @@ LedgerIndex getCanDelete(soci::session& session) { LedgerIndex seq; - session << "SELECT CanDeleteSeq FROM CanDelete WHERE Key = 1;", - soci::into(seq); + session << "SELECT CanDeleteSeq FROM CanDelete WHERE Key = 1;", soci::into(seq); ; return seq; } @@ -71,8 +63,7 @@ getCanDelete(soci::session& session) LedgerIndex setCanDelete(soci::session& session, LedgerIndex canDelete) { - session << "UPDATE CanDelete SET CanDeleteSeq = :canDelete WHERE Key = 1;", - soci::use(canDelete); + session << "UPDATE CanDelete SET CanDeleteSeq = :canDelete WHERE Key = 1;", soci::use(canDelete); return canDelete; } @@ -82,8 +73,7 @@ getSavedState(soci::session& session) SavedState state; session << "SELECT WritableDb, ArchiveDb, LastRotatedLedger" " FROM DbState WHERE Key = 1;", - soci::into(state.writableDb), soci::into(state.archiveDb), - soci::into(state.lastRotated); + soci::into(state.writableDb), soci::into(state.archiveDb), soci::into(state.lastRotated); return state; } @@ -96,8 +86,7 @@ setSavedState(soci::session& session, SavedState const& state) " ArchiveDb = :archiveDb," " LastRotatedLedger = :lastRotated" " WHERE Key = 1;", - soci::use(state.writableDb), soci::use(state.archiveDb), - soci::use(state.lastRotated); + soci::use(state.writableDb), soci::use(state.archiveDb), soci::use(state.lastRotated); } void diff --git a/src/xrpld/app/rdb/detail/Vacuum.cpp b/src/libxrpl/server/Vacuum.cpp similarity index 65% rename from src/xrpld/app/rdb/detail/Vacuum.cpp rename to src/libxrpl/server/Vacuum.cpp index 8423f20992..cb31c6fa7a 100644 --- a/src/xrpld/app/rdb/detail/Vacuum.cpp +++ b/src/libxrpl/server/Vacuum.cpp @@ -1,7 +1,9 @@ -#include +#include #include +#include + namespace xrpl { bool @@ -10,22 +12,18 @@ doVacuumDB(DatabaseCon::Setup const& setup, beast::Journal j) boost::filesystem::path dbPath = setup.dataDir / TxDBName; uintmax_t const dbSize = file_size(dbPath); - XRPL_ASSERT( - dbSize != static_cast(-1), - "ripple:doVacuumDB : file_size succeeded"); + XRPL_ASSERT(dbSize != static_cast(-1), "ripple:doVacuumDB : file_size succeeded"); - if (auto available = space(dbPath.parent_path()).available; - available < dbSize) + if (auto available = space(dbPath.parent_path()).available; available < dbSize) { std::cerr << "The database filesystem must have at least as " "much free space as the size of " - << dbPath.string() << ", which is " << dbSize - << " bytes. Only " << available << " bytes are available.\n"; + << dbPath.string() << ", which is " << dbSize << " bytes. Only " << available + << " bytes are available.\n"; return false; } - auto txnDB = std::make_unique( - setup, TxDBName, setup.txPragma, TxDBInit, j); + auto txnDB = std::make_unique(setup, TxDBName, setup.txPragma, TxDBInit, j); auto& session = txnDB->getSession(); std::uint32_t pageSize; @@ -38,8 +36,7 @@ doVacuumDB(DatabaseCon::Setup const& setup, beast::Journal j) std::cout << "VACUUM beginning. page_size: " << pageSize << std::endl; session << "VACUUM;"; - XRPL_ASSERT( - setup.globalPragma, "ripple:doVacuumDB : non-null global pragma"); + XRPL_ASSERT(setup.globalPragma, "ripple:doVacuumDB : non-null global pragma"); for (auto const& p : *setup.globalPragma) session << p; session << "PRAGMA page_size;", soci::into(pageSize); diff --git a/src/xrpld/app/rdb/detail/Wallet.cpp b/src/libxrpl/server/Wallet.cpp similarity index 79% rename from src/xrpld/app/rdb/detail/Wallet.cpp rename to src/libxrpl/server/Wallet.cpp index fc4f5ea89b..51f1326674 100644 --- a/src/xrpld/app/rdb/detail/Wallet.cpp +++ b/src/libxrpl/server/Wallet.cpp @@ -1,4 +1,5 @@ -#include +#include +#include #include @@ -8,27 +9,18 @@ std::unique_ptr makeWalletDB(DatabaseCon::Setup const& setup, beast::Journal j) { // wallet database - return std::make_unique( - setup, WalletDBName, std::array(), WalletDBInit, j); + return std::make_unique(setup, WalletDBName, std::array(), WalletDBInit, j); } std::unique_ptr -makeTestWalletDB( - DatabaseCon::Setup const& setup, - std::string const& dbname, - beast::Journal j) +makeTestWalletDB(DatabaseCon::Setup const& setup, std::string const& dbname, beast::Journal j) { // wallet database - return std::make_unique( - setup, dbname.data(), std::array(), WalletDBInit, j); + return std::make_unique(setup, dbname.data(), std::array(), WalletDBInit, j); } void -getManifests( - soci::session& session, - std::string const& dbTable, - ManifestCache& mCache, - beast::Journal j) +getManifests(soci::session& session, std::string const& dbTable, ManifestCache& mCache, beast::Journal j) { // Load manifests stored in database std::string const sql = "SELECT RawData FROM " + dbTable + ";"; @@ -57,18 +49,14 @@ getManifests( } static void -saveManifest( - soci::session& session, - std::string const& dbTable, - std::string const& serialized) +saveManifest(soci::session& session, std::string const& dbTable, std::string const& serialized) { // soci does not support bulk insertion of blob data // Do not reuse blob because manifest ecdsa signatures vary in length // but blob write length is expected to be >= the last write soci::blob rawData(session); convert(serialized, rawData); - session << "INSERT INTO " << dbTable << " (RawData) VALUES (:rawData);", - soci::use(rawData); + session << "INSERT INTO " << dbTable << " (RawData) VALUES (:rawData);", soci::use(rawData); } void @@ -117,17 +105,14 @@ getNodeIdentity(soci::session& session) // SOCI requires boost::optional (not std::optional) as the parameter. boost::optional pubKO, priKO; soci::statement st = - (session.prepare - << "SELECT PublicKey, PrivateKey FROM NodeIdentity;", + (session.prepare << "SELECT PublicKey, PrivateKey FROM NodeIdentity;", soci::into(pubKO), soci::into(priKO)); st.execute(); while (st.fetch()) { - auto const sk = parseBase58( - TokenType::NodePrivate, priKO.value_or("")); - auto const pk = parseBase58( - TokenType::NodePublic, pubKO.value_or("")); + auto const sk = parseBase58(TokenType::NodePrivate, priKO.value_or("")); + auto const pk = parseBase58(TokenType::NodePublic, pubKO.value_or("")); // Only use if the public and secret keys are a pair if (sk && pk && (*pk == derivePublicKey(KeyType::secp256k1, *sk))) @@ -141,8 +126,7 @@ getNodeIdentity(soci::session& session) session << str( boost::format("INSERT INTO NodeIdentity (PublicKey,PrivateKey) " "VALUES ('%s','%s');") % - toBase58(TokenType::NodePublic, newpublicKey) % - toBase58(TokenType::NodePrivate, newsecretKey)); + toBase58(TokenType::NodePublic, newpublicKey) % toBase58(TokenType::NodePrivate, newsecretKey)); return {newpublicKey, newsecretKey}; } @@ -158,8 +142,7 @@ getPeerReservationTable(soci::session& session, beast::Journal j) // but no one else does. Because it is too tedious? It would be easy if we // had a jOOQ for C++. soci::statement st = - (session.prepare - << "SELECT PublicKey, Description FROM PeerReservations;", + (session.prepare << "SELECT PublicKey, Description FROM PeerReservations;", soci::into(valPubKey), soci::into(valDesc)); st.execute(); @@ -171,8 +154,7 @@ getPeerReservationTable(soci::session& session, beast::Journal j) // unreachable. continue; } - auto const optNodeId = - parseBase58(TokenType::NodePublic, *valPubKey); + auto const optNodeId = parseBase58(TokenType::NodePublic, *valPubKey); if (!optNodeId) { JLOG(j.warn()) << "load: not a public key: " << valPubKey; @@ -185,10 +167,7 @@ getPeerReservationTable(soci::session& session, beast::Journal j) } void -insertPeerReservation( - soci::session& session, - PublicKey const& nodeId, - std::string const& description) +insertPeerReservation(soci::session& session, PublicKey const& nodeId, std::string const& description) { auto const sNodeId = toBase58(TokenType::NodePublic, nodeId); session << "INSERT INTO PeerReservations (PublicKey, Description) " @@ -202,8 +181,7 @@ void deletePeerReservation(soci::session& session, PublicKey const& nodeId) { auto const sNodeId = toBase58(TokenType::NodePublic, nodeId); - session << "DELETE FROM PeerReservations WHERE PublicKey = :nodeId", - soci::use(sNodeId); + session << "DELETE FROM PeerReservations WHERE PublicKey = :nodeId", soci::use(sNodeId); } bool @@ -239,8 +217,7 @@ readAmendments( boost::optional vote)> const& callback) { // lambda that converts the internally stored int to an AmendmentVote. - auto intToVote = [](boost::optional const& dbVote) - -> boost::optional { + auto intToVote = [](boost::optional const& dbVote) -> boost::optional { return safe_cast(dbVote.value_or(1)); }; @@ -255,10 +232,7 @@ readAmendments( boost::optional amendment_name; boost::optional vote_to_veto; soci::statement st = - (session.prepare << sql, - soci::into(amendment_hash), - soci::into(amendment_name), - soci::into(vote_to_veto)); + (session.prepare << sql, soci::into(amendment_hash), soci::into(amendment_name), soci::into(vote_to_veto)); st.execute(); while (st.fetch()) { @@ -267,11 +241,7 @@ readAmendments( } void -voteAmendment( - soci::session& session, - uint256 const& amendment, - std::string const& name, - AmendmentVote vote) +voteAmendment(soci::session& session, uint256 const& amendment, std::string const& name, AmendmentVote vote) { soci::transaction tr(session); std::string sql = diff --git a/src/libxrpl/shamap/SHAMap.cpp b/src/libxrpl/shamap/SHAMap.cpp index 2a156dc2d4..e84a620b77 100644 --- a/src/libxrpl/shamap/SHAMap.cpp +++ b/src/libxrpl/shamap/SHAMap.cpp @@ -10,30 +10,23 @@ namespace xrpl { [[nodiscard]] intr_ptr::SharedPtr -makeTypedLeaf( - SHAMapNodeType type, - boost::intrusive_ptr item, - std::uint32_t owner) +makeTypedLeaf(SHAMapNodeType type, boost::intrusive_ptr item, std::uint32_t owner) { if (type == SHAMapNodeType::tnTRANSACTION_NM) return intr_ptr::make_shared(std::move(item), owner); if (type == SHAMapNodeType::tnTRANSACTION_MD) - return intr_ptr::make_shared( - std::move(item), owner); + return intr_ptr::make_shared(std::move(item), owner); if (type == SHAMapNodeType::tnACCOUNT_STATE) - return intr_ptr::make_shared( - std::move(item), owner); + return intr_ptr::make_shared(std::move(item), owner); LogicError( "Attempt to create leaf node of unknown type " + - std::to_string( - static_cast>(type))); + std::to_string(static_cast>(type))); } -SHAMap::SHAMap(SHAMapType t, Family& f) - : f_(f), journal_(f.journal()), state_(SHAMapState::Modifying), type_(t) +SHAMap::SHAMap(SHAMapType t, Family& f) : f_(f), journal_(f.journal()), state_(SHAMapState::Modifying), type_(t) { root_ = intr_ptr::make_shared(cowid_); } @@ -59,8 +52,7 @@ SHAMap::SHAMap(SHAMap const& other, bool isMutable) , backed_(other.backed_) { // If either map may change, they cannot share nodes - if ((state_ != SHAMapState::Immutable) || - (other.state_ != SHAMapState::Immutable)) + if ((state_ != SHAMapState::Immutable) || (other.state_ != SHAMapState::Immutable)) { unshare(); } @@ -73,10 +65,7 @@ SHAMap::snapShot(bool isMutable) const } void -SHAMap::dirtyUp( - SharedPtrNodeStack& stack, - uint256 const& target, - intr_ptr::SharedPtr child) +SHAMap::dirtyUp(SharedPtrNodeStack& stack, uint256 const& target, intr_ptr::SharedPtr child) { // walk the tree up from through the inner nodes to the root_ // update hashes and links @@ -84,16 +73,12 @@ SHAMap::dirtyUp( // child can be an inner node or a leaf XRPL_ASSERT( - (state_ != SHAMapState::Synching) && (state_ != SHAMapState::Immutable), - "xrpl::SHAMap::dirtyUp : valid state"); - XRPL_ASSERT( - child && (child->cowid() == cowid_), - "xrpl::SHAMap::dirtyUp : valid child input"); + (state_ != SHAMapState::Synching) && (state_ != SHAMapState::Immutable), "xrpl::SHAMap::dirtyUp : valid state"); + XRPL_ASSERT(child && (child->cowid() == cowid_), "xrpl::SHAMap::dirtyUp : valid child input"); while (!stack.empty()) { - auto node = - intr_ptr::dynamic_pointer_cast(stack.top().first); + auto node = intr_ptr::dynamic_pointer_cast(stack.top().first); SHAMapNodeID nodeID = stack.top().second; stack.pop(); XRPL_ASSERT(node, "xrpl::SHAMap::dirtyUp : non-null node"); @@ -111,9 +96,7 @@ SHAMap::dirtyUp( SHAMapLeafNode* SHAMap::walkTowardsKey(uint256 const& id, SharedPtrNodeStack* stack) const { - XRPL_ASSERT( - stack == nullptr || stack->empty(), - "xrpl::SHAMap::walkTowardsKey : empty stack input"); + XRPL_ASSERT(stack == nullptr || stack->empty(), "xrpl::SHAMap::walkTowardsKey : empty stack input"); auto inNode = root_; SHAMapNodeID nodeID; @@ -122,8 +105,7 @@ SHAMap::walkTowardsKey(uint256 const& id, SharedPtrNodeStack* stack) const if (stack != nullptr) stack->push({inNode, nodeID}); - auto const inner = - intr_ptr::static_pointer_cast(inNode); + auto const inner = intr_ptr::static_pointer_cast(inNode); auto const branch = selectBranch(nodeID, id); if (inner->isEmptyBranch(branch)) return nullptr; @@ -155,9 +137,7 @@ SHAMap::fetchNodeFromDB(SHAMapHash const& hash) const } intr_ptr::SharedPtr -SHAMap::finishFetch( - SHAMapHash const& hash, - std::shared_ptr const& object) const +SHAMap::finishFetch(SHAMapHash const& hash, std::shared_ptr const& object) const { XRPL_ASSERT(backed_, "xrpl::SHAMap::finishFetch : is backed"); @@ -173,8 +153,7 @@ SHAMap::finishFetch( return {}; } - auto node = - SHAMapTreeNode::makeFromPrefix(makeSlice(object->getData()), hash); + auto node = SHAMapTreeNode::makeFromPrefix(makeSlice(object->getData()), hash); if (node) canonicalize(hash, node); return node; @@ -185,8 +164,7 @@ SHAMap::finishFetch( } catch (...) { - JLOG(journal_.warn()) - << "finishFetch exception: unknown exception: " << hash; + JLOG(journal_.warn()) << "finishFetch exception: unknown exception: " << hash; } return {}; @@ -200,16 +178,10 @@ SHAMap::checkFilter(SHAMapHash const& hash, SHAMapSyncFilter* filter) const { try { - auto node = - SHAMapTreeNode::makeFromPrefix(makeSlice(*nodeData), hash); + auto node = SHAMapTreeNode::makeFromPrefix(makeSlice(*nodeData), hash); if (node) { - filter->gotNode( - true, - hash, - ledgerSeq_, - std::move(*nodeData), - node->getType()); + filter->gotNode(true, hash, ledgerSeq_, std::move(*nodeData), node->getType()); if (backed_) canonicalize(hash, node); } @@ -217,8 +189,7 @@ SHAMap::checkFilter(SHAMapHash const& hash, SHAMapSyncFilter* filter) const } catch (std::exception const& x) { - JLOG(f_.journal().warn()) - << "Invalid node/data, hash=" << hash << ": " << x.what(); + JLOG(f_.journal().warn()) << "Invalid node/data, hash=" << hash << ": " << x.what(); } } return {}; @@ -301,8 +272,7 @@ SHAMap::descend(SHAMapInnerNode* parent, int branch) const if (ret || !backed_) return ret; - intr_ptr::SharedPtr node = - fetchNodeNT(parent->getChildHash(branch)); + intr_ptr::SharedPtr node = fetchNodeNT(parent->getChildHash(branch)); if (!node) return nullptr; @@ -337,28 +307,18 @@ SHAMap::descendNoStore(SHAMapInnerNode& parent, int branch) const } std::pair -SHAMap::descend( - SHAMapInnerNode* parent, - SHAMapNodeID const& parentID, - int branch, - SHAMapSyncFilter* filter) const +SHAMap::descend(SHAMapInnerNode* parent, SHAMapNodeID const& parentID, int branch, SHAMapSyncFilter* filter) const { - XRPL_ASSERT( - parent->isInner(), "xrpl::SHAMap::descend : valid parent input"); - XRPL_ASSERT( - (branch >= 0) && (branch < branchFactor), - "xrpl::SHAMap::descend : valid branch input"); - XRPL_ASSERT( - !parent->isEmptyBranch(branch), - "xrpl::SHAMap::descend : parent branch is non-empty"); + XRPL_ASSERT(parent->isInner(), "xrpl::SHAMap::descend : valid parent input"); + XRPL_ASSERT((branch >= 0) && (branch < branchFactor), "xrpl::SHAMap::descend : valid branch input"); + XRPL_ASSERT(!parent->isEmptyBranch(branch), "xrpl::SHAMap::descend : parent branch is non-empty"); SHAMapTreeNode* child = parent->getChildPointer(branch); if (!child) { auto const& childHash = parent->getChildHash(branch); - intr_ptr::SharedPtr childNode = - fetchNodeNT(childHash, filter); + intr_ptr::SharedPtr childNode = fetchNodeNT(childHash, filter); if (childNode) { @@ -397,8 +357,7 @@ SHAMap::descendAsync( f_.db().asyncFetch( hash.as_uint256(), ledgerSeq_, - [this, hash, cb{std::move(callback)}]( - std::shared_ptr const& object) { + [this, hash, cb{std::move(callback)}](std::shared_ptr const& object) { auto node = finishFetch(hash, object); cb(node, hash); }); @@ -418,15 +377,11 @@ intr_ptr::SharedPtr SHAMap::unshareNode(intr_ptr::SharedPtr node, SHAMapNodeID const& nodeID) { // make sure the node is suitable for the intended operation (copy on write) - XRPL_ASSERT( - node->cowid() <= cowid_, - "xrpl::SHAMap::unshareNode : node valid for cowid"); + XRPL_ASSERT(node->cowid() <= cowid_, "xrpl::SHAMap::unshareNode : node valid for cowid"); if (node->cowid() != cowid_) { // have a CoW - XRPL_ASSERT( - state_ != SHAMapState::Immutable, - "xrpl::SHAMap::unshareNode : not immutable"); + XRPL_ASSERT(state_ != SHAMapState::Immutable, "xrpl::SHAMap::unshareNode : not immutable"); node = intr_ptr::static_pointer_cast(node->clone(cowid_)); if (nodeID.isRoot()) root_ = node; @@ -439,8 +394,7 @@ SHAMap::belowHelper( intr_ptr::SharedPtr node, SharedPtrNodeStack& stack, int branch, - std::tuple, std::function> const& - loopParams) const + std::tuple, std::function> const& loopParams) const { auto& [init, cmp, incr] = loopParams; if (node->isLeaf()) @@ -459,8 +413,7 @@ SHAMap::belowHelper( if (!inner->isEmptyBranch(i)) { node.adopt(descendThrow(inner.get(), i)); - XRPL_ASSERT( - !stack.empty(), "xrpl::SHAMap::belowHelper : non-empty stack"); + XRPL_ASSERT(!stack.empty(), "xrpl::SHAMap::belowHelper : non-empty stack"); if (node->isLeaf()) { auto n = intr_ptr::static_pointer_cast(node); @@ -477,10 +430,7 @@ SHAMap::belowHelper( return nullptr; } SHAMapLeafNode* -SHAMap::lastBelow( - intr_ptr::SharedPtr node, - SharedPtrNodeStack& stack, - int branch) const +SHAMap::lastBelow(intr_ptr::SharedPtr node, SharedPtrNodeStack& stack, int branch) const { auto init = branchFactor - 1; auto cmp = [](int i) { return i >= 0; }; @@ -489,10 +439,7 @@ SHAMap::lastBelow( return belowHelper(node, stack, branch, {init, cmp, incr}); } SHAMapLeafNode* -SHAMap::firstBelow( - intr_ptr::SharedPtr node, - SharedPtrNodeStack& stack, - int branch) const +SHAMap::firstBelow(intr_ptr::SharedPtr node, SharedPtrNodeStack& stack, int branch) const { auto init = 0; auto cmp = [](int i) { return i <= branchFactor; }; @@ -536,17 +483,14 @@ SHAMap::onlyBelow(SHAMapTreeNode* node) const // An inner node must have at least one leaf // below it, unless it's the root_ auto const leaf = static_cast(node); - XRPL_ASSERT( - leaf->peekItem() || (leaf == root_.get()), - "xrpl::SHAMap::onlyBelow : valid inner node"); + XRPL_ASSERT(leaf->peekItem() || (leaf == root_.get()), "xrpl::SHAMap::onlyBelow : valid inner node"); return leaf->peekItem(); } SHAMapLeafNode const* SHAMap::peekFirstItem(SharedPtrNodeStack& stack) const { - XRPL_ASSERT( - stack.empty(), "xrpl::SHAMap::peekFirstItem : empty stack input"); + XRPL_ASSERT(stack.empty(), "xrpl::SHAMap::peekFirstItem : empty stack input"); SHAMapLeafNode* node = firstBelow(root_, stack); if (!node) { @@ -560,18 +504,13 @@ SHAMap::peekFirstItem(SharedPtrNodeStack& stack) const SHAMapLeafNode const* SHAMap::peekNextItem(uint256 const& id, SharedPtrNodeStack& stack) const { - XRPL_ASSERT( - !stack.empty(), "xrpl::SHAMap::peekNextItem : non-empty stack input"); - XRPL_ASSERT( - stack.top().first->isLeaf(), - "xrpl::SHAMap::peekNextItem : stack starts with leaf"); + XRPL_ASSERT(!stack.empty(), "xrpl::SHAMap::peekNextItem : non-empty stack input"); + XRPL_ASSERT(stack.top().first->isLeaf(), "xrpl::SHAMap::peekNextItem : stack starts with leaf"); stack.pop(); while (!stack.empty()) { auto [node, nodeID] = stack.top(); - XRPL_ASSERT( - !node->isLeaf(), - "xrpl::SHAMap::peekNextItem : another node is not leaf"); + XRPL_ASSERT(!node->isLeaf(), "xrpl::SHAMap::peekNextItem : another node is not leaf"); auto inner = intr_ptr::static_pointer_cast(node); for (auto i = selectBranch(nodeID, id) + 1; i < branchFactor; ++i) { @@ -581,9 +520,7 @@ SHAMap::peekNextItem(uint256 const& id, SharedPtrNodeStack& stack) const auto leaf = firstBelow(node, stack, i); if (!leaf) Throw(type_, id); - XRPL_ASSERT( - leaf->isLeaf(), - "xrpl::SHAMap::peekNextItem : leaf is valid"); + XRPL_ASSERT(leaf->isLeaf(), "xrpl::SHAMap::peekNextItem : leaf is valid"); return leaf; } } @@ -628,15 +565,12 @@ SHAMap::upper_bound(uint256 const& id) const { auto leaf = static_cast(node.get()); if (leaf->peekItem()->key() > id) - return const_iterator( - this, leaf->peekItem().get(), std::move(stack)); + return const_iterator(this, leaf->peekItem().get(), std::move(stack)); } else { auto inner = intr_ptr::static_pointer_cast(node); - for (auto branch = selectBranch(nodeID, id) + 1; - branch < branchFactor; - ++branch) + for (auto branch = selectBranch(nodeID, id) + 1; branch < branchFactor; ++branch) { if (!inner->isEmptyBranch(branch)) { @@ -644,8 +578,7 @@ SHAMap::upper_bound(uint256 const& id) const auto leaf = firstBelow(node, stack, branch); if (!leaf) Throw(type_, id); - return const_iterator( - this, leaf->peekItem().get(), std::move(stack)); + return const_iterator(this, leaf->peekItem().get(), std::move(stack)); } } } @@ -665,14 +598,12 @@ SHAMap::lower_bound(uint256 const& id) const { auto leaf = static_cast(node.get()); if (leaf->peekItem()->key() < id) - return const_iterator( - this, leaf->peekItem().get(), std::move(stack)); + return const_iterator(this, leaf->peekItem().get(), std::move(stack)); } else { auto inner = intr_ptr::static_pointer_cast(node); - for (int branch = selectBranch(nodeID, id) - 1; branch >= 0; - --branch) + for (int branch = selectBranch(nodeID, id) - 1; branch >= 0; --branch) { if (!inner->isEmptyBranch(branch)) { @@ -680,8 +611,7 @@ SHAMap::lower_bound(uint256 const& id) const auto leaf = lastBelow(node, stack, branch); if (!leaf) Throw(type_, id); - return const_iterator( - this, leaf->peekItem().get(), std::move(stack)); + return const_iterator(this, leaf->peekItem().get(), std::move(stack)); } } } @@ -701,9 +631,7 @@ bool SHAMap::delItem(uint256 const& id) { // delete the item with this ID - XRPL_ASSERT( - state_ != SHAMapState::Immutable, - "xrpl::SHAMap::delItem : not immutable"); + XRPL_ASSERT(state_ != SHAMapState::Immutable, "xrpl::SHAMap::delItem : not immutable"); SharedPtrNodeStack stack; walkTowardsKey(id, &stack); @@ -711,8 +639,7 @@ SHAMap::delItem(uint256 const& id) if (stack.empty()) Throw(type_, id); - auto leaf = - intr_ptr::dynamic_pointer_cast(stack.top().first); + auto leaf = intr_ptr::dynamic_pointer_cast(stack.top().first); stack.pop(); if (!leaf || (leaf->peekItem()->key() != id)) @@ -726,8 +653,7 @@ SHAMap::delItem(uint256 const& id) while (!stack.empty()) { - auto node = - intr_ptr::static_pointer_cast(stack.top().first); + auto node = intr_ptr::static_pointer_cast(stack.top().first); SHAMapNodeID nodeID = stack.top().second; stack.pop(); @@ -755,8 +681,7 @@ SHAMap::delItem(uint256 const& id) { if (!node->isEmptyBranch(i)) { - node->setChild( - i, intr_ptr::SharedPtr{}); + node->setChild(i, intr_ptr::SharedPtr{}); break; } } @@ -780,16 +705,10 @@ SHAMap::delItem(uint256 const& id) } bool -SHAMap::addGiveItem( - SHAMapNodeType type, - boost::intrusive_ptr item) +SHAMap::addGiveItem(SHAMapNodeType type, boost::intrusive_ptr item) { - XRPL_ASSERT( - state_ != SHAMapState::Immutable, - "xrpl::SHAMap::addGiveItem : not immutable"); - XRPL_ASSERT( - type != SHAMapNodeType::tnINNER, - "xrpl::SHAMap::addGiveItem : valid type input"); + XRPL_ASSERT(state_ != SHAMapState::Immutable, "xrpl::SHAMap::addGiveItem : not immutable"); + XRPL_ASSERT(type != SHAMapNodeType::tnINNER, "xrpl::SHAMap::addGiveItem : valid type input"); // add the specified item, does not update uint256 tag = item->key(); @@ -815,9 +734,7 @@ SHAMap::addGiveItem( // easy case, we end on an inner node auto inner = intr_ptr::static_pointer_cast(node); int branch = selectBranch(nodeID, tag); - XRPL_ASSERT( - inner->isEmptyBranch(branch), - "xrpl::SHAMap::addGiveItem : inner branch is empty"); + XRPL_ASSERT(inner->isEmptyBranch(branch), "xrpl::SHAMap::addGiveItem : inner branch is empty"); inner->setChild(branch, makeTypedLeaf(type, std::move(item), cowid_)); } else @@ -826,16 +743,13 @@ SHAMap::addGiveItem( // items auto leaf = intr_ptr::static_pointer_cast(node); auto otherItem = leaf->peekItem(); - XRPL_ASSERT( - otherItem && (tag != otherItem->key()), - "xrpl::SHAMap::addGiveItem : non-null item"); + XRPL_ASSERT(otherItem && (tag != otherItem->key()), "xrpl::SHAMap::addGiveItem : non-null item"); node = intr_ptr::make_shared(node->cowid()); unsigned int b1, b2; - while ((b1 = selectBranch(nodeID, tag)) == - (b2 = selectBranch(nodeID, otherItem->key()))) + while ((b1 = selectBranch(nodeID, tag)) == (b2 = selectBranch(nodeID, otherItem->key()))) { stack.push({node, nodeID}); @@ -846,8 +760,7 @@ SHAMap::addGiveItem( } // we can add the two leaf nodes here - XRPL_ASSERT( - node->isInner(), "xrpl::SHAMap::addGiveItem : node is inner"); + XRPL_ASSERT(node->isInner(), "xrpl::SHAMap::addGiveItem : node is inner"); auto inner = static_cast(node.get()); inner->setChild(b1, makeTypedLeaf(type, std::move(item), cowid_)); @@ -859,9 +772,7 @@ SHAMap::addGiveItem( } bool -SHAMap::addItem( - SHAMapNodeType type, - boost::intrusive_ptr item) +SHAMap::addItem(SHAMapNodeType type, boost::intrusive_ptr item) { return addGiveItem(type, std::move(item)); } @@ -879,16 +790,12 @@ SHAMap::getHash() const } bool -SHAMap::updateGiveItem( - SHAMapNodeType type, - boost::intrusive_ptr item) +SHAMap::updateGiveItem(SHAMapNodeType type, boost::intrusive_ptr item) { // can't change the tag but can change the hash uint256 tag = item->key(); - XRPL_ASSERT( - state_ != SHAMapState::Immutable, - "xrpl::SHAMap::updateGiveItem : not immutable"); + XRPL_ASSERT(state_ != SHAMapState::Immutable, "xrpl::SHAMap::updateGiveItem : not immutable"); SharedPtrNodeStack stack; walkTowardsKey(tag, &stack); @@ -896,8 +803,7 @@ SHAMap::updateGiveItem( if (stack.empty()) Throw(type_, tag); - auto node = - intr_ptr::dynamic_pointer_cast(stack.top().first); + auto node = intr_ptr::dynamic_pointer_cast(stack.top().first); auto nodeID = stack.top().second; stack.pop(); @@ -950,9 +856,7 @@ SHAMap::fetchRoot(SHAMapHash const& hash, SHAMapSyncFilter* filter) if (newRoot) { root_ = newRoot; - XRPL_ASSERT( - root_->getHash() == hash, - "xrpl::SHAMap::fetchRoot : root hash do match"); + XRPL_ASSERT(root_->getHash() == hash, "xrpl::SHAMap::fetchRoot : root hash do match"); return true; } @@ -972,19 +876,16 @@ SHAMap::fetchRoot(SHAMapHash const& hash, SHAMapSyncFilter* filter) first call SHAMapTreeNode::unshare(). */ intr_ptr::SharedPtr -SHAMap::writeNode(NodeObjectType t, intr_ptr::SharedPtr node) - const +SHAMap::writeNode(NodeObjectType t, intr_ptr::SharedPtr node) const { - XRPL_ASSERT( - node->cowid() == 0, "xrpl::SHAMap::writeNode : valid input node"); + XRPL_ASSERT(node->cowid() == 0, "xrpl::SHAMap::writeNode : valid input node"); XRPL_ASSERT(backed_, "xrpl::SHAMap::writeNode : is backed"); canonicalize(node->getHash(), node); Serializer s; node->serializeWithPrefix(s); - f_.db().store( - t, std::move(s.modData()), node->getHash().as_uint256(), ledgerSeq_); + f_.db().store(t, std::move(s.modData()), node->getHash().as_uint256(), ledgerSeq_); return node; } @@ -1091,8 +992,7 @@ SHAMap::walkSubTree(bool doWrite, NodeObjectType t) // The semantics of this changes when we move to c++-20 // Right now no move will occur; With c++-20 child will // be moved from. - node = intr_ptr::static_pointer_cast( - std::move(child)); + node = intr_ptr::static_pointer_cast(std::move(child)); pos = 0; } else @@ -1123,8 +1023,7 @@ SHAMap::walkSubTree(bool doWrite, NodeObjectType t) node->unshare(); if (doWrite) - node = intr_ptr::static_pointer_cast( - writeNode(t, std::move(node))); + node = intr_ptr::static_pointer_cast(writeNode(t, std::move(node))); ++flushed; @@ -1136,9 +1035,7 @@ SHAMap::walkSubTree(bool doWrite, NodeObjectType t) stack.pop(); // Hook this inner node to its parent - XRPL_ASSERT( - parent->cowid() == cowid_, - "xrpl::SHAMap::walkSubTree : parent cowid do match"); + XRPL_ASSERT(parent->cowid() == cowid_, "xrpl::SHAMap::walkSubTree : parent cowid do match"); parent->shareChild(pos, node); // Continue with parent's next child, if any @@ -1183,8 +1080,7 @@ SHAMap::dump(bool hash) const if (child) { XRPL_ASSERT( - child->getHash() == inner->getChildHash(i), - "xrpl::SHAMap::dump : child hash do match"); + child->getHash() == inner->getChildHash(i), "xrpl::SHAMap::dump : child hash do match"); stack.push({child, nodeID.getChildNodeID(i)}); } } @@ -1201,23 +1097,16 @@ intr_ptr::SharedPtr SHAMap::cacheLookup(SHAMapHash const& hash) const { auto ret = f_.getTreeNodeCache()->fetch(hash.as_uint256()); - XRPL_ASSERT( - !ret || !ret->cowid(), - "xrpl::SHAMap::cacheLookup : not found or zero cowid"); + XRPL_ASSERT(!ret || !ret->cowid(), "xrpl::SHAMap::cacheLookup : not found or zero cowid"); return ret; } void -SHAMap::canonicalize( - SHAMapHash const& hash, - intr_ptr::SharedPtr& node) const +SHAMap::canonicalize(SHAMapHash const& hash, intr_ptr::SharedPtr& node) const { XRPL_ASSERT(backed_, "xrpl::SHAMap::canonicalize : is backed"); - XRPL_ASSERT( - node->cowid() == 0, "xrpl::SHAMap::canonicalize : valid node input"); - XRPL_ASSERT( - node->getHash() == hash, - "xrpl::SHAMap::canonicalize : node hash do match"); + XRPL_ASSERT(node->cowid() == 0, "xrpl::SHAMap::canonicalize : valid node input"); + XRPL_ASSERT(node->getHash() == hash, "xrpl::SHAMap::canonicalize : node hash do match"); f_.getTreeNodeCache()->canonicalize_replace_client(hash.as_uint256(), node); } @@ -1228,11 +1117,9 @@ SHAMap::invariants() const (void)getHash(); // update node hashes auto node = root_.get(); XRPL_ASSERT(node, "xrpl::SHAMap::invariants : non-null root node"); - XRPL_ASSERT( - !node->isLeaf(), "xrpl::SHAMap::invariants : root node is not leaf"); + XRPL_ASSERT(!node->isLeaf(), "xrpl::SHAMap::invariants : root node is not leaf"); SharedPtrNodeStack stack; - for (auto leaf = peekFirstItem(stack); leaf != nullptr; - leaf = peekNextItem(leaf->peekItem()->key(), stack)) + for (auto leaf = peekFirstItem(stack); leaf != nullptr; leaf = peekNextItem(leaf->peekItem()->key(), stack)) ; node->invariants(true); } diff --git a/src/libxrpl/shamap/SHAMapDelta.cpp b/src/libxrpl/shamap/SHAMapDelta.cpp index d7234bcbab..d8aabcc67c 100644 --- a/src/libxrpl/shamap/SHAMapDelta.cpp +++ b/src/libxrpl/shamap/SHAMapDelta.cpp @@ -53,11 +53,9 @@ SHAMap::walkBranch( { // unmatched if (isFirstMap) - differences.insert( - std::make_pair(item->key(), DeltaRef(item, nullptr))); + differences.insert(std::make_pair(item->key(), DeltaRef(item, nullptr))); else - differences.insert( - std::make_pair(item->key(), DeltaRef(nullptr, item))); + differences.insert(std::make_pair(item->key(), DeltaRef(nullptr, item))); if (--maxCount <= 0) return false; @@ -66,11 +64,9 @@ SHAMap::walkBranch( { // non-matching items with same tag if (isFirstMap) - differences.insert(std::make_pair( - item->key(), DeltaRef(item, otherMapItem))); + differences.insert(std::make_pair(item->key(), DeltaRef(item, otherMapItem))); else - differences.insert(std::make_pair( - item->key(), DeltaRef(otherMapItem, item))); + differences.insert(std::make_pair(item->key(), DeltaRef(otherMapItem, item))); if (--maxCount <= 0) return false; @@ -89,11 +85,9 @@ SHAMap::walkBranch( { // otherMapItem was unmatched, must add if (isFirstMap) // this is first map, so other item is from second - differences.insert(std::make_pair( - otherMapItem->key(), DeltaRef(nullptr, otherMapItem))); + differences.insert(std::make_pair(otherMapItem->key(), DeltaRef(nullptr, otherMapItem))); else - differences.insert(std::make_pair( - otherMapItem->key(), DeltaRef(otherMapItem, nullptr))); + differences.insert(std::make_pair(otherMapItem->key(), DeltaRef(otherMapItem, nullptr))); if (--maxCount <= 0) return false; @@ -110,16 +104,13 @@ SHAMap::compare(SHAMap const& otherMap, Delta& differences, int maxCount) const // many differences throws on corrupt tables or missing nodes CAUTION: // otherMap is not locked and must be immutable - XRPL_ASSERT( - isValid() && otherMap.isValid(), - "xrpl::SHAMap::compare : valid state and valid input"); + XRPL_ASSERT(isValid() && otherMap.isValid(), "xrpl::SHAMap::compare : valid state and valid input"); if (getHash() == otherMap.getHash()) return true; using StackEntry = std::pair; - std::stack> - nodeStack; // track nodes we've pushed + std::stack> nodeStack; // track nodes we've pushed nodeStack.push({root_.get(), otherMap.root_.get()}); while (!nodeStack.empty()) @@ -144,24 +135,19 @@ SHAMap::compare(SHAMap const& otherMap, Delta& differences, int maxCount) const { if (ours->peekItem()->slice() != other->peekItem()->slice()) { - differences.insert(std::make_pair( - ours->peekItem()->key(), - DeltaRef(ours->peekItem(), other->peekItem()))); + differences.insert( + std::make_pair(ours->peekItem()->key(), DeltaRef(ours->peekItem(), other->peekItem()))); if (--maxCount <= 0) return false; } } else { - differences.insert(std::make_pair( - ours->peekItem()->key(), - DeltaRef(ours->peekItem(), nullptr))); + differences.insert(std::make_pair(ours->peekItem()->key(), DeltaRef(ours->peekItem(), nullptr))); if (--maxCount <= 0) return false; - differences.insert(std::make_pair( - other->peekItem()->key(), - DeltaRef(nullptr, other->peekItem()))); + differences.insert(std::make_pair(other->peekItem()->key(), DeltaRef(nullptr, other->peekItem()))); if (--maxCount <= 0) return false; } @@ -170,16 +156,14 @@ SHAMap::compare(SHAMap const& otherMap, Delta& differences, int maxCount) const { auto ours = static_cast(ourNode); auto other = static_cast(otherNode); - if (!walkBranch( - ours, other->peekItem(), true, differences, maxCount)) + if (!walkBranch(ours, other->peekItem(), true, differences, maxCount)) return false; } else if (ourNode->isLeaf() && otherNode->isInner()) { auto ours = static_cast(ourNode); auto other = static_cast(otherNode); - if (!otherMap.walkBranch( - other, ours->peekItem(), false, differences, maxCount)) + if (!otherMap.walkBranch(other, ours->peekItem(), false, differences, maxCount)) return false; } else if (ourNode->isInner() && otherNode->isInner()) @@ -193,22 +177,18 @@ SHAMap::compare(SHAMap const& otherMap, Delta& differences, int maxCount) const { // We have a branch, the other tree does not SHAMapTreeNode* iNode = descendThrow(ours, i); - if (!walkBranch( - iNode, nullptr, true, differences, maxCount)) + if (!walkBranch(iNode, nullptr, true, differences, maxCount)) return false; } else if (ours->isEmptyBranch(i)) { // The other tree has a branch, we do not SHAMapTreeNode* iNode = otherMap.descendThrow(other, i); - if (!otherMap.walkBranch( - iNode, nullptr, false, differences, maxCount)) + if (!otherMap.walkBranch(iNode, nullptr, false, differences, maxCount)) return false; } else // The two trees have different non-empty branches - nodeStack.push( - {descendThrow(ours, i), - otherMap.descendThrow(other, i)}); + nodeStack.push({descendThrow(ours, i), otherMap.descendThrow(other, i)}); } } else @@ -223,8 +203,7 @@ SHAMap::compare(SHAMap const& otherMap, Delta& differences, int maxCount) const } void -SHAMap::walkMap(std::vector& missingNodes, int maxMissing) - const +SHAMap::walkMap(std::vector& missingNodes, int maxMissing) const { if (!root_->isInner()) // root_ is only node, and we have it return; @@ -243,15 +222,12 @@ SHAMap::walkMap(std::vector& missingNodes, int maxMissing) { if (!node->isEmptyBranch(i)) { - intr_ptr::SharedPtr nextNode = - descendNoStore(*node, i); + intr_ptr::SharedPtr nextNode = descendNoStore(*node, i); if (nextNode) { if (nextNode->isInner()) - nodeStack.push( - intr_ptr::static_pointer_cast( - nextNode)); + nodeStack.push(intr_ptr::static_pointer_cast(nextNode)); } else { @@ -265,9 +241,7 @@ SHAMap::walkMap(std::vector& missingNodes, int maxMissing) } bool -SHAMap::walkMapParallel( - std::vector& missingNodes, - int maxMissing) const +SHAMap::walkMapParallel(std::vector& missingNodes, int maxMissing) const { if (!root_->isInner()) // root_ is only node, and we have it return false; @@ -275,8 +249,7 @@ SHAMap::walkMapParallel( using StackEntry = intr_ptr::SharedPtr; std::array, 16> topChildren; { - auto const& innerRoot = - intr_ptr::static_pointer_cast(root_); + auto const& innerRoot = intr_ptr::static_pointer_cast(root_); for (int i = 0; i < 16; ++i) { if (!innerRoot->isEmptyBranch(i)) @@ -300,8 +273,7 @@ SHAMap::walkMapParallel( if (!child || !child->isInner()) continue; - nodeStacks[rootChildIndex].push( - intr_ptr::static_pointer_cast(child)); + nodeStacks[rootChildIndex].push(intr_ptr::static_pointer_cast(child)); JLOG(journal_.debug()) << "starting worker " << rootChildIndex; workers.push_back(std::thread( @@ -311,32 +283,25 @@ SHAMap::walkMapParallel( { while (!nodeStack.empty()) { - intr_ptr::SharedPtr node = - std::move(nodeStack.top()); - XRPL_ASSERT( - node, - "xrpl::SHAMap::walkMapParallel : non-null node"); + intr_ptr::SharedPtr node = std::move(nodeStack.top()); + XRPL_ASSERT(node, "xrpl::SHAMap::walkMapParallel : non-null node"); nodeStack.pop(); for (int i = 0; i < 16; ++i) { if (node->isEmptyBranch(i)) continue; - intr_ptr::SharedPtr nextNode = - descendNoStore(*node, i); + intr_ptr::SharedPtr nextNode = descendNoStore(*node, i); if (nextNode) { if (nextNode->isInner()) - nodeStack.push( - intr_ptr::static_pointer_cast< - SHAMapInnerNode>(nextNode)); + nodeStack.push(intr_ptr::static_pointer_cast(nextNode)); } else { std::lock_guard l{m}; - missingNodes.emplace_back( - type_, node->getChildHash(i)); + missingNodes.emplace_back(type_, node->getChildHash(i)); if (--maxMissing <= 0) return; } diff --git a/src/libxrpl/shamap/SHAMapInnerNode.cpp b/src/libxrpl/shamap/SHAMapInnerNode.cpp index 5d4a0fd27f..5ccca9c2f4 100644 --- a/src/libxrpl/shamap/SHAMapInnerNode.cpp +++ b/src/libxrpl/shamap/SHAMapInnerNode.cpp @@ -10,9 +10,7 @@ namespace xrpl { -SHAMapInnerNode::SHAMapInnerNode( - std::uint32_t cowid, - std::uint8_t numAllocatedChildren) +SHAMapInnerNode::SHAMapInnerNode(std::uint32_t cowid, std::uint8_t numAllocatedChildren) : SHAMapTreeNode(cowid), hashesAndChildren_(numAllocatedChildren) { } @@ -24,10 +22,8 @@ SHAMapInnerNode::partialDestructor() { intr_ptr::SharedPtr* children; // structured bindings can't be captured in c++ 17; use tie instead - std::tie(std::ignore, std::ignore, children) = - hashesAndChildren_.getHashesAndChildren(); - iterNonEmptyChildIndexes( - [&](auto branchNum, auto indexNum) { children[indexNum].reset(); }); + std::tie(std::ignore, std::ignore, children) = hashesAndChildren_.getHashesAndChildren(); + iterNonEmptyChildIndexes([&](auto branchNum, auto indexNum) { children[indexNum].reset(); }); } template @@ -47,8 +43,7 @@ SHAMapInnerNode::iterNonEmptyChildIndexes(F&& f) const void SHAMapInnerNode::resizeChildArrays(std::uint8_t toAllocate) { - hashesAndChildren_ = - TaggedPointer(std::move(hashesAndChildren_), isBranch_, toAllocate); + hashesAndChildren_ = TaggedPointer(std::move(hashesAndChildren_), isBranch_, toAllocate); } std::optional @@ -69,23 +64,18 @@ SHAMapInnerNode::clone(std::uint32_t cowid) const SHAMapHash *cloneHashes, *thisHashes; intr_ptr::SharedPtr*cloneChildren, *thisChildren; // structured bindings can't be captured in c++ 17; use tie instead - std::tie(std::ignore, cloneHashes, cloneChildren) = - p->hashesAndChildren_.getHashesAndChildren(); - std::tie(std::ignore, thisHashes, thisChildren) = - hashesAndChildren_.getHashesAndChildren(); + std::tie(std::ignore, cloneHashes, cloneChildren) = p->hashesAndChildren_.getHashesAndChildren(); + std::tie(std::ignore, thisHashes, thisChildren) = hashesAndChildren_.getHashesAndChildren(); if (thisIsSparse) { int cloneChildIndex = 0; - iterNonEmptyChildIndexes([&](auto branchNum, auto indexNum) { - cloneHashes[cloneChildIndex++] = thisHashes[indexNum]; - }); + iterNonEmptyChildIndexes( + [&](auto branchNum, auto indexNum) { cloneHashes[cloneChildIndex++] = thisHashes[indexNum]; }); } else { - iterNonEmptyChildIndexes([&](auto branchNum, auto indexNum) { - cloneHashes[branchNum] = thisHashes[indexNum]; - }); + iterNonEmptyChildIndexes([&](auto branchNum, auto indexNum) { cloneHashes[branchNum] = thisHashes[indexNum]; }); } spinlock sl(lock_); @@ -94,25 +84,20 @@ SHAMapInnerNode::clone(std::uint32_t cowid) const if (thisIsSparse) { int cloneChildIndex = 0; - iterNonEmptyChildIndexes([&](auto branchNum, auto indexNum) { - cloneChildren[cloneChildIndex++] = thisChildren[indexNum]; - }); + iterNonEmptyChildIndexes( + [&](auto branchNum, auto indexNum) { cloneChildren[cloneChildIndex++] = thisChildren[indexNum]; }); } else { - iterNonEmptyChildIndexes([&](auto branchNum, auto indexNum) { - cloneChildren[branchNum] = thisChildren[indexNum]; - }); + iterNonEmptyChildIndexes( + [&](auto branchNum, auto indexNum) { cloneChildren[branchNum] = thisChildren[indexNum]; }); } return p; } intr_ptr::SharedPtr -SHAMapInnerNode::makeFullInner( - Slice data, - SHAMapHash const& hash, - bool hashValid) +SHAMapInnerNode::makeFullInner(Slice data, SHAMapHash const& hash, bool hashValid) { // A full inner node is serialized as 16 256-bit hashes, back to back: if (data.size() != branchFactor * uint256::bytes) @@ -149,8 +134,7 @@ SHAMapInnerNode::makeCompressedInner(Slice data) // representing a one byte "position" and a 256-bit hash: constexpr std::size_t chunkSize = uint256::bytes + 1; - if (auto const s = data.size(); - (s % chunkSize != 0) || (s > chunkSize * branchFactor)) + if (auto const s = data.size(); (s % chunkSize != 0) || (s > chunkSize * branchFactor)) Throw("Invalid CI node"); SerialIter si(data); @@ -199,8 +183,7 @@ SHAMapInnerNode::updateHashDeep() SHAMapHash* hashes; intr_ptr::SharedPtr* children; // structured bindings can't be captured in c++ 17; use tie instead - std::tie(std::ignore, hashes, children) = - hashesAndChildren_.getHashesAndChildren(); + std::tie(std::ignore, hashes, children) = hashesAndChildren_.getHashesAndChildren(); iterNonEmptyChildIndexes([&](auto branchNum, auto indexNum) { if (auto p = children[indexNum].get()) hashes[indexNum] = p->getHash(); @@ -211,8 +194,7 @@ SHAMapInnerNode::updateHashDeep() void SHAMapInnerNode::serializeForWire(Serializer& s) const { - XRPL_ASSERT( - !isEmpty(), "xrpl::SHAMapInnerNode::serializeForWire : is non-empty"); + XRPL_ASSERT(!isEmpty(), "xrpl::SHAMapInnerNode::serializeForWire : is non-empty"); // If the node is sparse, then only send non-empty branches: if (getBranchCount() < 12) @@ -227,8 +209,7 @@ SHAMapInnerNode::serializeForWire(Serializer& s) const } else { - iterChildren( - [&](SHAMapHash const& hh) { s.addBitString(hh.as_uint256()); }); + iterChildren([&](SHAMapHash const& hh) { s.addBitString(hh.as_uint256()); }); s.add8(wireTypeInner); } } @@ -236,13 +217,10 @@ SHAMapInnerNode::serializeForWire(Serializer& s) const void SHAMapInnerNode::serializeWithPrefix(Serializer& s) const { - XRPL_ASSERT( - !isEmpty(), - "xrpl::SHAMapInnerNode::serializeWithPrefix : is non-empty"); + XRPL_ASSERT(!isEmpty(), "xrpl::SHAMapInnerNode::serializeWithPrefix : is non-empty"); s.add32(HashPrefix::innerNode); - iterChildren( - [&](SHAMapHash const& hh) { s.addBitString(hh.as_uint256()); }); + iterChildren([&](SHAMapHash const& hh) { s.addBitString(hh.as_uint256()); }); } std::string @@ -263,13 +241,9 @@ SHAMapInnerNode::getString(SHAMapNodeID const& id) const void SHAMapInnerNode::setChild(int m, intr_ptr::SharedPtr child) { - XRPL_ASSERT( - (m >= 0) && (m < branchFactor), - "xrpl::SHAMapInnerNode::setChild : valid branch input"); + XRPL_ASSERT((m >= 0) && (m < branchFactor), "xrpl::SHAMapInnerNode::setChild : valid branch input"); XRPL_ASSERT(cowid_, "xrpl::SHAMapInnerNode::setChild : nonzero cowid"); - XRPL_ASSERT( - child.get() != this, - "xrpl::SHAMapInnerNode::setChild : valid child input"); + XRPL_ASSERT(child.get() != this, "xrpl::SHAMapInnerNode::setChild : valid child input"); auto const dstIsBranch = [&] { if (child) @@ -281,8 +255,7 @@ SHAMapInnerNode::setChild(int m, intr_ptr::SharedPtr child) auto const dstToAllocate = popcnt16(dstIsBranch); // change hashesAndChildren to remove the element, or make room for the // added element, if necessary - hashesAndChildren_ = TaggedPointer( - std::move(hashesAndChildren_), isBranch_, dstIsBranch, dstToAllocate); + hashesAndChildren_ = TaggedPointer(std::move(hashesAndChildren_), isBranch_, dstIsBranch, dstToAllocate); isBranch_ = dstIsBranch; @@ -297,41 +270,27 @@ SHAMapInnerNode::setChild(int m, intr_ptr::SharedPtr child) hash_.zero(); XRPL_ASSERT( - getBranchCount() <= hashesAndChildren_.capacity(), - "xrpl::SHAMapInnerNode::setChild : maximum branch count"); + getBranchCount() <= hashesAndChildren_.capacity(), "xrpl::SHAMapInnerNode::setChild : maximum branch count"); } // finished modifying, now make shareable void -SHAMapInnerNode::shareChild( - int m, - intr_ptr::SharedPtr const& child) +SHAMapInnerNode::shareChild(int m, intr_ptr::SharedPtr const& child) { - XRPL_ASSERT( - (m >= 0) && (m < branchFactor), - "xrpl::SHAMapInnerNode::shareChild : valid branch input"); + XRPL_ASSERT((m >= 0) && (m < branchFactor), "xrpl::SHAMapInnerNode::shareChild : valid branch input"); XRPL_ASSERT(cowid_, "xrpl::SHAMapInnerNode::shareChild : nonzero cowid"); - XRPL_ASSERT( - child, "xrpl::SHAMapInnerNode::shareChild : non-null child input"); - XRPL_ASSERT( - child.get() != this, - "xrpl::SHAMapInnerNode::shareChild : valid child input"); + XRPL_ASSERT(child, "xrpl::SHAMapInnerNode::shareChild : non-null child input"); + XRPL_ASSERT(child.get() != this, "xrpl::SHAMapInnerNode::shareChild : valid child input"); - XRPL_ASSERT( - !isEmptyBranch(m), - "xrpl::SHAMapInnerNode::shareChild : non-empty branch input"); + XRPL_ASSERT(!isEmptyBranch(m), "xrpl::SHAMapInnerNode::shareChild : non-empty branch input"); hashesAndChildren_.getChildren()[*getChildIndex(m)] = child; } SHAMapTreeNode* SHAMapInnerNode::getChildPointer(int branch) { - XRPL_ASSERT( - branch >= 0 && branch < branchFactor, - "xrpl::SHAMapInnerNode::getChildPointer : valid branch input"); - XRPL_ASSERT( - !isEmptyBranch(branch), - "xrpl::SHAMapInnerNode::getChildPointer : non-empty branch input"); + XRPL_ASSERT(branch >= 0 && branch < branchFactor, "xrpl::SHAMapInnerNode::getChildPointer : valid branch input"); + XRPL_ASSERT(!isEmptyBranch(branch), "xrpl::SHAMapInnerNode::getChildPointer : non-empty branch input"); auto const index = *getChildIndex(branch); @@ -343,12 +302,8 @@ SHAMapInnerNode::getChildPointer(int branch) intr_ptr::SharedPtr SHAMapInnerNode::getChild(int branch) { - XRPL_ASSERT( - branch >= 0 && branch < branchFactor, - "xrpl::SHAMapInnerNode::getChild : valid branch input"); - XRPL_ASSERT( - !isEmptyBranch(branch), - "xrpl::SHAMapInnerNode::getChild : non-empty branch input"); + XRPL_ASSERT(branch >= 0 && branch < branchFactor, "xrpl::SHAMapInnerNode::getChild : valid branch input"); + XRPL_ASSERT(!isEmptyBranch(branch), "xrpl::SHAMapInnerNode::getChild : non-empty branch input"); auto const index = *getChildIndex(branch); @@ -360,9 +315,7 @@ SHAMapInnerNode::getChild(int branch) SHAMapHash const& SHAMapInnerNode::getChildHash(int m) const { - XRPL_ASSERT( - (m >= 0) && (m < branchFactor), - "xrpl::SHAMapInnerNode::getChildHash : valid branch input"); + XRPL_ASSERT((m >= 0) && (m < branchFactor), "xrpl::SHAMapInnerNode::getChildHash : valid branch input"); if (auto const i = getChildIndex(m)) return hashesAndChildren_.getHashes()[*i]; @@ -370,19 +323,11 @@ SHAMapInnerNode::getChildHash(int m) const } intr_ptr::SharedPtr -SHAMapInnerNode::canonicalizeChild( - int branch, - intr_ptr::SharedPtr node) +SHAMapInnerNode::canonicalizeChild(int branch, intr_ptr::SharedPtr node) { - XRPL_ASSERT( - branch >= 0 && branch < branchFactor, - "xrpl::SHAMapInnerNode::canonicalizeChild : valid branch input"); - XRPL_ASSERT( - node != nullptr, - "xrpl::SHAMapInnerNode::canonicalizeChild : valid node input"); - XRPL_ASSERT( - !isEmptyBranch(branch), - "xrpl::SHAMapInnerNode::canonicalizeChild : non-empty branch input"); + XRPL_ASSERT(branch >= 0 && branch < branchFactor, "xrpl::SHAMapInnerNode::canonicalizeChild : valid branch input"); + XRPL_ASSERT(node != nullptr, "xrpl::SHAMapInnerNode::canonicalizeChild : valid node input"); + XRPL_ASSERT(!isEmptyBranch(branch), "xrpl::SHAMapInnerNode::canonicalizeChild : non-empty branch input"); auto const childIndex = *getChildIndex(branch); auto [_, hashes, children] = hashesAndChildren_.getHashesAndChildren(); XRPL_ASSERT( @@ -410,17 +355,14 @@ void SHAMapInnerNode::invariants(bool is_root) const { [[maybe_unused]] unsigned count = 0; - auto [numAllocated, hashes, children] = - hashesAndChildren_.getHashesAndChildren(); + auto [numAllocated, hashes, children] = hashesAndChildren_.getHashesAndChildren(); if (numAllocated != branchFactor) { auto const branchCount = getBranchCount(); for (int i = 0; i < branchCount; ++i) { - XRPL_ASSERT( - hashes[i].isNonZero(), - "xrpl::SHAMapInnerNode::invariants : nonzero hash in branch"); + XRPL_ASSERT(hashes[i].isNonZero(), "xrpl::SHAMapInnerNode::invariants : nonzero hash in branch"); if (children[i] != nullptr) children[i]->invariants(); ++count; @@ -452,11 +394,8 @@ SHAMapInnerNode::invariants(bool is_root) const if (!is_root) { - XRPL_ASSERT( - hash_.isNonZero(), - "xrpl::SHAMapInnerNode::invariants : nonzero hash"); - XRPL_ASSERT( - count >= 1, "xrpl::SHAMapInnerNode::invariants : minimum count"); + XRPL_ASSERT(hash_.isNonZero(), "xrpl::SHAMapInnerNode::invariants : nonzero hash"); + XRPL_ASSERT(count >= 1, "xrpl::SHAMapInnerNode::invariants : minimum count"); } XRPL_ASSERT( (count == 0) ? hash_.isZero() : hash_.isNonZero(), diff --git a/src/libxrpl/shamap/SHAMapLeafNode.cpp b/src/libxrpl/shamap/SHAMapLeafNode.cpp index 72e57cd737..7f449af3a7 100644 --- a/src/libxrpl/shamap/SHAMapLeafNode.cpp +++ b/src/libxrpl/shamap/SHAMapLeafNode.cpp @@ -2,9 +2,7 @@ namespace xrpl { -SHAMapLeafNode::SHAMapLeafNode( - boost::intrusive_ptr item, - std::uint32_t cowid) +SHAMapLeafNode::SHAMapLeafNode(boost::intrusive_ptr item, std::uint32_t cowid) : SHAMapTreeNode(cowid), item_(std::move(item)) { XRPL_ASSERT( @@ -13,10 +11,7 @@ SHAMapLeafNode::SHAMapLeafNode( "SHAMapItem const>, std::uint32_t) : minimum input size"); } -SHAMapLeafNode::SHAMapLeafNode( - boost::intrusive_ptr item, - std::uint32_t cowid, - SHAMapHash const& hash) +SHAMapLeafNode::SHAMapLeafNode(boost::intrusive_ptr item, std::uint32_t cowid, SHAMapHash const& hash) : SHAMapTreeNode(cowid, hash), item_(std::move(item)) { XRPL_ASSERT( @@ -73,8 +68,7 @@ SHAMapLeafNode::getString(SHAMapNodeID const& id) const void SHAMapLeafNode::invariants(bool) const { - XRPL_ASSERT( - hash_.isNonZero(), "xrpl::SHAMapLeafNode::invariants : nonzero hash"); + XRPL_ASSERT(hash_.isNonZero(), "xrpl::SHAMapLeafNode::invariants : nonzero hash"); XRPL_ASSERT(item_, "xrpl::SHAMapLeafNode::invariants : non-null item"); } diff --git a/src/libxrpl/shamap/SHAMapNodeID.cpp b/src/libxrpl/shamap/SHAMapNodeID.cpp index a32ff5c28e..e8840f398d 100644 --- a/src/libxrpl/shamap/SHAMapNodeID.cpp +++ b/src/libxrpl/shamap/SHAMapNodeID.cpp @@ -34,15 +34,10 @@ depthMask(unsigned int depth) } // canonicalize the hash to a node ID for this depth -SHAMapNodeID::SHAMapNodeID(unsigned int depth, uint256 const& hash) - : id_(hash), depth_(depth) +SHAMapNodeID::SHAMapNodeID(unsigned int depth, uint256 const& hash) : id_(hash), depth_(depth) { - XRPL_ASSERT( - depth <= SHAMap::leafDepth, - "xrpl::SHAMapNodeID::SHAMapNodeID : maximum depth input"); - XRPL_ASSERT( - id_ == (id_ & depthMask(depth)), - "xrpl::SHAMapNodeID::SHAMapNodeID : hash and depth inputs do match"); + XRPL_ASSERT(depth <= SHAMap::leafDepth, "xrpl::SHAMapNodeID::SHAMapNodeID : maximum depth input"); + XRPL_ASSERT(id_ == (id_ & depthMask(depth)), "xrpl::SHAMapNodeID::SHAMapNodeID : hash and depth inputs do match"); } std::string @@ -57,9 +52,7 @@ SHAMapNodeID::getRawString() const SHAMapNodeID SHAMapNodeID::getChildNodeID(unsigned int m) const { - XRPL_ASSERT( - m < SHAMap::branchFactor, - "xrpl::SHAMapNodeID::getChildNodeID : valid branch input"); + XRPL_ASSERT(m < SHAMap::branchFactor, "xrpl::SHAMapNodeID::getChildNodeID : valid branch input"); // A SHAMap has exactly 65 levels, so nodes must not exceed that // depth; if they do, this breaks the invariant of never allowing @@ -69,13 +62,10 @@ SHAMapNodeID::getChildNodeID(unsigned int m) const // We throw (but never assert) if the node is at level 64, since // entries at that depth are leaf nodes and have no children and even // constructing a child node from them would break the above invariant. - XRPL_ASSERT( - depth_ <= SHAMap::leafDepth, - "xrpl::SHAMapNodeID::getChildNodeID : maximum leaf depth"); + XRPL_ASSERT(depth_ <= SHAMap::leafDepth, "xrpl::SHAMapNodeID::getChildNodeID : maximum leaf depth"); if (depth_ >= SHAMap::leafDepth) - Throw( - "Request for child node ID of " + to_string(*this)); + Throw("Request for child node ID of " + to_string(*this)); if (id_ != (id_ & depthMask(depth_))) Throw("Incorrect mask for " + to_string(*this)); @@ -116,17 +106,14 @@ selectBranch(SHAMapNodeID const& id, uint256 const& hash) else branch >>= 4; - XRPL_ASSERT( - branch < SHAMap::branchFactor, "xrpl::selectBranch : maximum result"); + XRPL_ASSERT(branch < SHAMap::branchFactor, "xrpl::selectBranch : maximum result"); return branch; } SHAMapNodeID SHAMapNodeID::createID(int depth, uint256 const& key) { - XRPL_ASSERT( - (depth >= 0) && (depth < 65), - "xrpl::SHAMapNodeID::createID : valid branch input"); + XRPL_ASSERT((depth >= 0) && (depth < 65), "xrpl::SHAMapNodeID::createID : valid branch input"); return SHAMapNodeID(depth, key & depthMask(depth)); } diff --git a/src/libxrpl/shamap/SHAMapSync.cpp b/src/libxrpl/shamap/SHAMapSync.cpp index d9c0846fbf..503505b80c 100644 --- a/src/libxrpl/shamap/SHAMapSync.cpp +++ b/src/libxrpl/shamap/SHAMapSync.cpp @@ -6,9 +6,7 @@ namespace xrpl { void -SHAMap::visitLeaves( - std::function const& - item)> const& leafFunction) const +SHAMap::visitLeaves(std::function const& item)> const& leafFunction) const { visitNodes([&leafFunction](SHAMapTreeNode& node) { if (!node.isInner()) @@ -40,8 +38,7 @@ SHAMap::visitNodes(std::function const& function) const { if (!node->isEmptyBranch(pos)) { - intr_ptr::SharedPtr child = - descendNoStore(*node, pos); + intr_ptr::SharedPtr child = descendNoStore(*node, pos); if (!function(*child)) return; @@ -60,8 +57,7 @@ SHAMap::visitNodes(std::function const& function) const } // descend to the child's first position - node = - intr_ptr::static_pointer_cast(child); + node = intr_ptr::static_pointer_cast(child); pos = 0; } } @@ -80,9 +76,7 @@ SHAMap::visitNodes(std::function const& function) const } void -SHAMap::visitDifferences( - SHAMap const* have, - std::function const& function) const +SHAMap::visitDifferences(SHAMap const* have, std::function const& function) const { // Visit every node in this SHAMap that is not present // in the specified SHAMap @@ -98,8 +92,7 @@ SHAMap::visitDifferences( if (root_->isLeaf()) { auto leaf = intr_ptr::static_pointer_cast(root_); - if (!have || - !have->hasLeafNode(leaf->peekItem()->key(), leaf->getHash())) + if (!have || !have->hasLeafNode(leaf->peekItem()->key(), leaf->getHash())) function(*root_); return; } @@ -130,14 +123,9 @@ SHAMap::visitDifferences( if (next->isInner()) { if (!have || !have->hasInnerNode(childID, childHash)) - stack.push( - {static_cast(next), childID}); + stack.push({static_cast(next), childID}); } - else if ( - !have || - !have->hasLeafNode( - static_cast(next)->peekItem()->key(), - childHash)) + else if (!have || !have->hasLeafNode(static_cast(next)->peekItem()->key(), childHash)) { if (!function(*next)) return; @@ -173,9 +161,7 @@ SHAMap::gmn_ProcessNodes(MissingNodes& mn, MissingNodes::StackEntry& se) // we already know this child node is missing fullBelow = false; } - else if ( - !backed_ || - !f_.getFullBelowCache()->touch_if_exists(childHash.as_uint256())) + else if (!backed_ || !f_.getFullBelowCache()->touch_if_exists(childHash.as_uint256())) { bool pending = false; auto d = descendAsync( @@ -183,13 +169,10 @@ SHAMap::gmn_ProcessNodes(MissingNodes& mn, MissingNodes::StackEntry& se) branch, mn.filter_, pending, - [node, nodeID, branch, &mn]( - intr_ptr::SharedPtr found, - SHAMapHash const&) { + [node, nodeID, branch, &mn](intr_ptr::SharedPtr found, SHAMapHash const&) { // a read completed asynchronously std::unique_lock lock{mn.deferLock_}; - mn.finishedReads_.emplace_back( - node, nodeID, branch, std::move(found)); + mn.finishedReads_.emplace_back(node, nodeID, branch, std::move(found)); mn.deferCondVar_.notify_one(); }); @@ -204,15 +187,12 @@ SHAMap::gmn_ProcessNodes(MissingNodes& mn, MissingNodes::StackEntry& se) fullBelow = false; // for now, not known full below mn.missingHashes_.insert(childHash); - mn.missingNodes_.emplace_back( - nodeID.getChildNodeID(branch), childHash.as_uint256()); + mn.missingNodes_.emplace_back(nodeID.getChildNodeID(branch), childHash.as_uint256()); if (--mn.max_ <= 0) return; } - else if ( - d->isInner() && - !static_cast(d)->isFullBelow(mn.generation_)) + else if (d->isInner() && !static_cast(d)->isFullBelow(mn.generation_)) { mn.stack_.push(se); @@ -250,12 +230,7 @@ SHAMap::gmn_ProcessDeferredReads(MissingNodes& mn) int complete = 0; while (complete != mn.deferred_) { - std::tuple< - SHAMapInnerNode*, - SHAMapNodeID, - int, - intr_ptr::SharedPtr> - deferredNode; + std::tuple> deferredNode; { std::unique_lock lock{mn.deferLock_}; @@ -280,8 +255,7 @@ SHAMap::gmn_ProcessDeferredReads(MissingNodes& mn) } else if ((mn.max_ > 0) && (mn.missingHashes_.insert(nodeHash).second)) { - mn.missingNodes_.emplace_back( - parentID.getChildNodeID(branch), nodeHash.as_uint256()); + mn.missingNodes_.emplace_back(parentID.getChildNodeID(branch), nodeHash.as_uint256()); --mn.max_; } } @@ -298,9 +272,7 @@ SHAMap::gmn_ProcessDeferredReads(MissingNodes& mn) std::vector> SHAMap::getMissingNodes(int max, SHAMapSyncFilter* filter) { - XRPL_ASSERT( - root_->getHash().isNonZero(), - "xrpl::SHAMap::getMissingNodes : nonzero root hash"); + XRPL_ASSERT(root_->getHash().isNonZero(), "xrpl::SHAMap::getMissingNodes : nonzero root hash"); XRPL_ASSERT(max > 0, "xrpl::SHAMap::getMissingNodes : valid max input"); MissingNodes mn( @@ -309,9 +281,7 @@ SHAMap::getMissingNodes(int max, SHAMapSyncFilter* filter) 512, // number of async reads per pass f_.getFullBelowCache()->getGeneration()); - if (!root_->isInner() || - intr_ptr::static_pointer_cast(root_)->isFullBelow( - mn.generation_)) + if (!root_->isInner() || intr_ptr::static_pointer_cast(root_)->isFullBelow(mn.generation_)) { clearSynching(); return std::move(mn.missingNodes_); @@ -323,12 +293,7 @@ SHAMap::getMissingNodes(int max, SHAMapSyncFilter* filter) // (randomly selected) inner node. This increases the likelihood // that the two threads will produce different request sets (which is // more efficient than sending identical requests). - MissingNodes::StackEntry pos{ - static_cast(root_.get()), - SHAMapNodeID(), - rand_int(255), - 0, - true}; + MissingNodes::StackEntry pos{static_cast(root_.get()), SHAMapNodeID(), rand_int(255), 0, true}; auto& node = std::get<0>(pos); auto& nextChild = std::get<3>(pos); auto& fullBelow = std::get<4>(pos); @@ -360,9 +325,7 @@ SHAMap::getMissingNodes(int max, SHAMapSyncFilter* filter) // This is a node we are continuing to process fullBelow = fullBelow && was; // was and still is } - XRPL_ASSERT( - node, - "xrpl::SHAMap::getMissingNodes : first non-null node"); + XRPL_ASSERT(node, "xrpl::SHAMap::getMissingNodes : first non-null node"); } } @@ -382,8 +345,7 @@ SHAMap::getMissingNodes(int max, SHAMapSyncFilter* filter) // Recheck nodes we could not finish before for (auto const& [innerNode, nodeId] : mn.resumes_) if (!innerNode->isFullBelow(mn.generation_)) - mn.stack_.push(std::make_tuple( - innerNode, nodeId, rand_int(255), 0, true)); + mn.stack_.push(std::make_tuple(innerNode, nodeId, rand_int(255), 0, true)); mn.resumes_.clear(); } @@ -393,9 +355,7 @@ SHAMap::getMissingNodes(int max, SHAMapSyncFilter* filter) // Resume at the top of the stack pos = mn.stack_.top(); mn.stack_.pop(); - XRPL_ASSERT( - node, - "xrpl::SHAMap::getMissingNodes : second non-null node"); + XRPL_ASSERT(node, "xrpl::SHAMap::getMissingNodes : second non-null node"); } } @@ -436,9 +396,7 @@ SHAMap::getNodeFat( if (node == nullptr || wanted != nodeID) { - JLOG(journal_.info()) - << "peer requested node that is not in the map: " << wanted - << " but found " << nodeID; + JLOG(journal_.info()) << "peer requested node that is not in the map: " << wanted << " but found " << nodeID; return false; } @@ -484,18 +442,14 @@ SHAMap::getNodeFat( { // If there's more than one child, reduce the depth // If only one child, follow the chain - stack.emplace( - childNode, - childID, - (bc > 1) ? (depth - 1) : depth); + stack.emplace(childNode, childID, (bc > 1) ? (depth - 1) : depth); } else if (childNode->isInner() || fatLeaves) { // Just include this node s.erase(); childNode->serializeForWire(s); - data.emplace_back( - std::make_pair(childID, s.getData())); + data.emplace_back(std::make_pair(childID, s.getData())); } } } @@ -513,18 +467,13 @@ SHAMap::serializeRoot(Serializer& s) const } SHAMapAddNode -SHAMap::addRootNode( - SHAMapHash const& hash, - Slice const& rootNode, - SHAMapSyncFilter* filter) +SHAMap::addRootNode(SHAMapHash const& hash, Slice const& rootNode, SHAMapSyncFilter* filter) { // we already have a root_ node if (root_->getHash().isNonZero()) { JLOG(journal_.trace()) << "got root node, already have one"; - XRPL_ASSERT( - root_->getHash() == hash, - "xrpl::SHAMap::addRootNode : valid hash input"); + XRPL_ASSERT(root_->getHash() == hash, "xrpl::SHAMap::addRootNode : valid hash input"); return SHAMapAddNode::duplicate(); } @@ -545,25 +494,16 @@ SHAMap::addRootNode( { Serializer s; root_->serializeWithPrefix(s); - filter->gotNode( - false, - root_->getHash(), - ledgerSeq_, - std::move(s.modData()), - root_->getType()); + filter->gotNode(false, root_->getHash(), ledgerSeq_, std::move(s.modData()), root_->getType()); } return SHAMapAddNode::useful(); } SHAMapAddNode -SHAMap::addKnownNode( - SHAMapNodeID const& node, - Slice const& rawNode, - SHAMapSyncFilter* filter) +SHAMap::addKnownNode(SHAMapNodeID const& node, Slice const& rawNode, SHAMapSyncFilter* filter) { - XRPL_ASSERT( - !node.isRoot(), "xrpl::SHAMap::addKnownNode : valid node input"); + XRPL_ASSERT(!node.isRoot(), "xrpl::SHAMap::addKnownNode : valid node input"); if (!isSynching()) { @@ -575,8 +515,7 @@ SHAMap::addKnownNode( SHAMapNodeID currNodeID; auto currNode = root_.get(); - while (currNode->isInner() && - !static_cast(currNode)->isFullBelow(generation) && + while (currNode->isInner() && !static_cast(currNode)->isFullBelow(generation) && (currNodeID.getDepth() < node.getDepth())) { int const branch = selectBranch(currNodeID, node.getNodeID()); @@ -595,8 +534,7 @@ SHAMap::addKnownNode( } auto prevNode = inner; - std::tie(currNode, currNodeID) = - descend(inner, currNodeID, branch, filter); + std::tie(currNode, currNodeID) = descend(inner, currNodeID, branch, filter); if (currNode != nullptr) continue; @@ -616,20 +554,14 @@ SHAMap::addKnownNode( // propagate further down the line. if (newNode->isLeaf()) { - auto const& actualKey = - static_cast(newNode.get()) - ->peekItem() - ->key(); + auto const& actualKey = static_cast(newNode.get())->peekItem()->key(); // Validate that this leaf belongs at the target position - auto const expectedNodeID = - SHAMapNodeID::createID(node.getDepth(), actualKey); + auto const expectedNodeID = SHAMapNodeID::createID(node.getDepth(), actualKey); if (expectedNodeID.getNodeID() != node.getNodeID()) { - JLOG(journal_.debug()) - << "Leaf node position mismatch: " - << "expected=" << expectedNodeID.getNodeID() - << ", actual=" << node.getNodeID(); + JLOG(journal_.debug()) << "Leaf node position mismatch: " + << "expected=" << expectedNodeID.getNodeID() << ", actual=" << node.getNodeID(); return SHAMapAddNode::invalid(); } } @@ -637,8 +569,7 @@ SHAMap::addKnownNode( // Inner nodes must be at a level strictly less than 64 // but leaf nodes (while notionally at level 64) can be // at any depth up to and including 64: - if ((currNodeID.getDepth() > leafDepth) || - (newNode->isInner() && currNodeID.getDepth() == leafDepth)) + if ((currNodeID.getDepth() > leafDepth) || (newNode->isInner() && currNodeID.getDepth() == leafDepth)) { // Map is provably invalid state_ = SHAMapState::Invalid; @@ -650,8 +581,7 @@ SHAMap::addKnownNode( // Either this node is broken or we didn't request it (yet) JLOG(journal_.warn()) << "unable to hook node " << node; JLOG(journal_.info()) << " stuck at " << currNodeID; - JLOG(journal_.info()) << "got depth=" << node.getDepth() - << ", walked to= " << currNodeID.getDepth(); + JLOG(journal_.info()) << "got depth=" << node.getDepth() << ", walked to= " << currNodeID.getDepth(); return SHAMapAddNode::useful(); } @@ -664,12 +594,7 @@ SHAMap::addKnownNode( { Serializer s; newNode->serializeWithPrefix(s); - filter->gotNode( - false, - childHash, - ledgerSeq_, - std::move(s.modData()), - newNode->getType()); + filter->gotNode(false, childHash, ledgerSeq_, std::move(s.modData()), newNode->getType()); } return SHAMapAddNode::useful(); @@ -708,8 +633,7 @@ SHAMap::deepCompare(SHAMap& other) const if (!otherNode->isLeaf()) return false; auto& nodePeek = static_cast(node)->peekItem(); - auto& otherNodePeek = - static_cast(otherNode)->peekItem(); + auto& otherNodePeek = static_cast(otherNode)->peekItem(); if (nodePeek->key() != otherNodePeek->key()) return false; if (nodePeek->slice() != otherNodePeek->slice()) @@ -752,9 +676,7 @@ SHAMap::deepCompare(SHAMap& other) const /** Does this map have this inner node? */ bool -SHAMap::hasInnerNode( - SHAMapNodeID const& targetNodeID, - SHAMapHash const& targetNodeHash) const +SHAMap::hasInnerNode(SHAMapNodeID const& targetNodeID, SHAMapHash const& targetNodeHash) const { auto node = root_.get(); SHAMapNodeID nodeID; @@ -791,8 +713,7 @@ SHAMap::hasLeafNode(uint256 const& tag, SHAMapHash const& targetNodeHash) const if (inner->isEmptyBranch(branch)) return false; // Dead end, node must not be here - if (inner->getChildHash(branch) == - targetNodeHash) // Matching leaf, no need to retrieve it + if (inner->getChildHash(branch) == targetNodeHash) // Matching leaf, no need to retrieve it return true; node = descendThrow(inner, branch); @@ -815,10 +736,8 @@ SHAMap::getProofPath(uint256 const& key) const return {}; } - if (auto const& node = stack.top().first; !node || node->isInner() || - intr_ptr::static_pointer_cast(node) - ->peekItem() - ->key() != key) + if (auto const& node = stack.top().first; + !node || node->isInner() || intr_ptr::static_pointer_cast(node)->peekItem()->key() != key) { JLOG(journal_.debug()) << "no path to " << key; return {}; @@ -834,16 +753,12 @@ SHAMap::getProofPath(uint256 const& key) const stack.pop(); } - JLOG(journal_.debug()) << "getPath for key " << key << ", path length " - << path.size(); + JLOG(journal_.debug()) << "getPath for key " << key << ", path length " << path.size(); return path; } bool -SHAMap::verifyProofPath( - uint256 const& rootHash, - uint256 const& key, - std::vector const& path) +SHAMap::verifyProofPath(uint256 const& rootHash, uint256 const& key, std::vector const& path) { if (path.empty() || path.size() > 65) return false; @@ -865,8 +780,7 @@ SHAMap::verifyProofPath( if (node->isInner()) { auto nodeId = SHAMapNodeID::createID(depth, key); - hash = static_cast(node.get()) - ->getChildHash(selectBranch(nodeId, key)); + hash = static_cast(node.get())->getChildHash(selectBranch(nodeId, key)); } else { diff --git a/src/libxrpl/shamap/SHAMapTreeNode.cpp b/src/libxrpl/shamap/SHAMapTreeNode.cpp index 854b4c1097..156570a60f 100644 --- a/src/libxrpl/shamap/SHAMapTreeNode.cpp +++ b/src/libxrpl/shamap/SHAMapTreeNode.cpp @@ -13,26 +13,18 @@ namespace xrpl { intr_ptr::SharedPtr -SHAMapTreeNode::makeTransaction( - Slice data, - SHAMapHash const& hash, - bool hashValid) +SHAMapTreeNode::makeTransaction(Slice data, SHAMapHash const& hash, bool hashValid) { - auto item = - make_shamapitem(sha512Half(HashPrefix::transactionID, data), data); + auto item = make_shamapitem(sha512Half(HashPrefix::transactionID, data), data); if (hashValid) - return intr_ptr::make_shared( - std::move(item), 0, hash); + return intr_ptr::make_shared(std::move(item), 0, hash); return intr_ptr::make_shared(std::move(item), 0); } intr_ptr::SharedPtr -SHAMapTreeNode::makeTransactionWithMeta( - Slice data, - SHAMapHash const& hash, - bool hashValid) +SHAMapTreeNode::makeTransactionWithMeta(Slice data, SHAMapHash const& hash, bool hashValid) { Serializer s(data.data(), data.size()); @@ -43,25 +35,20 @@ SHAMapTreeNode::makeTransactionWithMeta( // FIXME: improve this interface so that the above check isn't needed if (!s.getBitString(tag, s.size() - tag.bytes)) - Throw( - "Short TXN+MD node (" + std::to_string(s.size()) + ")"); + Throw("Short TXN+MD node (" + std::to_string(s.size()) + ")"); s.chop(tag.bytes); auto item = make_shamapitem(tag, s.slice()); if (hashValid) - return intr_ptr::make_shared( - std::move(item), 0, hash); + return intr_ptr::make_shared(std::move(item), 0, hash); return intr_ptr::make_shared(std::move(item), 0); } intr_ptr::SharedPtr -SHAMapTreeNode::makeAccountState( - Slice data, - SHAMapHash const& hash, - bool hashValid) +SHAMapTreeNode::makeAccountState(Slice data, SHAMapHash const& hash, bool hashValid) { Serializer s(data.data(), data.size()); @@ -72,8 +59,7 @@ SHAMapTreeNode::makeAccountState( // FIXME: improve this interface so that the above check isn't needed if (!s.getBitString(tag, s.size() - tag.bytes)) - Throw( - "Short AS node (" + std::to_string(s.size()) + ")"); + Throw("Short AS node (" + std::to_string(s.size()) + ")"); s.chop(tag.bytes); @@ -83,11 +69,9 @@ SHAMapTreeNode::makeAccountState( auto item = make_shamapitem(tag, s.slice()); if (hashValid) - return intr_ptr::make_shared( - std::move(item), 0, hash); + return intr_ptr::make_shared(std::move(item), 0, hash); - return intr_ptr::make_shared( - std::move(item), 0); + return intr_ptr::make_shared(std::move(item), 0); } intr_ptr::SharedPtr @@ -118,8 +102,7 @@ SHAMapTreeNode::makeFromWire(Slice rawNode) if (type == wireTypeTransactionWithMeta) return makeTransactionWithMeta(rawNode, hash, hashValid); - Throw( - "wire: Unknown type (" + std::to_string(type) + ")"); + Throw("wire: Unknown type (" + std::to_string(type) + ")"); } intr_ptr::SharedPtr @@ -131,10 +114,8 @@ SHAMapTreeNode::makeFromPrefix(Slice rawNode, SHAMapHash const& hash) // FIXME: Use SerialIter::get32? // Extract the prefix auto const type = safe_cast( - (safe_cast(rawNode[0]) << 24) + - (safe_cast(rawNode[1]) << 16) + - (safe_cast(rawNode[2]) << 8) + - (safe_cast(rawNode[3]))); + (safe_cast(rawNode[0]) << 24) + (safe_cast(rawNode[1]) << 16) + + (safe_cast(rawNode[2]) << 8) + (safe_cast(rawNode[3]))); rawNode.remove_prefix(4); @@ -153,9 +134,7 @@ SHAMapTreeNode::makeFromPrefix(Slice rawNode, SHAMapHash const& hash) return makeTransactionWithMeta(rawNode, hash, hashValid); Throw( - "prefix: unknown type (" + - std::to_string(safe_cast>(type)) + - ")"); + "prefix: unknown type (" + std::to_string(safe_cast>(type)) + ")"); } std::string diff --git a/src/test/app/AMMCalc_test.cpp b/src/test/app/AMMCalc_test.cpp index abfb548b64..bc50f02d3d 100644 --- a/src/test/app/AMMCalc_test.cpp +++ b/src/test/app/AMMCalc_test.cpp @@ -23,8 +23,8 @@ class AMMCalc_test : public beast::unit_test::suite { using token_iter = boost::sregex_token_iterator; using steps = std::vector>; - using trates = std::map; - using swapargs = std::tuple; + using transfer_rates = std::map; + using swapargs = std::tuple; jtx::Account const gw{jtx::Account("gw")}; token_iter const end_; @@ -101,10 +101,10 @@ class AMMCalc_test : public beast::unit_test::suite return {{{*a1, *a2}, amm}}; } - std::optional + std::optional getTransferRate(token_iter& p) { - trates rates{}; + transfer_rates rates{}; if (p == end_) return rates; std::string str = *p; @@ -115,8 +115,8 @@ class AMMCalc_test : public beast::unit_test::suite { if (auto const rate = getRate(p++)) { - auto const [currency, trate, delimited] = *rate; - rates[currency] = trate; + auto const [currency, transferRate, delimited] = *rate; + rates[currency] = transferRate; if (delimited) break; } @@ -180,22 +180,21 @@ class AMMCalc_test : public beast::unit_test::suite auto const vp = std::get(args); STAmount sout = std::get(args); auto const fee = std::get(args); - auto const rates = std::get(args); + auto const rates = std::get(args); STAmount resultOut = sout; STAmount resultIn{}; STAmount sin{}; int limitingStep = vp.size(); STAmount limitStepOut{}; - auto trate = [&](auto const& amt) { + auto transferRate = [&](auto const& amt) { auto const currency = to_string(amt.issue().currency); - return rates.find(currency) != rates.end() ? rates.at(currency) - : QUALITY_ONE; + return rates.find(currency) != rates.end() ? rates.at(currency) : QUALITY_ONE; }; // swap out reverse sin = sout; for (auto it = vp.rbegin(); it != vp.rend(); ++it) { - sout = mulratio(sin, trate(sin), QUALITY_ONE, true); + sout = mulratio(sin, transferRate(sin), QUALITY_ONE, true); auto const [amts, amm] = *it; // assume no amm limit if (amm) @@ -222,7 +221,7 @@ class AMMCalc_test : public beast::unit_test::suite for (int i = limitingStep + 1; i < vp.size(); ++i) { auto const [amts, amm] = vp[i]; - sin = mulratio(sin, QUALITY_ONE, trate(sin), false); + sin = mulratio(sin, QUALITY_ONE, transferRate(sin), false); if (amm) { sout = swapAssetIn(amts, sin, fee); @@ -235,8 +234,7 @@ class AMMCalc_test : public beast::unit_test::suite sin = sout; resultOut = sout; } - std::cout << "in: " << toString(resultIn) - << " out: " << toString(resultOut) << std::endl; + std::cout << "in: " << toString(resultIn) << " out: " << toString(resultOut) << std::endl; } void @@ -245,26 +243,22 @@ class AMMCalc_test : public beast::unit_test::suite auto const vp = std::get(args); STAmount sin = std::get(args); auto const fee = std::get(args); - auto const rates = std::get(args); + auto const rates = std::get(args); STAmount resultIn = sin; STAmount resultOut{}; STAmount sout{}; int limitingStep = 0; STAmount limitStepIn{}; - auto trate = [&](auto const& amt) { + auto transferRate = [&](auto const& amt) { auto const currency = to_string(amt.issue().currency); - return rates.find(currency) != rates.end() ? rates.at(currency) - : QUALITY_ONE; + return rates.find(currency) != rates.end() ? rates.at(currency) : QUALITY_ONE; }; // Swap in forward for (auto it = vp.begin(); it != vp.end(); ++it) { auto const [amts, amm] = *it; - sin = mulratio( - sin, - QUALITY_ONE, - trate(sin), - false); // out of the next step + sin = mulratio(sin, QUALITY_ONE, transferRate(sin), + false); // out of the next step // assume no amm limit if (amm) { @@ -289,7 +283,7 @@ class AMMCalc_test : public beast::unit_test::suite // swap out if limiting step for (int i = limitingStep - 1; i >= 0; --i) { - sout = mulratio(sin, trate(sin), QUALITY_ONE, false); + sout = mulratio(sin, transferRate(sin), QUALITY_ONE, false); auto const [amts, amm] = vp[i]; if (amm) { @@ -302,9 +296,8 @@ class AMMCalc_test : public beast::unit_test::suite } resultIn = sin; } - resultOut = mulratio(resultOut, QUALITY_ONE, trate(resultOut), true); - std::cout << "in: " << toString(resultIn) - << " out: " << toString(resultOut) << std::endl; + resultOut = mulratio(resultOut, QUALITY_ONE, transferRate(resultOut), true); + std::cout << "in: " << toString(resultIn) << " out: " << toString(resultOut) << std::endl; } void @@ -378,11 +371,7 @@ class AMMCalc_test : public beast::unit_test::suite { Account const amm("amm"); auto const LPT = amm["LPT"]; - std::cout - << to_string( - ammLPTokens(pool->first.in, pool->first.out, LPT) - .iou()) - << std::endl; + std::cout << to_string(ammLPTokens(pool->first.in, pool->first.out, LPT).iou()) << std::endl; return true; } } @@ -409,17 +398,11 @@ class AMMCalc_test : public beast::unit_test::suite env.current()->rules(), beast::Journal(beast::Journal::getNullSink())); ammOffer) - std::cout - << "amm offer: " << toString(ammOffer->in) - << " " << toString(ammOffer->out) - << "\nnew pool: " - << toString(pool->first.in + ammOffer->in) - << " " - << toString(pool->first.out - ammOffer->out) - << std::endl; + std::cout << "amm offer: " << toString(ammOffer->in) << " " << toString(ammOffer->out) + << "\nnew pool: " << toString(pool->first.in + ammOffer->in) << " " + << toString(pool->first.out - ammOffer->out) << std::endl; else - std::cout << "can't change the pool's SP quality" - << std::endl; + std::cout << "can't change the pool's SP quality" << std::endl; return true; } } diff --git a/src/test/app/AMMClawback_test.cpp b/src/test/app/AMMClawback_test.cpp index 52f05f9ed5..65cf7f0a60 100644 --- a/src/test/app/AMMClawback_test.cpp +++ b/src/test/app/AMMClawback_test.cpp @@ -36,9 +36,7 @@ class AMMClawback_test : public beast::unit_test::suite AMM amm(env, alice, XRP(100), USD(100)); env.close(); - env(amm::ammClawback( - gw, Account("unknown"), USD, XRP, std::nullopt), - ter(terNO_ACCOUNT)); + env(amm::ammClawback(gw, Account("unknown"), USD, XRP, std::nullopt), ter(terNO_ACCOUNT)); } // Test if asset pair provided does not exist. This should @@ -70,8 +68,7 @@ class AMMClawback_test : public beast::unit_test::suite // The AMM account does not exist at all now. // It should return terNO_AMM error. - env(amm::ammClawback(gw, alice, USD, gw["EUR"], std::nullopt), - ter(terNO_AMM)); + env(amm::ammClawback(gw, alice, USD, gw["EUR"], std::nullopt), ter(terNO_AMM)); } // Test if the issuer field and holder field is the same. This should @@ -97,12 +94,10 @@ class AMMClawback_test : public beast::unit_test::suite AMM amm(env, gw, XRP(100), USD(100), ter(tesSUCCESS)); // Issuer can not clawback from himself. - env(amm::ammClawback(gw, gw, USD, XRP, std::nullopt), - ter(temMALFORMED)); + env(amm::ammClawback(gw, gw, USD, XRP, std::nullopt), ter(temMALFORMED)); // Holder can not clawback from himself. - env(amm::ammClawback(alice, alice, USD, XRP, std::nullopt), - ter(temMALFORMED)); + env(amm::ammClawback(alice, alice, USD, XRP, std::nullopt), ter(temMALFORMED)); } // Test if the Asset field matches the Account field. @@ -128,12 +123,7 @@ class AMMClawback_test : public beast::unit_test::suite // The Asset's issuer field is alice, while the Account field is gw. // This should return temMALFORMED because they do not match. - env(amm::ammClawback( - gw, - alice, - Issue{gw["USD"].currency, alice.id()}, - XRP, - std::nullopt), + env(amm::ammClawback(gw, alice, Issue{gw["USD"].currency, alice.id()}, XRP, std::nullopt), ter(temMALFORMED)); } @@ -161,12 +151,7 @@ class AMMClawback_test : public beast::unit_test::suite // The Asset's issuer subfield is gw account and Amount's issuer // subfield is alice account. Return temBAD_AMOUNT because // they do not match. - env(amm::ammClawback( - gw, - alice, - USD, - XRP, - STAmount{Issue{gw["USD"].currency, alice.id()}, 1}), + env(amm::ammClawback(gw, alice, USD, XRP, STAmount{Issue{gw["USD"].currency, alice.id()}, 1}), ter(temBAD_AMOUNT)); } @@ -192,21 +177,11 @@ class AMMClawback_test : public beast::unit_test::suite AMM amm(env, gw, XRP(100), USD(100), ter(tesSUCCESS)); // Return temBAD_AMOUNT if the Amount value is less than 0. - env(amm::ammClawback( - gw, - alice, - USD, - XRP, - STAmount{Issue{gw["USD"].currency, gw.id()}, -1}), + env(amm::ammClawback(gw, alice, USD, XRP, STAmount{Issue{gw["USD"].currency, gw.id()}, -1}), ter(temBAD_AMOUNT)); // Return temBAD_AMOUNT if the Amount value is 0. - env(amm::ammClawback( - gw, - alice, - USD, - XRP, - STAmount{Issue{gw["USD"].currency, gw.id()}, 0}), + env(amm::ammClawback(gw, alice, USD, XRP, STAmount{Issue{gw["USD"].currency, gw.id()}, 0}), ter(temBAD_AMOUNT)); } @@ -232,8 +207,7 @@ class AMMClawback_test : public beast::unit_test::suite // If asfAllowTrustLineClawback is not set, the issuer is not // allowed to send the AMMClawback transaction. - env(amm::ammClawback(gw, alice, USD, XRP, std::nullopt), - ter(tecNO_PERMISSION)); + env(amm::ammClawback(gw, alice, USD, XRP, std::nullopt), ter(tecNO_PERMISSION)); } // Test invalid flag. @@ -258,9 +232,7 @@ class AMMClawback_test : public beast::unit_test::suite AMM amm(env, gw, XRP(100), USD(100), ter(tesSUCCESS)); // Return temINVALID_FLAG when providing invalid flag. - env(amm::ammClawback(gw, alice, USD, XRP, std::nullopt), - txflags(tfTwoAssetIfEmpty), - ter(temINVALID_FLAG)); + env(amm::ammClawback(gw, alice, USD, XRP, std::nullopt), txflags(tfTwoAssetIfEmpty), ter(temINVALID_FLAG)); } // Test if tfClawTwoAssets is set when the two assets in the AMM pool @@ -290,9 +262,7 @@ class AMMClawback_test : public beast::unit_test::suite // but the issuer only issues USD in the pool. The issuer is not // allowed to set tfClawTwoAssets flag if he did not issue both // assets in the pool. - env(amm::ammClawback(gw, alice, USD, XRP, std::nullopt), - txflags(tfClawTwoAssets), - ter(temINVALID_FLAG)); + env(amm::ammClawback(gw, alice, USD, XRP, std::nullopt), txflags(tfClawTwoAssets), ter(temINVALID_FLAG)); } // Test clawing back XRP is being prohibited. @@ -319,8 +289,7 @@ class AMMClawback_test : public beast::unit_test::suite env.close(); // Clawback XRP is prohibited. - env(amm::ammClawback(gw, alice, XRP, USD, std::nullopt), - ter(temMALFORMED)); + env(amm::ammClawback(gw, alice, XRP, USD, std::nullopt), ter(temMALFORMED)); } } @@ -351,8 +320,7 @@ class AMMClawback_test : public beast::unit_test::suite // When featureAMMClawback is not enabled, AMMClawback is disabled. // Because when featureAMMClawback is disabled, we can not create // amm account, call amm::ammClawback directly for testing purpose. - env(amm::ammClawback(gw, alice, USD, XRP, std::nullopt), - ter(temDISABLED)); + env(amm::ammClawback(gw, alice, USD, XRP, std::nullopt), ter(temDISABLED)); } } @@ -397,12 +365,10 @@ class AMMClawback_test : public beast::unit_test::suite AMM amm(env, alice, EUR(1000), USD(2000), ter(tesSUCCESS)); env.close(); - BEAST_EXPECT(amm.expectBalances( - USD(2000), EUR(1000), IOUAmount{1414213562373095, -12})); + BEAST_EXPECT(amm.expectBalances(USD(2000), EUR(1000), IOUAmount{1414213562373095, -12})); // gw clawback 1000 USD from the AMM pool. - env(amm::ammClawback(gw, alice, USD, EUR, USD(1000)), - ter(tesSUCCESS)); + env(amm::ammClawback(gw, alice, USD, EUR, USD(1000)), ter(tesSUCCESS)); env.close(); // Alice's initial balance for USD is 3000 USD. Alice deposited 2000 @@ -419,17 +385,14 @@ class AMMClawback_test : public beast::unit_test::suite // 1000 USD and 500 EUR was withdrawn from the AMM pool, so the // current balance is 1000 USD and 500 EUR. - BEAST_EXPECT(amm.expectBalances( - USD(1000), EUR(500), IOUAmount{7071067811865475, -13})); + BEAST_EXPECT(amm.expectBalances(USD(1000), EUR(500), IOUAmount{7071067811865475, -13})); // Alice has half of its initial lptokens Left. - BEAST_EXPECT( - amm.expectLPTokens(alice, IOUAmount{7071067811865475, -13})); + BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{7071067811865475, -13})); // gw clawback another 1000 USD from the AMM pool. The AMM pool will // be empty and get deleted. - env(amm::ammClawback(gw, alice, USD, EUR, USD(1000)), - ter(tesSUCCESS)); + env(amm::ammClawback(gw, alice, USD, EUR, USD(1000)), ter(tesSUCCESS)); env.close(); // Alice should still has 1000 USD because gw clawed back from the @@ -472,14 +435,12 @@ class AMMClawback_test : public beast::unit_test::suite AMM amm(env, alice, XRP(1000), USD(2000), ter(tesSUCCESS)); env.close(); - BEAST_EXPECT(amm.expectBalances( - USD(2000), XRP(1000), IOUAmount{1414213562373095, -9})); + BEAST_EXPECT(amm.expectBalances(USD(2000), XRP(1000), IOUAmount{1414213562373095, -9})); auto aliceXrpBalance = env.balance(alice, XRP); // gw clawback 1000 USD from the AMM pool. - env(amm::ammClawback(gw, alice, USD, XRP, USD(1000)), - ter(tesSUCCESS)); + env(amm::ammClawback(gw, alice, USD, XRP, USD(1000)), ter(tesSUCCESS)); env.close(); // Alice's initial balance for USD is 3000 USD. Alice deposited 2000 @@ -489,23 +450,19 @@ class AMMClawback_test : public beast::unit_test::suite env.require(balance(alice, USD(1000))); // Alice will get 500 XRP back. - BEAST_EXPECT( - expectLedgerEntryRoot(env, alice, aliceXrpBalance + XRP(500))); + BEAST_EXPECT(expectLedgerEntryRoot(env, alice, aliceXrpBalance + XRP(500))); aliceXrpBalance = env.balance(alice, XRP); // 1000 USD and 500 XRP was withdrawn from the AMM pool, so the // current balance is 1000 USD and 500 XRP. - BEAST_EXPECT(amm.expectBalances( - USD(1000), XRP(500), IOUAmount{7071067811865475, -10})); + BEAST_EXPECT(amm.expectBalances(USD(1000), XRP(500), IOUAmount{7071067811865475, -10})); // Alice has half of its initial lptokens Left. - BEAST_EXPECT( - amm.expectLPTokens(alice, IOUAmount{7071067811865475, -10})); + BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{7071067811865475, -10})); // gw clawback another 1000 USD from the AMM pool. The AMM pool will // be empty and get deleted. - env(amm::ammClawback(gw, alice, USD, XRP, USD(1000)), - ter(tesSUCCESS)); + env(amm::ammClawback(gw, alice, USD, XRP, USD(1000)), ter(tesSUCCESS)); env.close(); // Alice should still has 1000 USD because gw clawed back from the @@ -514,8 +471,7 @@ class AMMClawback_test : public beast::unit_test::suite env.require(balance(alice, USD(1000))); // Alice will get another 500 XRP back. - BEAST_EXPECT( - expectLedgerEntryRoot(env, alice, aliceXrpBalance + XRP(500))); + BEAST_EXPECT(expectLedgerEntryRoot(env, alice, aliceXrpBalance + XRP(500))); // amm is automatically deleted. BEAST_EXPECT(!amm.ammExists()); @@ -566,15 +522,12 @@ class AMMClawback_test : public beast::unit_test::suite env.close(); if (!features[fixAMMv1_3]) - BEAST_EXPECT(amm.expectBalances( - USD(4000), EUR(5000), IOUAmount{4472135954999580, -12})); + BEAST_EXPECT(amm.expectBalances(USD(4000), EUR(5000), IOUAmount{4472135954999580, -12})); else - BEAST_EXPECT(amm.expectBalances( - USD(4000), EUR(5000), IOUAmount{4472135954999579, -12})); + BEAST_EXPECT(amm.expectBalances(USD(4000), EUR(5000), IOUAmount{4472135954999579, -12})); // gw clawback 1000 USD from the AMM pool - env(amm::ammClawback(gw, alice, USD, EUR, USD(1000)), - ter(tesSUCCESS)); + env(amm::ammClawback(gw, alice, USD, EUR, USD(1000)), ter(tesSUCCESS)); env.close(); // Alice's initial balance for USD is 6000 USD. Alice deposited 4000 @@ -590,23 +543,18 @@ class AMMClawback_test : public beast::unit_test::suite // 1000 USD and 1250 EUR was withdrawn from the AMM pool, so the // current balance is 3000 USD and 3750 EUR. if (!features[fixAMMv1_3]) - BEAST_EXPECT(amm.expectBalances( - USD(3000), EUR(3750), IOUAmount{3354101966249685, -12})); + BEAST_EXPECT(amm.expectBalances(USD(3000), EUR(3750), IOUAmount{3354101966249685, -12})); else - BEAST_EXPECT(amm.expectBalances( - USD(3000), EUR(3750), IOUAmount{3354101966249684, -12})); + BEAST_EXPECT(amm.expectBalances(USD(3000), EUR(3750), IOUAmount{3354101966249684, -12})); // Alice has 3/4 of its initial lptokens Left. if (!features[fixAMMv1_3]) - BEAST_EXPECT(amm.expectLPTokens( - alice, IOUAmount{3354101966249685, -12})); + BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{3354101966249685, -12})); else - BEAST_EXPECT(amm.expectLPTokens( - alice, IOUAmount{3354101966249684, -12})); + BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{3354101966249684, -12})); // gw clawback another 500 USD from the AMM pool. - env(amm::ammClawback(gw, alice, USD, EUR, USD(500)), - ter(tesSUCCESS)); + env(amm::ammClawback(gw, alice, USD, EUR, USD(500)), ter(tesSUCCESS)); env.close(); // Alice should still has 2000 USD because gw clawed back from the @@ -619,13 +567,10 @@ class AMMClawback_test : public beast::unit_test::suite STAmount{EUR, UINT64_C(3125000000000001), -12}, IOUAmount{2795084971874738, -12})); else - BEAST_EXPECT(amm.expectBalances( - USD(2500), EUR(3125), IOUAmount{2795084971874737, -12})); + BEAST_EXPECT(amm.expectBalances(USD(2500), EUR(3125), IOUAmount{2795084971874737, -12})); if (!features[fixAMMv1_3]) - BEAST_EXPECT( - env.balance(alice, EUR) == - STAmount(EUR, UINT64_C(2874999999999999), -12)); + BEAST_EXPECT(env.balance(alice, EUR) == STAmount(EUR, UINT64_C(2874999999999999), -12)); else BEAST_EXPECT(env.balance(alice, EUR) == EUR(2875)); @@ -642,8 +587,7 @@ class AMMClawback_test : public beast::unit_test::suite STAmount{EUR, UINT64_C(3123750000000002), -12}, IOUAmount{2793966937885989, -12})); else if (!features[fixAMMClawbackRounding]) - BEAST_EXPECT(amm.expectBalances( - USD(2499), EUR(3123.75), IOUAmount{2793966937885987, -12})); + BEAST_EXPECT(amm.expectBalances(USD(2499), EUR(3123.75), IOUAmount{2793966937885987, -12})); else if (features[fixAMMClawbackRounding] && features[fixAMMv1_3]) BEAST_EXPECT(amm.expectBalances( STAmount{USD, UINT64_C(2499000000000001), -12}, @@ -651,28 +595,21 @@ class AMMClawback_test : public beast::unit_test::suite IOUAmount{2793966937885988, -12})); if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) - BEAST_EXPECT( - env.balance(alice, EUR) == - STAmount(EUR, UINT64_C(2876'249999999998), -12)); + BEAST_EXPECT(env.balance(alice, EUR) == STAmount(EUR, UINT64_C(2876'249999999998), -12)); else if (!features[fixAMMClawbackRounding]) BEAST_EXPECT(env.balance(alice, EUR) == EUR(2876.25)); else if (features[fixAMMClawbackRounding] && features[fixAMMv1_3]) - BEAST_EXPECT( - env.balance(alice, EUR) == - STAmount(EUR, UINT64_C(2876'249999999999), -12)); + BEAST_EXPECT(env.balance(alice, EUR) == STAmount(EUR, UINT64_C(2876'249999999999), -12)); // gw clawback 4000 USD, exceeding the current balance. We // will clawback all. - env(amm::ammClawback(gw, alice, USD, EUR, USD(4000)), - ter(tesSUCCESS)); + env(amm::ammClawback(gw, alice, USD, EUR, USD(4000)), ter(tesSUCCESS)); env.close(); env.require(balance(alice, USD(2000))); // All alice's EUR in the pool goes back to alice. - BEAST_EXPECT( - env.balance(alice, EUR) == - STAmount(EUR, UINT64_C(6000000000000000), -12)); + BEAST_EXPECT(env.balance(alice, EUR) == STAmount(EUR, UINT64_C(6000000000000000), -12)); // amm is automatically deleted. BEAST_EXPECT(!amm.ammExists()); @@ -720,48 +657,38 @@ class AMMClawback_test : public beast::unit_test::suite // gw creates AMM pool of XRP/USD, alice and bob deposit XRP/USD. AMM amm(env, gw, XRP(2000), USD(1000), ter(tesSUCCESS)); - BEAST_EXPECT(amm.expectBalances( - USD(1000), XRP(2000), IOUAmount{1414213562373095, -9})); + BEAST_EXPECT(amm.expectBalances(USD(1000), XRP(2000), IOUAmount{1414213562373095, -9})); amm.deposit(alice, USD(1000), XRP(2000)); - BEAST_EXPECT(amm.expectBalances( - USD(2000), XRP(4000), IOUAmount{2828427124746190, -9})); + BEAST_EXPECT(amm.expectBalances(USD(2000), XRP(4000), IOUAmount{2828427124746190, -9})); amm.deposit(bob, USD(1000), XRP(2000)); - BEAST_EXPECT(amm.expectBalances( - USD(3000), XRP(6000), IOUAmount{4242640687119285, -9})); + BEAST_EXPECT(amm.expectBalances(USD(3000), XRP(6000), IOUAmount{4242640687119285, -9})); env.close(); // gw2 creates AMM pool of XRP/EUR, alice and bob deposit XRP/EUR. AMM amm2(env, gw2, XRP(3000), EUR(1000), ter(tesSUCCESS)); if (!features[fixAMMv1_3]) - BEAST_EXPECT(amm2.expectBalances( - EUR(1000), XRP(3000), IOUAmount{1732050807568878, -9})); + BEAST_EXPECT(amm2.expectBalances(EUR(1000), XRP(3000), IOUAmount{1732050807568878, -9})); else - BEAST_EXPECT(amm2.expectBalances( - EUR(1000), XRP(3000), IOUAmount{1732050807568877, -9})); + BEAST_EXPECT(amm2.expectBalances(EUR(1000), XRP(3000), IOUAmount{1732050807568877, -9})); amm2.deposit(alice, EUR(1000), XRP(3000)); if (!features[fixAMMv1_3]) - BEAST_EXPECT(amm2.expectBalances( - EUR(2000), XRP(6000), IOUAmount{3464101615137756, -9})); + BEAST_EXPECT(amm2.expectBalances(EUR(2000), XRP(6000), IOUAmount{3464101615137756, -9})); else - BEAST_EXPECT(amm2.expectBalances( - EUR(2000), XRP(6000), IOUAmount{3464101615137754, -9})); + BEAST_EXPECT(amm2.expectBalances(EUR(2000), XRP(6000), IOUAmount{3464101615137754, -9})); amm2.deposit(bob, EUR(1000), XRP(3000)); if (!features[fixAMMv1_3]) - BEAST_EXPECT(amm2.expectBalances( - EUR(3000), XRP(9000), IOUAmount{5196152422706634, -9})); + BEAST_EXPECT(amm2.expectBalances(EUR(3000), XRP(9000), IOUAmount{5196152422706634, -9})); else - BEAST_EXPECT(amm2.expectBalances( - EUR(3000), XRP(9000), IOUAmount{5196152422706631, -9})); + BEAST_EXPECT(amm2.expectBalances(EUR(3000), XRP(9000), IOUAmount{5196152422706631, -9})); env.close(); auto aliceXrpBalance = env.balance(alice, XRP); auto bobXrpBalance = env.balance(bob, XRP); // gw clawback 500 USD from alice in amm - env(amm::ammClawback(gw, alice, USD, XRP, USD(500)), - ter(tesSUCCESS)); + env(amm::ammClawback(gw, alice, USD, XRP, USD(500)), ter(tesSUCCESS)); env.close(); // Alice's initial balance for USD is 6000 USD. Alice deposited 1000 @@ -774,37 +701,26 @@ class AMMClawback_test : public beast::unit_test::suite // Alice gets 1000 XRP back. if (features[fixAMMClawbackRounding] && features[fixAMMv1_3]) - BEAST_EXPECT(expectLedgerEntryRoot( - env, alice, aliceXrpBalance + XRP(1000) - XRPAmount(1))); + BEAST_EXPECT(expectLedgerEntryRoot(env, alice, aliceXrpBalance + XRP(1000) - XRPAmount(1))); else - BEAST_EXPECT(expectLedgerEntryRoot( - env, alice, aliceXrpBalance + XRP(1000))); + BEAST_EXPECT(expectLedgerEntryRoot(env, alice, aliceXrpBalance + XRP(1000))); aliceXrpBalance = env.balance(alice, XRP); if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) - BEAST_EXPECT(amm.expectBalances( - USD(2500), XRP(5000), IOUAmount{3535533905932738, -9})); + BEAST_EXPECT(amm.expectBalances(USD(2500), XRP(5000), IOUAmount{3535533905932738, -9})); else if (!features[fixAMMClawbackRounding]) - BEAST_EXPECT(amm.expectBalances( - USD(2500), XRP(5000), IOUAmount{3535533905932737, -9})); + BEAST_EXPECT(amm.expectBalances(USD(2500), XRP(5000), IOUAmount{3535533905932737, -9})); else if (features[fixAMMClawbackRounding] && features[fixAMMv1_3]) - BEAST_EXPECT(amm.expectBalances( - USD(2500), - XRPAmount(5000000001), - IOUAmount{3'535'533'905932738, -9})); + BEAST_EXPECT(amm.expectBalances(USD(2500), XRPAmount(5000000001), IOUAmount{3'535'533'905932738, -9})); if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) - BEAST_EXPECT(amm.expectLPTokens( - alice, IOUAmount{7071067811865480, -10})); + BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{7071067811865480, -10})); else if (!features[fixAMMClawbackRounding]) - BEAST_EXPECT(amm.expectLPTokens( - alice, IOUAmount{7071067811865474, -10})); + BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{7071067811865474, -10})); else if (features[fixAMMClawbackRounding] && features[fixAMMv1_3]) - BEAST_EXPECT( - amm.expectLPTokens(alice, IOUAmount{707106781186548, -9})); + BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{707106781186548, -9})); - BEAST_EXPECT( - amm.expectLPTokens(bob, IOUAmount{1414213562373095, -9})); + BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount{1414213562373095, -9})); // gw clawback 10 USD from bob in amm. env(amm::ammClawback(gw, bob, USD, XRP, USD(10)), ter(tesSUCCESS)); @@ -814,18 +730,14 @@ class AMMClawback_test : public beast::unit_test::suite env.require(balance(bob, USD(4000))); // Bob gets 20 XRP back. - BEAST_EXPECT( - expectLedgerEntryRoot(env, bob, bobXrpBalance + XRP(20))); + BEAST_EXPECT(expectLedgerEntryRoot(env, bob, bobXrpBalance + XRP(20))); bobXrpBalance = env.balance(bob, XRP); if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) BEAST_EXPECT(amm.expectBalances( - STAmount{USD, UINT64_C(2490000000000001), -12}, - XRP(4980), - IOUAmount{3521391770309008, -9})); + STAmount{USD, UINT64_C(2490000000000001), -12}, XRP(4980), IOUAmount{3521391770309008, -9})); else if (!features[fixAMMClawbackRounding]) - BEAST_EXPECT(amm.expectBalances( - USD(2'490), XRP(4980), IOUAmount{3521391770309006, -9})); + BEAST_EXPECT(amm.expectBalances(USD(2'490), XRP(4980), IOUAmount{3521391770309006, -9})); else if (features[fixAMMClawbackRounding] && features[fixAMMv1_3]) BEAST_EXPECT(amm.expectBalances( STAmount{USD, UINT64_C(2490000000000001), -12}, @@ -833,74 +745,54 @@ class AMMClawback_test : public beast::unit_test::suite IOUAmount{3521391'770309008, -9})); if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) - BEAST_EXPECT(amm.expectLPTokens( - alice, IOUAmount{7071067811865480, -10})); + BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{7071067811865480, -10})); else if (!features[fixAMMClawbackRounding]) - BEAST_EXPECT(amm.expectLPTokens( - alice, IOUAmount{7071067811865474, -10})); + BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{7071067811865474, -10})); else if (features[fixAMMClawbackRounding] && features[fixAMMv1_3]) - BEAST_EXPECT( - amm.expectLPTokens(alice, IOUAmount{707106781186548, -9})); + BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{707106781186548, -9})); if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) - BEAST_EXPECT( - amm.expectLPTokens(bob, IOUAmount{1400071426749365, -9})); + BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount{1400071426749365, -9})); else if (!features[fixAMMClawbackRounding]) - BEAST_EXPECT( - amm.expectLPTokens(bob, IOUAmount{1400071426749364, -9})); + BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount{1400071426749364, -9})); else if (features[fixAMMClawbackRounding] && features[fixAMMv1_3]) - BEAST_EXPECT( - amm.expectLPTokens(bob, IOUAmount{1400071426749365, -9})); + BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount{1400071426749365, -9})); // gw2 clawback 200 EUR from amm2. - env(amm::ammClawback(gw2, alice, EUR, XRP, EUR(200)), - ter(tesSUCCESS)); + env(amm::ammClawback(gw2, alice, EUR, XRP, EUR(200)), ter(tesSUCCESS)); env.close(); env.require(balance(alice, EUR(4000))); env.require(balance(bob, EUR(3000))); if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) - BEAST_EXPECT(expectLedgerEntryRoot( - env, alice, aliceXrpBalance + XRP(600))); + BEAST_EXPECT(expectLedgerEntryRoot(env, alice, aliceXrpBalance + XRP(600))); else if (!features[fixAMMClawbackRounding]) - BEAST_EXPECT(expectLedgerEntryRoot( - env, alice, aliceXrpBalance + XRP(600))); + BEAST_EXPECT(expectLedgerEntryRoot(env, alice, aliceXrpBalance + XRP(600))); else if (features[fixAMMClawbackRounding] && features[fixAMMv1_3]) - BEAST_EXPECT(expectLedgerEntryRoot( - env, alice, aliceXrpBalance + XRP(600) - XRPAmount{1})); + BEAST_EXPECT(expectLedgerEntryRoot(env, alice, aliceXrpBalance + XRP(600) - XRPAmount{1})); aliceXrpBalance = env.balance(alice, XRP); if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) - BEAST_EXPECT(amm2.expectBalances( - EUR(2800), XRP(8400), IOUAmount{4849742261192859, -9})); + BEAST_EXPECT(amm2.expectBalances(EUR(2800), XRP(8400), IOUAmount{4849742261192859, -9})); else if (!features[fixAMMClawbackRounding]) - BEAST_EXPECT(amm2.expectBalances( - EUR(2800), XRP(8400), IOUAmount{4849742261192856, -9})); + BEAST_EXPECT(amm2.expectBalances(EUR(2800), XRP(8400), IOUAmount{4849742261192856, -9})); else if (features[fixAMMv1_3] && features[fixAMMClawbackRounding]) - BEAST_EXPECT(amm2.expectBalances( - EUR(2800), - XRPAmount(8400000001), - IOUAmount{4849742261192856, -9})); + BEAST_EXPECT(amm2.expectBalances(EUR(2800), XRPAmount(8400000001), IOUAmount{4849742261192856, -9})); if (!features[fixAMMv1_3]) - BEAST_EXPECT(amm2.expectLPTokens( - alice, IOUAmount{1385640646055103, -9})); + BEAST_EXPECT(amm2.expectLPTokens(alice, IOUAmount{1385640646055103, -9})); else - BEAST_EXPECT(amm2.expectLPTokens( - alice, IOUAmount{1385640646055102, -9})); + BEAST_EXPECT(amm2.expectLPTokens(alice, IOUAmount{1385640646055102, -9})); if (!features[fixAMMv1_3]) - BEAST_EXPECT( - amm2.expectLPTokens(bob, IOUAmount{1732050807568878, -9})); + BEAST_EXPECT(amm2.expectLPTokens(bob, IOUAmount{1732050807568878, -9})); else - BEAST_EXPECT( - amm2.expectLPTokens(bob, IOUAmount{1732050807568877, -9})); + BEAST_EXPECT(amm2.expectLPTokens(bob, IOUAmount{1732050807568877, -9})); // gw claw back 1000 USD from alice in amm, which exceeds alice's // balance. This will clawback all the remaining LP tokens of alice // (corresponding 500 USD / 1000 XRP). - env(amm::ammClawback(gw, alice, USD, XRP, USD(1000)), - ter(tesSUCCESS)); + env(amm::ammClawback(gw, alice, USD, XRP, USD(1000)), ter(tesSUCCESS)); env.close(); env.require(balance(alice, USD(5000))); @@ -908,37 +800,26 @@ class AMMClawback_test : public beast::unit_test::suite // Alice gets 1000 XRP back. if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) - BEAST_EXPECT(expectLedgerEntryRoot( - env, alice, aliceXrpBalance + XRP(1000))); + BEAST_EXPECT(expectLedgerEntryRoot(env, alice, aliceXrpBalance + XRP(1000))); else if (!features[fixAMMClawbackRounding]) - BEAST_EXPECT(expectLedgerEntryRoot( - env, alice, aliceXrpBalance + XRP(1000) - XRPAmount{1})); + BEAST_EXPECT(expectLedgerEntryRoot(env, alice, aliceXrpBalance + XRP(1000) - XRPAmount{1})); else if (features[fixAMMv1_3] && features[fixAMMClawbackRounding]) - BEAST_EXPECT(expectLedgerEntryRoot( - env, alice, aliceXrpBalance + XRP(1000))); + BEAST_EXPECT(expectLedgerEntryRoot(env, alice, aliceXrpBalance + XRP(1000))); aliceXrpBalance = env.balance(alice, XRP); BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount(0))); if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) - BEAST_EXPECT( - amm.expectLPTokens(bob, IOUAmount{1400071426749365, -9})); + BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount{1400071426749365, -9})); else if (!features[fixAMMClawbackRounding]) - BEAST_EXPECT( - amm.expectLPTokens(bob, IOUAmount{1400071426749364, -9})); + BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount{1400071426749364, -9})); else if (features[fixAMMClawbackRounding] && features[fixAMMv1_3]) - BEAST_EXPECT( - amm.expectLPTokens(bob, IOUAmount{1400071426749365, -9})); + BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount{1400071426749365, -9})); if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) BEAST_EXPECT(amm.expectBalances( - STAmount{USD, UINT64_C(1990000000000001), -12}, - XRP(3980), - IOUAmount{2814284989122460, -9})); + STAmount{USD, UINT64_C(1990000000000001), -12}, XRP(3980), IOUAmount{2814284989122460, -9})); else if (!features[fixAMMClawbackRounding]) - BEAST_EXPECT(amm.expectBalances( - USD(1'990), - XRPAmount{3'980'000'001}, - IOUAmount{2814284989122459, -9})); + BEAST_EXPECT(amm.expectBalances(USD(1'990), XRPAmount{3'980'000'001}, IOUAmount{2814284989122459, -9})); else if (features[fixAMMv1_3] && features[fixAMMClawbackRounding]) BEAST_EXPECT(amm.expectBalances( STAmount{USD, UINT64_C(1990000000000001), -12}, @@ -948,8 +829,7 @@ class AMMClawback_test : public beast::unit_test::suite // gw clawback 1000 USD from bob in amm, which also exceeds bob's // balance in amm. All bob's lptoken in amm will be consumed, which // corresponds to 990 USD / 1980 XRP - env(amm::ammClawback(gw, bob, USD, XRP, USD(1000)), - ter(tesSUCCESS)); + env(amm::ammClawback(gw, bob, USD, XRP, USD(1000)), ter(tesSUCCESS)); env.close(); env.require(balance(alice, USD(5000))); @@ -957,8 +837,7 @@ class AMMClawback_test : public beast::unit_test::suite BEAST_EXPECT(expectLedgerEntryRoot(env, alice, aliceXrpBalance)); - BEAST_EXPECT( - expectLedgerEntryRoot(env, bob, bobXrpBalance + XRP(1980))); + BEAST_EXPECT(expectLedgerEntryRoot(env, bob, bobXrpBalance + XRP(1980))); bobXrpBalance = env.balance(bob, XRP); // Now neither alice nor bob has any lptoken in amm. @@ -968,8 +847,7 @@ class AMMClawback_test : public beast::unit_test::suite // gw2 claw back 1000 EUR from alice in amm2, which exceeds alice's // balance. All alice's lptokens will be consumed, which corresponds // to 800EUR / 2400 XRP. - env(amm::ammClawback(gw2, alice, EUR, XRP, EUR(1000)), - ter(tesSUCCESS)); + env(amm::ammClawback(gw2, alice, EUR, XRP, EUR(1000)), ter(tesSUCCESS)); env.close(); env.require(balance(alice, EUR(4000))); @@ -977,8 +855,7 @@ class AMMClawback_test : public beast::unit_test::suite // Alice gets another 2400 XRP back, bob's XRP balance remains the // same. - BEAST_EXPECT( - expectLedgerEntryRoot(env, alice, aliceXrpBalance + XRP(2400))); + BEAST_EXPECT(expectLedgerEntryRoot(env, alice, aliceXrpBalance + XRP(2400))); BEAST_EXPECT(expectLedgerEntryRoot(env, bob, bobXrpBalance)); aliceXrpBalance = env.balance(alice, XRP); @@ -987,22 +864,16 @@ class AMMClawback_test : public beast::unit_test::suite BEAST_EXPECT(amm2.expectLPTokens(alice, IOUAmount(0))); if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) - BEAST_EXPECT(amm2.expectBalances( - EUR(2000), XRP(6000), IOUAmount{3464101615137756, -9})); + BEAST_EXPECT(amm2.expectBalances(EUR(2000), XRP(6000), IOUAmount{3464101615137756, -9})); else if (!features[fixAMMClawbackRounding]) - BEAST_EXPECT(amm2.expectBalances( - EUR(2000), XRP(6000), IOUAmount{3464101615137754, -9})); + BEAST_EXPECT(amm2.expectBalances(EUR(2000), XRP(6000), IOUAmount{3464101615137754, -9})); else if (features[fixAMMv1_3] && features[fixAMMClawbackRounding]) - BEAST_EXPECT(amm2.expectBalances( - EUR(2000), - XRPAmount(6000000001), - IOUAmount{3464101615137754, -9})); + BEAST_EXPECT(amm2.expectBalances(EUR(2000), XRPAmount(6000000001), IOUAmount{3464101615137754, -9})); // gw2 claw back 2000 EUR from bob in amm2, which exceeds bob's // balance. All bob's lptokens will be consumed, which corresponds // to 1000EUR / 3000 XRP. - env(amm::ammClawback(gw2, bob, EUR, XRP, EUR(2000)), - ter(tesSUCCESS)); + env(amm::ammClawback(gw2, bob, EUR, XRP, EUR(2000)), ter(tesSUCCESS)); env.close(); env.require(balance(alice, EUR(4000))); @@ -1012,8 +883,7 @@ class AMMClawback_test : public beast::unit_test::suite // same. BEAST_EXPECT(expectLedgerEntryRoot(env, alice, aliceXrpBalance)); - BEAST_EXPECT( - expectLedgerEntryRoot(env, bob, bobXrpBalance + XRP(3000))); + BEAST_EXPECT(expectLedgerEntryRoot(env, bob, bobXrpBalance + XRP(3000))); bobXrpBalance = env.balance(bob, XRP); // Neither alice nor bob has any lptoken in amm2 @@ -1021,16 +891,11 @@ class AMMClawback_test : public beast::unit_test::suite BEAST_EXPECT(amm2.expectLPTokens(bob, IOUAmount(0))); if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) - BEAST_EXPECT(amm2.expectBalances( - EUR(1000), XRP(3000), IOUAmount{1732050807568878, -9})); + BEAST_EXPECT(amm2.expectBalances(EUR(1000), XRP(3000), IOUAmount{1732050807568878, -9})); else if (!features[fixAMMClawbackRounding]) - BEAST_EXPECT(amm2.expectBalances( - EUR(1000), XRP(3000), IOUAmount{1732050807568877, -9})); + BEAST_EXPECT(amm2.expectBalances(EUR(1000), XRP(3000), IOUAmount{1732050807568877, -9})); else if (features[fixAMMv1_3] && features[fixAMMClawbackRounding]) - BEAST_EXPECT(amm2.expectBalances( - EUR(1000), - XRPAmount(3000000001), - IOUAmount{1732050807568877, -9})); + BEAST_EXPECT(amm2.expectBalances(EUR(1000), XRPAmount(3000000001), IOUAmount{1732050807568877, -9})); } } @@ -1089,44 +954,32 @@ class AMMClawback_test : public beast::unit_test::suite env.close(); if (!features[fixAMMv1_3]) - BEAST_EXPECT(amm.expectBalances( - USD(4000), EUR(5000), IOUAmount{4472135954999580, -12})); + BEAST_EXPECT(amm.expectBalances(USD(4000), EUR(5000), IOUAmount{4472135954999580, -12})); else - BEAST_EXPECT(amm.expectBalances( - USD(4000), EUR(5000), IOUAmount{4472135954999579, -12})); + BEAST_EXPECT(amm.expectBalances(USD(4000), EUR(5000), IOUAmount{4472135954999579, -12})); amm.deposit(bob, USD(2000), EUR(2500)); if (!features[fixAMMv1_3]) - BEAST_EXPECT(amm.expectBalances( - USD(6000), EUR(7500), IOUAmount{6708203932499370, -12})); + BEAST_EXPECT(amm.expectBalances(USD(6000), EUR(7500), IOUAmount{6708203932499370, -12})); else - BEAST_EXPECT(amm.expectBalances( - USD(6000), EUR(7500), IOUAmount{6708203932499368, -12})); + BEAST_EXPECT(amm.expectBalances(USD(6000), EUR(7500), IOUAmount{6708203932499368, -12})); amm.deposit(carol, USD(1000), EUR(1250)); if (!features[fixAMMv1_3]) - BEAST_EXPECT(amm.expectBalances( - USD(7000), EUR(8750), IOUAmount{7826237921249265, -12})); + BEAST_EXPECT(amm.expectBalances(USD(7000), EUR(8750), IOUAmount{7826237921249265, -12})); else - BEAST_EXPECT(amm.expectBalances( - USD(7000), EUR(8750), IOUAmount{7826237921249262, -12})); + BEAST_EXPECT(amm.expectBalances(USD(7000), EUR(8750), IOUAmount{7826237921249262, -12})); if (!features[fixAMMv1_3]) - BEAST_EXPECT(amm.expectLPTokens( - alice, IOUAmount{4472135954999580, -12})); + BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{4472135954999580, -12})); else - BEAST_EXPECT(amm.expectLPTokens( - alice, IOUAmount{4472135954999579, -12})); + BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{4472135954999579, -12})); if (!features[fixAMMv1_3]) - BEAST_EXPECT( - amm.expectLPTokens(bob, IOUAmount{2236067977499790, -12})); + BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount{2236067977499790, -12})); else - BEAST_EXPECT( - amm.expectLPTokens(bob, IOUAmount{2236067977499789, -12})); + BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount{2236067977499789, -12})); if (!features[fixAMMv1_3]) - BEAST_EXPECT(amm.expectLPTokens( - carol, IOUAmount{1118033988749895, -12})); + BEAST_EXPECT(amm.expectLPTokens(carol, IOUAmount{1118033988749895, -12})); else - BEAST_EXPECT(amm.expectLPTokens( - carol, IOUAmount{1118033988749894, -12})); + BEAST_EXPECT(amm.expectLPTokens(carol, IOUAmount{1118033988749894, -12})); env.require(balance(alice, USD(2000))); env.require(balance(alice, EUR(1000))); @@ -1136,8 +989,7 @@ class AMMClawback_test : public beast::unit_test::suite env.require(balance(carol, EUR(2750))); // gw clawback all the bob's USD in amm. (2000 USD / 2500 EUR) - env(amm::ammClawback(gw, bob, USD, EUR, std::nullopt), - ter(tesSUCCESS)); + env(amm::ammClawback(gw, bob, USD, EUR, std::nullopt), ter(tesSUCCESS)); env.close(); if (!features[fixAMMv1_3]) @@ -1152,40 +1004,29 @@ class AMMClawback_test : public beast::unit_test::suite IOUAmount{5590169943749473, -12})); if (!features[fixAMMv1_3]) - BEAST_EXPECT(amm.expectLPTokens( - alice, IOUAmount{4472135954999580, -12})); + BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{4472135954999580, -12})); else - BEAST_EXPECT(amm.expectLPTokens( - alice, IOUAmount{4472135954999579, -12})); + BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{4472135954999579, -12})); BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount(0))); if (!features[fixAMMv1_3]) - BEAST_EXPECT(amm.expectLPTokens( - carol, IOUAmount{1118033988749895, -12})); + BEAST_EXPECT(amm.expectLPTokens(carol, IOUAmount{1118033988749895, -12})); else - BEAST_EXPECT(amm.expectLPTokens( - carol, IOUAmount{1118033988749894, -12})); + BEAST_EXPECT(amm.expectLPTokens(carol, IOUAmount{1118033988749894, -12})); // Bob will get 2500 EUR back. env.require(balance(alice, USD(2000))); env.require(balance(alice, EUR(1000))); - BEAST_EXPECT( - env.balance(bob, USD) == - STAmount(USD, UINT64_C(3000000000000000), -12)); + BEAST_EXPECT(env.balance(bob, USD) == STAmount(USD, UINT64_C(3000000000000000), -12)); if (!features[fixAMMv1_3]) - BEAST_EXPECT( - env.balance(bob, EUR) == - STAmount(EUR, UINT64_C(5000000000000001), -12)); + BEAST_EXPECT(env.balance(bob, EUR) == STAmount(EUR, UINT64_C(5000000000000001), -12)); else - BEAST_EXPECT( - env.balance(bob, EUR) == - STAmount(EUR, UINT64_C(4999999999999999), -12)); + BEAST_EXPECT(env.balance(bob, EUR) == STAmount(EUR, UINT64_C(4999999999999999), -12)); env.require(balance(carol, USD(3000))); env.require(balance(carol, EUR(2750))); // gw2 clawback all carol's EUR in amm. (1000 USD / 1250 EUR) - env(amm::ammClawback(gw2, carol, EUR, USD, std::nullopt), - ter(tesSUCCESS)); + env(amm::ammClawback(gw2, carol, EUR, USD, std::nullopt), ter(tesSUCCESS)); env.close(); if (!features[fixAMMv1_3]) BEAST_EXPECT(amm.expectBalances( @@ -1199,17 +1040,14 @@ class AMMClawback_test : public beast::unit_test::suite IOUAmount{4472135954999579, -12})); if (!features[fixAMMv1_3]) - BEAST_EXPECT(amm.expectLPTokens( - alice, IOUAmount{4472135954999580, -12})); + BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{4472135954999580, -12})); else - BEAST_EXPECT(amm.expectLPTokens( - alice, IOUAmount{4472135954999579, -12})); + BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{4472135954999579, -12})); BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount(0))); BEAST_EXPECT(amm.expectLPTokens(carol, IOUAmount(0))); // gw2 clawback all alice's EUR in amm. (4000 USD / 5000 EUR) - env(amm::ammClawback(gw2, alice, EUR, USD, std::nullopt), - ter(tesSUCCESS)); + env(amm::ammClawback(gw2, alice, EUR, USD, std::nullopt), ter(tesSUCCESS)); env.close(); env.require(balance(carol, EUR(2750))); @@ -1243,64 +1081,45 @@ class AMMClawback_test : public beast::unit_test::suite // gw creates AMM pool of XRP/USD, alice and bob deposit XRP/USD. AMM amm(env, gw, XRP(2000), USD(10000), ter(tesSUCCESS)); if (!features[fixAMMv1_3]) - BEAST_EXPECT(amm.expectBalances( - USD(10000), XRP(2000), IOUAmount{4472135954999580, -9})); + BEAST_EXPECT(amm.expectBalances(USD(10000), XRP(2000), IOUAmount{4472135954999580, -9})); else - BEAST_EXPECT(amm.expectBalances( - USD(10000), XRP(2000), IOUAmount{4472135954999579, -9})); + BEAST_EXPECT(amm.expectBalances(USD(10000), XRP(2000), IOUAmount{4472135954999579, -9})); amm.deposit(alice, USD(1000), XRP(200)); if (!features[fixAMMv1_3]) - BEAST_EXPECT(amm.expectBalances( - USD(11000), XRP(2200), IOUAmount{4919349550499538, -9})); + BEAST_EXPECT(amm.expectBalances(USD(11000), XRP(2200), IOUAmount{4919349550499538, -9})); else - BEAST_EXPECT(amm.expectBalances( - USD(11000), XRP(2200), IOUAmount{4919349550499536, -9})); + BEAST_EXPECT(amm.expectBalances(USD(11000), XRP(2200), IOUAmount{4919349550499536, -9})); amm.deposit(bob, USD(2000), XRP(400)); if (!features[fixAMMv1_3]) - BEAST_EXPECT(amm.expectBalances( - USD(13000), XRP(2600), IOUAmount{5813776741499453, -9})); + BEAST_EXPECT(amm.expectBalances(USD(13000), XRP(2600), IOUAmount{5813776741499453, -9})); else - BEAST_EXPECT(amm.expectBalances( - USD(13000), XRP(2600), IOUAmount{5813776741499451, -9})); + BEAST_EXPECT(amm.expectBalances(USD(13000), XRP(2600), IOUAmount{5813776741499451, -9})); env.close(); auto aliceXrpBalance = env.balance(alice, XRP); auto bobXrpBalance = env.balance(bob, XRP); // gw clawback all alice's USD in amm. (1000 USD / 200 XRP) - env(amm::ammClawback(gw, alice, USD, XRP, std::nullopt), - ter(tesSUCCESS)); + env(amm::ammClawback(gw, alice, USD, XRP, std::nullopt), ter(tesSUCCESS)); env.close(); if (!features[fixAMMv1_3]) - BEAST_EXPECT(amm.expectBalances( - USD(12000), XRP(2400), IOUAmount{5366563145999495, -9})); + BEAST_EXPECT(amm.expectBalances(USD(12000), XRP(2400), IOUAmount{5366563145999495, -9})); else - BEAST_EXPECT(amm.expectBalances( - USD(12000), - XRPAmount(2400000001), - IOUAmount{5366563145999494, -9})); + BEAST_EXPECT(amm.expectBalances(USD(12000), XRPAmount(2400000001), IOUAmount{5366563145999494, -9})); if (!features[fixAMMv1_3]) - BEAST_EXPECT(expectLedgerEntryRoot( - env, alice, aliceXrpBalance + XRP(200))); + BEAST_EXPECT(expectLedgerEntryRoot(env, alice, aliceXrpBalance + XRP(200))); else - BEAST_EXPECT(expectLedgerEntryRoot( - env, alice, aliceXrpBalance + XRP(200) - XRPAmount{1})); + BEAST_EXPECT(expectLedgerEntryRoot(env, alice, aliceXrpBalance + XRP(200) - XRPAmount{1})); BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount(0))); // gw clawback all bob's USD in amm. (2000 USD / 400 XRP) - env(amm::ammClawback(gw, bob, USD, XRP, std::nullopt), - ter(tesSUCCESS)); + env(amm::ammClawback(gw, bob, USD, XRP, std::nullopt), ter(tesSUCCESS)); env.close(); if (!features[fixAMMv1_3]) - BEAST_EXPECT(amm.expectBalances( - USD(10000), XRP(2000), IOUAmount{4472135954999580, -9})); + BEAST_EXPECT(amm.expectBalances(USD(10000), XRP(2000), IOUAmount{4472135954999580, -9})); else - BEAST_EXPECT(amm.expectBalances( - USD(10000), - XRPAmount(2000000001), - IOUAmount{4472135954999579, -9})); - BEAST_EXPECT( - expectLedgerEntryRoot(env, bob, bobXrpBalance + XRP(400))); + BEAST_EXPECT(amm.expectBalances(USD(10000), XRPAmount(2000000001), IOUAmount{4472135954999579, -9})); + BEAST_EXPECT(expectLedgerEntryRoot(env, bob, bobXrpBalance + XRP(400))); BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount(0))); BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount(0))); } @@ -1352,19 +1171,16 @@ class AMMClawback_test : public beast::unit_test::suite BEAST_EXPECT(amm.expectBalances(USD(8000), EUR(2000), IOUAmount(4000))); amm.deposit(bob, USD(4000), EUR(1000)); - BEAST_EXPECT( - amm.expectBalances(USD(12000), EUR(3000), IOUAmount(6000))); + BEAST_EXPECT(amm.expectBalances(USD(12000), EUR(3000), IOUAmount(6000))); if (!features[fixAMMv1_3]) amm.deposit(carol, USD(2000), EUR(500)); else amm.deposit(carol, USD(2000.25), EUR(500)); - BEAST_EXPECT( - amm.expectBalances(USD(14000), EUR(3500), IOUAmount(7000))); + BEAST_EXPECT(amm.expectBalances(USD(14000), EUR(3500), IOUAmount(7000))); // gw clawback 1000 USD from carol. env(amm::ammClawback(gw, carol, USD, EUR, USD(1000)), ter(tesSUCCESS)); env.close(); - BEAST_EXPECT( - amm.expectBalances(USD(13000), EUR(3250), IOUAmount(6500))); + BEAST_EXPECT(amm.expectBalances(USD(13000), EUR(3250), IOUAmount(6500))); BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount(4000))); BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount(2000))); @@ -1376,21 +1192,16 @@ class AMMClawback_test : public beast::unit_test::suite if (!features[fixAMMv1_3]) BEAST_EXPECT(env.balance(carol, USD) == USD(6000)); else - BEAST_EXPECT( - env.balance(carol, USD) == - STAmount(USD, UINT64_C(5999'999999999999), -12)); + BEAST_EXPECT(env.balance(carol, USD) == STAmount(USD, UINT64_C(5999'999999999999), -12)); // 250 EUR goes back to carol. BEAST_EXPECT(env.balance(carol, EUR) == EUR(7750)); // gw clawback 1000 USD from bob with tfClawTwoAssets flag. // then the corresponding EUR will also be clawed back // by gw. - env(amm::ammClawback(gw, bob, USD, EUR, USD(1000)), - txflags(tfClawTwoAssets), - ter(tesSUCCESS)); + env(amm::ammClawback(gw, bob, USD, EUR, USD(1000)), txflags(tfClawTwoAssets), ter(tesSUCCESS)); env.close(); - BEAST_EXPECT( - amm.expectBalances(USD(12000), EUR(3000), IOUAmount(6000))); + BEAST_EXPECT(amm.expectBalances(USD(12000), EUR(3000), IOUAmount(6000))); BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount(4000))); BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount(1500))); @@ -1403,15 +1214,11 @@ class AMMClawback_test : public beast::unit_test::suite if (!features[fixAMMv1_3]) BEAST_EXPECT(env.balance(carol, USD) == USD(6000)); else - BEAST_EXPECT( - env.balance(carol, USD) == - STAmount(USD, UINT64_C(5999'999999999999), -12)); + BEAST_EXPECT(env.balance(carol, USD) == STAmount(USD, UINT64_C(5999'999999999999), -12)); BEAST_EXPECT(env.balance(carol, EUR) == EUR(7750)); // gw clawback all USD from alice and set tfClawTwoAssets. - env(amm::ammClawback(gw, alice, USD, EUR, std::nullopt), - txflags(tfClawTwoAssets), - ter(tesSUCCESS)); + env(amm::ammClawback(gw, alice, USD, EUR, std::nullopt), txflags(tfClawTwoAssets), ter(tesSUCCESS)); env.close(); BEAST_EXPECT(amm.expectBalances(USD(4000), EUR(1000), IOUAmount(2000))); @@ -1425,9 +1232,7 @@ class AMMClawback_test : public beast::unit_test::suite if (!features[fixAMMv1_3]) BEAST_EXPECT(env.balance(carol, USD) == USD(6000)); else - BEAST_EXPECT( - env.balance(carol, USD) == - STAmount(USD, UINT64_C(5999'999999999999), -12)); + BEAST_EXPECT(env.balance(carol, USD) == STAmount(USD, UINT64_C(5999'999999999999), -12)); BEAST_EXPECT(env.balance(carol, EUR) == EUR(7750)); } @@ -1473,64 +1278,37 @@ class AMMClawback_test : public beast::unit_test::suite AMM amm(env, alice, gw["USD"](1000), gw2["USD"](1500), ter(tesSUCCESS)); env.close(); - BEAST_EXPECT(amm.expectBalances( - gw["USD"](1000), - gw2["USD"](1500), - IOUAmount{1224744871391589, -12})); + BEAST_EXPECT(amm.expectBalances(gw["USD"](1000), gw2["USD"](1500), IOUAmount{1224744871391589, -12})); amm.deposit(bob, gw["USD"](2000), gw2["USD"](3000)); - BEAST_EXPECT(amm.expectBalances( - gw["USD"](3000), - gw2["USD"](4500), - IOUAmount{3674234614174767, -12})); + BEAST_EXPECT(amm.expectBalances(gw["USD"](3000), gw2["USD"](4500), IOUAmount{3674234614174767, -12})); // Issuer does not match with asset. - env(amm::ammClawback( - gw, - alice, - gw2["USD"], - gw["USD"], - STAmount{Issue{gw2["USD"].currency, gw2.id()}, 500}), + env(amm::ammClawback(gw, alice, gw2["USD"], gw["USD"], STAmount{Issue{gw2["USD"].currency, gw2.id()}, 500}), ter(temMALFORMED)); // gw2 clawback 500 gw2[USD] from alice. - env(amm::ammClawback( - gw2, - alice, - gw2["USD"], - gw["USD"], - STAmount{Issue{gw2["USD"].currency, gw2.id()}, 500}), + env(amm::ammClawback(gw2, alice, gw2["USD"], gw["USD"], STAmount{Issue{gw2["USD"].currency, gw2.id()}, 500}), ter(tesSUCCESS)); env.close(); BEAST_EXPECT(amm.expectBalances( - STAmount{gw["USD"], UINT64_C(2666666666666667), -12}, - gw2["USD"](4000), - IOUAmount{3265986323710904, -12})); + STAmount{gw["USD"], UINT64_C(2666666666666667), -12}, gw2["USD"](4000), IOUAmount{3265986323710904, -12})); - BEAST_EXPECT( - amm.expectLPTokens(alice, IOUAmount{8164965809277260, -13})); + BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{8164965809277260, -13})); BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount{2449489742783178, -12})); - BEAST_EXPECT( - env.balance(alice, gw["USD"]) == - STAmount(gw["USD"], UINT64_C(7333333333333333), -12)); + BEAST_EXPECT(env.balance(alice, gw["USD"]) == STAmount(gw["USD"], UINT64_C(7333333333333333), -12)); BEAST_EXPECT(env.balance(alice, gw2["USD"]) == gw2["USD"](4500)); BEAST_EXPECT(env.balance(bob, gw["USD"]) == gw["USD"](5000)); BEAST_EXPECT(env.balance(bob, gw2["USD"]) == gw2["USD"](2000)); // gw clawback all gw["USD"] from bob. - env(amm::ammClawback(gw, bob, gw["USD"], gw2["USD"], std::nullopt), - ter(tesSUCCESS)); + env(amm::ammClawback(gw, bob, gw["USD"], gw2["USD"], std::nullopt), ter(tesSUCCESS)); env.close(); BEAST_EXPECT(amm.expectBalances( - STAmount{gw["USD"], UINT64_C(6666666666666670), -13}, - gw2["USD"](1000), - IOUAmount{8164965809277260, -13})); + STAmount{gw["USD"], UINT64_C(6666666666666670), -13}, gw2["USD"](1000), IOUAmount{8164965809277260, -13})); - BEAST_EXPECT( - amm.expectLPTokens(alice, IOUAmount{8164965809277260, -13})); + BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{8164965809277260, -13})); BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount(0))); - BEAST_EXPECT( - env.balance(alice, gw["USD"]) == - STAmount(gw["USD"], UINT64_C(7333333333333333), -12)); + BEAST_EXPECT(env.balance(alice, gw["USD"]) == STAmount(gw["USD"], UINT64_C(7333333333333333), -12)); BEAST_EXPECT(env.balance(alice, gw2["USD"]) == gw2["USD"](4500)); BEAST_EXPECT(env.balance(bob, gw["USD"]) == gw["USD"](5000)); // Bob gets 3000 gw2["USD"] back and now his balance is 5000. @@ -1577,41 +1355,32 @@ class AMMClawback_test : public beast::unit_test::suite AMM amm(env, gw, USD(1000), EUR(2000), ter(tesSUCCESS)); env.close(); - BEAST_EXPECT(amm.expectBalances( - USD(1000), EUR(2000), IOUAmount{1414213562373095, -12})); + BEAST_EXPECT(amm.expectBalances(USD(1000), EUR(2000), IOUAmount{1414213562373095, -12})); amm.deposit(gw2, USD(2000), EUR(4000)); - BEAST_EXPECT(amm.expectBalances( - USD(3000), EUR(6000), IOUAmount{4242640687119285, -12})); + BEAST_EXPECT(amm.expectBalances(USD(3000), EUR(6000), IOUAmount{4242640687119285, -12})); amm.deposit(alice, USD(3000), EUR(6000)); - BEAST_EXPECT(amm.expectBalances( - USD(6000), EUR(12000), IOUAmount{8485281374238570, -12})); + BEAST_EXPECT(amm.expectBalances(USD(6000), EUR(12000), IOUAmount{8485281374238570, -12})); BEAST_EXPECT(amm.expectLPTokens(gw, IOUAmount{1414213562373095, -12})); BEAST_EXPECT(amm.expectLPTokens(gw2, IOUAmount{2828427124746190, -12})); - BEAST_EXPECT( - amm.expectLPTokens(alice, IOUAmount{4242640687119285, -12})); + BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{4242640687119285, -12})); // gw claws back 1000 USD from gw2. env(amm::ammClawback(gw, gw2, USD, EUR, USD(1000)), ter(tesSUCCESS)); env.close(); if (!features[fixAMMv1_3] || !features[fixAMMClawbackRounding]) - BEAST_EXPECT(amm.expectBalances( - USD(5000), EUR(10000), IOUAmount{7071067811865475, -12})); + BEAST_EXPECT(amm.expectBalances(USD(5000), EUR(10000), IOUAmount{7071067811865475, -12})); else - BEAST_EXPECT(amm.expectBalances( - USD(5000), EUR(10000), IOUAmount{7071067811865474, -12})); + BEAST_EXPECT(amm.expectBalances(USD(5000), EUR(10000), IOUAmount{7071067811865474, -12})); BEAST_EXPECT(amm.expectLPTokens(gw, IOUAmount{1414213562373095, -12})); if (!features[fixAMMv1_3] || !features[fixAMMClawbackRounding]) - BEAST_EXPECT( - amm.expectLPTokens(gw2, IOUAmount{1414213562373095, -12})); + BEAST_EXPECT(amm.expectLPTokens(gw2, IOUAmount{1414213562373095, -12})); else - BEAST_EXPECT( - amm.expectLPTokens(gw2, IOUAmount{1414213562373094, -12})); - BEAST_EXPECT( - amm.expectLPTokens(alice, IOUAmount{4242640687119285, -12})); + BEAST_EXPECT(amm.expectLPTokens(gw2, IOUAmount{1414213562373094, -12})); + BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{4242640687119285, -12})); BEAST_EXPECT(env.balance(alice, USD) == USD(2000)); BEAST_EXPECT(env.balance(alice, EUR) == EUR(0)); @@ -1623,37 +1392,26 @@ class AMMClawback_test : public beast::unit_test::suite env.close(); if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) BEAST_EXPECT(amm.expectBalances( - USD(4500), - STAmount(EUR, UINT64_C(9000000000000001), -12), - IOUAmount{6363961030678928, -12})); + USD(4500), STAmount(EUR, UINT64_C(9000000000000001), -12), IOUAmount{6363961030678928, -12})); else if (!features[fixAMMClawbackRounding]) - BEAST_EXPECT(amm.expectBalances( - USD(4500), EUR(9000), IOUAmount{6363961030678928, -12})); + BEAST_EXPECT(amm.expectBalances(USD(4500), EUR(9000), IOUAmount{6363961030678928, -12})); else if (features[fixAMMv1_3] && features[fixAMMClawbackRounding]) BEAST_EXPECT(amm.expectBalances( - USD(4500), - STAmount(EUR, UINT64_C(9000000000000001), -12), - IOUAmount{6363961030678927, -12})); + USD(4500), STAmount(EUR, UINT64_C(9000000000000001), -12), IOUAmount{6363961030678927, -12})); if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) - BEAST_EXPECT( - amm.expectLPTokens(gw, IOUAmount{7071067811865480, -13})); + BEAST_EXPECT(amm.expectLPTokens(gw, IOUAmount{7071067811865480, -13})); else if (!features[fixAMMClawbackRounding]) - BEAST_EXPECT( - amm.expectLPTokens(gw, IOUAmount{7071067811865475, -13})); + BEAST_EXPECT(amm.expectLPTokens(gw, IOUAmount{7071067811865475, -13})); else if (features[fixAMMv1_3] && features[fixAMMClawbackRounding]) - BEAST_EXPECT( - amm.expectLPTokens(gw, IOUAmount{7071067811865480, -13})); + BEAST_EXPECT(amm.expectLPTokens(gw, IOUAmount{7071067811865480, -13})); if (!features[fixAMMv1_3] || !features[fixAMMClawbackRounding]) - BEAST_EXPECT( - amm.expectLPTokens(gw2, IOUAmount{1414213562373095, -12})); + BEAST_EXPECT(amm.expectLPTokens(gw2, IOUAmount{1414213562373095, -12})); else - BEAST_EXPECT( - amm.expectLPTokens(gw2, IOUAmount{1414213562373094, -12})); + BEAST_EXPECT(amm.expectLPTokens(gw2, IOUAmount{1414213562373094, -12})); - BEAST_EXPECT( - amm.expectLPTokens(alice, IOUAmount{4242640687119285, -12})); + BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{4242640687119285, -12})); BEAST_EXPECT(env.balance(alice, USD) == USD(2000)); BEAST_EXPECT(env.balance(alice, EUR) == EUR(0)); @@ -1665,36 +1423,25 @@ class AMMClawback_test : public beast::unit_test::suite env.close(); if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) BEAST_EXPECT(amm.expectBalances( - USD(2500), - STAmount(EUR, UINT64_C(5000000000000001), -12), - IOUAmount{3535533905932738, -12})); + USD(2500), STAmount(EUR, UINT64_C(5000000000000001), -12), IOUAmount{3535533905932738, -12})); else if (!features[fixAMMClawbackRounding]) - BEAST_EXPECT(amm.expectBalances( - USD(2500), EUR(5000), IOUAmount{3535533905932738, -12})); + BEAST_EXPECT(amm.expectBalances(USD(2500), EUR(5000), IOUAmount{3535533905932738, -12})); else if (features[fixAMMv1_3] && features[fixAMMClawbackRounding]) BEAST_EXPECT(amm.expectBalances( - USD(2500), - STAmount(EUR, UINT64_C(5000000000000001), -12), - IOUAmount{3535533905932737, -12})); + USD(2500), STAmount(EUR, UINT64_C(5000000000000001), -12), IOUAmount{3535533905932737, -12})); if (!features[fixAMMv1_3] && !features[fixAMMClawbackRounding]) - BEAST_EXPECT( - amm.expectLPTokens(gw, IOUAmount{7071067811865480, -13})); + BEAST_EXPECT(amm.expectLPTokens(gw, IOUAmount{7071067811865480, -13})); else if (!features[fixAMMClawbackRounding]) - BEAST_EXPECT( - amm.expectLPTokens(gw, IOUAmount{7071067811865475, -13})); + BEAST_EXPECT(amm.expectLPTokens(gw, IOUAmount{7071067811865475, -13})); else if (features[fixAMMv1_3] && features[fixAMMClawbackRounding]) - BEAST_EXPECT( - amm.expectLPTokens(gw, IOUAmount{7071067811865480, -13})); + BEAST_EXPECT(amm.expectLPTokens(gw, IOUAmount{7071067811865480, -13})); if (!features[fixAMMv1_3] || !features[fixAMMClawbackRounding]) - BEAST_EXPECT( - amm.expectLPTokens(gw2, IOUAmount{1414213562373095, -12})); + BEAST_EXPECT(amm.expectLPTokens(gw2, IOUAmount{1414213562373095, -12})); else - BEAST_EXPECT( - amm.expectLPTokens(gw2, IOUAmount{1414213562373094, -12})); - BEAST_EXPECT( - amm.expectLPTokens(alice, IOUAmount{1414213562373095, -12})); + BEAST_EXPECT(amm.expectLPTokens(gw2, IOUAmount{1414213562373094, -12})); + BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{1414213562373095, -12})); BEAST_EXPECT(env.balance(alice, USD) == USD(4000)); BEAST_EXPECT(env.balance(alice, EUR) == EUR(0)); @@ -1730,8 +1477,7 @@ class AMMClawback_test : public beast::unit_test::suite // Alice did not deposit in the amm pool. So AMMClawback from Alice // will fail. - env(amm::ammClawback(gw, alice, USD, XRP, USD(1000)), - ter(tecAMM_BALANCE)); + env(amm::ammClawback(gw, alice, USD, XRP, USD(1000)), ter(tecAMM_BALANCE)); } void @@ -1772,31 +1518,26 @@ class AMMClawback_test : public beast::unit_test::suite AMM amm(env, alice, EUR(1000), USD(2000), ter(tesSUCCESS)); env.close(); - BEAST_EXPECT(amm.expectBalances( - USD(2000), EUR(1000), IOUAmount{1414213562373095, -12})); + BEAST_EXPECT(amm.expectBalances(USD(2000), EUR(1000), IOUAmount{1414213562373095, -12})); // freeze trustline env(trust(gw, alice["USD"](0), tfSetFreeze)); env.close(); // gw clawback 1000 USD from the AMM pool. - env(amm::ammClawback(gw, alice, USD, EUR, USD(1000)), - ter(tesSUCCESS)); + env(amm::ammClawback(gw, alice, USD, EUR, USD(1000)), ter(tesSUCCESS)); env.close(); env.require(balance(alice, USD(1000))); env.require(balance(alice, EUR(2500))); - BEAST_EXPECT(amm.expectBalances( - USD(1000), EUR(500), IOUAmount{7071067811865475, -13})); + BEAST_EXPECT(amm.expectBalances(USD(1000), EUR(500), IOUAmount{7071067811865475, -13})); // Alice has half of its initial lptokens Left. - BEAST_EXPECT( - amm.expectLPTokens(alice, IOUAmount{7071067811865475, -13})); + BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{7071067811865475, -13})); // gw clawback another 1000 USD from the AMM pool. The AMM pool will // be empty and get deleted. - env(amm::ammClawback(gw, alice, USD, EUR, USD(1000)), - ter(tesSUCCESS)); + env(amm::ammClawback(gw, alice, USD, EUR, USD(1000)), ter(tesSUCCESS)); env.close(); // Alice should still has 1000 USD because gw clawed back from the @@ -1840,8 +1581,7 @@ class AMMClawback_test : public beast::unit_test::suite AMM amm(env, alice, EUR(1000), USD(2000), ter(tesSUCCESS)); env.close(); - BEAST_EXPECT(amm.expectBalances( - USD(2000), EUR(1000), IOUAmount{1414213562373095, -12})); + BEAST_EXPECT(amm.expectBalances(USD(2000), EUR(1000), IOUAmount{1414213562373095, -12})); // freeze trustlines env(trust(gw, alice["USD"](0), tfSetFreeze)); @@ -1849,16 +1589,13 @@ class AMMClawback_test : public beast::unit_test::suite env.close(); // gw clawback 1000 USD from the AMM pool. - env(amm::ammClawback(gw, alice, USD, EUR, USD(1000)), - ter(tesSUCCESS)); + env(amm::ammClawback(gw, alice, USD, EUR, USD(1000)), ter(tesSUCCESS)); env.close(); env.require(balance(alice, USD(1000))); env.require(balance(alice, EUR(2500))); - BEAST_EXPECT(amm.expectBalances( - USD(1000), EUR(500), IOUAmount{7071067811865475, -13})); - BEAST_EXPECT( - amm.expectLPTokens(alice, IOUAmount{7071067811865475, -13})); + BEAST_EXPECT(amm.expectBalances(USD(1000), EUR(500), IOUAmount{7071067811865475, -13})); + BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{7071067811865475, -13})); } // test gw global freeze. @@ -1893,24 +1630,20 @@ class AMMClawback_test : public beast::unit_test::suite AMM amm(env, alice, EUR(1000), USD(2000), ter(tesSUCCESS)); env.close(); - BEAST_EXPECT(amm.expectBalances( - USD(2000), EUR(1000), IOUAmount{1414213562373095, -12})); + BEAST_EXPECT(amm.expectBalances(USD(2000), EUR(1000), IOUAmount{1414213562373095, -12})); // global freeze env(fset(gw, asfGlobalFreeze)); env.close(); // gw clawback 1000 USD from the AMM pool. - env(amm::ammClawback(gw, alice, USD, EUR, USD(1000)), - ter(tesSUCCESS)); + env(amm::ammClawback(gw, alice, USD, EUR, USD(1000)), ter(tesSUCCESS)); env.close(); env.require(balance(alice, USD(1000))); env.require(balance(alice, EUR(2500))); - BEAST_EXPECT(amm.expectBalances( - USD(1000), EUR(500), IOUAmount{7071067811865475, -13})); - BEAST_EXPECT( - amm.expectLPTokens(alice, IOUAmount{7071067811865475, -13})); + BEAST_EXPECT(amm.expectBalances(USD(1000), EUR(500), IOUAmount{7071067811865475, -13})); + BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{7071067811865475, -13})); } // Test both assets are issued by the same issuer. And issuer sets @@ -1950,28 +1683,23 @@ class AMMClawback_test : public beast::unit_test::suite AMM amm(env, alice, EUR(2000), USD(8000), ter(tesSUCCESS)); env.close(); - BEAST_EXPECT( - amm.expectBalances(USD(8000), EUR(2000), IOUAmount(4000))); + BEAST_EXPECT(amm.expectBalances(USD(8000), EUR(2000), IOUAmount(4000))); amm.deposit(bob, USD(4000), EUR(1000)); - BEAST_EXPECT( - amm.expectBalances(USD(12000), EUR(3000), IOUAmount(6000))); + BEAST_EXPECT(amm.expectBalances(USD(12000), EUR(3000), IOUAmount(6000))); if (!features[fixAMMv1_3]) amm.deposit(carol, USD(2000), EUR(500)); else amm.deposit(carol, USD(2000.25), EUR(500)); - BEAST_EXPECT( - amm.expectBalances(USD(14000), EUR(3500), IOUAmount(7000))); + BEAST_EXPECT(amm.expectBalances(USD(14000), EUR(3500), IOUAmount(7000))); // global freeze env(fset(gw, asfGlobalFreeze)); env.close(); // gw clawback 1000 USD from carol. - env(amm::ammClawback(gw, carol, USD, EUR, USD(1000)), - ter(tesSUCCESS)); + env(amm::ammClawback(gw, carol, USD, EUR, USD(1000)), ter(tesSUCCESS)); env.close(); - BEAST_EXPECT( - amm.expectBalances(USD(13000), EUR(3250), IOUAmount(6500))); + BEAST_EXPECT(amm.expectBalances(USD(13000), EUR(3250), IOUAmount(6500))); BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount(4000))); BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount(2000))); @@ -1983,21 +1711,16 @@ class AMMClawback_test : public beast::unit_test::suite if (!features[fixAMMv1_3]) BEAST_EXPECT(env.balance(carol, USD) == USD(6000)); else - BEAST_EXPECT( - env.balance(carol, USD) == - STAmount(USD, UINT64_C(5999'999999999999), -12)); + BEAST_EXPECT(env.balance(carol, USD) == STAmount(USD, UINT64_C(5999'999999999999), -12)); // 250 EUR goes back to carol. BEAST_EXPECT(env.balance(carol, EUR) == EUR(7750)); // gw clawback 1000 USD from bob with tfClawTwoAssets flag. // then the corresponding EUR will also be clawed back // by gw. - env(amm::ammClawback(gw, bob, USD, EUR, USD(1000)), - txflags(tfClawTwoAssets), - ter(tesSUCCESS)); + env(amm::ammClawback(gw, bob, USD, EUR, USD(1000)), txflags(tfClawTwoAssets), ter(tesSUCCESS)); env.close(); - BEAST_EXPECT( - amm.expectBalances(USD(12000), EUR(3000), IOUAmount(6000))); + BEAST_EXPECT(amm.expectBalances(USD(12000), EUR(3000), IOUAmount(6000))); BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount(4000))); BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount(1500))); @@ -2010,18 +1733,13 @@ class AMMClawback_test : public beast::unit_test::suite if (!features[fixAMMv1_3]) BEAST_EXPECT(env.balance(carol, USD) == USD(6000)); else - BEAST_EXPECT( - env.balance(carol, USD) == - STAmount(USD, UINT64_C(5999'999999999999), -12)); + BEAST_EXPECT(env.balance(carol, USD) == STAmount(USD, UINT64_C(5999'999999999999), -12)); BEAST_EXPECT(env.balance(carol, EUR) == EUR(7750)); // gw clawback all USD from alice and set tfClawTwoAssets. - env(amm::ammClawback(gw, alice, USD, EUR, std::nullopt), - txflags(tfClawTwoAssets), - ter(tesSUCCESS)); + env(amm::ammClawback(gw, alice, USD, EUR, std::nullopt), txflags(tfClawTwoAssets), ter(tesSUCCESS)); env.close(); - BEAST_EXPECT( - amm.expectBalances(USD(4000), EUR(1000), IOUAmount(2000))); + BEAST_EXPECT(amm.expectBalances(USD(4000), EUR(1000), IOUAmount(2000))); BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount(0))); BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount(1500))); @@ -2033,9 +1751,7 @@ class AMMClawback_test : public beast::unit_test::suite if (!features[fixAMMv1_3]) BEAST_EXPECT(env.balance(carol, USD) == USD(6000)); else - BEAST_EXPECT( - env.balance(carol, USD) == - STAmount(USD, UINT64_C(5999'999999999999), -12)); + BEAST_EXPECT(env.balance(carol, USD) == STAmount(USD, UINT64_C(5999'999999999999), -12)); BEAST_EXPECT(env.balance(carol, EUR) == EUR(7750)); } } @@ -2076,8 +1792,7 @@ class AMMClawback_test : public beast::unit_test::suite amm.deposit(alice, USD(400)); env.close(); - BEAST_EXPECT(amm.expectBalances( - USD(800), XRP(100), IOUAmount{2828427124746190, -10})); + BEAST_EXPECT(amm.expectBalances(USD(800), XRP(100), IOUAmount{2828427124746190, -10})); auto aliceXrpBalance = env.balance(alice, XRP); @@ -2085,22 +1800,16 @@ class AMMClawback_test : public beast::unit_test::suite env.close(); if (!features[fixAMMv1_3]) - BEAST_EXPECT(amm.expectBalances( - STAmount(USD, UINT64_C(5656854249492380), -13), - XRP(70.710678), - IOUAmount(200000))); + BEAST_EXPECT( + amm.expectBalances(STAmount(USD, UINT64_C(5656854249492380), -13), XRP(70.710678), IOUAmount(200000))); else - BEAST_EXPECT(amm.expectBalances( - STAmount(USD, UINT64_C(565'685424949238), -12), - XRP(70.710679), - IOUAmount(200000))); + BEAST_EXPECT( + amm.expectBalances(STAmount(USD, UINT64_C(565'685424949238), -12), XRP(70.710679), IOUAmount(200000))); BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount(0))); if (!features[fixAMMv1_3]) - BEAST_EXPECT(expectLedgerEntryRoot( - env, alice, aliceXrpBalance + XRP(29.289322))); + BEAST_EXPECT(expectLedgerEntryRoot(env, alice, aliceXrpBalance + XRP(29.289322))); else - BEAST_EXPECT(expectLedgerEntryRoot( - env, alice, aliceXrpBalance + XRP(29.289321))); + BEAST_EXPECT(expectLedgerEntryRoot(env, alice, aliceXrpBalance + XRP(29.289321))); } void @@ -2112,34 +1821,26 @@ class AMMClawback_test : public beast::unit_test::suite using namespace jtx; std::string logs; - auto setupAccounts = - [&](Env& env, Account& gw, Account& alice, Account& bob) { - env.fund(XRP(100000), gw, alice, bob); - env.close(); - env(fset(gw, asfAllowTrustLineClawback)); - env.close(); + auto setupAccounts = [&](Env& env, Account& gw, Account& alice, Account& bob) { + env.fund(XRP(100000), gw, alice, bob); + env.close(); + env(fset(gw, asfAllowTrustLineClawback)); + env.close(); - auto const USD = gw["USD"]; - env.trust(USD(100000), alice); - env(pay(gw, alice, USD(50000))); - env.trust(USD(100000), bob); - env(pay(gw, bob, USD(40000))); - env.close(); + auto const USD = gw["USD"]; + env.trust(USD(100000), alice); + env(pay(gw, alice, USD(50000))); + env.trust(USD(100000), bob); + env(pay(gw, bob, USD(40000))); + env.close(); - return USD; - }; + return USD; + }; auto getLPTokenBalances = - [&](auto& env, - auto const& amm, - auto const& account) -> std::pair { - auto const lpToken = - getAccountLines( - env, account, amm.lptIssue())[jss::lines][0u][jss::balance] - .asString(); - auto const lpTokenBalance = - amm.ammRpcInfo()[jss::amm][jss::lp_token][jss::value] - .asString(); + [&](auto& env, auto const& amm, auto const& account) -> std::pair { + auto const lpToken = getAccountLines(env, account, amm.lptIssue())[jss::lines][0u][jss::balance].asString(); + auto const lpTokenBalance = amm.ammRpcInfo()[jss::amm][jss::lp_token][jss::value].asString(); return {lpToken, lpTokenBalance}; }; @@ -2155,30 +1856,23 @@ class AMMClawback_test : public beast::unit_test::suite amm.withdraw(alice, IOUAmount{1'876123487565916, -15}); amm.withdrawAll(bob); - auto [lpToken, lpTokenBalance] = - getLPTokenBalances(env, amm, alice); - BEAST_EXPECT( - lpToken == "1414.21356237366" && - lpTokenBalance == "1414.213562374"); + auto [lpToken, lpTokenBalance] = getLPTokenBalances(env, amm, alice); + BEAST_EXPECT(lpToken == "1414.21356237366" && lpTokenBalance == "1414.213562374"); - auto res = - isOnlyLiquidityProvider(*env.current(), amm.lptIssue(), alice); + auto res = isOnlyLiquidityProvider(*env.current(), amm.lptIssue(), alice); BEAST_EXPECT(res && res.value()); if (!features[fixAMMClawbackRounding] || !features[fixAMMv1_3]) { - env(amm::ammClawback(gw, alice, USD, XRP, USD(1)), - ter(tecAMM_BALANCE)); + env(amm::ammClawback(gw, alice, USD, XRP, USD(1)), ter(tecAMM_BALANCE)); BEAST_EXPECT(amm.ammExists()); } else { auto const lpBalance = IOUAmount{989, -12}; env(amm::ammClawback(gw, alice, USD, XRP, USD(1))); - BEAST_EXPECT(amm.expectBalances( - STAmount(USD, UINT64_C(7000000000000000), -28), - XRPAmount(1), - lpBalance)); + BEAST_EXPECT( + amm.expectBalances(STAmount(USD, UINT64_C(7000000000000000), -28), XRPAmount(1), lpBalance)); BEAST_EXPECT(amm.expectLPTokens(alice, lpBalance)); } } @@ -2194,14 +1888,10 @@ class AMMClawback_test : public beast::unit_test::suite amm.deposit(bob, IOUAmount{1'000'000}); amm.withdrawAll(bob); - auto [lpToken, lpTokenBalance] = - getLPTokenBalances(env, amm, alice); - BEAST_EXPECT( - lpToken == "1416.08968586066" && - lpTokenBalance == "1416.089685861"); + auto [lpToken, lpTokenBalance] = getLPTokenBalances(env, amm, alice); + BEAST_EXPECT(lpToken == "1416.08968586066" && lpTokenBalance == "1416.089685861"); - auto res = - isOnlyLiquidityProvider(*env.current(), amm.lptIssue(), alice); + auto res = isOnlyLiquidityProvider(*env.current(), amm.lptIssue(), alice); BEAST_EXPECT(res && res.value()); env(amm::ammClawback(gw, alice, USD, XRP, USD(0.5))); @@ -2223,10 +1913,8 @@ class AMMClawback_test : public beast::unit_test::suite else if (features[fixAMMv1_3] && features[fixAMMClawbackRounding]) { auto const lpBalance = IOUAmount{708'9829046743238, -13}; - BEAST_EXPECT(amm.expectBalances( - STAmount(USD, UINT64_C(5013266196406999), -16), - XRPAmount(1002655), - lpBalance)); + BEAST_EXPECT( + amm.expectBalances(STAmount(USD, UINT64_C(5013266196406999), -16), XRPAmount(1002655), lpBalance)); BEAST_EXPECT(amm.expectLPTokens(alice, lpBalance)); } } @@ -2243,28 +1931,21 @@ class AMMClawback_test : public beast::unit_test::suite amm.withdraw(alice, IOUAmount{1'876123487565916, -15}); amm.withdrawAll(bob); - auto [lpToken, lpTokenBalance] = - getLPTokenBalances(env, amm, alice); - BEAST_EXPECT( - lpToken == "1414.21356237366" && - lpTokenBalance == "1414.213562374"); + auto [lpToken, lpTokenBalance] = getLPTokenBalances(env, amm, alice); + BEAST_EXPECT(lpToken == "1414.21356237366" && lpTokenBalance == "1414.213562374"); - auto res = - isOnlyLiquidityProvider(*env.current(), amm.lptIssue(), alice); + auto res = isOnlyLiquidityProvider(*env.current(), amm.lptIssue(), alice); BEAST_EXPECT(res && res.value()); if (!features[fixAMMClawbackRounding] && !features[fixAMMv1_3]) { - env(amm::ammClawback(gw, alice, USD, XRP, std::nullopt), - ter(tecAMM_BALANCE)); + env(amm::ammClawback(gw, alice, USD, XRP, std::nullopt), ter(tecAMM_BALANCE)); } else if (!features[fixAMMClawbackRounding]) { env(amm::ammClawback(gw, alice, USD, XRP, std::nullopt)); BEAST_EXPECT(amm.expectBalances( - STAmount(USD, UINT64_C(2410000000000000), -28), - XRPAmount(1), - IOUAmount{34, -11})); + STAmount(USD, UINT64_C(2410000000000000), -28), XRPAmount(1), IOUAmount{34, -11})); } else if (features[fixAMMv1_3] && features[fixAMMClawbackRounding]) { @@ -2295,14 +1976,10 @@ class AMMClawback_test : public beast::unit_test::suite amm.withdraw(alice, IOUAmount{1'576123487565916, -15}); amm.withdrawAll(bob); - auto [lpToken, lpTokenBalance] = - getLPTokenBalances(env, amm, alice); - BEAST_EXPECT( - lpToken == "1.414213562374011" && - lpTokenBalance == "1.414213562374"); + auto [lpToken, lpTokenBalance] = getLPTokenBalances(env, amm, alice); + BEAST_EXPECT(lpToken == "1.414213562374011" && lpTokenBalance == "1.414213562374"); - auto res = - isOnlyLiquidityProvider(*env.current(), amm.lptIssue(), alice); + auto res = isOnlyLiquidityProvider(*env.current(), amm.lptIssue(), alice); BEAST_EXPECT(res && res.value()); if (features[fixAMMv1_3] && features[fixAMMClawbackRounding]) @@ -2312,8 +1989,7 @@ class AMMClawback_test : public beast::unit_test::suite } else { - env(amm::ammClawback(gw, alice, USD, EUR, std::nullopt), - ter(tecINTERNAL)); + env(amm::ammClawback(gw, alice, USD, EUR, std::nullopt), ter(tecINTERNAL)); BEAST_EXPECT(amm.ammExists()); } } @@ -2337,27 +2013,20 @@ class AMMClawback_test : public beast::unit_test::suite amm.withdraw(alice, IOUAmount{1'076123487565916, -15}); amm.withdrawAll(bob); - auto [lpToken, lpTokenBalance] = - getLPTokenBalances(env, amm, alice); - BEAST_EXPECT( - lpToken == "1.414213562374011" && - lpTokenBalance == "1.414213562374"); + auto [lpToken, lpTokenBalance] = getLPTokenBalances(env, amm, alice); + BEAST_EXPECT(lpToken == "1.414213562374011" && lpTokenBalance == "1.414213562374"); - auto res = - isOnlyLiquidityProvider(*env.current(), amm.lptIssue(), alice); + auto res = isOnlyLiquidityProvider(*env.current(), amm.lptIssue(), alice); BEAST_EXPECT(res && res.value()); if (features[fixAMMClawbackRounding]) { - env(amm::ammClawback(gw, alice, USD, EUR, std::nullopt), - txflags(tfClawTwoAssets)); + env(amm::ammClawback(gw, alice, USD, EUR, std::nullopt), txflags(tfClawTwoAssets)); BEAST_EXPECT(!amm.ammExists()); } else { - env(amm::ammClawback(gw, alice, USD, EUR, std::nullopt), - txflags(tfClawTwoAssets), - ter(tecINTERNAL)); + env(amm::ammClawback(gw, alice, USD, EUR, std::nullopt), txflags(tfClawTwoAssets), ter(tecINTERNAL)); BEAST_EXPECT(amm.ammExists()); } } @@ -2381,42 +2050,32 @@ class AMMClawback_test : public beast::unit_test::suite amm.withdraw(alice, IOUAmount{1'076123487565916, -12}); amm.withdrawAll(bob); - auto [lpToken, lpTokenBalance] = - getLPTokenBalances(env, amm, alice); + auto [lpToken, lpTokenBalance] = getLPTokenBalances(env, amm, alice); - BEAST_EXPECT( - lpToken == "1414.213562373101" && - lpTokenBalance == "1414.2135623731"); + BEAST_EXPECT(lpToken == "1414.213562373101" && lpTokenBalance == "1414.2135623731"); - auto res = - isOnlyLiquidityProvider(*env.current(), amm.lptIssue(), alice); + auto res = isOnlyLiquidityProvider(*env.current(), amm.lptIssue(), alice); BEAST_EXPECT(res && res.value()); if (!features[fixAMMClawbackRounding] && !features[fixAMMv1_3]) { env(amm::ammClawback(gw, alice, USD, EUR, USD(1))); BEAST_EXPECT(amm.expectBalances( - STAmount(USD, UINT64_C(4), -15), - STAmount(EUR, UINT64_C(8), -9), - IOUAmount{6, -12})); + STAmount(USD, UINT64_C(4), -15), STAmount(EUR, UINT64_C(8), -9), IOUAmount{6, -12})); } else if (!features[fixAMMClawbackRounding]) { // sqrt(amount * amount2) >= LPTokens and exceeds the allowed // tolerance - env(amm::ammClawback(gw, alice, USD, EUR, USD(1)), - ter(tecINVARIANT_FAILED)); + env(amm::ammClawback(gw, alice, USD, EUR, USD(1)), ter(tecINVARIANT_FAILED)); BEAST_EXPECT(amm.ammExists()); } else if (features[fixAMMv1_3] && features[fixAMMClawbackRounding]) { - env(amm::ammClawback(gw, alice, USD, EUR, USD(1)), - txflags(tfClawTwoAssets)); + env(amm::ammClawback(gw, alice, USD, EUR, USD(1)), txflags(tfClawTwoAssets)); auto const lpBalance = IOUAmount{5, -12}; - BEAST_EXPECT(amm.expectBalances( - STAmount(USD, UINT64_C(4), -15), - STAmount(EUR, UINT64_C(8), -9), - lpBalance)); + BEAST_EXPECT( + amm.expectBalances(STAmount(USD, UINT64_C(4), -15), STAmount(EUR, UINT64_C(8), -9), lpBalance)); BEAST_EXPECT(amm.expectLPTokens(alice, lpBalance)); } } @@ -2427,15 +2086,11 @@ class AMMClawback_test : public beast::unit_test::suite { // For now, just disable SAV entirely, which locks in the small Number // mantissas - FeatureBitset const all = jtx::testable_amendments() - - featureSingleAssetVault - featureLendingProtocol; + FeatureBitset const all = jtx::testable_amendments() - featureSingleAssetVault - featureLendingProtocol; testInvalidRequest(); testFeatureDisabled(all - featureAMMClawback); - for (auto const& features : - {all - fixAMMv1_3 - fixAMMClawbackRounding, - all - fixAMMClawbackRounding, - all}) + for (auto const& features : {all - fixAMMv1_3 - fixAMMClawbackRounding, all - fixAMMClawbackRounding, all}) { testAMMClawbackSpecificAmount(features); testAMMClawbackExceedBalance(features); diff --git a/src/test/app/AMMExtended_test.cpp b/src/test/app/AMMExtended_test.cpp index d1816df51b..4eecb05905 100644 --- a/src/test/app/AMMExtended_test.cpp +++ b/src/test/app/AMMExtended_test.cpp @@ -48,12 +48,7 @@ private: Env env{*this, features}; - fund( - env, - gw, - {alice, bob, carol}, - XRP(10'000), - {USD(200'000), BTC(2'000)}); + fund(env, gw, {alice, bob, carol}, XRP(10'000), {USD(200'000), BTC(2'000)}); // Must be two offers at the same quality // "taker gets" must be XRP @@ -71,24 +66,17 @@ private: PathSet paths(Path(XRP, USD), Path(USD)); - env(pay(alice, bob, USD(100)), - json(paths.json()), - sendmax(BTC(1'000)), - txflags(tfPartialPayment)); + env(pay(alice, bob, USD(100)), json(paths.json()), sendmax(BTC(1'000)), txflags(tfPartialPayment)); if (!features[fixAMMv1_1]) { BEAST_EXPECT(ammCarol.expectBalances( - STAmount{BTC, UINT64_C(1'001'000000374812), -12}, - USD(100'000), - ammCarol.tokens())); + STAmount{BTC, UINT64_C(1'001'000000374812), -12}, USD(100'000), ammCarol.tokens())); } else { BEAST_EXPECT(ammCarol.expectBalances( - STAmount{BTC, UINT64_C(1'001'000000374815), -12}, - USD(100'000), - ammCarol.tokens())); + STAmount{BTC, UINT64_C(1'001'000000374815), -12}, USD(100'000), ammCarol.tokens())); } env.require(balance(bob, USD(200'100))); @@ -157,15 +145,10 @@ private: AMM ammDan(env, dan, XRP(10'000), USD1(10'050)); - env(pay(alice, carol, USD2(50)), - path(~USD1, bob), - sendmax(XRP(50)), - txflags(tfNoRippleDirect)); - BEAST_EXPECT(ammDan.expectBalances( - XRP(10'050), USD1(10'000), ammDan.tokens())); + env(pay(alice, carol, USD2(50)), path(~USD1, bob), sendmax(XRP(50)), txflags(tfNoRippleDirect)); + BEAST_EXPECT(ammDan.expectBalances(XRP(10'050), USD1(10'000), ammDan.tokens())); - BEAST_EXPECT(expectLedgerEntryRoot( - env, alice, XRP(20'000) - XRP(50) - txfee(env, 1))); + BEAST_EXPECT(expectLedgerEntryRoot(env, alice, XRP(20'000) - XRP(50) - txfee(env, 1))); BEAST_EXPECT(expectHolding(env, bob, USD1(100))); BEAST_EXPECT(expectHolding(env, bob, USD2(0))); BEAST_EXPECT(expectHolding(env, carol, USD2(50))); @@ -187,26 +170,18 @@ private: [&](AMM& ammAlice, Env& env) { // Order that can't be filled TER const killedCode{TER{tecKILLED}}; - env(offer(carol, USD(100), XRP(100)), - txflags(tfFillOrKill), - ter(killedCode)); + env(offer(carol, USD(100), XRP(100)), txflags(tfFillOrKill), ter(killedCode)); env.close(); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'100), USD(10'000), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'100), USD(10'000), ammAlice.tokens())); // fee = AMM - BEAST_EXPECT(expectLedgerEntryRoot( - env, carol, XRP(30'000) - (txfee(env, 1)))); + BEAST_EXPECT(expectLedgerEntryRoot(env, carol, XRP(30'000) - (txfee(env, 1)))); BEAST_EXPECT(expectOffers(env, carol, 0)); BEAST_EXPECT(expectHolding(env, carol, USD(30'000))); // Order that can be filled - env(offer(carol, XRP(100), USD(100)), - txflags(tfFillOrKill), - ter(tesSUCCESS)); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'000), USD(10'100), ammAlice.tokens())); - BEAST_EXPECT(expectLedgerEntryRoot( - env, carol, XRP(30'000) + XRP(100) - txfee(env, 2))); + env(offer(carol, XRP(100), USD(100)), txflags(tfFillOrKill), ter(tesSUCCESS)); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), USD(10'100), ammAlice.tokens())); + BEAST_EXPECT(expectLedgerEntryRoot(env, carol, XRP(30'000) + XRP(100) - txfee(env, 2))); BEAST_EXPECT(expectHolding(env, carol, USD(29'900))); BEAST_EXPECT(expectOffers(env, carol, 0)); }, @@ -219,17 +194,13 @@ private: // and add nothing on the books. testAMM( [&](AMM& ammAlice, Env& env) { - env(offer(carol, XRP(200), USD(200)), - txflags(tfImmediateOrCancel), - ter(tesSUCCESS)); + env(offer(carol, XRP(200), USD(200)), txflags(tfImmediateOrCancel), ter(tesSUCCESS)); // AMM generates a synthetic offer of 100USD/100XRP // to match the CLOB offer quality. - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'000), USD(10'100), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), USD(10'100), ammAlice.tokens())); // +AMM - offer * fee - BEAST_EXPECT(expectLedgerEntryRoot( - env, carol, XRP(30'000) + XRP(100) - txfee(env, 1))); + BEAST_EXPECT(expectLedgerEntryRoot(env, carol, XRP(30'000) + XRP(100) - txfee(env, 1))); // AMM BEAST_EXPECT(expectHolding(env, carol, USD(29'900))); BEAST_EXPECT(expectOffers(env, carol, 0)); @@ -246,10 +217,8 @@ private: // Carol's offer should stay in the ledger. env(offer(carol, XRP(100), USD(100), tfPassive)); env.close(); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'100), STAmount{USD, 10'000}, ammAlice.tokens())); - BEAST_EXPECT(expectOffers( - env, carol, 1, {{{XRP(100), STAmount{USD, 100}}}})); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'100), STAmount{USD, 10'000}, ammAlice.tokens())); + BEAST_EXPECT(expectOffers(env, carol, 1, {{{XRP(100), STAmount{USD, 100}}}})); }, {{XRP(10'100), USD(10'000)}}, 0, @@ -267,9 +236,7 @@ private: env(offer(carol, XRP(100), USD(100), tfPassive)); env.close(); BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'900), - STAmount{USD, UINT64_C(9'082'56880733945), -11}, - ammAlice.tokens())); + XRP(10'900), STAmount{USD, UINT64_C(9'082'56880733945), -11}, ammAlice.tokens())); BEAST_EXPECT(expectOffers(env, carol, 0)); BEAST_EXPECT(expectOffers(env, alice, 1)); }, @@ -298,14 +265,10 @@ private: auto const xrpTransferred = XRPAmount{3'061'224'490}; env(offer(bob, USD(1), XRP(4'000))); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(150'000) + xrpTransferred, - USD(49), - IOUAmount{273'861'278752583, -8})); + BEAST_EXPECT(ammAlice.expectBalances(XRP(150'000) + xrpTransferred, USD(49), IOUAmount{273'861'278752583, -8})); BEAST_EXPECT(expectHolding(env, bob, STAmount{USD, 101})); - BEAST_EXPECT(expectLedgerEntryRoot( - env, bob, XRP(300'000) - xrpTransferred - txfee(env, 1))); + BEAST_EXPECT(expectLedgerEntryRoot(env, bob, XRP(300'000) - xrpTransferred - txfee(env, 1))); BEAST_EXPECT(expectOffers(env, bob, 0)); } @@ -328,17 +291,14 @@ private: AMM ammAlice(env, alice, XRP(150'000), USD(51)); env(offer(bob, USD(1), XRP(3'000))); - BEAST_EXPECT( - ammAlice.expectBalances(XRP(153'000), USD(50), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectBalances(XRP(153'000), USD(50), ammAlice.tokens())); auto jrr = ledgerEntryState(env, bob, gw, "USD"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-1"); jrr = ledgerEntryRoot(env, bob); BEAST_EXPECT( jrr[jss::node][sfBalance.fieldName] == - to_string( - (XRP(200'000) - XRP(3'000) - env.current()->fees().base * 1) - .xrp())); + to_string((XRP(200'000) - XRP(3'000) - env.current()->fees().base * 1).xrp())); } void @@ -364,15 +324,13 @@ private: env(pay(alice, alice, XRP(500)), sendmax(USD(100))); - BEAST_EXPECT( - ammBob.expectBalances(USD(300), XRP(1'000), ammBob.tokens())); + BEAST_EXPECT(ammBob.expectBalances(USD(300), XRP(1'000), ammBob.tokens())); BEAST_EXPECT(expectHolding(env, alice, USD(0))); auto jrr = ledgerEntryRoot(env, alice); BEAST_EXPECT( jrr[jss::node][sfBalance.fieldName] == - to_string((XRP(10'000) + XRP(500) - env.current()->fees().base * 2) - .xrp())); + to_string((XRP(10'000) + XRP(500) - env.current()->fees().base * 2).xrp())); } void @@ -386,26 +344,18 @@ private: [&](AMM& ammAlice, Env& env) { // Alice converts USD to XRP which should fail // due to PartialPayment. - env(pay(alice, alice, XRP(100)), - sendmax(USD(100)), - ter(tecPATH_PARTIAL)); + env(pay(alice, alice, XRP(100)), sendmax(USD(100)), ter(tecPATH_PARTIAL)); // Alice converts USD to XRP, should succeed because // we permit partial payment - env(pay(alice, alice, XRP(100)), - sendmax(USD(100)), - txflags(tfPartialPayment)); + env(pay(alice, alice, XRP(100)), sendmax(USD(100)), txflags(tfPartialPayment)); env.close(); - BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount{9'900'990'100}, USD(10'100), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectBalances(XRPAmount{9'900'990'100}, USD(10'100), ammAlice.tokens())); // initial 30,000 - 10,000AMM - 100pay BEAST_EXPECT(expectHolding(env, alice, USD(19'900))); // initial 30,000 - 10,0000AMM + 99.009900pay - fee*3 BEAST_EXPECT(expectLedgerEntryRoot( - env, - alice, - XRP(30'000) - XRP(10'000) + XRPAmount{99'009'900} - - ammCrtFee(env) - txfee(env, 2))); + env, alice, XRP(30'000) - XRP(10'000) + XRPAmount{99'009'900} - ammCrtFee(env) - txfee(env, 2))); }, {{XRP(10'000), USD(10'000)}}, 0, @@ -427,8 +377,7 @@ private: env(trust(bob, USD(100))); env.close(); env(pay(alice, bob, USD(100)), sendmax(XRP(100))); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'100), USD(10'000), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'100), USD(10'000), ammAlice.tokens())); BEAST_EXPECT(expectHolding(env, bob, USD(100))); }, {{XRP(10'000), USD(10'100)}}, @@ -451,10 +400,8 @@ private: env(trust(bob, USD(100))); env.close(); env(pay(alice, bob, XRP(100)), sendmax(USD(100))); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'000), USD(10'100), ammAlice.tokens())); - BEAST_EXPECT(expectLedgerEntryRoot( - env, bob, XRP(1'000) + XRP(100) - txfee(env, 1))); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), USD(10'100), ammAlice.tokens())); + BEAST_EXPECT(expectLedgerEntryRoot(env, bob, XRP(1'000) + XRP(100) - txfee(env, 1))); }, {{XRP(10'100), USD(10'000)}}, 0, @@ -500,14 +447,10 @@ private: Json::Value jtp{Json::arrayValue}; jtp[0u][0u][jss::currency] = "XRP"; - env(pay(alice, bob, EUR1(30)), - json(jss::Paths, jtp), - sendmax(USD1(333))); + env(pay(alice, bob, EUR1(30)), json(jss::Paths, jtp), sendmax(USD1(333))); env.close(); - BEAST_EXPECT(ammCarol.expectBalances( - XRP(49'700), - STAmount{USD1, UINT64_C(5'030'181086519115), -12}, - ammCarol.tokens())); + BEAST_EXPECT( + ammCarol.expectBalances(XRP(49'700), STAmount{USD1, UINT64_C(5'030'181086519115), -12}, ammCarol.tokens())); BEAST_EXPECT(expectOffers(env, dan, 1, {{Amounts{XRP(200), EUR(20)}}})); BEAST_EXPECT(expectHolding(env, bob, STAmount{EUR1, 30})); } @@ -536,9 +479,7 @@ private: // fees: // 1 for each trust limit == 3 (alice < mtgox/amazon/bitstamp) + // 1 for payment == 4 - auto const starting_xrp = XRP(100) + - env.current()->fees().accountReserve(3) + - env.current()->fees().base * 4; + auto const starting_xrp = XRP(100) + env.current()->fees().accountReserve(3) + env.current()->fees().base * 4; env.fund(starting_xrp, gw1, gw2, gw3, alice); env.fund(XRP(2'000), bob); @@ -559,18 +500,13 @@ private: // The pool gets only 100XRP for ~109.09USD, even though // it can exchange more. - BEAST_EXPECT(ammBob.expectBalances( - XRP(1'100), - STAmount{USD1, UINT64_C(1'090'909090909091), -12}, - ammBob.tokens())); + BEAST_EXPECT( + ammBob.expectBalances(XRP(1'100), STAmount{USD1, UINT64_C(1'090'909090909091), -12}, ammBob.tokens())); auto jrr = ledgerEntryState(env, alice, gw1, "USD"); - BEAST_EXPECT( - jrr[jss::node][sfBalance.fieldName][jss::value] == - "109.090909090909"); + BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "109.090909090909"); jrr = ledgerEntryRoot(env, alice); - BEAST_EXPECT( - jrr[jss::node][sfBalance.fieldName] == XRP(350).value().getText()); + BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName] == XRP(350).value().getText()); } void @@ -595,13 +531,11 @@ private: AMM ammAlice(env, alice, USD(150), XRP(150'100)); env(offer(bob, XRP(100), USD(0.1))); - BEAST_EXPECT(ammAlice.expectBalances( - USD(150.1), XRP(150'000), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectBalances(USD(150.1), XRP(150'000), ammAlice.tokens())); auto const jrr = ledgerEntryState(env, bob, gw, "USD"); // Bob pays 0.005 transfer fee. Note 10**-10 round-off. - BEAST_EXPECT( - jrr[jss::node][sfBalance.fieldName][jss::value] == "-0.8995000001"); + BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-0.8995000001"); } void @@ -615,12 +549,10 @@ private: [&](AMM& ammAlice, Env& env) { env(offer(carol, USD(100), XRP(100)), json(jss::Flags, tfSell)); env.close(); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'000), USD(9'999), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), USD(9'999), ammAlice.tokens())); BEAST_EXPECT(expectOffers(env, carol, 0)); BEAST_EXPECT(expectHolding(env, carol, USD(30'101))); - BEAST_EXPECT(expectLedgerEntryRoot( - env, carol, XRP(30'000) - XRP(100) - txfee(env, 1))); + BEAST_EXPECT(expectLedgerEntryRoot(env, carol, XRP(30'000) - XRP(100) - txfee(env, 1))); }, {{XRP(9'900), USD(10'100)}}, 0, @@ -637,8 +569,7 @@ private: Env env{*this, features}; - auto const starting_xrp = - XRP(100) + reserve(env, 1) + env.current()->fees().base * 2; + auto const starting_xrp = XRP(100) + reserve(env, 1) + env.current()->fees().base * 2; env.fund(starting_xrp, gw, alice); env.fund(XRP(2'000), bob); @@ -656,8 +587,7 @@ private: // Selling XRP. // Will sell all 100 XRP and get more USD than asked for. env(offer(alice, USD(100), XRP(200)), json(jss::Flags, tfSell)); - BEAST_EXPECT( - ammBob.expectBalances(XRP(1'100), USD(2'000), ammBob.tokens())); + BEAST_EXPECT(ammBob.expectBalances(XRP(1'100), USD(2'000), ammBob.tokens())); BEAST_EXPECT(expectHolding(env, alice, USD(200))); BEAST_EXPECT(expectLedgerEntryRoot(env, alice, XRP(250))); BEAST_EXPECT(expectOffers(env, alice, 0)); @@ -675,15 +605,8 @@ private: auto const XTS = gw["XTS"]; auto const XXX = gw["XXX"]; - auto const starting_xrp = - XRP(100.1) + reserve(env, 1) + env.current()->fees().base * 2; - fund( - env, - gw, - {alice, bob}, - starting_xrp, - {XTS(100), XXX(100)}, - Fund::All); + auto const starting_xrp = XRP(100.1) + reserve(env, 1) + env.current()->fees().base * 2; + fund(env, gw, {alice, bob}, starting_xrp, {XTS(100), XXX(100)}, Fund::All); AMM ammAlice(env, alice, XTS(100), XXX(100)); @@ -692,34 +615,24 @@ private: payment[jss::id] = env.seq(bob); payment[jss::build_path] = true; payment[jss::tx_json] = pay(bob, bob, bob["XXX"](1)); - payment[jss::tx_json][jss::Sequence] = - env.current() - ->read(keylet::account(bob.id())) - ->getFieldU32(sfSequence); + payment[jss::tx_json][jss::Sequence] = env.current()->read(keylet::account(bob.id()))->getFieldU32(sfSequence); payment[jss::tx_json][jss::Fee] = to_string(env.current()->fees().base); - payment[jss::tx_json][jss::SendMax] = - bob["XTS"](1.5).value().getJson(JsonOptions::none); + payment[jss::tx_json][jss::SendMax] = bob["XTS"](1.5).value().getJson(JsonOptions::none); payment[jss::tx_json][jss::Flags] = tfPartialPayment; auto const jrr = env.rpc("json", "submit", to_string(payment)); BEAST_EXPECT(jrr[jss::result][jss::status] == "success"); BEAST_EXPECT(jrr[jss::result][jss::engine_result] == "tesSUCCESS"); if (!features[fixAMMv1_1]) { - BEAST_EXPECT(ammAlice.expectBalances( - STAmount(XTS, UINT64_C(101'010101010101), -12), - XXX(99), - ammAlice.tokens())); - BEAST_EXPECT(expectHolding( - env, bob, STAmount{XTS, UINT64_C(98'989898989899), -12})); + BEAST_EXPECT( + ammAlice.expectBalances(STAmount(XTS, UINT64_C(101'010101010101), -12), XXX(99), ammAlice.tokens())); + BEAST_EXPECT(expectHolding(env, bob, STAmount{XTS, UINT64_C(98'989898989899), -12})); } else { - BEAST_EXPECT(ammAlice.expectBalances( - STAmount(XTS, UINT64_C(101'0101010101011), -13), - XXX(99), - ammAlice.tokens())); - BEAST_EXPECT(expectHolding( - env, bob, STAmount{XTS, UINT64_C(98'9898989898989), -13})); + BEAST_EXPECT( + ammAlice.expectBalances(STAmount(XTS, UINT64_C(101'0101010101011), -13), XXX(99), ammAlice.tokens())); + BEAST_EXPECT(expectHolding(env, bob, STAmount{XTS, UINT64_C(98'9898989898989), -13})); } BEAST_EXPECT(expectHolding(env, bob, XXX(101))); } @@ -734,12 +647,7 @@ private: { Env env{*this, features}; - fund( - env, - gw, - {alice, bob, carol}, - {USD(15'000), EUR(15'000)}, - Fund::All); + fund(env, gw, {alice, bob, carol}, {USD(15'000), EUR(15'000)}, Fund::All); // The scenario: // o USD/XRP AMM is created. @@ -755,10 +663,8 @@ private: env(offer(carol, USD(100), EUR(100))); env.close(); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'100), USD(10'000), ammAlice.tokens())); - BEAST_EXPECT(ammBob.expectBalances( - XRP(10'000), EUR(10'100), ammBob.tokens())); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'100), USD(10'000), ammAlice.tokens())); + BEAST_EXPECT(ammBob.expectBalances(XRP(10'000), EUR(10'100), ammBob.tokens())); BEAST_EXPECT(expectHolding(env, carol, USD(15'100))); BEAST_EXPECT(expectHolding(env, carol, EUR(14'900))); BEAST_EXPECT(expectOffers(env, carol, 0)); @@ -767,12 +673,7 @@ private: { Env env{*this, features}; - fund( - env, - gw, - {alice, bob, carol}, - {USD(15'000), EUR(15'000)}, - Fund::All); + fund(env, gw, {alice, bob, carol}, {USD(15'000), EUR(15'000)}, Fund::All); // The scenario: // o USD/XRP AMM is created. @@ -790,8 +691,7 @@ private: env(offer(carol, USD(100), EUR(100))); env.close(); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'100), USD(10'000), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'100), USD(10'000), ammAlice.tokens())); BEAST_EXPECT(expectHolding(env, carol, USD(15'100))); BEAST_EXPECT(expectHolding(env, carol, EUR(14'900))); BEAST_EXPECT(expectOffers(env, carol, 0)); @@ -801,12 +701,7 @@ private: { Env env{*this, features}; - fund( - env, - gw, - {alice, bob, carol}, - {USD(15'000), EUR(15'000)}, - Fund::All); + fund(env, gw, {alice, bob, carol}, {USD(15'000), EUR(15'000)}, Fund::All); // The scenario: // o USD/XRP offer is created. @@ -824,8 +719,7 @@ private: env(offer(carol, USD(100), EUR(100))); env.close(); - BEAST_EXPECT(ammBob.expectBalances( - XRP(10'000), EUR(10'100), ammBob.tokens())); + BEAST_EXPECT(ammBob.expectBalances(XRP(10'000), EUR(10'100), ammBob.tokens())); BEAST_EXPECT(expectHolding(env, carol, USD(15'100))); BEAST_EXPECT(expectHolding(env, carol, EUR(14'900))); BEAST_EXPECT(expectOffers(env, carol, 0)); @@ -850,11 +744,9 @@ private: fund(env, gw, {alice, bob}, {USD(20'000)}, Fund::All); AMM ammBob(env, bob, XRP(20'000), USD(200)); // alice submits a tfSell | tfFillOrKill offer that does not cross. - env(offer(alice, USD(2.1), XRP(210), tfSell | tfFillOrKill), - ter(killedCode)); + env(offer(alice, USD(2.1), XRP(210), tfSell | tfFillOrKill), ter(killedCode)); - BEAST_EXPECT( - ammBob.expectBalances(XRP(20'000), USD(200), ammBob.tokens())); + BEAST_EXPECT(ammBob.expectBalances(XRP(20'000), USD(200), ammBob.tokens())); BEAST_EXPECT(expectOffers(env, bob, 0)); } { @@ -865,12 +757,9 @@ private: // Even though tfSell is present it doesn't matter this time. env(offer(alice, USD(2), XRP(220), tfSell | tfFillOrKill)); env.close(); - BEAST_EXPECT(ammBob.expectBalances( - XRP(20'220), - STAmount{USD, UINT64_C(197'8239366963403), -13}, - ammBob.tokens())); - BEAST_EXPECT(expectHolding( - env, alice, STAmount{USD, UINT64_C(1'002'17606330366), -11})); + BEAST_EXPECT( + ammBob.expectBalances(XRP(20'220), STAmount{USD, UINT64_C(197'8239366963403), -13}, ammBob.tokens())); + BEAST_EXPECT(expectHolding(env, alice, STAmount{USD, UINT64_C(1'002'17606330366), -11})); BEAST_EXPECT(expectOffers(env, alice, 0)); } { @@ -883,12 +772,9 @@ private: env(offer(alice, USD(10), XRP(1'500), tfSell | tfFillOrKill)); env.close(); - BEAST_EXPECT(ammBob.expectBalances( - XRP(21'500), - STAmount{USD, UINT64_C(186'046511627907), -12}, - ammBob.tokens())); - BEAST_EXPECT(expectHolding( - env, alice, STAmount{USD, UINT64_C(1'013'953488372093), -12})); + BEAST_EXPECT( + ammBob.expectBalances(XRP(21'500), STAmount{USD, UINT64_C(186'046511627907), -12}, ammBob.tokens())); + BEAST_EXPECT(expectHolding(env, alice, STAmount{USD, UINT64_C(1'013'953488372093), -12})); BEAST_EXPECT(expectOffers(env, alice, 0)); } { @@ -901,8 +787,7 @@ private: fund(env, gw, {alice, bob}, {USD(10'000)}, Fund::All); AMM ammBob(env, bob, XRP(5000), USD(10)); - env(offer(alice, USD(1), XRP(501), tfSell | tfFillOrKill), - ter(tecKILLED)); + env(offer(alice, USD(1), XRP(501), tfSell | tfFillOrKill), ter(tecKILLED)); env.close(); BEAST_EXPECT(expectOffers(env, alice, 0)); BEAST_EXPECT(expectOffers(env, bob, 0)); @@ -926,8 +811,7 @@ private: env.close(); // AMM doesn't pay the transfer fee - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'100), USD(10'000), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'100), USD(10'000), ammAlice.tokens())); BEAST_EXPECT(expectHolding(env, carol, USD(30'100))); BEAST_EXPECT(expectOffers(env, carol, 0)); }, @@ -946,8 +830,7 @@ private: env(offer(carol, XRP(100), USD(100))); env.close(); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'000), USD(10'100), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), USD(10'100), ammAlice.tokens())); // Carol pays 25% transfer fee BEAST_EXPECT(expectHolding(env, carol, USD(29'875))); BEAST_EXPECT(expectOffers(env, carol, 0)); @@ -960,12 +843,7 @@ private: { // Bridged crossing. Env env{*this, features}; - fund( - env, - gw, - {alice, bob, carol}, - {USD(15'000), EUR(15'000)}, - Fund::All); + fund(env, gw, {alice, bob, carol}, {USD(15'000), EUR(15'000)}, Fund::All); env(rate(gw, 1.25)); // The scenario: @@ -984,8 +862,7 @@ private: env.close(); // AMM doesn't pay the transfer fee - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'100), USD(10'000), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'100), USD(10'000), ammAlice.tokens())); BEAST_EXPECT(expectHolding(env, carol, USD(15'100))); // Carol pays 25% transfer fee. BEAST_EXPECT(expectHolding(env, carol, EUR(14'875))); @@ -997,12 +874,7 @@ private: // Bridged crossing. The transfer fee is paid on the step not // involving AMM as src/dst. Env env{*this, features}; - fund( - env, - gw, - {alice, bob, carol}, - {USD(15'000), EUR(15'000)}, - Fund::All); + fund(env, gw, {alice, bob, carol}, {USD(15'000), EUR(15'000)}, Fund::All); env(rate(gw, 1.25)); // The scenario: @@ -1024,14 +896,12 @@ private: // account but not from the remaining offer. // AMM doesn't pay the transfer fee - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'050), USD(10'000), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'050), USD(10'000), ammAlice.tokens())); BEAST_EXPECT(expectHolding(env, carol, USD(15'050))); // Carol pays 25% transfer fee. BEAST_EXPECT(expectHolding(env, carol, EUR(14'937.5))); BEAST_EXPECT(expectOffers(env, carol, 0)); - BEAST_EXPECT( - expectOffers(env, bob, 1, {{Amounts{EUR(50), XRP(50)}}})); + BEAST_EXPECT(expectOffers(env, bob, 1, {{Amounts{EUR(50), XRP(50)}}})); } { @@ -1069,8 +939,7 @@ private: env.close(); // AMM doesn't pay the transfer fee - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'100), USD(10'000), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'100), USD(10'000), ammAlice.tokens())); BEAST_EXPECT(expectHolding(env, carol, USD(100))); // Carol pays 25% transfer fee: 1250 - 100(offer) - 25(transfer fee) BEAST_EXPECT(expectHolding(env, carol, EUR(1'125))); @@ -1112,8 +981,7 @@ private: env.close(); // AMM pay doesn't transfer fee - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'100), USD(10'000), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'100), USD(10'000), ammAlice.tokens())); BEAST_EXPECT(expectHolding(env, carol, USD(100))); // Carol pays 25% transfer fee: 1000 - 100(offer) - 25(transfer fee) BEAST_EXPECT(expectHolding(env, carol, EUR(875))); @@ -1142,8 +1010,7 @@ private: env(offer(alice, USD_bob(100), XRP(100))); env.close(); - BEAST_EXPECT(ammBob.expectBalances( - XRP(10'100), USD_bob(10'000), ammBob.tokens())); + BEAST_EXPECT(ammBob.expectBalances(XRP(10'100), USD_bob(10'000), ammBob.tokens())); BEAST_EXPECT(expectOffers(env, alice, 0)); BEAST_EXPECT(expectHolding(env, alice, USD_bob(100))); } @@ -1201,14 +1068,10 @@ private: env.close(); // This payment caused the assert. - env(pay(ann, ann, D_BUX(30)), - path(A_BUX, D_BUX), - sendmax(A_BUX(30)), - ter(temBAD_PATH)); + env(pay(ann, ann, D_BUX(30)), path(A_BUX, D_BUX), sendmax(A_BUX(30)), ter(temBAD_PATH)); env.close(); - BEAST_EXPECT( - ammBob.expectBalances(A_BUX(30), D_BUX(30), ammBob.tokens())); + BEAST_EXPECT(ammBob.expectBalances(A_BUX(30), D_BUX(30), ammBob.tokens())); BEAST_EXPECT(expectHolding(env, ann, A_BUX(none))); BEAST_EXPECT(expectHolding(env, ann, D_BUX(0))); BEAST_EXPECT(expectHolding(env, cam, A_BUX(none))); @@ -1331,8 +1194,7 @@ private: AMM ammAlice(env, alice, USD(1'000), XRP(1'050)); // Set up authorized trust line for AMM. - env(trust(gw, STAmount{Issue{USD.currency, ammAlice.ammAccount()}, 10}), - txflags(tfSetfAuth)); + env(trust(gw, STAmount{Issue{USD.currency, ammAlice.ammAccount()}, 10}), txflags(tfSetfAuth)); env.close(); env(pay(gw, bob, USD(50))); @@ -1344,8 +1206,7 @@ private: env(offer(bob, XRP(50), USD(50))); env.close(); - BEAST_EXPECT( - ammAlice.expectBalances(USD(1'050), XRP(1'000), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectBalances(USD(1'050), XRP(1'000), ammAlice.tokens())); BEAST_EXPECT(expectOffers(env, bob, 0)); BEAST_EXPECT(expectHolding(env, bob, USD(0))); } @@ -1364,8 +1225,7 @@ private: // Alice doesn't have the funds { - AMM ammAlice( - env, alice, USD(1'000), XRP(1'000), ter(tecUNFUNDED_AMM)); + AMM ammAlice(env, alice, USD(1'000), XRP(1'000), ter(tecUNFUNDED_AMM)); } env(fset(gw, asfRequireAuth)); @@ -1404,16 +1264,14 @@ private: AMM ammAlice(env, alice, USD(1'000), XRP(1'050)); // Set up authorized trust line for AMM. - env(trust(gw, STAmount{Issue{USD.currency, ammAlice.ammAccount()}, 10}), - txflags(tfSetfAuth)); + env(trust(gw, STAmount{Issue{USD.currency, ammAlice.ammAccount()}, 10}), txflags(tfSetfAuth)); env.close(); // Now bob creates his offer again, which crosses with alice's AMM. env(offer(bob, XRP(50), USD(50))); env.close(); - BEAST_EXPECT( - ammAlice.expectBalances(USD(1'050), XRP(1'000), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectBalances(USD(1'050), XRP(1'000), ammAlice.tokens())); BEAST_EXPECT(expectOffers(env, bob, 0)); BEAST_EXPECT(expectHolding(env, bob, USD(0))); } @@ -1424,9 +1282,7 @@ private: using namespace jtx; // For now, just disable SAV entirely, which locks in the small Number // mantissas - FeatureBitset const all{ - testable_amendments() - featureSingleAssetVault - - featureLendingProtocol}; + FeatureBitset const all{testable_amendments() - featureSingleAssetVault - featureLendingProtocol}; testRmFundedOffer(all); testRmFundedOffer(all - fixAMMv1_1 - fixAMMv1_3); @@ -1471,25 +1327,14 @@ private: STPathSet st; STAmount sa; STAmount da; - std::tie(st, sa, da) = find_paths( - env, - alice, - bob, - bob["AUD"](-1), - std::optional(XRP(100'000'000))); + std::tie(st, sa, da) = find_paths(env, alice, bob, bob["AUD"](-1), std::optional(XRP(100'000'000))); BEAST_EXPECT(st.empty()); - std::tie(st, sa, da) = find_paths( - env, - alice, - bob, - bob["USD"](-1), - std::optional(XRP(100'000'000))); + std::tie(st, sa, da) = find_paths(env, alice, bob, bob["USD"](-1), std::optional(XRP(100'000'000))); // Alice sends all requested 100,000,000XRP BEAST_EXPECT(sa == XRP(100'000'000)); // Bob gets ~99.99USD. This is the amount Bob // can get out of AMM for 100,000,000XRP. - BEAST_EXPECT(equal( - da, STAmount{bob["USD"].issue(), UINT64_C(99'9999000001), -10})); + BEAST_EXPECT(equal(da, STAmount{bob["USD"].issue(), UINT64_C(99'9999000001), -10})); } // carol holds gateway AUD, sells gateway AUD for XRP @@ -1513,12 +1358,10 @@ private: env(pay(alice, bob, AUD(10)), sendmax(XRP(100)), paths(XRP)); env.close(); // AMM offer is 51.282052XRP/11AUD, 11AUD/1.1 = 10AUD to bob - BEAST_EXPECT( - ammCarol.expectBalances(XRP(51), AUD(40), ammCarol.tokens())); + BEAST_EXPECT(ammCarol.expectBalances(XRP(51), AUD(40), ammCarol.tokens())); BEAST_EXPECT(expectHolding(env, bob, AUD(10))); - auto const result = - find_paths(env, alice, bob, Account(bob)["USD"](25)); + auto const result = find_paths(env, alice, bob, Account(bob)["USD"](25)); BEAST_EXPECT(std::get<0>(result).empty()); } @@ -1533,16 +1376,14 @@ private: Env env = pathTestEnv(); fund(env, gw, {alice, bob, charlie}, {USD(11)}, Fund::All); AMM ammCharlie(env, charlie, XRP(10), USD(11)); - auto [st, sa, da] = - find_paths(env, alice, bob, USD(-1), XRP(1).value()); + auto [st, sa, da] = find_paths(env, alice, bob, USD(-1), XRP(1).value()); BEAST_EXPECT(sa == XRP(1)); BEAST_EXPECT(equal(da, USD(1))); if (BEAST_EXPECT(st.size() == 1 && st[0].size() == 1)) { auto const& pathElem = st[0][0]; BEAST_EXPECT( - pathElem.isOffer() && pathElem.getIssuerID() == gw.id() && - pathElem.getCurrency() == USD.currency); + pathElem.isOffer() && pathElem.getIssuerID() == gw.id() && pathElem.getCurrency() == USD.currency); } } { @@ -1551,16 +1392,14 @@ private: fund(env, gw, {alice, bob, charlie}, {USD(11)}, Fund::All); AMM ammCharlie(env, charlie, XRP(11), USD(10)); env.close(); - auto [st, sa, da] = - find_paths(env, alice, bob, drops(-1), USD(1).value()); + auto [st, sa, da] = find_paths(env, alice, bob, drops(-1), USD(1).value()); BEAST_EXPECT(sa == USD(1)); BEAST_EXPECT(equal(da, XRP(1))); if (BEAST_EXPECT(st.size() == 1 && st[0].size() == 1)) { auto const& pathElem = st[0][0]; BEAST_EXPECT( - pathElem.isOffer() && - pathElem.getIssuerID() == xrpAccount() && + pathElem.isOffer() && pathElem.getIssuerID() == xrpAccount() && pathElem.getCurrency() == xrpCurrency()); } } @@ -1611,8 +1450,7 @@ private: { auto const& send_amt = XRP(10); - std::tie(st, sa, da) = - find_paths(env, A1, A2, send_amt, std::nullopt, xrpCurrency()); + std::tie(st, sa, da) = find_paths(env, A1, A2, send_amt, std::nullopt, xrpCurrency()); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(st.empty()); } @@ -1621,16 +1459,14 @@ private: // no path should exist for this since dest account // does not exist. auto const& send_amt = XRP(200); - std::tie(st, sa, da) = find_paths( - env, A1, Account{"A0"}, send_amt, std::nullopt, xrpCurrency()); + std::tie(st, sa, da) = find_paths(env, A1, Account{"A0"}, send_amt, std::nullopt, xrpCurrency()); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(st.empty()); } { auto const& send_amt = G3["ABC"](10); - std::tie(st, sa, da) = - find_paths(env, A2, G3, send_amt, std::nullopt, xrpCurrency()); + std::tie(st, sa, da) = find_paths(env, A2, G3, send_amt, std::nullopt, xrpCurrency()); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, XRPAmount{101'010'102})); BEAST_EXPECT(same(st, stpath(IPE(G3["ABC"])))); @@ -1638,8 +1474,7 @@ private: { auto const& send_amt = A2["ABC"](1); - std::tie(st, sa, da) = - find_paths(env, A1, A2, send_amt, std::nullopt, xrpCurrency()); + std::tie(st, sa, da) = find_paths(env, A1, A2, send_amt, std::nullopt, xrpCurrency()); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, XRPAmount{10'010'011})); BEAST_EXPECT(same(st, stpath(IPE(G3["ABC"]), G3))); @@ -1647,8 +1482,7 @@ private: { auto const& send_amt = A3["ABC"](1); - std::tie(st, sa, da) = - find_paths(env, A1, A3, send_amt, std::nullopt, xrpCurrency()); + std::tie(st, sa, da) = find_paths(env, A1, A3, send_amt, std::nullopt, xrpCurrency()); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, XRPAmount{10'010'011})); BEAST_EXPECT(same(st, stpath(IPE(G3["ABC"]), G3, A2))); @@ -1685,8 +1519,7 @@ private: STAmount sa, da; auto const& send_amt = XRP(10); - std::tie(st, sa, da) = - find_paths(env, A1, A2, send_amt, std::nullopt, A2["ABC"].currency); + std::tie(st, sa, da) = find_paths(env, A1, A2, send_amt, std::nullopt, A2["ABC"].currency); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, A1["ABC"](1))); BEAST_EXPECT(same(st, stpath(G3, IPE(xrpIssue())))); @@ -1743,8 +1576,7 @@ private: // A) Borrow or repay -- // Source -> Destination (repay source issuer) auto const& send_amt = G1["HKD"](10); - std::tie(st, sa, da) = find_paths( - env, A1, G1, send_amt, std::nullopt, G1["HKD"].currency); + std::tie(st, sa, da) = find_paths(env, A1, G1, send_amt, std::nullopt, G1["HKD"].currency); BEAST_EXPECT(st.empty()); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, A1["HKD"](10))); @@ -1754,8 +1586,7 @@ private: // A2) Borrow or repay -- // Source -> Destination (repay destination issuer) auto const& send_amt = A1["HKD"](10); - std::tie(st, sa, da) = find_paths( - env, A1, G1, send_amt, std::nullopt, G1["HKD"].currency); + std::tie(st, sa, da) = find_paths(env, A1, G1, send_amt, std::nullopt, G1["HKD"].currency); BEAST_EXPECT(st.empty()); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, A1["HKD"](10))); @@ -1765,8 +1596,7 @@ private: // B) Common gateway -- // Source -> AC -> Destination auto const& send_amt = A3["HKD"](10); - std::tie(st, sa, da) = find_paths( - env, A1, A3, send_amt, std::nullopt, G1["HKD"].currency); + std::tie(st, sa, da) = find_paths(env, A1, A3, send_amt, std::nullopt, G1["HKD"].currency); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, A1["HKD"](10))); BEAST_EXPECT(same(st, stpath(G1))); @@ -1776,24 +1606,18 @@ private: // C) Gateway to gateway -- // Source -> OB -> Destination auto const& send_amt = G2["HKD"](10); - std::tie(st, sa, da) = find_paths( - env, G1, G2, send_amt, std::nullopt, G1["HKD"].currency); + std::tie(st, sa, da) = find_paths(env, G1, G2, send_amt, std::nullopt, G1["HKD"].currency); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, G1["HKD"](10))); - BEAST_EXPECT(same( - st, - stpath(IPE(G2["HKD"])), - stpath(M1), - stpath(M2), - stpath(IPE(xrpIssue()), IPE(G2["HKD"])))); + BEAST_EXPECT( + same(st, stpath(IPE(G2["HKD"])), stpath(M1), stpath(M2), stpath(IPE(xrpIssue()), IPE(G2["HKD"])))); } { // D) User to unlinked gateway via order book -- // Source -> AC -> OB -> Destination auto const& send_amt = G2["HKD"](10); - std::tie(st, sa, da) = find_paths( - env, A1, G2, send_amt, std::nullopt, G1["HKD"].currency); + std::tie(st, sa, da) = find_paths(env, A1, G2, send_amt, std::nullopt, G1["HKD"].currency); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, A1["HKD"](10))); BEAST_EXPECT(same( @@ -1809,8 +1633,7 @@ private: // Source -> AC -> OB to XRP -> OB from XRP -> AC -> // Destination auto const& send_amt = A2["HKD"](10); - std::tie(st, sa, da) = find_paths( - env, A1, A2, send_amt, std::nullopt, G1["HKD"].currency); + std::tie(st, sa, da) = find_paths(env, A1, A2, send_amt, std::nullopt, G1["HKD"].currency); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, A1["HKD"](10))); BEAST_EXPECT(same( @@ -1859,8 +1682,7 @@ private: auto const& send_amt = A2["HKD"](10); STPathSet st; STAmount sa, da; - std::tie(st, sa, da) = - find_paths(env, G1, A2, send_amt, std::nullopt, G1["HKD"].currency); + std::tie(st, sa, da) = find_paths(env, G1, A2, send_amt, std::nullopt, G1["HKD"].currency); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, G1["HKD"](10))); BEAST_EXPECT(same(st, stpath(M1, G2), stpath(IPE(G2["HKD"]), G2))); @@ -1879,8 +1701,8 @@ private: // This removes no ripple for carol, // different from the original test fund(env, gw, {carol}, XRP(10'000), {}, Fund::Acct); - auto const AMMXRPPool = env.current()->fees().increment * 2; - env.fund(reserve(env, 5) + ammCrtFee(env) + AMMXRPPool, bob); + auto const ammXrpPool = env.current()->fees().increment * 2; + env.fund(reserve(env, 5) + ammCrtFee(env) + ammXrpPool, bob); env.close(); env.trust(USD(1'000), alice, bob, carol); env.trust(EUR(1'000), alice, bob, carol); @@ -1896,7 +1718,7 @@ private: // tecPATH_DRY, but the entire path should not be marked as dry. // This is the second error case to test (when flowV1 is used). env(offer(bob, EUR(50), XRP(50))); - AMM ammBob(env, bob, AMMXRPPool, USD(150)); + AMM ammBob(env, bob, ammXrpPool, USD(150)); env(pay(alice, carol, USD(1'000'000)), path(~XRP, ~USD), @@ -1918,13 +1740,7 @@ private: // simple IOU/IOU offer Env env(*this, features); - fund( - env, - gw, - {alice, bob, carol}, - XRP(10'000), - {BTC(100), USD(150)}, - Fund::All); + fund(env, gw, {alice, bob, carol}, XRP(10'000), {BTC(100), USD(150)}, Fund::All); AMM ammBob(env, bob, BTC(100), USD(150)); @@ -1934,20 +1750,13 @@ private: BEAST_EXPECT(expectHolding(env, bob, BTC(0))); BEAST_EXPECT(expectHolding(env, bob, USD(0))); BEAST_EXPECT(expectHolding(env, carol, USD(200))); - BEAST_EXPECT( - ammBob.expectBalances(BTC(150), USD(100), ammBob.tokens())); + BEAST_EXPECT(ammBob.expectBalances(BTC(150), USD(100), ammBob.tokens())); } { // simple IOU/XRP XRP/IOU offer Env env(*this, features); - fund( - env, - gw, - {alice, carol, bob}, - XRP(10'000), - {BTC(100), USD(150)}, - Fund::All); + fund(env, gw, {alice, carol, bob}, XRP(10'000), {BTC(100), USD(150)}, Fund::All); AMM ammBobBTC_XRP(env, bob, BTC(100), XRP(150)); AMM ammBobXRP_USD(env, bob, XRP(100), USD(150)); @@ -1958,59 +1767,40 @@ private: BEAST_EXPECT(expectHolding(env, bob, BTC(0))); BEAST_EXPECT(expectHolding(env, bob, USD(0))); BEAST_EXPECT(expectHolding(env, carol, USD(200))); - BEAST_EXPECT(ammBobBTC_XRP.expectBalances( - BTC(150), XRP(100), ammBobBTC_XRP.tokens())); - BEAST_EXPECT(ammBobXRP_USD.expectBalances( - XRP(150), USD(100), ammBobXRP_USD.tokens())); + BEAST_EXPECT(ammBobBTC_XRP.expectBalances(BTC(150), XRP(100), ammBobBTC_XRP.tokens())); + BEAST_EXPECT(ammBobXRP_USD.expectBalances(XRP(150), USD(100), ammBobXRP_USD.tokens())); } { // simple XRP -> USD through offer and sendmax Env env(*this, features); - fund( - env, - gw, - {alice, carol, bob}, - XRP(10'000), - {USD(150)}, - Fund::All); + fund(env, gw, {alice, carol, bob}, XRP(10'000), {USD(150)}, Fund::All); AMM ammBob(env, bob, XRP(100), USD(150)); env(pay(alice, carol, USD(50)), path(~USD), sendmax(XRP(50))); - BEAST_EXPECT(expectLedgerEntryRoot( - env, alice, xrpMinusFee(env, 10'000 - 50))); - BEAST_EXPECT(expectLedgerEntryRoot( - env, bob, XRP(10'000) - XRP(100) - ammCrtFee(env))); + BEAST_EXPECT(expectLedgerEntryRoot(env, alice, xrpMinusFee(env, 10'000 - 50))); + BEAST_EXPECT(expectLedgerEntryRoot(env, bob, XRP(10'000) - XRP(100) - ammCrtFee(env))); BEAST_EXPECT(expectHolding(env, bob, USD(0))); BEAST_EXPECT(expectHolding(env, carol, USD(200))); - BEAST_EXPECT( - ammBob.expectBalances(XRP(150), USD(100), ammBob.tokens())); + BEAST_EXPECT(ammBob.expectBalances(XRP(150), USD(100), ammBob.tokens())); } { // simple USD -> XRP through offer and sendmax Env env(*this, features); - fund( - env, - gw, - {alice, carol, bob}, - XRP(10'000), - {USD(100)}, - Fund::All); + fund(env, gw, {alice, carol, bob}, XRP(10'000), {USD(100)}, Fund::All); AMM ammBob(env, bob, USD(100), XRP(150)); env(pay(alice, carol, XRP(50)), path(~XRP), sendmax(USD(50))); BEAST_EXPECT(expectHolding(env, alice, USD(50))); - BEAST_EXPECT(expectLedgerEntryRoot( - env, bob, XRP(10'000) - XRP(150) - ammCrtFee(env))); + BEAST_EXPECT(expectLedgerEntryRoot(env, bob, XRP(10'000) - XRP(150) - ammCrtFee(env))); BEAST_EXPECT(expectHolding(env, bob, USD(0))); BEAST_EXPECT(expectLedgerEntryRoot(env, carol, XRP(10'000 + 50))); - BEAST_EXPECT( - ammBob.expectBalances(USD(150), XRP(100), ammBob.tokens())); + BEAST_EXPECT(ammBob.expectBalances(USD(150), XRP(100), ammBob.tokens())); } { // test unfunded offers are removed when payment succeeds @@ -2039,10 +1829,7 @@ private: BEAST_EXPECT(isOffer(env, bob, BTC(50), USD(50))); BEAST_EXPECT(isOffer(env, bob, BTC(40), EUR(50))); - env(pay(alice, carol, USD(50)), - path(~USD), - path(~EUR, ~USD), - sendmax(BTC(60))); + env(pay(alice, carol, USD(50)), path(~USD), path(~EUR, ~USD), sendmax(BTC(60))); env.require(balance(alice, BTC(10))); env.require(balance(bob, BTC(50))); @@ -2054,8 +1841,7 @@ private: // found unfunded BEAST_EXPECT(!isOffer(env, bob, BTC(40), EUR(50))); // unchanged - BEAST_EXPECT( - ammBob.expectBalances(EUR(100), USD(150), ammBob.tokens())); + BEAST_EXPECT(ammBob.expectBalances(EUR(100), USD(150), ammBob.tokens())); } { // test unfunded offers are removed when the payment fails. @@ -2094,8 +1880,7 @@ private: // unfund offer env(pay(bob, gw, EUR(50))); - BEAST_EXPECT(ammBobBTC_USD.expectBalances( - BTC(50), USD(50), ammBobBTC_USD.tokens())); + BEAST_EXPECT(ammBobBTC_USD.expectBalances(BTC(50), USD(50), ammBobBTC_USD.tokens())); BEAST_EXPECT(isOffer(env, bob, BTC(60), EUR(50))); BEAST_EXPECT(isOffer(env, carol, BTC(1'000), EUR(1))); BEAST_EXPECT(isOffer(env, bob, EUR(50), USD(50))); @@ -2139,21 +1924,19 @@ private: }(); BEAST_EXPECT(flowResult.removableOffers.size() == 1); - env.app().openLedger().modify( - [&](OpenView& view, beast::Journal j) { - if (flowResult.removableOffers.empty()) - return false; - Sandbox sb(&view, tapNONE); - for (auto const& o : flowResult.removableOffers) - if (auto ok = sb.peek(keylet::offer(o))) - offerDelete(sb, ok, flowJournal); - sb.apply(view); - return true; - }); + env.app().openLedger().modify([&](OpenView& view, beast::Journal j) { + if (flowResult.removableOffers.empty()) + return false; + Sandbox sb(&view, tapNONE); + for (auto const& o : flowResult.removableOffers) + if (auto ok = sb.peek(keylet::offer(o))) + offerDelete(sb, ok, flowJournal); + sb.apply(view); + return true; + }); // used in payment, but since payment failed should be untouched - BEAST_EXPECT(ammBobBTC_USD.expectBalances( - BTC(50), USD(50), ammBobBTC_USD.tokens())); + BEAST_EXPECT(ammBobBTC_USD.expectBalances(BTC(50), USD(50), ammBobBTC_USD.tokens())); BEAST_EXPECT(isOffer(env, carol, BTC(1'000), EUR(1))); // found unfunded BEAST_EXPECT(!isOffer(env, bob, BTC(60), EUR(50))); @@ -2190,8 +1973,7 @@ private: txflags(tfNoRippleDirect | tfPartialPayment)); BEAST_EXPECT(expectHolding(env, carol, EUR(1))); - BEAST_EXPECT(ammBob.expectBalances( - USD(8.4), XRPAmount{20}, ammBob.tokens())); + BEAST_EXPECT(ammBob.expectBalances(USD(8.4), XRPAmount{20}, ammBob.tokens())); } } @@ -2205,12 +1987,7 @@ private: // payment via AMM Env env(*this, features); - fund( - env, - gw, - {alice, bob, carol}, - XRP(1'000), - {USD(1'000), GBP(1'000)}); + fund(env, gw, {alice, bob, carol}, XRP(1'000), {USD(1'000), GBP(1'000)}); env(rate(gw, 1.25)); env.close(); @@ -2228,22 +2005,17 @@ private: if (!features[fixAMMv1_1]) { // 120GBP is swapped in for 107.1428USD - BEAST_EXPECT(amm.expectBalances( - GBP(1'120), - STAmount{USD, UINT64_C(892'8571428571428), -13}, - amm.tokens())); + BEAST_EXPECT( + amm.expectBalances(GBP(1'120), STAmount{USD, UINT64_C(892'8571428571428), -13}, amm.tokens())); } else { - BEAST_EXPECT(amm.expectBalances( - GBP(1'120), - STAmount{USD, UINT64_C(892'8571428571429), -13}, - amm.tokens())); + BEAST_EXPECT( + amm.expectBalances(GBP(1'120), STAmount{USD, UINT64_C(892'8571428571429), -13}, amm.tokens())); } // 25% of 85.7142USD is paid in tr fee // 85.7142*1.25 = 107.1428USD - BEAST_EXPECT(expectHolding( - env, carol, STAmount(USD, UINT64_C(1'085'714285714286), -12))); + BEAST_EXPECT(expectHolding(env, carol, STAmount(USD, UINT64_C(1'085'714285714286), -12))); } { @@ -2251,12 +2023,7 @@ private: Env env(*this, features); Account const ed("ed"); - fund( - env, - gw, - {alice, bob, carol, ed}, - XRP(1'000), - {USD(1'000), EUR(1'000), GBP(1'000)}); + fund(env, gw, {alice, bob, carol, ed}, XRP(1'000), {USD(1'000), EUR(1'000), GBP(1'000)}); env(rate(gw, 1.25)); env.close(); @@ -2278,29 +2045,19 @@ private: // consumed offer is 120GBP/120EUR // ed doesn't pay tr fee BEAST_EXPECT(expectHolding(env, ed, EUR(880), GBP(1'120))); - BEAST_EXPECT( - expectOffers(env, ed, 1, {Amounts{GBP(880), EUR(880)}})); + BEAST_EXPECT(expectOffers(env, ed, 1, {Amounts{GBP(880), EUR(880)}})); // 25% on 96EUR is paid in tr fee 96*1.25 = 120EUR // 96EUR is swapped in for 87.5912USD - BEAST_EXPECT(amm.expectBalances( - EUR(1'096), - STAmount{USD, UINT64_C(912'4087591240876), -13}, - amm.tokens())); + BEAST_EXPECT(amm.expectBalances(EUR(1'096), STAmount{USD, UINT64_C(912'4087591240876), -13}, amm.tokens())); // 25% on 70.0729USD is paid in tr fee 70.0729*1.25 = 87.5912USD - BEAST_EXPECT(expectHolding( - env, carol, STAmount(USD, UINT64_C(1'070'07299270073), -11))); + BEAST_EXPECT(expectHolding(env, carol, STAmount(USD, UINT64_C(1'070'07299270073), -11))); } { // Payment via AMM, AMM Env env(*this, features); Account const ed("ed"); - fund( - env, - gw, - {alice, bob, carol, ed}, - XRP(1'000), - {USD(1'000), EUR(1'000), GBP(1'000)}); + fund(env, gw, {alice, bob, carol, ed}, XRP(1'000), {USD(1'000), EUR(1'000), GBP(1'000)}); env(rate(gw, 1.25)); env.close(); @@ -2319,10 +2076,8 @@ private: // alice buys 107.1428EUR with 120GBP and pays 25% tr fee on // 120GBP 1,000 - 120*1.25 = 850GBP 120GBP is swapped in for // 107.1428EUR - BEAST_EXPECT(amm1.expectBalances( - GBP(1'120), - STAmount{EUR, UINT64_C(892'8571428571428), -13}, - amm1.tokens())); + BEAST_EXPECT( + amm1.expectBalances(GBP(1'120), STAmount{EUR, UINT64_C(892'8571428571428), -13}, amm1.tokens())); // 25% on 85.7142EUR is paid in tr fee 85.7142*1.25 = // 107.1428EUR 85.7142EUR is swapped in for 78.9473USD BEAST_EXPECT(amm2.expectBalances( @@ -2335,10 +2090,8 @@ private: // alice buys 107.1428EUR with 120GBP and pays 25% tr fee on // 120GBP 1,000 - 120*1.25 = 850GBP 120GBP is swapped in for // 107.1428EUR - BEAST_EXPECT(amm1.expectBalances( - GBP(1'120), - STAmount{EUR, UINT64_C(892'8571428571429), -13}, - amm1.tokens())); + BEAST_EXPECT( + amm1.expectBalances(GBP(1'120), STAmount{EUR, UINT64_C(892'8571428571429), -13}, amm1.tokens())); // 25% on 85.7142EUR is paid in tr fee 85.7142*1.25 = // 107.1428EUR 85.7142EUR is swapped in for 78.9473USD BEAST_EXPECT(amm2.expectBalances( @@ -2347,8 +2100,7 @@ private: amm2.tokens())); } // 25% on 63.1578USD is paid in tr fee 63.1578*1.25 = 78.9473USD - BEAST_EXPECT(expectHolding( - env, carol, STAmount(USD, UINT64_C(1'063'157894736842), -12))); + BEAST_EXPECT(expectHolding(env, carol, STAmount(USD, UINT64_C(1'063'157894736842), -12))); } { // AMM offer crossing @@ -2363,8 +2115,7 @@ private: env.close(); // 100USD is swapped in for 100EUR - BEAST_EXPECT( - amm.expectBalances(USD(1'100), EUR(1'000), amm.tokens())); + BEAST_EXPECT(amm.expectBalances(USD(1'100), EUR(1'000), amm.tokens())); // alice pays 25% tr fee on 100USD 1100-100*1.25 = 975USD BEAST_EXPECT(expectHolding(env, alice, USD(975), EUR(1'200))); BEAST_EXPECT(expectOffers(env, alice, 0)); @@ -2374,12 +2125,7 @@ private: // Payment via AMM with limit quality Env env(*this, features); - fund( - env, - gw, - {alice, bob, carol}, - XRP(1'000), - {USD(1'000), GBP(1'000)}); + fund(env, gw, {alice, bob, carol}, XRP(1'000), {USD(1'000), GBP(1'000)}); env(rate(gw, 1.25)); env.close(); @@ -2396,13 +2142,9 @@ private: // alice buys 125USD with 142.8571GBP and pays 25% tr fee // on 142.8571GBP // 1,000 - 142.8571*1.25 = 821.4285GBP - BEAST_EXPECT(expectHolding( - env, alice, STAmount(GBP, UINT64_C(821'4285714285712), -13))); + BEAST_EXPECT(expectHolding(env, alice, STAmount(GBP, UINT64_C(821'4285714285712), -13))); // 142.8571GBP is swapped in for 125USD - BEAST_EXPECT(amm.expectBalances( - STAmount{GBP, UINT64_C(1'142'857142857143), -12}, - USD(875), - amm.tokens())); + BEAST_EXPECT(amm.expectBalances(STAmount{GBP, UINT64_C(1'142'857142857143), -12}, USD(875), amm.tokens())); // 25% on 100USD is paid in tr fee // 100*1.25 = 125USD BEAST_EXPECT(expectHolding(env, carol, USD(1'100))); @@ -2412,12 +2154,7 @@ private: // than requested Env env(*this, features); - fund( - env, - gw, - {alice, bob, carol}, - XRP(1'000), - {USD(1'200), GBP(1'200)}); + fund(env, gw, {alice, bob, carol}, XRP(1'000), {USD(1'200), GBP(1'200)}); env(rate(gw, 1.25)); env.close(); @@ -2438,23 +2175,17 @@ private: // 1,200 - 24*1.25 = 1,170GBP BEAST_EXPECT(expectHolding(env, alice, GBP(1'170))); // 24GBP is swapped in for 28.125USD - BEAST_EXPECT(amm.expectBalances( - GBP(1'024), USD(1'171.875), amm.tokens())); + BEAST_EXPECT(amm.expectBalances(GBP(1'024), USD(1'171.875), amm.tokens())); } else { // alice buys 28.125USD with 24GBP and pays 25% tr fee // on 24GBP // 1,200 - 24*1.25 =~ 1,170GBP - BEAST_EXPECT(expectHolding( - env, - alice, - STAmount{GBP, UINT64_C(1'169'999999999999), -12})); + BEAST_EXPECT(expectHolding(env, alice, STAmount{GBP, UINT64_C(1'169'999999999999), -12})); // 24GBP is swapped in for 28.125USD - BEAST_EXPECT(amm.expectBalances( - STAmount{GBP, UINT64_C(1'024'000000000001), -12}, - USD(1'171.875), - amm.tokens())); + BEAST_EXPECT( + amm.expectBalances(STAmount{GBP, UINT64_C(1'024'000000000001), -12}, USD(1'171.875), amm.tokens())); } // 25% on 22.5USD is paid in tr fee // 22.5*1.25 = 28.125USD @@ -2466,12 +2197,7 @@ private: Env env(*this, features); Account const ed("ed"); - fund( - env, - gw, - {alice, bob, carol, ed}, - XRP(1'000), - {USD(1'400), EUR(1'400), GBP(1'400)}); + fund(env, gw, {alice, bob, carol, ed}, XRP(1'000), {USD(1'400), EUR(1'400), GBP(1'400)}); env(rate(gw, 1.25)); env.close(); @@ -2493,10 +2219,7 @@ private: // alice buys 70.4210EUR with 70.4210GBP via the offer // and pays 25% tr fee on 70.4210GBP // 1,400 - 70.4210*1.25 = 1400 - 88.0262 = 1311.9736GBP - BEAST_EXPECT(expectHolding( - env, - alice, - STAmount{GBP, UINT64_C(1'311'973684210527), -12})); + BEAST_EXPECT(expectHolding(env, alice, STAmount{GBP, UINT64_C(1'311'973684210527), -12})); // ed doesn't pay tr fee, the balances reflect consumed offer // 70.4210GBP/70.4210EUR BEAST_EXPECT(expectHolding( @@ -2523,10 +2246,7 @@ private: // alice buys 70.4210EUR with 70.4210GBP via the offer // and pays 25% tr fee on 70.4210GBP // 1,400 - 70.4210*1.25 = 1400 - 88.0262 = 1311.9736GBP - BEAST_EXPECT(expectHolding( - env, - alice, - STAmount{GBP, UINT64_C(1'311'973684210525), -12})); + BEAST_EXPECT(expectHolding(env, alice, STAmount{GBP, UINT64_C(1'311'973684210525), -12})); // ed doesn't pay tr fee, the balances reflect consumed offer // 70.4210GBP/70.4210EUR BEAST_EXPECT(expectHolding( @@ -2549,8 +2269,7 @@ private: amm.tokens())); } // 25% on 59.7321USD is paid in tr fee 59.7321*1.25 = 74.6651USD - BEAST_EXPECT(expectHolding( - env, carol, STAmount(USD, UINT64_C(1'459'732142857143), -12))); + BEAST_EXPECT(expectHolding(env, carol, STAmount(USD, UINT64_C(1'459'732142857143), -12))); } { // Payment via AMM and offer with limit quality, deliver less @@ -2558,12 +2277,7 @@ private: Env env(*this, features); Account const ed("ed"); - fund( - env, - gw, - {alice, bob, carol, ed}, - XRP(1'000), - {USD(1'400), EUR(1'400), GBP(1'400)}); + fund(env, gw, {alice, bob, carol, ed}, XRP(1'000), {USD(1'400), EUR(1'400), GBP(1'400)}); env(rate(gw, 1.25)); env.close(); @@ -2585,10 +2299,7 @@ private: // alice buys 53.3322EUR with 56.3368GBP via the amm // and pays 25% tr fee on 56.3368GBP // 1,400 - 56.3368*1.25 = 1400 - 70.4210 = 1329.5789GBP - BEAST_EXPECT(expectHolding( - env, - alice, - STAmount{GBP, UINT64_C(1'329'578947368421), -12})); + BEAST_EXPECT(expectHolding(env, alice, STAmount{GBP, UINT64_C(1'329'578947368421), -12})); //// 25% on 56.3368EUR is paid in tr fee 56.3368*1.25 ///= 70.4210EUR // 56.3368GBP is swapped in for 53.3322EUR @@ -2602,10 +2313,7 @@ private: // alice buys 53.3322EUR with 56.3368GBP via the amm // and pays 25% tr fee on 56.3368GBP // 1,400 - 56.3368*1.25 = 1400 - 70.4210 = 1329.5789GBP - BEAST_EXPECT(expectHolding( - env, - alice, - STAmount{GBP, UINT64_C(1'329'57894736842), -11})); + BEAST_EXPECT(expectHolding(env, alice, STAmount{GBP, UINT64_C(1'329'57894736842), -11})); //// 25% on 56.3368EUR is paid in tr fee 56.3368*1.25 ///= 70.4210EUR // 56.3368GBP is swapped in for 53.3322EUR @@ -2629,8 +2337,7 @@ private: STAmount{EUR, UINT64_C(957'3341836734693), -13}, STAmount{USD, UINT64_C(1'340'267857142857), -12}}})); // 25% on 47.7857USD is paid in tr fee 47.7857*1.25 = 59.7321USD - BEAST_EXPECT(expectHolding( - env, carol, STAmount(USD, UINT64_C(1'447'785714285714), -12))); + BEAST_EXPECT(expectHolding(env, carol, STAmount(USD, UINT64_C(1'447'785714285714), -12))); } { // Payment via AMM, AMM with limit quality, deliver less @@ -2638,12 +2345,7 @@ private: Env env(*this, features); Account const ed("ed"); - fund( - env, - gw, - {alice, bob, carol, ed}, - XRP(1'000), - {USD(1'400), EUR(1'400), GBP(1'400)}); + fund(env, gw, {alice, bob, carol, ed}, XRP(1'000), {USD(1'400), EUR(1'400), GBP(1'400)}); env(rate(gw, 1.25)); env.close(); @@ -2663,10 +2365,7 @@ private: // alice buys 53.3322EUR with 107.5308GBP // 25% on 86.0246GBP is paid in tr fee // 1,400 - 86.0246*1.25 = 1400 - 107.5308 = 1229.4691GBP - BEAST_EXPECT(expectHolding( - env, - alice, - STAmount{GBP, UINT64_C(1'292'469135802469), -12})); + BEAST_EXPECT(expectHolding(env, alice, STAmount{GBP, UINT64_C(1'292'469135802469), -12})); // 86.0246GBP is swapped in for 79.2106EUR BEAST_EXPECT(amm1.expectBalances( STAmount{GBP, UINT64_C(1'086'024691358025), -12}, @@ -2684,10 +2383,7 @@ private: // alice buys 53.3322EUR with 107.5308GBP // 25% on 86.0246GBP is paid in tr fee // 1,400 - 86.0246*1.25 = 1400 - 107.5308 = 1229.4691GBP - BEAST_EXPECT(expectHolding( - env, - alice, - STAmount{GBP, UINT64_C(1'292'469135802466), -12})); + BEAST_EXPECT(expectHolding(env, alice, STAmount{GBP, UINT64_C(1'292'469135802466), -12})); // 86.0246GBP is swapped in for 79.2106EUR BEAST_EXPECT(amm1.expectBalances( STAmount{GBP, UINT64_C(1'086'024691358027), -12}, @@ -2701,20 +2397,14 @@ private: amm2.tokens())); } // 25% on 66.7432USD is paid in tr fee 66.7432*1.25 = 83.4291USD - BEAST_EXPECT(expectHolding( - env, carol, STAmount(USD, UINT64_C(1'466'743295019157), -12))); + BEAST_EXPECT(expectHolding(env, carol, STAmount(USD, UINT64_C(1'466'743295019157), -12))); } { // Payment by the issuer via AMM, AMM with limit quality, // deliver less than requested Env env(*this, features); - fund( - env, - gw, - {alice, bob, carol}, - XRP(1'000), - {USD(1'400), EUR(1'400), GBP(1'400)}); + fund(env, gw, {alice, bob, carol}, XRP(1'000), {USD(1'400), EUR(1'400), GBP(1'400)}); env(rate(gw, 1.25)); env.close(); @@ -2758,8 +2448,7 @@ private: amm2.tokens())); } // 25% on 81.1111USD is paid in tr fee 81.1111*1.25 = 101.3888USD - BEAST_EXPECT(expectHolding( - env, carol, STAmount{USD, UINT64_C(1'481'111111111111), -12})); + BEAST_EXPECT(expectHolding(env, carol, STAmount{USD, UINT64_C(1'481'111111111111), -12})); } } @@ -2786,8 +2475,7 @@ private: sendmax(XRP(100)), txflags(tfNoRippleDirect | tfPartialPayment | tfLimitQuality)); - BEAST_EXPECT( - ammBob.expectBalances(XRP(1'050), USD(1'000), ammBob.tokens())); + BEAST_EXPECT(ammBob.expectBalances(XRP(1'050), USD(1'000), ammBob.tokens())); BEAST_EXPECT(expectHolding(env, carol, USD(2'050))); BEAST_EXPECT(expectOffers(env, bob, 1, {{{XRP(100), USD(50)}}})); } @@ -2804,13 +2492,7 @@ private: Env env(*this, testable_amendments()); // Note, if alice doesn't have default ripple, then pay // fails with tecPATH_DRY. - fund( - env, - gw, - {alice, bob}, - XRP(10'000), - {USD(200), EUR(200)}, - Fund::All); + fund(env, gw, {alice, bob}, XRP(10'000), {USD(200), EUR(200)}, Fund::All); AMM ammAliceXRP_USD(env, alice, XRP(100), USD(101)); AMM ammAliceXRP_EUR(env, alice, XRP(100), EUR(101)); @@ -2828,13 +2510,7 @@ private: Env env(*this); // Note, if alice doesn't have default ripple, then pay fails // with tecPATH_DRY. - fund( - env, - gw, - {alice, bob}, - XRP(10'000), - {USD(200), EUR(200)}, - Fund::All); + fund(env, gw, {alice, bob}, XRP(10'000), {USD(200), EUR(200)}, Fund::All); AMM ammAliceXRP_USD(env, alice, XRP(100), USD(100)); AMM ammAliceXRP_EUR(env, alice, XRP(100), EUR(100)); @@ -2852,13 +2528,7 @@ private: Env env(*this); // Note, if alice doesn't have default ripple, then pay fails // with tecPATH_DRY. - fund( - env, - gw, - {alice, bob}, - XRP(10'000), - {USD(200), EUR(200), JPY(200)}, - Fund::All); + fund(env, gw, {alice, bob}, XRP(10'000), {USD(200), EUR(200), JPY(200)}, Fund::All); AMM ammAliceXRP_USD(env, alice, XRP(100), USD(100)); AMM ammAliceXRP_EUR(env, alice, XRP(100), EUR(100)); @@ -2897,11 +2567,9 @@ private: // offer, removes 999 more as unfunded, then hits the step limit. env(offer(alice, USD(1'000), XRP(1'000))); if (!features[fixAMMv1_1]) - env.require(balance( - alice, STAmount{USD, UINT64_C(2'050126257867561), -15})); + env.require(balance(alice, STAmount{USD, UINT64_C(2'050126257867561), -15})); else - env.require(balance( - alice, STAmount{USD, UINT64_C(2'050125257867587), -15})); + env.require(balance(alice, STAmount{USD, UINT64_C(2'050125257867587), -15})); env.require(owners(alice, 2)); env.require(balance(bob, USD(0))); env.require(owners(bob, 1'001)); @@ -2930,25 +2598,14 @@ private: Env env(*this, features); fund(env, gw, {alice, bob, carol}, XRP(10'000)); env.trust(USD(100), alice, bob, carol); - env(pay(alice, bob, USD(10)), - deliver_min(USD(10)), - ter(temBAD_AMOUNT)); - env(pay(alice, bob, USD(10)), - deliver_min(USD(-5)), - txflags(tfPartialPayment), - ter(temBAD_AMOUNT)); - env(pay(alice, bob, USD(10)), - deliver_min(XRP(5)), - txflags(tfPartialPayment), - ter(temBAD_AMOUNT)); + env(pay(alice, bob, USD(10)), deliver_min(USD(10)), ter(temBAD_AMOUNT)); + env(pay(alice, bob, USD(10)), deliver_min(USD(-5)), txflags(tfPartialPayment), ter(temBAD_AMOUNT)); + env(pay(alice, bob, USD(10)), deliver_min(XRP(5)), txflags(tfPartialPayment), ter(temBAD_AMOUNT)); env(pay(alice, bob, USD(10)), deliver_min(Account(carol)["USD"](5)), txflags(tfPartialPayment), ter(temBAD_AMOUNT)); - env(pay(alice, bob, USD(10)), - deliver_min(USD(15)), - txflags(tfPartialPayment), - ter(temBAD_AMOUNT)); + env(pay(alice, bob, USD(10)), deliver_min(USD(15)), txflags(tfPartialPayment), ter(temBAD_AMOUNT)); env(pay(gw, carol, USD(50))); AMM ammCarol(env, carol, XRP(10), USD(15)); env(pay(alice, bob, USD(10)), @@ -2957,9 +2614,7 @@ private: txflags(tfPartialPayment), sendmax(XRP(5)), ter(tecPATH_PARTIAL)); - env.require(balance( - alice, - drops(10'000'000'000 - env.current()->fees().base.drops()))); + env.require(balance(alice, drops(10'000'000'000 - env.current()->fees().base.drops()))); env.require(balance(bob, XRP(10'000))); } @@ -2994,8 +2649,7 @@ private: deliver_min(USD(200)), txflags(tfPartialPayment), sendmax(XRP(1'100))); - BEAST_EXPECT( - ammBob.expectBalances(XRP(6'600), USD(1'000), ammBob.tokens())); + BEAST_EXPECT(ammBob.expectBalances(XRP(6'600), USD(1'000), ammBob.tokens())); env.require(balance(carol, USD(200))); } @@ -3019,8 +2673,7 @@ private: sendmax(XRP(200))); env.require(balance(bob, USD(0))); env.require(balance(carol, USD(200))); - BEAST_EXPECT(ammDan.expectBalances( - XRP(1'100), USD(1'000), ammDan.tokens())); + BEAST_EXPECT(ammDan.expectBalances(XRP(1'100), USD(1'000), ammDan.tokens())); } else { @@ -3030,12 +2683,9 @@ private: txflags(tfPartialPayment), sendmax(XRPAmount(200'000'001))); env.require(balance(bob, USD(0))); - env.require(balance( - carol, STAmount{USD, UINT64_C(200'00000090909), -11})); + env.require(balance(carol, STAmount{USD, UINT64_C(200'00000090909), -11})); BEAST_EXPECT(ammDan.expectBalances( - XRPAmount{1'100'000'001}, - STAmount{USD, UINT64_C(999'99999909091), -11}, - ammDan.tokens())); + XRPAmount{1'100'000'001}, STAmount{USD, UINT64_C(999'99999909091), -11}, ammDan.tokens())); } } } @@ -3068,18 +2718,14 @@ private: // Make sure the payment works if PaymentAuth is not involved. env(pay(becky, becky, USD(10)), path(~USD), sendmax(XRP(10))); env.close(); - BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount(107'692'308), USD(130), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectBalances(XRPAmount(107'692'308), USD(130), ammAlice.tokens())); // becky decides to require authorization for deposits. env(fset(becky, asfDepositAuth)); env.close(); // becky pays herself again. - env(pay(becky, becky, USD(10)), - path(~USD), - sendmax(XRP(10)), - ter(tesSUCCESS)); + env(pay(becky, becky, USD(10)), path(~USD), sendmax(XRP(10)), ter(tesSUCCESS)); env.close(); } @@ -3126,9 +2772,7 @@ private: // Note that even though alice is paying bob in XRP, the payment // is still not allowed since the payment passes through an // offer. - env(pay(alice, bob, drops(1)), - sendmax(USD(1)), - ter(tecNO_PERMISSION)); + env(pay(alice, bob, drops(1)), sendmax(USD(1)), ter(tecNO_PERMISSION)); env.close(); BEAST_EXPECT(bobXrpBalance == env.balance(bob, XRP)); @@ -3174,8 +2818,7 @@ private: env(pay(alice, bob, drops(1)), sendmax(USD(1))); env.close(); - BEAST_EXPECT(ammCarol.expectBalances( - USD(101), XRPAmount(100), ammCarol.tokens())); + BEAST_EXPECT(ammCarol.expectBalances(USD(101), XRPAmount(100), ammCarol.tokens())); } void @@ -3240,8 +2883,7 @@ private: // test: can buy more assets on that line env(offer(bob, G1["USD"](5), XRP(25))); env.close(); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(525), G1["USD"](100), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectBalances(XRP(525), G1["USD"](100), ammAlice.tokens())); } { @@ -3296,15 +2938,11 @@ private: // Is cleared via a TrustSet with ClearFreeze flag // test: sets LowFreeze | HighFreeze flags env(trust(G1, bob["USD"](0), tfClearFreeze)); - auto affected = env.meta()->getJson( - JsonOptions::none)[sfAffectedNodes.fieldName]; + auto affected = env.meta()->getJson(JsonOptions::none)[sfAffectedNodes.fieldName]; if (!BEAST_EXPECT(checkArraySize(affected, 2u))) return; - auto ff = - affected[1u][sfModifiedNode.fieldName][sfFinalFields.fieldName]; - BEAST_EXPECT( - ff[sfLowLimit.fieldName] == - G1["USD"](0).value().getJson(JsonOptions::none)); + auto ff = affected[1u][sfModifiedNode.fieldName][sfFinalFields.fieldName]; + BEAST_EXPECT(ff[sfLowLimit.fieldName] == G1["USD"](0).value().getJson(JsonOptions::none)); BEAST_EXPECT(!(ff[jss::Flags].asUInt() & lsfLowFreeze)); BEAST_EXPECT(!(ff[jss::Flags].asUInt() & lsfHighFreeze)); env.close(); @@ -3351,10 +2989,7 @@ private: // Account without GlobalFreeze (proving operations normally // work) // test: visible offers where taker_pays is unfrozen issuer - auto offers = env.rpc( - "book_offers", - std::string("USD/") + G1.human(), - "XRP")[jss::result][jss::offers]; + auto offers = env.rpc("book_offers", std::string("USD/") + G1.human(), "XRP")[jss::result][jss::offers]; if (!BEAST_EXPECT(checkArraySize(offers, 1u))) return; std::set accounts; @@ -3365,10 +3000,7 @@ private: BEAST_EXPECT(accounts.find(A2.human()) != std::end(accounts)); // test: visible offers where taker_gets is unfrozen issuer - offers = env.rpc( - "book_offers", - "XRP", - std::string("USD/") + G1.human())[jss::result][jss::offers]; + offers = env.rpc("book_offers", "XRP", std::string("USD/") + G1.human())[jss::result][jss::offers]; if (!BEAST_EXPECT(checkArraySize(offers, 1u))) return; accounts.clear(); @@ -3421,17 +3053,11 @@ private: { // test: book_offers shows offers // (should these actually be filtered?) - auto offers = env.rpc( - "book_offers", - "XRP", - std::string("USD/") + G1.human())[jss::result][jss::offers]; + auto offers = env.rpc("book_offers", "XRP", std::string("USD/") + G1.human())[jss::result][jss::offers]; if (!BEAST_EXPECT(checkArraySize(offers, 1u))) return; - offers = env.rpc( - "book_offers", - std::string("USD/") + G1.human(), - "XRP")[jss::result][jss::offers]; + offers = env.rpc("book_offers", std::string("USD/") + G1.human(), "XRP")[jss::result][jss::offers]; if (!BEAST_EXPECT(checkArraySize(offers, 1u))) return; } @@ -3482,19 +3108,16 @@ private: env(pay(A2, G1, G1["USD"](1)), paths(G1["USD"]), sendmax(XRP(1))); env.close(); - BEAST_EXPECT( - ammA3.expectBalances(XRP(1'001), G1["USD"](1'000), ammA3.tokens())); + BEAST_EXPECT(ammA3.expectBalances(XRP(1'001), G1["USD"](1'000), ammA3.tokens())); // test: someone else creates an offer providing liquidity env(offer(A4, XRP(999), G1["USD"](999))); env.close(); // The offer consumes AMM offer - BEAST_EXPECT( - ammA3.expectBalances(XRP(1'000), G1["USD"](1'001), ammA3.tokens())); + BEAST_EXPECT(ammA3.expectBalances(XRP(1'000), G1["USD"](1'001), ammA3.tokens())); // test: AMM line is frozen - auto const a3am = - STAmount{Issue{to_currency("USD"), ammA3.ammAccount()}, 0}; + auto const a3am = STAmount{Issue{to_currency("USD"), ammA3.ammAccount()}, 0}; env(trust(G1, a3am, tfSetFreeze)); auto const info = ammA3.ammRpcInfo(); BEAST_EXPECT(info[jss::amm][jss::asset2_frozen].asBool()); @@ -3504,8 +3127,7 @@ private: env(pay(A2, G1, G1["USD"](1)), paths(G1["USD"]), sendmax(XRP(1))); env.close(); // AMM is not consumed - BEAST_EXPECT( - ammA3.expectBalances(XRP(1'000), G1["USD"](1'001), ammA3.tokens())); + BEAST_EXPECT(ammA3.expectBalances(XRP(1'000), G1["USD"](1'001), ammA3.tokens())); // removal buy successful OfferCreate // test: freeze the new offer @@ -3560,16 +3182,13 @@ private: std::nullopt, ms, ter(tesSUCCESS)); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'000), USD(10'000), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), USD(10'000), ammAlice.tokens())); ammAlice.deposit(alice, 1'000'000); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(11'000), USD(11'000), IOUAmount{11'000'000, 0})); + BEAST_EXPECT(ammAlice.expectBalances(XRP(11'000), USD(11'000), IOUAmount{11'000'000, 0})); ammAlice.withdraw(alice, 1'000'000); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'000), USD(10'000), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), USD(10'000), ammAlice.tokens())); ammAlice.vote({}, 1'000); BEAST_EXPECT(ammAlice.expectTradingFee(1'000)); @@ -3577,8 +3196,7 @@ private: env(ammAlice.bid({.account = alice, .bidMin = 100}), ms).close(); BEAST_EXPECT(ammAlice.expectAuctionSlot(100, 0, IOUAmount{4'000})); // 4000 tokens burnt - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'000), USD(10'000), IOUAmount{9'996'000, 0})); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), USD(10'000), IOUAmount{9'996'000, 0})); } void @@ -3592,12 +3210,7 @@ private: Env env(*this, features); - fund( - env, - gw, - {alice, bob, carol}, - XRP(10'000), - {USD(2'000), EUR(1'000)}); + fund(env, gw, {alice, bob, carol}, XRP(10'000), {USD(2'000), EUR(1'000)}); AMM bobXRP_USD(env, bob, XRP(1'000), USD(1'000)); AMM bobUSD_EUR(env, bob, USD(1'000), EUR(1'000)); @@ -3624,12 +3237,7 @@ private: env.trust(USD(1'000), alice, bob); env.trust(EUR(1'000), alice, bob); env.close(); - fund( - env, - bob, - {alice, gw}, - {BobUSD(100), BobEUR(100)}, - Fund::IOUOnly); + fund(env, bob, {alice, gw}, {BobUSD(100), BobEUR(100)}, Fund::IOUOnly); env.close(); AMM ammBobXRP_USD(env, bob, XRP(100), BobUSD(100)); @@ -3640,7 +3248,7 @@ private: Path const p = [&] { Path result; - result.push_back(allpe(gw, BobUSD)); + result.push_back(allPathElements(gw, BobUSD)); result.push_back(cpe(EUR.currency)); return result; }(); @@ -3662,10 +3270,7 @@ private: AMM ammBob(env, bob, XRP(100), USD(100)); // payment path: XRP -> XRP/USD -> USD/XRP - env(pay(alice, carol, XRP(100)), - path(~USD, ~XRP), - txflags(tfNoRippleDirect), - ter(temBAD_SEND_XRP_PATHS)); + env(pay(alice, carol, XRP(100)), path(~USD, ~XRP), txflags(tfNoRippleDirect), ter(temBAD_SEND_XRP_PATHS)); } { @@ -3757,9 +3362,7 @@ private: using namespace jtx; // For now, just disable SAV entirely, which locks in the small Number // mantissas in the transaction engine - FeatureBitset const all{ - testable_amendments() - featureSingleAssetVault - - featureLendingProtocol}; + FeatureBitset const all{testable_amendments() - featureSingleAssetVault - featureLendingProtocol}; testFalseDry(all); testBookStep(all); @@ -3775,9 +3378,7 @@ private: using namespace jtx; // For now, just disable SAV entirely, which locks in the small Number // mantissas in the transaction engine - FeatureBitset const all{ - testable_amendments() - featureSingleAssetVault - - featureLendingProtocol}; + FeatureBitset const all{testable_amendments() - featureSingleAssetVault - featureLendingProtocol}; testStepLimit(all); testStepLimit(all - fixAMMv1_1 - fixAMMv1_3); } @@ -3788,9 +3389,7 @@ private: using namespace jtx; // For now, just disable SAV entirely, which locks in the small Number // mantissas in the transaction engine - FeatureBitset const all{ - testable_amendments() - featureSingleAssetVault - - featureLendingProtocol}; + FeatureBitset const all{testable_amendments() - featureSingleAssetVault - featureLendingProtocol}; test_convert_all_of_an_asset(all); test_convert_all_of_an_asset(all - fixAMMv1_1 - fixAMMv1_3); } @@ -3800,9 +3399,7 @@ private: { // For now, just disable SAV entirely, which locks in the small Number // mantissas in the transaction engine - FeatureBitset const all{ - jtx::testable_amendments() - featureSingleAssetVault - - featureLendingProtocol}; + FeatureBitset const all{jtx::testable_amendments() - featureSingleAssetVault - featureLendingProtocol}; testPayment(all); testPayIOU(); } @@ -3813,9 +3410,7 @@ private: using namespace test::jtx; // For now, just disable SAV entirely, which locks in the small Number // mantissas in the transaction engine - FeatureBitset const sa{ - testable_amendments() - featureSingleAssetVault - - featureLendingProtocol}; + FeatureBitset const sa{testable_amendments() - featureSingleAssetVault - featureLendingProtocol}; testRippleState(sa); testGlobalFreeze(sa); testOffersWhenFrozen(sa); diff --git a/src/test/app/AMM_test.cpp b/src/test/app/AMM_test.cpp index 55bf4aa0a3..8a60e5f667 100644 --- a/src/test/app/AMM_test.cpp +++ b/src/test/app/AMM_test.cpp @@ -39,8 +39,7 @@ private: { // For now, just disable SAV entirely, which locks in the small Number // mantissas - return jtx::testable_amendments() - featureSingleAssetVault - - featureLendingProtocol; + return jtx::testable_amendments() - featureSingleAssetVault - featureLendingProtocol; } void @@ -54,8 +53,7 @@ private: // XRP to IOU, with featureSingleAssetVault testAMM( [&](AMM& ammAlice, Env&) { - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'000), USD(10'000), IOUAmount{10'000'000, 0})); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), USD(10'000), IOUAmount{10'000'000, 0})); }, {}, 0, @@ -66,8 +64,7 @@ private: // XRP to IOU, without featureSingleAssetVault testAMM( [&](AMM& ammAlice, Env&) { - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'000), USD(10'000), IOUAmount{10'000'000, 0})); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), USD(10'000), IOUAmount{10'000'000, 0})); }, {}, 0, @@ -77,8 +74,7 @@ private: // IOU to IOU testAMM( [&](AMM& ammAlice, Env&) { - BEAST_EXPECT(ammAlice.expectBalances( - USD(20'000), BTC(0.5), IOUAmount{100, 0})); + BEAST_EXPECT(ammAlice.expectBalances(USD(20'000), BTC(0.5), IOUAmount{100, 0})); }, {{USD(20'000), BTC(0.5)}}); @@ -90,8 +86,7 @@ private: env.close(); // no transfer fee on create AMM ammAlice(env, alice, USD(20'000), BTC(0.5)); - BEAST_EXPECT(ammAlice.expectBalances( - USD(20'000), BTC(0.5), IOUAmount{100, 0})); + BEAST_EXPECT(ammAlice.expectBalances(USD(20'000), BTC(0.5), IOUAmount{100, 0})); BEAST_EXPECT(expectHolding(env, alice, USD(0))); BEAST_EXPECT(expectHolding(env, alice, BTC(0))); } @@ -121,8 +116,7 @@ private: env.close(); env(fset(gw, asfGlobalFreeze)); env.close(); - AMM ammAliceFail( - env, alice, XRP(10'000), USD(10'000), ter(tecFROZEN)); + AMM ammAliceFail(env, alice, XRP(10'000), USD(10'000), ter(tecFROZEN)); env(fclear(gw, asfGlobalFreeze)); env.close(); AMM ammAlice(env, alice, XRP(10'000), USD(10'000)); @@ -138,12 +132,8 @@ private: 1'000); // Make sure asset comparison works. - BEAST_EXPECT( - STIssue(sfAsset, STAmount(XRP(2'000)).issue()) == - STIssue(sfAsset, STAmount(XRP(2'000)).issue())); - BEAST_EXPECT( - STIssue(sfAsset, STAmount(XRP(2'000)).issue()) != - STIssue(sfAsset, STAmount(USD(2'000)).issue())); + BEAST_EXPECT(STIssue(sfAsset, STAmount(XRP(2'000)).issue()) == STIssue(sfAsset, STAmount(XRP(2'000)).issue())); + BEAST_EXPECT(STIssue(sfAsset, STAmount(XRP(2'000)).issue()) != STIssue(sfAsset, STAmount(USD(2'000)).issue())); } void @@ -157,8 +147,7 @@ private: { Env env{*this}; fund(env, gw, {alice}, {USD(30'000)}, Fund::All); - AMM ammAlice( - env, alice, XRP(10'000), XRP(10'000), ter(temBAD_AMM_TOKENS)); + AMM ammAlice(env, alice, XRP(10'000), XRP(10'000), ter(temBAD_AMM_TOKENS)); BEAST_EXPECT(!ammAlice.ammExists()); } @@ -166,8 +155,7 @@ private: { Env env{*this}; fund(env, gw, {alice}, {USD(30'000)}, Fund::All); - AMM ammAlice( - env, alice, USD(10'000), USD(10'000), ter(temBAD_AMM_TOKENS)); + AMM ammAlice(env, alice, USD(10'000), USD(10'000), ter(temBAD_AMM_TOKENS)); BEAST_EXPECT(!ammAlice.ammExists()); } @@ -179,11 +167,9 @@ private: BEAST_EXPECT(!ammAlice.ammExists()); AMM ammAlice1(env, alice, XRP(10'000), USD(0), ter(temBAD_AMOUNT)); BEAST_EXPECT(!ammAlice1.ammExists()); - AMM ammAlice2( - env, alice, XRP(10'000), USD(-10'000), ter(temBAD_AMOUNT)); + AMM ammAlice2(env, alice, XRP(10'000), USD(-10'000), ter(temBAD_AMOUNT)); BEAST_EXPECT(!ammAlice2.ammExists()); - AMM ammAlice3( - env, alice, XRP(-10'000), USD(10'000), ter(temBAD_AMOUNT)); + AMM ammAlice3(env, alice, XRP(-10'000), USD(10'000), ter(temBAD_AMOUNT)); BEAST_EXPECT(!ammAlice3.ammExists()); } @@ -191,8 +177,7 @@ private: { Env env{*this}; fund(env, gw, {alice}, {USD(30'000)}, Fund::All); - AMM ammAlice( - env, alice, XRP(10'000), BAD(10'000), ter(temBAD_CURRENCY)); + AMM ammAlice(env, alice, XRP(10'000), BAD(10'000), ter(temBAD_CURRENCY)); BEAST_EXPECT(!ammAlice.ammExists()); } @@ -200,8 +185,7 @@ private: { Env env{*this}; fund(env, gw, {alice}, {USD(30'000)}, Fund::All); - AMM ammAlice( - env, alice, XRP(10'000), USD(40'000), ter(tecUNFUNDED_AMM)); + AMM ammAlice(env, alice, XRP(10'000), USD(40'000), ter(tecUNFUNDED_AMM)); BEAST_EXPECT(!ammAlice.ammExists()); } @@ -209,8 +193,7 @@ private: { Env env{*this}; fund(env, gw, {alice}, {USD(30'000)}, Fund::All); - AMM ammAlice( - env, alice, XRP(40'000), USD(10'000), ter(tecUNFUNDED_AMM)); + AMM ammAlice(env, alice, XRP(40'000), USD(10'000), ter(tecUNFUNDED_AMM)); BEAST_EXPECT(!ammAlice.ammExists()); } @@ -234,10 +217,8 @@ private: } // AMM already exists - testAMM([&](AMM& ammAlice, Env& env) { - AMM ammCarol( - env, carol, XRP(10'000), USD(10'000), ter(tecDUPLICATE)); - }); + testAMM( + [&](AMM& ammAlice, Env& env) { AMM ammCarol(env, carol, XRP(10'000), USD(10'000), ter(tecDUPLICATE)); }); // Invalid flags { @@ -320,8 +301,7 @@ private: // Insufficient reserve, XRP/IOU { Env env(*this); - auto const starting_xrp = - XRP(1'000) + reserve(env, 3) + env.current()->fees().base * 4; + auto const starting_xrp = XRP(1'000) + reserve(env, 3) + env.current()->fees().base * 4; env.fund(starting_xrp, gw); env.fund(starting_xrp, alice); env.trust(USD(2'000), alice); @@ -330,15 +310,13 @@ private: env.close(); env(offer(alice, XRP(101), USD(100))); env(offer(alice, XRP(102), USD(100))); - AMM ammAlice( - env, alice, XRP(1'000), USD(1'000), ter(tecUNFUNDED_AMM)); + AMM ammAlice(env, alice, XRP(1'000), USD(1'000), ter(tecUNFUNDED_AMM)); } // Insufficient reserve, IOU/IOU { Env env(*this); - auto const starting_xrp = - reserve(env, 4) + env.current()->fees().base * 5; + auto const starting_xrp = reserve(env, 4) + env.current()->fees().base * 5; env.fund(starting_xrp, gw); env.fund(starting_xrp, alice); env.trust(USD(2'000), alice); @@ -349,8 +327,7 @@ private: env.close(); env(offer(alice, EUR(101), USD(100))); env(offer(alice, EUR(102), USD(100))); - AMM ammAlice( - env, alice, EUR(1'000), USD(1'000), ter(tecINSUF_RESERVE_LINE)); + AMM ammAlice(env, alice, EUR(1'000), USD(1'000), ter(tecINSUF_RESERVE_LINE)); } // Insufficient fee @@ -377,17 +354,9 @@ private: testAMM([&](AMM& ammAlice, Env& env) { fund(env, gw, {alice}, {EUR(10'000)}, Fund::IOUOnly); AMM ammAMMToken( - env, - alice, - EUR(10'000), - STAmount{ammAlice.lptIssue(), 1'000'000}, - ter(tecAMM_INVALID_TOKENS)); + env, alice, EUR(10'000), STAmount{ammAlice.lptIssue(), 1'000'000}, ter(tecAMM_INVALID_TOKENS)); AMM ammAMMToken1( - env, - alice, - STAmount{ammAlice.lptIssue(), 1'000'000}, - EUR(10'000), - ter(tecAMM_INVALID_TOKENS)); + env, alice, STAmount{ammAlice.lptIssue(), 1'000'000}, EUR(10'000), ter(tecAMM_INVALID_TOKENS)); }); // AMM with two LPTokens from other AMMs. @@ -397,11 +366,7 @@ private: auto const token1 = ammAlice.lptIssue(); auto const token2 = ammAlice1.lptIssue(); AMM ammAMMTokens( - env, - alice, - STAmount{token1, 1'000'000}, - STAmount{token2, 1'000'000}, - ter(tecAMM_INVALID_TOKENS)); + env, alice, STAmount{token1, 1'000'000}, STAmount{token2, 1'000'000}, ter(tecAMM_INVALID_TOKENS)); }); // Issuer has DefaultRipple disabled @@ -413,8 +378,7 @@ private: env.fund(XRP(30'000), alice); env.trust(USD(30'000), alice); env(pay(gw, alice, USD(30'000))); - AMM ammAlice( - env, alice, XRP(10'000), USD(10'000), ter(terNO_RIPPLE)); + AMM ammAlice(env, alice, XRP(10'000), USD(10'000), ter(terNO_RIPPLE)); Account const gw1("gw1"); env.fund(XRP(30'000), gw1); env(fclear(gw1, asfDefaultRipple)); @@ -424,8 +388,7 @@ private: AMM ammGwGw1(env, gw, USD(10'000), USD1(10'000), ter(terNO_RIPPLE)); env.trust(USD1(30'000), alice); env(pay(gw1, alice, USD1(30'000))); - AMM ammAlice1( - env, alice, USD(10'000), USD1(10'000), ter(terNO_RIPPLE)); + AMM ammAlice1(env, alice, USD(10'000), USD1(10'000), ter(terNO_RIPPLE)); } } @@ -438,12 +401,7 @@ private: testAMM([&](AMM& ammAlice, Env& env) { // Invalid flags - ammAlice.deposit( - alice, - 1'000'000, - std::nullopt, - tfWithdrawAll, - ter(temINVALID_FLAG)); + ammAlice.deposit(alice, 1'000'000, std::nullopt, tfWithdrawAll, ter(temINVALID_FLAG)); // Invalid options std::vector>> invalidOptions = { // flags, tokens, asset1In, asset2in, EPrice, tfee - {tfLPToken, - 1'000, - std::nullopt, - USD(100), - std::nullopt, - std::nullopt}, - {tfLPToken, - 1'000, - XRP(100), - std::nullopt, - std::nullopt, - std::nullopt}, - {tfLPToken, - 1'000, - std::nullopt, - std::nullopt, - STAmount{USD, 1, -1}, - std::nullopt}, - {tfLPToken, - std::nullopt, - USD(100), - std::nullopt, - STAmount{USD, 1, -1}, - std::nullopt}, - {tfLPToken, - 1'000, - XRP(100), - std::nullopt, - STAmount{USD, 1, -1}, - std::nullopt}, - {tfLPToken, - 1'000, - std::nullopt, - std::nullopt, - std::nullopt, - 1'000}, - {tfSingleAsset, - 1'000, - std::nullopt, - std::nullopt, - std::nullopt, - std::nullopt}, - {tfSingleAsset, - std::nullopt, - std::nullopt, - USD(100), - std::nullopt, - std::nullopt}, - {tfSingleAsset, - std::nullopt, - std::nullopt, - std::nullopt, - STAmount{USD, 1, -1}, - std::nullopt}, - {tfSingleAsset, - std::nullopt, - USD(100), - std::nullopt, - std::nullopt, - 1'000}, - {tfTwoAsset, - 1'000, - std::nullopt, - std::nullopt, - std::nullopt, - std::nullopt}, - {tfTwoAsset, - std::nullopt, - XRP(100), - USD(100), - STAmount{USD, 1, -1}, - std::nullopt}, - {tfTwoAsset, - std::nullopt, - XRP(100), - std::nullopt, - std::nullopt, - std::nullopt}, - {tfTwoAsset, - std::nullopt, - XRP(100), - USD(100), - std::nullopt, - 1'000}, - {tfTwoAsset, - std::nullopt, - std::nullopt, - USD(100), - STAmount{USD, 1, -1}, - std::nullopt}, - {tfOneAssetLPToken, - 1'000, - std::nullopt, - std::nullopt, - std::nullopt, - std::nullopt}, - {tfOneAssetLPToken, - std::nullopt, - XRP(100), - USD(100), - std::nullopt, - std::nullopt}, - {tfOneAssetLPToken, - std::nullopt, - XRP(100), - std::nullopt, - STAmount{USD, 1, -1}, - std::nullopt}, - {tfOneAssetLPToken, - 1'000, - XRP(100), - std::nullopt, - std::nullopt, - 1'000}, - {tfLimitLPToken, - 1'000, - std::nullopt, - std::nullopt, - std::nullopt, - std::nullopt}, - {tfLimitLPToken, - 1'000, - USD(100), - std::nullopt, - std::nullopt, - std::nullopt}, - {tfLimitLPToken, - std::nullopt, - USD(100), - XRP(100), - std::nullopt, - std::nullopt}, - {tfLimitLPToken, - std::nullopt, - XRP(100), - std::nullopt, - STAmount{USD, 1, -1}, - 1'000}, - {tfTwoAssetIfEmpty, - std::nullopt, - std::nullopt, - std::nullopt, - std::nullopt, - 1'000}, - {tfTwoAssetIfEmpty, - 1'000, - std::nullopt, - std::nullopt, - std::nullopt, - std::nullopt}, - {tfTwoAssetIfEmpty, - std::nullopt, - XRP(100), - USD(100), - STAmount{USD, 1, -1}, - std::nullopt}, + {tfLPToken, 1'000, std::nullopt, USD(100), std::nullopt, std::nullopt}, + {tfLPToken, 1'000, XRP(100), std::nullopt, std::nullopt, std::nullopt}, + {tfLPToken, 1'000, std::nullopt, std::nullopt, STAmount{USD, 1, -1}, std::nullopt}, + {tfLPToken, std::nullopt, USD(100), std::nullopt, STAmount{USD, 1, -1}, std::nullopt}, + {tfLPToken, 1'000, XRP(100), std::nullopt, STAmount{USD, 1, -1}, std::nullopt}, + {tfLPToken, 1'000, std::nullopt, std::nullopt, std::nullopt, 1'000}, + {tfSingleAsset, 1'000, std::nullopt, std::nullopt, std::nullopt, std::nullopt}, + {tfSingleAsset, std::nullopt, std::nullopt, USD(100), std::nullopt, std::nullopt}, + {tfSingleAsset, std::nullopt, std::nullopt, std::nullopt, STAmount{USD, 1, -1}, std::nullopt}, + {tfSingleAsset, std::nullopt, USD(100), std::nullopt, std::nullopt, 1'000}, + {tfTwoAsset, 1'000, std::nullopt, std::nullopt, std::nullopt, std::nullopt}, + {tfTwoAsset, std::nullopt, XRP(100), USD(100), STAmount{USD, 1, -1}, std::nullopt}, + {tfTwoAsset, std::nullopt, XRP(100), std::nullopt, std::nullopt, std::nullopt}, + {tfTwoAsset, std::nullopt, XRP(100), USD(100), std::nullopt, 1'000}, + {tfTwoAsset, std::nullopt, std::nullopt, USD(100), STAmount{USD, 1, -1}, std::nullopt}, + {tfOneAssetLPToken, 1'000, std::nullopt, std::nullopt, std::nullopt, std::nullopt}, + {tfOneAssetLPToken, std::nullopt, XRP(100), USD(100), std::nullopt, std::nullopt}, + {tfOneAssetLPToken, std::nullopt, XRP(100), std::nullopt, STAmount{USD, 1, -1}, std::nullopt}, + {tfOneAssetLPToken, 1'000, XRP(100), std::nullopt, std::nullopt, 1'000}, + {tfLimitLPToken, 1'000, std::nullopt, std::nullopt, std::nullopt, std::nullopt}, + {tfLimitLPToken, 1'000, USD(100), std::nullopt, std::nullopt, std::nullopt}, + {tfLimitLPToken, std::nullopt, USD(100), XRP(100), std::nullopt, std::nullopt}, + {tfLimitLPToken, std::nullopt, XRP(100), std::nullopt, STAmount{USD, 1, -1}, 1'000}, + {tfTwoAssetIfEmpty, std::nullopt, std::nullopt, std::nullopt, std::nullopt, 1'000}, + {tfTwoAssetIfEmpty, 1'000, std::nullopt, std::nullopt, std::nullopt, std::nullopt}, + {tfTwoAssetIfEmpty, std::nullopt, XRP(100), USD(100), STAmount{USD, 1, -1}, std::nullopt}, {tfTwoAssetIfEmpty | tfLPToken, std::nullopt, XRP(100), @@ -637,34 +465,23 @@ private: Json::Value jv = Json::objectValue; jv[jss::Account] = alice.human(); jv[jss::TransactionType] = jss::AMMDeposit; - jv[jss::Asset] = - STIssue(sfAsset, XRP).getJson(JsonOptions::none); - jv[jss::Asset2] = - STIssue(sfAsset, USD).getJson(JsonOptions::none); + jv[jss::Asset] = STIssue(sfAsset, XRP).getJson(JsonOptions::none); + jv[jss::Asset2] = STIssue(sfAsset, USD).getJson(JsonOptions::none); jv[jss::Fee] = "-1"; env(jv, ter(temBAD_FEE)); } // Invalid tokens - ammAlice.deposit( - alice, 0, std::nullopt, std::nullopt, ter(temBAD_AMM_TOKENS)); - ammAlice.deposit( - alice, - IOUAmount{-1}, - std::nullopt, - std::nullopt, - ter(temBAD_AMM_TOKENS)); + ammAlice.deposit(alice, 0, std::nullopt, std::nullopt, ter(temBAD_AMM_TOKENS)); + ammAlice.deposit(alice, IOUAmount{-1}, std::nullopt, std::nullopt, ter(temBAD_AMM_TOKENS)); { Json::Value jv = Json::objectValue; jv[jss::Account] = alice.human(); jv[jss::TransactionType] = jss::AMMDeposit; - jv[jss::Asset] = - STIssue(sfAsset, XRP).getJson(JsonOptions::none); - jv[jss::Asset2] = - STIssue(sfAsset, USD).getJson(JsonOptions::none); - jv[jss::LPTokenOut] = - USD(100).value().getJson(JsonOptions::none); + jv[jss::Asset] = STIssue(sfAsset, XRP).getJson(JsonOptions::none); + jv[jss::Asset2] = STIssue(sfAsset, USD).getJson(JsonOptions::none); + jv[jss::LPTokenOut] = USD(100).value().getJson(JsonOptions::none); jv[jss::Flags] = tfLPToken; env(jv, ter(temBAD_AMM_TOKENS)); } @@ -700,63 +517,21 @@ private: } // Depositing mismatched token, invalid Asset1In.issue - ammAlice.deposit( - alice, - GBP(100), - std::nullopt, - std::nullopt, - std::nullopt, - ter(temBAD_AMM_TOKENS)); + ammAlice.deposit(alice, GBP(100), std::nullopt, std::nullopt, std::nullopt, ter(temBAD_AMM_TOKENS)); // Depositing mismatched token, invalid Asset2In.issue - ammAlice.deposit( - alice, - USD(100), - GBP(100), - std::nullopt, - std::nullopt, - ter(temBAD_AMM_TOKENS)); + ammAlice.deposit(alice, USD(100), GBP(100), std::nullopt, std::nullopt, ter(temBAD_AMM_TOKENS)); // Depositing mismatched token, Asset1In.issue == Asset2In.issue - ammAlice.deposit( - alice, - USD(100), - USD(100), - std::nullopt, - std::nullopt, - ter(temBAD_AMM_TOKENS)); + ammAlice.deposit(alice, USD(100), USD(100), std::nullopt, std::nullopt, ter(temBAD_AMM_TOKENS)); // Invalid amount value - ammAlice.deposit( - alice, - USD(0), - std::nullopt, - std::nullopt, - std::nullopt, - ter(temBAD_AMOUNT)); - ammAlice.deposit( - alice, - USD(-1'000), - std::nullopt, - std::nullopt, - std::nullopt, - ter(temBAD_AMOUNT)); - ammAlice.deposit( - alice, - USD(10), - std::nullopt, - USD(-1), - std::nullopt, - ter(temBAD_AMOUNT)); + ammAlice.deposit(alice, USD(0), std::nullopt, std::nullopt, std::nullopt, ter(temBAD_AMOUNT)); + ammAlice.deposit(alice, USD(-1'000), std::nullopt, std::nullopt, std::nullopt, ter(temBAD_AMOUNT)); + ammAlice.deposit(alice, USD(10), std::nullopt, USD(-1), std::nullopt, ter(temBAD_AMOUNT)); // Bad currency - ammAlice.deposit( - alice, - BAD(100), - std::nullopt, - std::nullopt, - std::nullopt, - ter(temBAD_CURRENCY)); + ammAlice.deposit(alice, BAD(100), std::nullopt, std::nullopt, std::nullopt, ter(temBAD_CURRENCY)); // Invalid Account Account bad("bad"); @@ -816,54 +591,28 @@ private: // Deposit amount is invalid // Calculated amount to deposit is 98,000,000 - ammAlice.deposit( - alice, - USD(0), - std::nullopt, - STAmount{USD, 1, -1}, - std::nullopt, - ter(tecUNFUNDED_AMM)); + ammAlice.deposit(alice, USD(0), std::nullopt, STAmount{USD, 1, -1}, std::nullopt, ter(tecUNFUNDED_AMM)); // Calculated amount is 0 - ammAlice.deposit( - alice, - USD(0), - std::nullopt, - STAmount{USD, 2'000, -6}, - std::nullopt, - ter(tecAMM_FAILED)); + ammAlice.deposit(alice, USD(0), std::nullopt, STAmount{USD, 2'000, -6}, std::nullopt, ter(tecAMM_FAILED)); // Deposit non-empty AMM - ammAlice.deposit( - carol, - XRP(100), - USD(100), - std::nullopt, - tfTwoAssetIfEmpty, - ter(tecAMM_NOT_EMPTY)); + ammAlice.deposit(carol, XRP(100), USD(100), std::nullopt, tfTwoAssetIfEmpty, ter(tecAMM_NOT_EMPTY)); }); // Tiny deposit testAMM( [&](AMM& ammAlice, Env& env) { - auto const enabledV1_3 = - env.current()->rules().enabled(fixAMMv1_3); - auto const err = - !enabledV1_3 ? ter(temBAD_AMOUNT) : ter(tesSUCCESS); + auto const enabledV1_3 = env.current()->rules().enabled(fixAMMv1_3); + auto const err = !enabledV1_3 ? ter(temBAD_AMOUNT) : ter(tesSUCCESS); // Pre-amendment XRP deposit side is rounded to 0 // and deposit fails. // Post-amendment XRP deposit side is rounded to 1 // and deposit succeeds. - ammAlice.deposit( - carol, IOUAmount{1, -4}, std::nullopt, std::nullopt, err); + ammAlice.deposit(carol, IOUAmount{1, -4}, std::nullopt, std::nullopt, err); // Pre/post-amendment LPTokens is rounded to 0 and deposit // fails with tecAMM_INVALID_TOKENS. ammAlice.deposit( - carol, - STAmount{USD, 1, -12}, - std::nullopt, - std::nullopt, - std::nullopt, - ter(tecAMM_INVALID_TOKENS)); + carol, STAmount{USD, 1, -12}, std::nullopt, std::nullopt, std::nullopt, ter(tecAMM_INVALID_TOKENS)); }, std::nullopt, 0, @@ -873,8 +622,7 @@ private: // Invalid AMM testAMM([&](AMM& ammAlice, Env& env) { ammAlice.withdrawAll(alice); - ammAlice.deposit( - alice, 10'000, std::nullopt, std::nullopt, ter(terNO_AMM)); + ammAlice.deposit(alice, 10'000, std::nullopt, std::nullopt, ter(terNO_AMM)); }); // Globally frozen asset @@ -890,33 +638,10 @@ private: // If the issuer set global freeze, the holder cannot // deposit the other non-frozen token when AMMClawback is // enabled. - ammAlice.deposit( - carol, - XRP(100), - std::nullopt, - std::nullopt, - std::nullopt, - ter(tecFROZEN)); - ammAlice.deposit( - carol, - USD(100), - std::nullopt, - std::nullopt, - std::nullopt, - ter(tecFROZEN)); - ammAlice.deposit( - carol, - 1'000'000, - std::nullopt, - std::nullopt, - ter(tecFROZEN)); - ammAlice.deposit( - carol, - XRP(100), - USD(100), - std::nullopt, - std::nullopt, - ter(tecFROZEN)); + ammAlice.deposit(carol, XRP(100), std::nullopt, std::nullopt, std::nullopt, ter(tecFROZEN)); + ammAlice.deposit(carol, USD(100), std::nullopt, std::nullopt, std::nullopt, ter(tecFROZEN)); + ammAlice.deposit(carol, 1'000'000, std::nullopt, std::nullopt, ter(tecFROZEN)); + ammAlice.deposit(carol, XRP(100), USD(100), std::nullopt, std::nullopt, ter(tecFROZEN)); }, std::nullopt, 0, @@ -935,50 +660,18 @@ private: else // Cannot deposit non-frozen token if the other token is // frozen when AMMClawback is enabled - ammAlice.deposit( - carol, - XRP(100), - std::nullopt, - std::nullopt, - std::nullopt, - ter(tecFROZEN)); + ammAlice.deposit(carol, XRP(100), std::nullopt, std::nullopt, std::nullopt, ter(tecFROZEN)); - ammAlice.deposit( - carol, - 1'000'000, - std::nullopt, - std::nullopt, - ter(tecFROZEN)); - ammAlice.deposit( - carol, - USD(100), - std::nullopt, - std::nullopt, - std::nullopt, - ter(tecFROZEN)); + ammAlice.deposit(carol, 1'000'000, std::nullopt, std::nullopt, ter(tecFROZEN)); + ammAlice.deposit(carol, USD(100), std::nullopt, std::nullopt, std::nullopt, ter(tecFROZEN)); env(trust(gw, carol["USD"](0), tfClearFreeze)); // Individually frozen AMM - env(trust( - gw, - STAmount{ - Issue{gw["USD"].currency, ammAlice.ammAccount()}, 0}, - tfSetFreeze)); + env(trust(gw, STAmount{Issue{gw["USD"].currency, ammAlice.ammAccount()}, 0}, tfSetFreeze)); env.close(); // Can deposit non-frozen token ammAlice.deposit(carol, XRP(100)); - ammAlice.deposit( - carol, - 1'000'000, - std::nullopt, - std::nullopt, - ter(tecFROZEN)); - ammAlice.deposit( - carol, - USD(100), - std::nullopt, - std::nullopt, - std::nullopt, - ter(tecFROZEN)); + ammAlice.deposit(carol, 1'000'000, std::nullopt, std::nullopt, ter(tecFROZEN)); + ammAlice.deposit(carol, USD(100), std::nullopt, std::nullopt, std::nullopt, ter(tecFROZEN)); }, std::nullopt, 0, @@ -991,41 +684,15 @@ private: env(trust(gw, carol["USD"](0), tfSetFreeze)); env(trust(gw, carol["BTC"](0), tfSetFreeze)); env.close(); - ammAlice.deposit( - carol, - 1'000'000, - std::nullopt, - std::nullopt, - ter(tecFROZEN)); - ammAlice.deposit( - carol, - USD(100), - std::nullopt, - std::nullopt, - std::nullopt, - ter(tecFROZEN)); + ammAlice.deposit(carol, 1'000'000, std::nullopt, std::nullopt, ter(tecFROZEN)); + ammAlice.deposit(carol, USD(100), std::nullopt, std::nullopt, std::nullopt, ter(tecFROZEN)); env(trust(gw, carol["USD"](0), tfClearFreeze)); // Individually frozen AMM - env(trust( - gw, - STAmount{ - Issue{gw["USD"].currency, ammAlice.ammAccount()}, 0}, - tfSetFreeze)); + env(trust(gw, STAmount{Issue{gw["USD"].currency, ammAlice.ammAccount()}, 0}, tfSetFreeze)); env.close(); // Cannot deposit non-frozen token - ammAlice.deposit( - carol, - 1'000'000, - std::nullopt, - std::nullopt, - ter(tecFROZEN)); - ammAlice.deposit( - carol, - USD(100), - BTC(0.01), - std::nullopt, - std::nullopt, - ter(tecFROZEN)); + ammAlice.deposit(carol, 1'000'000, std::nullopt, std::nullopt, ter(tecFROZEN)); + ammAlice.deposit(carol, USD(100), BTC(0.01), std::nullopt, std::nullopt, ter(tecFROZEN)); }, {{USD(20'000), BTC(0.5)}}); @@ -1050,21 +717,9 @@ private: // if featureAMMClawback is enabled, bob can not deposit XRP // because he's not authorized to hold the paired token // gw["USD"]. - amm.deposit( - bob, - XRP(10), - std::nullopt, - std::nullopt, - std::nullopt, - ter(tecNO_AUTH)); + amm.deposit(bob, XRP(10), std::nullopt, std::nullopt, std::nullopt, ter(tecNO_AUTH)); else - amm.deposit( - bob, - XRP(10), - std::nullopt, - std::nullopt, - std::nullopt, - ter(tesSUCCESS)); + amm.deposit(bob, XRP(10), std::nullopt, std::nullopt, std::nullopt, ter(tesSUCCESS)); } // Insufficient XRP balance @@ -1073,26 +728,14 @@ private: env.close(); // Adds LPT trustline ammAlice.deposit(bob, XRP(10)); - ammAlice.deposit( - bob, - XRP(1'000), - std::nullopt, - std::nullopt, - std::nullopt, - ter(tecUNFUNDED_AMM)); + ammAlice.deposit(bob, XRP(1'000), std::nullopt, std::nullopt, std::nullopt, ter(tecUNFUNDED_AMM)); }); // Insufficient USD balance testAMM([&](AMM& ammAlice, Env& env) { fund(env, gw, {bob}, {USD(1'000)}, Fund::Acct); env.close(); - ammAlice.deposit( - bob, - USD(1'001), - std::nullopt, - std::nullopt, - std::nullopt, - ter(tecUNFUNDED_AMM)); + ammAlice.deposit(bob, USD(1'001), std::nullopt, std::nullopt, std::nullopt, ter(tecUNFUNDED_AMM)); }); // Insufficient USD balance by tokens @@ -1135,8 +778,7 @@ private: // Insufficient reserve, XRP/IOU { Env env(*this); - auto const starting_xrp = - reserve(env, 4) + env.current()->fees().base * 4; + auto const starting_xrp = reserve(env, 4) + env.current()->fees().base * 4; env.fund(XRP(10'000), gw); env.fund(XRP(10'000), alice); env.fund(starting_xrp, carol); @@ -1149,29 +791,16 @@ private: env(offer(carol, XRP(100), USD(101))); env(offer(carol, XRP(100), USD(102))); AMM ammAlice(env, alice, XRP(1'000), USD(1'000)); - ammAlice.deposit( - carol, - XRP(100), - std::nullopt, - std::nullopt, - std::nullopt, - ter(tecINSUF_RESERVE_LINE)); + ammAlice.deposit(carol, XRP(100), std::nullopt, std::nullopt, std::nullopt, ter(tecINSUF_RESERVE_LINE)); env(offer(carol, XRP(100), USD(103))); - ammAlice.deposit( - carol, - USD(100), - std::nullopt, - std::nullopt, - std::nullopt, - ter(tecINSUF_RESERVE_LINE)); + ammAlice.deposit(carol, USD(100), std::nullopt, std::nullopt, std::nullopt, ter(tecINSUF_RESERVE_LINE)); } // Insufficient reserve, IOU/IOU { Env env(*this); - auto const starting_xrp = - reserve(env, 4) + env.current()->fees().base * 4; + auto const starting_xrp = reserve(env, 4) + env.current()->fees().base * 4; env.fund(XRP(10'000), gw); env.fund(XRP(10'000), alice); env.fund(starting_xrp, carol); @@ -1188,22 +817,14 @@ private: env(offer(carol, XRP(100), USD(101))); env(offer(carol, XRP(100), USD(102))); AMM ammAlice(env, alice, XRP(1'000), USD(1'000)); - ammAlice.deposit( - carol, - XRP(100), - std::nullopt, - std::nullopt, - std::nullopt, - ter(tecINSUF_RESERVE_LINE)); + ammAlice.deposit(carol, XRP(100), std::nullopt, std::nullopt, std::nullopt, ter(tecINSUF_RESERVE_LINE)); } // Invalid min testAMM([&](AMM& ammAlice, Env& env) { // min tokens can't be <= zero - ammAlice.deposit( - carol, 0, XRP(100), tfSingleAsset, ter(temBAD_AMM_TOKENS)); - ammAlice.deposit( - carol, -1, XRP(100), tfSingleAsset, ter(temBAD_AMM_TOKENS)); + ammAlice.deposit(carol, 0, XRP(100), tfSingleAsset, ter(temBAD_AMM_TOKENS)); + ammAlice.deposit(carol, -1, XRP(100), tfSingleAsset, ter(temBAD_AMM_TOKENS)); ammAlice.deposit( carol, 0, @@ -1328,49 +949,36 @@ private: // Equal deposit, tokens rounded to 0 testAMM([&](AMM& amm, Env& env) { - amm.deposit(DepositArg{ - .tokens = IOUAmount{1, -12}, - .err = ter(tecAMM_INVALID_TOKENS)}); + amm.deposit(DepositArg{.tokens = IOUAmount{1, -12}, .err = ter(tecAMM_INVALID_TOKENS)}); }); // Equal deposit limit, tokens rounded to 0 testAMM( [&](AMM& amm, Env& env) { amm.deposit(DepositArg{ - .asset1In = STAmount{USD, 1, -15}, - .asset2In = XRPAmount{1}, - .err = ter(tecAMM_INVALID_TOKENS)}); + .asset1In = STAmount{USD, 1, -15}, .asset2In = XRPAmount{1}, .err = ter(tecAMM_INVALID_TOKENS)}); }, - {.pool = {{USD(1'000'000), XRP(1'000'000)}}, - .features = {features - fixAMMv1_3}}); + {.pool = {{USD(1'000'000), XRP(1'000'000)}}, .features = {features - fixAMMv1_3}}); testAMM([&](AMM& amm, Env& env) { amm.deposit(DepositArg{ - .asset1In = STAmount{USD, 1, -15}, - .asset2In = XRPAmount{1}, - .err = ter(tecAMM_INVALID_TOKENS)}); + .asset1In = STAmount{USD, 1, -15}, .asset2In = XRPAmount{1}, .err = ter(tecAMM_INVALID_TOKENS)}); }); // Single deposit by asset, tokens rounded to 0 testAMM([&](AMM& amm, Env& env) { - amm.deposit(DepositArg{ - .asset1In = STAmount{USD, 1, -15}, - .err = ter(tecAMM_INVALID_TOKENS)}); + amm.deposit(DepositArg{.asset1In = STAmount{USD, 1, -15}, .err = ter(tecAMM_INVALID_TOKENS)}); }); // Single deposit by tokens, tokens rounded to 0 testAMM([&](AMM& amm, Env& env) { amm.deposit(DepositArg{ - .tokens = IOUAmount{1, -10}, - .asset1In = STAmount{USD, 1, -15}, - .err = ter(tecAMM_INVALID_TOKENS)}); + .tokens = IOUAmount{1, -10}, .asset1In = STAmount{USD, 1, -15}, .err = ter(tecAMM_INVALID_TOKENS)}); }); - // Single deposit with eprice, tokens rounded to 0 + // Single deposit with EPrice, tokens rounded to 0 testAMM([&](AMM& amm, Env& env) { amm.deposit(DepositArg{ - .asset1In = STAmount{USD, 1, -15}, - .maxEP = STAmount{USD, 1, -1}, - .err = ter(tecAMM_INVALID_TOKENS)}); + .asset1In = STAmount{USD, 1, -15}, .maxEP = STAmount{USD, 1, -1}, .err = ter(tecAMM_INVALID_TOKENS)}); }); } @@ -1386,21 +994,18 @@ private: testAMM([&](AMM& ammAlice, Env& env) { auto const baseFee = env.current()->fees().base; ammAlice.deposit(carol, 1'000'000); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(11'000), USD(11'000), IOUAmount{11'000'000, 0})); + BEAST_EXPECT(ammAlice.expectBalances(XRP(11'000), USD(11'000), IOUAmount{11'000'000, 0})); // 30,000 less deposited 1,000 BEAST_EXPECT(expectHolding(env, carol, USD(29'000))); // 30,000 less deposited 1,000 and 10 drops tx fee - BEAST_EXPECT(expectLedgerEntryRoot( - env, carol, XRPAmount{29'000'000'000 - baseFee})); + BEAST_EXPECT(expectLedgerEntryRoot(env, carol, XRPAmount{29'000'000'000 - baseFee})); }); // equal asset deposit: unit test to exercise the rounding-down of // LPTokens in the AMMHelpers.cpp: adjustLPTokens calculations // The LPTokens need to have 16 significant digits and a fractional part for (Number const& deltaLPTokens : - {Number{UINT64_C(100000'0000000009), -10}, - Number{UINT64_C(100000'0000000001), -10}}) + {Number{UINT64_C(100000'0000000009), -10}, Number{UINT64_C(100000'0000000001), -10}}) { testAMM([&](AMM& ammAlice, Env& env) { // initial LPToken balance @@ -1408,8 +1013,7 @@ private: IOUAmount const newLPTokens{deltaLPTokens}; // carol performs a two-asset deposit - ammAlice.deposit( - DepositArg{.account = carol, .tokens = newLPTokens}); + ammAlice.deposit(DepositArg{.account = carol, .tokens = newLPTokens}); IOUAmount const finalLPToken = ammAlice.getLPTokensBalance(); @@ -1436,16 +1040,12 @@ private: // initial LPTokens (1e7) + newLPTokens BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'000) + depositXRP, - USD(10'000) + depositUSD, - IOUAmount{1, 7} + newLPTokens)); + XRP(10'000) + depositXRP, USD(10'000) + depositUSD, IOUAmount{1, 7} + newLPTokens)); // 30,000 less deposited depositUSD - BEAST_EXPECT( - expectHolding(env, carol, USD(30'000) - depositUSD)); + BEAST_EXPECT(expectHolding(env, carol, USD(30'000) - depositUSD)); // 30,000 less deposited depositXRP and 10 drops tx fee - BEAST_EXPECT(expectLedgerEntryRoot( - env, carol, XRP(30'000) - depositXRP - txfee(env, 1))); + BEAST_EXPECT(expectLedgerEntryRoot(env, carol, XRP(30'000) - depositXRP - txfee(env, 1))); }); } @@ -1456,85 +1056,66 @@ private: // Deposit 100USD/100XRP testAMM([&](AMM& ammAlice, Env&) { ammAlice.deposit(carol, USD(100), XRP(100)); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'100), USD(10'100), IOUAmount{10'100'000, 0})); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'100), USD(10'100), IOUAmount{10'100'000, 0})); }); // Equal limit deposit. // Try to deposit 200USD/100XRP. Is truncated to 100USD/100XRP. testAMM([&](AMM& ammAlice, Env&) { ammAlice.deposit(carol, USD(200), XRP(100)); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'100), USD(10'100), IOUAmount{10'100'000, 0})); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'100), USD(10'100), IOUAmount{10'100'000, 0})); }); // Try to deposit 100USD/200XRP. Is truncated to 100USD/100XRP. testAMM([&](AMM& ammAlice, Env&) { ammAlice.deposit(carol, USD(100), XRP(200)); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'100), USD(10'100), IOUAmount{10'100'000, 0})); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'100), USD(10'100), IOUAmount{10'100'000, 0})); }); // Single deposit: 1000 USD testAMM([&](AMM& ammAlice, Env&) { ammAlice.deposit(carol, USD(1'000)); BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'000), - STAmount{USD, UINT64_C(10'999'99999999999), -11}, - IOUAmount{10'488'088'48170151, -8})); + XRP(10'000), STAmount{USD, UINT64_C(10'999'99999999999), -11}, IOUAmount{10'488'088'48170151, -8})); }); // Single deposit: 1000 XRP testAMM([&](AMM& ammAlice, Env&) { ammAlice.deposit(carol, XRP(1'000)); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(11'000), USD(10'000), IOUAmount{10'488'088'48170151, -8})); + BEAST_EXPECT(ammAlice.expectBalances(XRP(11'000), USD(10'000), IOUAmount{10'488'088'48170151, -8})); }); // Single deposit: 100000 tokens worth of USD testAMM([&](AMM& ammAlice, Env&) { ammAlice.deposit(carol, 100000, USD(205)); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'000), USD(10'201), IOUAmount{10'100'000, 0})); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), USD(10'201), IOUAmount{10'100'000, 0})); }); // Single deposit: 100000 tokens worth of XRP testAMM([&](AMM& ammAlice, Env& env) { ammAlice.deposit(carol, 100'000, XRP(205)); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'201), USD(10'000), IOUAmount{10'100'000, 0})); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'201), USD(10'000), IOUAmount{10'100'000, 0})); }); // Single deposit with EP not exceeding specified: // 100USD with EP not to exceed 0.1 (AssetIn/TokensOut) testAMM([&](AMM& ammAlice, Env&) { - ammAlice.deposit( - carol, USD(1'000), std::nullopt, STAmount{USD, 1, -1}); + ammAlice.deposit(carol, USD(1'000), std::nullopt, STAmount{USD, 1, -1}); BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'000), - STAmount{USD, UINT64_C(10'999'99999999999), -11}, - IOUAmount{10'488'088'48170151, -8})); + XRP(10'000), STAmount{USD, UINT64_C(10'999'99999999999), -11}, IOUAmount{10'488'088'48170151, -8})); }); // Single deposit with EP not exceeding specified: // 100USD with EP not to exceed 0.002004 (AssetIn/TokensOut) testAMM([&](AMM& ammAlice, Env&) { - ammAlice.deposit( - carol, USD(100), std::nullopt, STAmount{USD, 2004, -6}); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'000), - STAmount{USD, 10'080'16, -2}, - IOUAmount{10'040'000, 0})); + ammAlice.deposit(carol, USD(100), std::nullopt, STAmount{USD, 2004, -6}); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), STAmount{USD, 10'080'16, -2}, IOUAmount{10'040'000, 0})); }); // Single deposit with EP not exceeding specified: // 0USD with EP not to exceed 0.002004 (AssetIn/TokensOut) testAMM([&](AMM& ammAlice, Env&) { - ammAlice.deposit( - carol, USD(0), std::nullopt, STAmount{USD, 2004, -6}); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'000), - STAmount{USD, 10'080'16, -2}, - IOUAmount{10'040'000, 0})); + ammAlice.deposit(carol, USD(0), std::nullopt, STAmount{USD, 2004, -6}); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), STAmount{USD, 10'080'16, -2}, IOUAmount{10'040'000, 0})); }); // IOU to IOU + transfer fee @@ -1544,15 +1125,13 @@ private: env(rate(gw, 1.25)); env.close(); AMM ammAlice(env, alice, USD(20'000), BTC(0.5)); - BEAST_EXPECT(ammAlice.expectBalances( - USD(20'000), BTC(0.5), IOUAmount{100, 0})); + BEAST_EXPECT(ammAlice.expectBalances(USD(20'000), BTC(0.5), IOUAmount{100, 0})); BEAST_EXPECT(expectHolding(env, alice, USD(0))); BEAST_EXPECT(expectHolding(env, alice, BTC(0))); fund(env, gw, {carol}, {USD(2'000), BTC(0.05)}, Fund::Acct); // no transfer fee on deposit ammAlice.deposit(carol, 10); - BEAST_EXPECT(ammAlice.expectBalances( - USD(22'000), BTC(0.55), IOUAmount{110, 0})); + BEAST_EXPECT(ammAlice.expectBalances(USD(22'000), BTC(0.55), IOUAmount{110, 0})); BEAST_EXPECT(expectHolding(env, carol, USD(0))); BEAST_EXPECT(expectHolding(env, carol, BTC(0))); } @@ -1561,25 +1140,19 @@ private: testAMM([&](AMM& ammAlice, Env&) { ammAlice.deposit(carol, IOUAmount{1, -3}); BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount{10'000'000'001}, - STAmount{USD, UINT64_C(10'000'000001), -6}, - IOUAmount{10'000'000'001, -3})); + XRPAmount{10'000'000'001}, STAmount{USD, UINT64_C(10'000'000001), -6}, IOUAmount{10'000'000'001, -3})); BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount{1, -3})); }); testAMM([&](AMM& ammAlice, Env&) { ammAlice.deposit(carol, XRPAmount{1}); - BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount{10'000'000'001}, - USD(10'000), - IOUAmount{1'000'000'000049999, -8})); + BEAST_EXPECT( + ammAlice.expectBalances(XRPAmount{10'000'000'001}, USD(10'000), IOUAmount{1'000'000'000049999, -8})); BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount{49999, -8})); }); testAMM([&](AMM& ammAlice, Env&) { ammAlice.deposit(carol, STAmount{USD, 1, -10}); BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'000), - STAmount{USD, UINT64_C(10'000'00000000008), -11}, - IOUAmount{10'000'000'00000004, -8})); + XRP(10'000), STAmount{USD, UINT64_C(10'000'00000000008), -11}, IOUAmount{10'000'000'00000004, -8})); BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount{4, -8})); }); @@ -1589,88 +1162,48 @@ private: Env env(*this, feat); env.fund(XRP(30000), gw); AMM ammGw(env, gw, XRP(10'000), USD(10'000)); - BEAST_EXPECT( - ammGw.expectBalances(XRP(10'000), USD(10'000), ammGw.tokens())); + BEAST_EXPECT(ammGw.expectBalances(XRP(10'000), USD(10'000), ammGw.tokens())); ammGw.deposit(gw, 1'000'000); - BEAST_EXPECT(ammGw.expectBalances( - XRP(11'000), USD(11'000), IOUAmount{11'000'000})); + BEAST_EXPECT(ammGw.expectBalances(XRP(11'000), USD(11'000), IOUAmount{11'000'000})); ammGw.deposit(gw, USD(1'000)); BEAST_EXPECT(ammGw.expectBalances( - XRP(11'000), - STAmount{USD, UINT64_C(11'999'99999999998), -11}, - IOUAmount{11'489'125'29307605, -8})); + XRP(11'000), STAmount{USD, UINT64_C(11'999'99999999998), -11}, IOUAmount{11'489'125'29307605, -8})); } // Issuer deposit testAMM([&](AMM& ammAlice, Env& env) { ammAlice.deposit(gw, 1'000'000); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(11'000), USD(11'000), IOUAmount{11'000'000})); + BEAST_EXPECT(ammAlice.expectBalances(XRP(11'000), USD(11'000), IOUAmount{11'000'000})); ammAlice.deposit(gw, USD(1'000)); BEAST_EXPECT(ammAlice.expectBalances( - XRP(11'000), - STAmount{USD, UINT64_C(11'999'99999999998), -11}, - IOUAmount{11'489'125'29307605, -8})); + XRP(11'000), STAmount{USD, UINT64_C(11'999'99999999998), -11}, IOUAmount{11'489'125'29307605, -8})); }); // Min deposit testAMM([&](AMM& ammAlice, Env& env) { // Equal deposit by tokens ammAlice.deposit( - carol, - 1'000'000, - XRP(1'000), - USD(1'000), - std::nullopt, - tfLPToken, - std::nullopt, - std::nullopt); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(11'000), USD(11'000), IOUAmount{11'000'000, 0})); + carol, 1'000'000, XRP(1'000), USD(1'000), std::nullopt, tfLPToken, std::nullopt, std::nullopt); + BEAST_EXPECT(ammAlice.expectBalances(XRP(11'000), USD(11'000), IOUAmount{11'000'000, 0})); }); testAMM([&](AMM& ammAlice, Env& env) { // Equal deposit by asset ammAlice.deposit( - carol, - 1'000'000, - XRP(1'000), - USD(1'000), - std::nullopt, - tfTwoAsset, - std::nullopt, - std::nullopt); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(11'000), USD(11'000), IOUAmount{11'000'000, 0})); + carol, 1'000'000, XRP(1'000), USD(1'000), std::nullopt, tfTwoAsset, std::nullopt, std::nullopt); + BEAST_EXPECT(ammAlice.expectBalances(XRP(11'000), USD(11'000), IOUAmount{11'000'000, 0})); }); testAMM([&](AMM& ammAlice, Env& env) { // Single deposit by asset ammAlice.deposit( - carol, - 488'088, - XRP(1'000), - std::nullopt, - std::nullopt, - tfSingleAsset, - std::nullopt, - std::nullopt); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(11'000), USD(10'000), IOUAmount{10'488'088'48170151, -8})); + carol, 488'088, XRP(1'000), std::nullopt, std::nullopt, tfSingleAsset, std::nullopt, std::nullopt); + BEAST_EXPECT(ammAlice.expectBalances(XRP(11'000), USD(10'000), IOUAmount{10'488'088'48170151, -8})); }); testAMM([&](AMM& ammAlice, Env& env) { // Single deposit by asset ammAlice.deposit( - carol, - 488'088, - USD(1'000), - std::nullopt, - std::nullopt, - tfSingleAsset, - std::nullopt, - std::nullopt); + carol, 488'088, USD(1'000), std::nullopt, std::nullopt, tfSingleAsset, std::nullopt, std::nullopt); BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'000), - STAmount{USD, UINT64_C(10'999'99999999999), -11}, - IOUAmount{10'488'088'48170151, -8})); + XRP(10'000), STAmount{USD, UINT64_C(10'999'99999999999), -11}, IOUAmount{10'488'088'48170151, -8})); }); } @@ -1758,96 +1291,26 @@ private: NotTEC>> invalidOptions = { // tokens, asset1Out, asset2Out, EPrice, flags, ter - {std::nullopt, - std::nullopt, - std::nullopt, - std::nullopt, - std::nullopt, - temMALFORMED}, - {std::nullopt, - std::nullopt, - std::nullopt, - std::nullopt, - tfSingleAsset | tfTwoAsset, - temMALFORMED}, - {1'000, - std::nullopt, - std::nullopt, - std::nullopt, - tfWithdrawAll, - temMALFORMED}, - {std::nullopt, - USD(0), - XRP(100), - std::nullopt, - tfWithdrawAll | tfLPToken, - temMALFORMED}, - {std::nullopt, - std::nullopt, - USD(100), - std::nullopt, - tfWithdrawAll, - temMALFORMED}, + {std::nullopt, std::nullopt, std::nullopt, std::nullopt, std::nullopt, temMALFORMED}, + {std::nullopt, std::nullopt, std::nullopt, std::nullopt, tfSingleAsset | tfTwoAsset, temMALFORMED}, + {1'000, std::nullopt, std::nullopt, std::nullopt, tfWithdrawAll, temMALFORMED}, + {std::nullopt, USD(0), XRP(100), std::nullopt, tfWithdrawAll | tfLPToken, temMALFORMED}, + {std::nullopt, std::nullopt, USD(100), std::nullopt, tfWithdrawAll, temMALFORMED}, {std::nullopt, std::nullopt, std::nullopt, std::nullopt, tfWithdrawAll | tfOneAssetWithdrawAll, temMALFORMED}, - {std::nullopt, - USD(100), - std::nullopt, - std::nullopt, - tfWithdrawAll, - temMALFORMED}, - {std::nullopt, - std::nullopt, - std::nullopt, - std::nullopt, - tfOneAssetWithdrawAll, - temMALFORMED}, - {1'000, - std::nullopt, - USD(100), - std::nullopt, - std::nullopt, - temMALFORMED}, - {std::nullopt, - std::nullopt, - std::nullopt, - IOUAmount{250, 0}, - tfWithdrawAll, - temMALFORMED}, - {1'000, - std::nullopt, - std::nullopt, - IOUAmount{250, 0}, - std::nullopt, - temMALFORMED}, - {std::nullopt, - std::nullopt, - USD(100), - IOUAmount{250, 0}, - std::nullopt, - temMALFORMED}, - {std::nullopt, - XRP(100), - USD(100), - IOUAmount{250, 0}, - std::nullopt, - temMALFORMED}, - {1'000, - XRP(100), - USD(100), - std::nullopt, - std::nullopt, - temMALFORMED}, - {std::nullopt, - XRP(100), - USD(100), - std::nullopt, - tfWithdrawAll, - temMALFORMED}}; + {std::nullopt, USD(100), std::nullopt, std::nullopt, tfWithdrawAll, temMALFORMED}, + {std::nullopt, std::nullopt, std::nullopt, std::nullopt, tfOneAssetWithdrawAll, temMALFORMED}, + {1'000, std::nullopt, USD(100), std::nullopt, std::nullopt, temMALFORMED}, + {std::nullopt, std::nullopt, std::nullopt, IOUAmount{250, 0}, tfWithdrawAll, temMALFORMED}, + {1'000, std::nullopt, std::nullopt, IOUAmount{250, 0}, std::nullopt, temMALFORMED}, + {std::nullopt, std::nullopt, USD(100), IOUAmount{250, 0}, std::nullopt, temMALFORMED}, + {std::nullopt, XRP(100), USD(100), IOUAmount{250, 0}, std::nullopt, temMALFORMED}, + {1'000, XRP(100), USD(100), std::nullopt, std::nullopt, temMALFORMED}, + {std::nullopt, XRP(100), USD(100), std::nullopt, tfWithdrawAll, temMALFORMED}}; for (auto const& it : invalidOptions) { ammAlice.withdraw( @@ -1863,69 +1326,27 @@ private: } // Invalid tokens - ammAlice.withdraw( - alice, 0, std::nullopt, std::nullopt, ter(temBAD_AMM_TOKENS)); - ammAlice.withdraw( - alice, - IOUAmount{-1}, - std::nullopt, - std::nullopt, - ter(temBAD_AMM_TOKENS)); + ammAlice.withdraw(alice, 0, std::nullopt, std::nullopt, ter(temBAD_AMM_TOKENS)); + ammAlice.withdraw(alice, IOUAmount{-1}, std::nullopt, std::nullopt, ter(temBAD_AMM_TOKENS)); // Mismatched token, invalid Asset1Out issue - ammAlice.withdraw( - alice, - GBP(100), - std::nullopt, - std::nullopt, - ter(temBAD_AMM_TOKENS)); + ammAlice.withdraw(alice, GBP(100), std::nullopt, std::nullopt, ter(temBAD_AMM_TOKENS)); // Mismatched token, invalid Asset2Out issue - ammAlice.withdraw( - alice, - USD(100), - GBP(100), - std::nullopt, - ter(temBAD_AMM_TOKENS)); + ammAlice.withdraw(alice, USD(100), GBP(100), std::nullopt, ter(temBAD_AMM_TOKENS)); // Mismatched token, Asset1Out.issue == Asset2Out.issue - ammAlice.withdraw( - alice, - USD(100), - USD(100), - std::nullopt, - ter(temBAD_AMM_TOKENS)); + ammAlice.withdraw(alice, USD(100), USD(100), std::nullopt, ter(temBAD_AMM_TOKENS)); // Invalid amount value - ammAlice.withdraw( - alice, USD(0), std::nullopt, std::nullopt, ter(temBAD_AMOUNT)); - ammAlice.withdraw( - alice, - USD(-100), - std::nullopt, - std::nullopt, - ter(temBAD_AMOUNT)); - ammAlice.withdraw( - alice, - USD(10), - std::nullopt, - IOUAmount{-1}, - ter(temBAD_AMOUNT)); + ammAlice.withdraw(alice, USD(0), std::nullopt, std::nullopt, ter(temBAD_AMOUNT)); + ammAlice.withdraw(alice, USD(-100), std::nullopt, std::nullopt, ter(temBAD_AMOUNT)); + ammAlice.withdraw(alice, USD(10), std::nullopt, IOUAmount{-1}, ter(temBAD_AMOUNT)); // Invalid amount/token value, withdraw all tokens from one side // of the pool. - ammAlice.withdraw( - alice, - USD(10'000), - std::nullopt, - std::nullopt, - ter(tecAMM_BALANCE)); - ammAlice.withdraw( - alice, - XRP(10'000), - std::nullopt, - std::nullopt, - ter(tecAMM_BALANCE)); + ammAlice.withdraw(alice, USD(10'000), std::nullopt, std::nullopt, ter(tecAMM_BALANCE)); + ammAlice.withdraw(alice, XRP(10'000), std::nullopt, std::nullopt, ter(tecAMM_BALANCE)); ammAlice.withdraw( alice, std::nullopt, @@ -1938,12 +1359,7 @@ private: ter(tecAMM_BALANCE)); // Bad currency - ammAlice.withdraw( - alice, - BAD(100), - std::nullopt, - std::nullopt, - ter(temBAD_CURRENCY)); + ammAlice.withdraw(alice, BAD(100), std::nullopt, std::nullopt, ter(temBAD_CURRENCY)); // Invalid Account Account bad("bad"); @@ -1972,31 +1388,15 @@ private: ter(terNO_AMM)); // Carol is not a Liquidity Provider - ammAlice.withdraw( - carol, 10'000, std::nullopt, std::nullopt, ter(tecAMM_BALANCE)); + ammAlice.withdraw(carol, 10'000, std::nullopt, std::nullopt, ter(tecAMM_BALANCE)); // Withdrawing from one side. // XRP by tokens - ammAlice.withdraw( - alice, - IOUAmount(9'999'999'9999, -4), - XRP(0), - std::nullopt, - ter(tecAMM_BALANCE)); + ammAlice.withdraw(alice, IOUAmount(9'999'999'9999, -4), XRP(0), std::nullopt, ter(tecAMM_BALANCE)); // USD by tokens - ammAlice.withdraw( - alice, - IOUAmount(9'999'999'9, -1), - USD(0), - std::nullopt, - ter(tecAMM_BALANCE)); + ammAlice.withdraw(alice, IOUAmount(9'999'999'9, -1), USD(0), std::nullopt, ter(tecAMM_BALANCE)); // XRP - ammAlice.withdraw( - alice, - XRP(10'000), - std::nullopt, - std::nullopt, - ter(tecAMM_BALANCE)); + ammAlice.withdraw(alice, XRP(10'000), std::nullopt, std::nullopt, ter(tecAMM_BALANCE)); // USD ammAlice.withdraw( alice, @@ -2015,17 +1415,10 @@ private: // while leaving a tiny amount in USD pool. // Post-amendment: // Most of the pool is withdrawn with remaining tiny amounts - auto err = env.enabled(fixAMMv1_3) ? ter(tesSUCCESS) - : ter(tecAMM_BALANCE); - ammAlice.withdraw( - alice, - IOUAmount{9'999'999'9999, -4}, - std::nullopt, - std::nullopt, - err); + auto err = env.enabled(fixAMMv1_3) ? ter(tesSUCCESS) : ter(tecAMM_BALANCE); + ammAlice.withdraw(alice, IOUAmount{9'999'999'9999, -4}, std::nullopt, std::nullopt, err); if (env.enabled(fixAMMv1_3)) - BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount(1), STAmount{USD, 1, -7}, IOUAmount{1, -4})); + BEAST_EXPECT(ammAlice.expectBalances(XRPAmount(1), STAmount{USD, 1, -7}, IOUAmount{1, -4})); }, std::nullopt, 0, @@ -2040,17 +1433,10 @@ private: // Equal withdraw but due to XRP precision limit, // this results in full withdraw of XRP pool only, // while leaving a tiny amount in USD pool. - auto err = env.enabled(fixAMMv1_3) ? ter(tesSUCCESS) - : ter(tecAMM_BALANCE); - ammAlice.withdraw( - alice, - IOUAmount{9'999'999'999999999, -9}, - std::nullopt, - std::nullopt, - err); + auto err = env.enabled(fixAMMv1_3) ? ter(tesSUCCESS) : ter(tecAMM_BALANCE); + ammAlice.withdraw(alice, IOUAmount{9'999'999'999999999, -9}, std::nullopt, std::nullopt, err); if (env.enabled(fixAMMv1_3)) - BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount(1), STAmount{USD, 1, -11}, IOUAmount{1, -8})); + BEAST_EXPECT(ammAlice.expectBalances(XRPAmount(1), STAmount{USD, 1, -11}, IOUAmount{1, -8})); }, std::nullopt, 0, @@ -2060,8 +1446,7 @@ private: // Invalid AMM testAMM([&](AMM& ammAlice, Env& env) { ammAlice.withdrawAll(alice); - ammAlice.withdraw( - alice, 10'000, std::nullopt, std::nullopt, ter(terNO_AMM)); + ammAlice.withdraw(alice, 10'000, std::nullopt, std::nullopt, ter(terNO_AMM)); }); // Globally frozen asset @@ -2070,10 +1455,8 @@ private: env.close(); // Can withdraw non-frozen token ammAlice.withdraw(alice, XRP(100)); - ammAlice.withdraw( - alice, USD(100), std::nullopt, std::nullopt, ter(tecFROZEN)); - ammAlice.withdraw( - alice, 1'000, std::nullopt, std::nullopt, ter(tecFROZEN)); + ammAlice.withdraw(alice, USD(100), std::nullopt, std::nullopt, ter(tecFROZEN)); + ammAlice.withdraw(alice, 1'000, std::nullopt, std::nullopt, ter(tecFROZEN)); }); // Individually frozen (AMM) account @@ -2082,22 +1465,15 @@ private: env.close(); // Can withdraw non-frozen token ammAlice.withdraw(alice, XRP(100)); - ammAlice.withdraw( - alice, 1'000, std::nullopt, std::nullopt, ter(tecFROZEN)); - ammAlice.withdraw( - alice, USD(100), std::nullopt, std::nullopt, ter(tecFROZEN)); + ammAlice.withdraw(alice, 1'000, std::nullopt, std::nullopt, ter(tecFROZEN)); + ammAlice.withdraw(alice, USD(100), std::nullopt, std::nullopt, ter(tecFROZEN)); env(trust(gw, alice["USD"](0), tfClearFreeze)); // Individually frozen AMM - env(trust( - gw, - STAmount{Issue{gw["USD"].currency, ammAlice.ammAccount()}, 0}, - tfSetFreeze)); + env(trust(gw, STAmount{Issue{gw["USD"].currency, ammAlice.ammAccount()}, 0}, tfSetFreeze)); // Can withdraw non-frozen token ammAlice.withdraw(alice, XRP(100)); - ammAlice.withdraw( - alice, 1'000, std::nullopt, std::nullopt, ter(tecFROZEN)); - ammAlice.withdraw( - alice, USD(100), std::nullopt, std::nullopt, ter(tecFROZEN)); + ammAlice.withdraw(alice, 1'000, std::nullopt, std::nullopt, ter(tecFROZEN)); + ammAlice.withdraw(alice, USD(100), std::nullopt, std::nullopt, ter(tecFROZEN)); }); // Carol withdraws more than she owns @@ -2105,17 +1481,10 @@ private: // Single deposit of 100000 worth of tokens, // which is 10% of the pool. Carol is LP now. ammAlice.deposit(carol, 1'000'000); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(11'000), USD(11'000), IOUAmount{11'000'000, 0})); + BEAST_EXPECT(ammAlice.expectBalances(XRP(11'000), USD(11'000), IOUAmount{11'000'000, 0})); - ammAlice.withdraw( - carol, - 2'000'000, - std::nullopt, - std::nullopt, - ter(tecAMM_INVALID_TOKENS)); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(11'000), USD(11'000), IOUAmount{11'000'000, 0})); + ammAlice.withdraw(carol, 2'000'000, std::nullopt, std::nullopt, ter(tecAMM_INVALID_TOKENS)); + BEAST_EXPECT(ammAlice.expectBalances(XRP(11'000), USD(11'000), IOUAmount{11'000'000, 0})); }); // Withdraw with EPrice limit. Fails to withdraw, calculated tokens @@ -2123,11 +1492,8 @@ private: testAMM( [&](AMM& ammAlice, Env& env) { ammAlice.deposit(carol, 1'000'000); - auto const err = env.enabled(fixAMMv1_3) - ? ter(tecAMM_INVALID_TOKENS) - : ter(tecAMM_FAILED); - ammAlice.withdraw( - carol, USD(100), std::nullopt, IOUAmount{500, 0}, err); + auto const err = env.enabled(fixAMMv1_3) ? ter(tecAMM_INVALID_TOKENS) : ter(tecAMM_FAILED); + ammAlice.withdraw(carol, USD(100), std::nullopt, IOUAmount{500, 0}, err); }, std::nullopt, 0, @@ -2138,48 +1504,28 @@ private: // to withdraw are greater than the LP shares. testAMM([&](AMM& ammAlice, Env&) { ammAlice.deposit(carol, 1'000'000); - ammAlice.withdraw( - carol, - USD(100), - std::nullopt, - IOUAmount{600, 0}, - ter(tecAMM_INVALID_TOKENS)); + ammAlice.withdraw(carol, USD(100), std::nullopt, IOUAmount{600, 0}, ter(tecAMM_INVALID_TOKENS)); }); // Withdraw with EPrice limit. Fails to withdraw, amount1 // to withdraw is less than 1700USD. testAMM([&](AMM& ammAlice, Env&) { ammAlice.deposit(carol, 1'000'000); - ammAlice.withdraw( - carol, - USD(1'700), - std::nullopt, - IOUAmount{520, 0}, - ter(tecAMM_FAILED)); + ammAlice.withdraw(carol, USD(1'700), std::nullopt, IOUAmount{520, 0}, ter(tecAMM_FAILED)); }); // Deposit/Withdraw the same amount with the trading fee testAMM( [&](AMM& ammAlice, Env&) { ammAlice.deposit(carol, USD(1'000)); - ammAlice.withdraw( - carol, - USD(1'000), - std::nullopt, - std::nullopt, - ter(tecAMM_INVALID_TOKENS)); + ammAlice.withdraw(carol, USD(1'000), std::nullopt, std::nullopt, ter(tecAMM_INVALID_TOKENS)); }, std::nullopt, 1'000); testAMM( [&](AMM& ammAlice, Env&) { ammAlice.deposit(carol, XRP(1'000)); - ammAlice.withdraw( - carol, - XRP(1'000), - std::nullopt, - std::nullopt, - ter(tecAMM_INVALID_TOKENS)); + ammAlice.withdraw(carol, XRP(1'000), std::nullopt, std::nullopt, ter(tecAMM_INVALID_TOKENS)); }, std::nullopt, 1'000); @@ -2187,70 +1533,33 @@ private: // Deposit/Withdraw the same amount fails due to the tokens adjustment testAMM([&](AMM& ammAlice, Env&) { ammAlice.deposit(carol, STAmount{USD, 1, -6}); - ammAlice.withdraw( - carol, - STAmount{USD, 1, -6}, - std::nullopt, - std::nullopt, - ter(tecAMM_INVALID_TOKENS)); + ammAlice.withdraw(carol, STAmount{USD, 1, -6}, std::nullopt, std::nullopt, ter(tecAMM_INVALID_TOKENS)); }); // Withdraw close to one side of the pool. Account's LP tokens // are rounded to all LP tokens. testAMM( [&](AMM& ammAlice, Env& env) { - auto const err = env.enabled(fixAMMv1_3) - ? ter(tecINVARIANT_FAILED) - : ter(tecAMM_BALANCE); + auto const err = env.enabled(fixAMMv1_3) ? ter(tecINVARIANT_FAILED) : ter(tecAMM_BALANCE); ammAlice.withdraw( - alice, - STAmount{USD, UINT64_C(9'999'999999999999), -12}, - std::nullopt, - std::nullopt, - err); + alice, STAmount{USD, UINT64_C(9'999'999999999999), -12}, std::nullopt, std::nullopt, err); }, {.features = {all, all - fixAMMv1_3}, .noLog = true}); // Tiny withdraw testAMM([&](AMM& ammAlice, Env&) { // XRP amount to withdraw is 0 - ammAlice.withdraw( - alice, - IOUAmount{1, -5}, - std::nullopt, - std::nullopt, - ter(tecAMM_FAILED)); + ammAlice.withdraw(alice, IOUAmount{1, -5}, std::nullopt, std::nullopt, ter(tecAMM_FAILED)); // Calculated tokens to withdraw are 0 - ammAlice.withdraw( - alice, - std::nullopt, - STAmount{USD, 1, -11}, - std::nullopt, - ter(tecAMM_INVALID_TOKENS)); + ammAlice.withdraw(alice, std::nullopt, STAmount{USD, 1, -11}, std::nullopt, ter(tecAMM_INVALID_TOKENS)); ammAlice.deposit(carol, STAmount{USD, 1, -10}); - ammAlice.withdraw( - carol, - std::nullopt, - STAmount{USD, 1, -9}, - std::nullopt, - ter(tecAMM_INVALID_TOKENS)); - ammAlice.withdraw( - carol, - std::nullopt, - XRPAmount{1}, - std::nullopt, - ter(tecAMM_INVALID_TOKENS)); + ammAlice.withdraw(carol, std::nullopt, STAmount{USD, 1, -9}, std::nullopt, ter(tecAMM_INVALID_TOKENS)); + ammAlice.withdraw(carol, std::nullopt, XRPAmount{1}, std::nullopt, ter(tecAMM_INVALID_TOKENS)); + ammAlice.withdraw(WithdrawArg{.tokens = IOUAmount{1, -10}, .err = ter(tecAMM_INVALID_TOKENS)}); ammAlice.withdraw(WithdrawArg{ - .tokens = IOUAmount{1, -10}, - .err = ter(tecAMM_INVALID_TOKENS)}); + .asset1Out = STAmount{USD, 1, -15}, .asset2Out = XRPAmount{1}, .err = ter(tecAMM_INVALID_TOKENS)}); ammAlice.withdraw(WithdrawArg{ - .asset1Out = STAmount{USD, 1, -15}, - .asset2Out = XRPAmount{1}, - .err = ter(tecAMM_INVALID_TOKENS)}); - ammAlice.withdraw(WithdrawArg{ - .tokens = IOUAmount{1, -10}, - .asset1Out = STAmount{USD, 1, -15}, - .err = ter(tecAMM_INVALID_TOKENS)}); + .tokens = IOUAmount{1, -10}, .asset1Out = STAmount{USD, 1, -15}, .err = ter(tecAMM_INVALID_TOKENS)}); }); } @@ -2269,31 +1578,25 @@ private: // Single deposit of 100000 worth of tokens, // which is 10% of the pool. Carol is LP now. ammAlice.deposit(carol, 1'000'000); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(11'000), USD(11'000), IOUAmount{11'000'000, 0})); - BEAST_EXPECT( - ammAlice.expectLPTokens(carol, IOUAmount{1'000'000, 0})); + BEAST_EXPECT(ammAlice.expectBalances(XRP(11'000), USD(11'000), IOUAmount{11'000'000, 0})); + BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount{1'000'000, 0})); // 30,000 less deposited 1,000 BEAST_EXPECT(expectHolding(env, carol, USD(29'000))); // 30,000 less deposited 1,000 and 10 drops tx fee - BEAST_EXPECT(expectLedgerEntryRoot( - env, carol, XRPAmount{29'000'000'000 - baseFee})); + BEAST_EXPECT(expectLedgerEntryRoot(env, carol, XRPAmount{29'000'000'000 - baseFee})); // Carol withdraws all tokens ammAlice.withdraw(carol, 1'000'000); - BEAST_EXPECT( - ammAlice.expectLPTokens(carol, IOUAmount(beast::Zero()))); + BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount(beast::Zero()))); BEAST_EXPECT(expectHolding(env, carol, USD(30'000))); - BEAST_EXPECT(expectLedgerEntryRoot( - env, carol, XRPAmount{30'000'000'000 - 2 * baseFee})); + BEAST_EXPECT(expectLedgerEntryRoot(env, carol, XRPAmount{30'000'000'000 - 2 * baseFee})); }); // Equal withdrawal by tokens 1000000, 10% // of the current pool testAMM([&](AMM& ammAlice, Env&) { ammAlice.withdraw(alice, 1'000'000); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(9'000), USD(9'000), IOUAmount{9'000'000, 0})); + BEAST_EXPECT(ammAlice.expectBalances(XRP(9'000), USD(9'000), IOUAmount{9'000'000, 0})); }); // Equal withdrawal with a limit. Withdraw XRP200. @@ -2303,15 +1606,13 @@ private: // in this case - XRP100/USD100. testAMM([&](AMM& ammAlice, Env&) { ammAlice.withdraw(alice, XRP(200), USD(100)); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(9'900), USD(9'900), IOUAmount{9'900'000, 0})); + BEAST_EXPECT(ammAlice.expectBalances(XRP(9'900), USD(9'900), IOUAmount{9'900'000, 0})); }); // Equal withdrawal with a limit. XRP100/USD100. testAMM([&](AMM& ammAlice, Env&) { ammAlice.withdraw(alice, XRP(100), USD(200)); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(9'900), USD(9'900), IOUAmount{9'900'000, 0})); + BEAST_EXPECT(ammAlice.expectBalances(XRP(9'900), USD(9'900), IOUAmount{9'900'000, 0})); }); // Single withdrawal by amount XRP1000 @@ -2319,15 +1620,10 @@ private: [&](AMM& ammAlice, Env& env) { ammAlice.withdraw(alice, XRP(1'000)); if (!env.enabled(fixAMMv1_3)) - BEAST_EXPECT(ammAlice.expectBalances( - XRP(9'000), - USD(10'000), - IOUAmount{9'486'832'98050514, -8})); + BEAST_EXPECT(ammAlice.expectBalances(XRP(9'000), USD(10'000), IOUAmount{9'486'832'98050514, -8})); else BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount{9'000'000'001}, - USD(10'000), - IOUAmount{9'486'832'98050514, -8})); + XRPAmount{9'000'000'001}, USD(10'000), IOUAmount{9'486'832'98050514, -8})); }, std::nullopt, 0, @@ -2337,19 +1633,14 @@ private: // Single withdrawal by tokens 10000. testAMM([&](AMM& ammAlice, Env&) { ammAlice.withdraw(alice, 10'000, USD(0)); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'000), USD(9980.01), IOUAmount{9'990'000, 0})); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), USD(9980.01), IOUAmount{9'990'000, 0})); }); // Withdraw all tokens. testAMM([&](AMM& ammAlice, Env& env) { env(trust(carol, STAmount{ammAlice.lptIssue(), 10'000})); // Can SetTrust only for AMM LP tokens - env(trust( - carol, - STAmount{ - Issue{EUR.currency, ammAlice.ammAccount()}, 10'000}), - ter(tecNO_PERMISSION)); + env(trust(carol, STAmount{Issue{EUR.currency, ammAlice.ammAccount()}, 10'000}), ter(tecNO_PERMISSION)); env.close(); ammAlice.withdrawAll(alice); BEAST_EXPECT(!ammAlice.ammExists()); @@ -2358,18 +1649,15 @@ private: // Can create AMM for the XRP/USD pair AMM ammCarol(env, carol, XRP(10'000), USD(10'000)); - BEAST_EXPECT(ammCarol.expectBalances( - XRP(10'000), USD(10'000), IOUAmount{10'000'000, 0})); + BEAST_EXPECT(ammCarol.expectBalances(XRP(10'000), USD(10'000), IOUAmount{10'000'000, 0})); }); // Single deposit 1000USD, withdraw all tokens in USD testAMM([&](AMM& ammAlice, Env& env) { ammAlice.deposit(carol, USD(1'000)); ammAlice.withdrawAll(carol, USD(0)); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'000), USD(10'000), IOUAmount{10'000'000, 0})); - BEAST_EXPECT( - ammAlice.expectLPTokens(carol, IOUAmount(beast::Zero()))); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), USD(10'000), IOUAmount{10'000'000, 0})); + BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount(beast::Zero()))); }); // Single deposit 1000USD, withdraw all tokens in XRP @@ -2377,9 +1665,7 @@ private: ammAlice.deposit(carol, USD(1'000)); ammAlice.withdrawAll(carol, XRP(0)); BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount(9'090'909'091), - STAmount{USD, UINT64_C(10'999'99999999999), -11}, - IOUAmount{10'000'000, 0})); + XRPAmount(9'090'909'091), STAmount{USD, UINT64_C(10'999'99999999999), -11}, IOUAmount{10'000'000, 0})); }); // Single deposit/withdraw by the same account @@ -2395,13 +1681,9 @@ private: lpTokens = ammAlice.deposit(carol, XRPAmount(1)); ammAlice.withdraw(carol, lpTokens, XRPAmount(0)); if (!env.enabled(fixAMMv1_3)) - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'000), USD(10'000), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), USD(10'000), ammAlice.tokens())); else - BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount(10'000'000'001), - USD(10'000), - ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectBalances(XRPAmount(10'000'000'001), USD(10'000), ammAlice.tokens())); BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount{0})); }, std::nullopt, @@ -2416,8 +1698,7 @@ private: auto const aliceTokens = ammAlice.deposit(alice, USD(1'000)); ammAlice.withdraw(alice, aliceTokens, USD(0)); ammAlice.withdraw(carol, carolTokens, USD(0)); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'000), USD(10'000), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), USD(10'000), ammAlice.tokens())); BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount{0})); BEAST_EXPECT(ammAlice.expectLPTokens(alice, ammAlice.tokens())); }); @@ -2426,8 +1707,7 @@ private: testAMM([&](AMM& ammAlice, Env&) { ammAlice.deposit(carol, 1'000'000); ammAlice.withdrawAll(carol); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'000), USD(10'000), IOUAmount{10'000'000, 0})); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), USD(10'000), IOUAmount{10'000'000, 0})); }); // Equal deposit 10%, withdraw all tokens in USD @@ -2435,29 +1715,22 @@ private: ammAlice.deposit(carol, 1'000'000); ammAlice.withdrawAll(carol, USD(0)); BEAST_EXPECT(ammAlice.expectBalances( - XRP(11'000), - STAmount{USD, UINT64_C(9'090'909090909092), -12}, - IOUAmount{10'000'000, 0})); + XRP(11'000), STAmount{USD, UINT64_C(9'090'909090909092), -12}, IOUAmount{10'000'000, 0})); }); // Equal deposit 10%, withdraw all tokens in XRP testAMM([&](AMM& ammAlice, Env&) { ammAlice.deposit(carol, 1'000'000); ammAlice.withdrawAll(carol, XRP(0)); - BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount(9'090'909'091), - USD(11'000), - IOUAmount{10'000'000, 0})); + BEAST_EXPECT(ammAlice.expectBalances(XRPAmount(9'090'909'091), USD(11'000), IOUAmount{10'000'000, 0})); }); // Withdraw with EPrice limit. testAMM( [&](AMM& ammAlice, Env& env) { ammAlice.deposit(carol, 1'000'000); - ammAlice.withdraw( - carol, USD(100), std::nullopt, IOUAmount{520, 0}); - BEAST_EXPECT(ammAlice.expectLPTokens( - carol, IOUAmount{153'846'15384616, -8})); + ammAlice.withdraw(carol, USD(100), std::nullopt, IOUAmount{520, 0}); + BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount{153'846'15384616, -8})); if (!env.enabled(fixAMMv1_1) && !env.enabled(fixAMMv1_3)) BEAST_EXPECT(ammAlice.expectBalances( XRPAmount(11'000'000'000), @@ -2476,17 +1749,14 @@ private: ammAlice.withdrawAll(carol); BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount{0})); }, - {.features = {all, all - fixAMMv1_3, all - fixAMMv1_1 - fixAMMv1_3}, - .noLog = true}); + {.features = {all, all - fixAMMv1_3, all - fixAMMv1_1 - fixAMMv1_3}, .noLog = true}); // Withdraw with EPrice limit. AssetOut is 0. testAMM( [&](AMM& ammAlice, Env& env) { ammAlice.deposit(carol, 1'000'000); - ammAlice.withdraw( - carol, USD(0), std::nullopt, IOUAmount{520, 0}); - BEAST_EXPECT(ammAlice.expectLPTokens( - carol, IOUAmount{153'846'15384616, -8})); + ammAlice.withdraw(carol, USD(0), std::nullopt, IOUAmount{520, 0}); + BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount{153'846'15384616, -8})); if (!env.enabled(fixAMMv1_1) && !env.enabled(fixAMMv1_3)) BEAST_EXPECT(ammAlice.expectBalances( XRP(11'000), @@ -2516,21 +1786,18 @@ private: env.close(); // no transfer fee on create AMM ammAlice(env, alice, USD(20'000), BTC(0.5)); - BEAST_EXPECT(ammAlice.expectBalances( - USD(20'000), BTC(0.5), IOUAmount{100, 0})); + BEAST_EXPECT(ammAlice.expectBalances(USD(20'000), BTC(0.5), IOUAmount{100, 0})); BEAST_EXPECT(expectHolding(env, alice, USD(0))); BEAST_EXPECT(expectHolding(env, alice, BTC(0))); fund(env, gw, {carol}, {USD(2'000), BTC(0.05)}, Fund::Acct); // no transfer fee on deposit ammAlice.deposit(carol, 10); - BEAST_EXPECT(ammAlice.expectBalances( - USD(22'000), BTC(0.55), IOUAmount{110, 0})); + BEAST_EXPECT(ammAlice.expectBalances(USD(22'000), BTC(0.55), IOUAmount{110, 0})); BEAST_EXPECT(expectHolding(env, carol, USD(0))); BEAST_EXPECT(expectHolding(env, carol, BTC(0))); // no transfer fee on withdraw ammAlice.withdraw(carol, 10); - BEAST_EXPECT(ammAlice.expectBalances( - USD(20'000), BTC(0.5), IOUAmount{100, 0})); + BEAST_EXPECT(ammAlice.expectBalances(USD(20'000), BTC(0.5), IOUAmount{100, 0})); BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount{0, 0})); BEAST_EXPECT(expectHolding(env, carol, USD(2'000))); BEAST_EXPECT(expectHolding(env, carol, BTC(0.05))); @@ -2541,24 +1808,17 @@ private: // By tokens ammAlice.withdraw(alice, IOUAmount{1, -3}); BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount{9'999'999'999}, - STAmount{USD, UINT64_C(9'999'999999), -6}, - IOUAmount{9'999'999'999, -3})); + XRPAmount{9'999'999'999}, STAmount{USD, UINT64_C(9'999'999999), -6}, IOUAmount{9'999'999'999, -3})); }); testAMM( [&](AMM& ammAlice, Env& env) { // Single XRP pool ammAlice.withdraw(alice, std::nullopt, XRPAmount{1}); if (!env.enabled(fixAMMv1_3)) - BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount{9'999'999'999}, - USD(10'000), - IOUAmount{9'999'999'9995, -4})); + BEAST_EXPECT( + ammAlice.expectBalances(XRPAmount{9'999'999'999}, USD(10'000), IOUAmount{9'999'999'9995, -4})); else - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'000), - USD(10'000), - IOUAmount{9'999'999'9995, -4})); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), USD(10'000), IOUAmount{9'999'999'9995, -4})); }, std::nullopt, 0, @@ -2568,42 +1828,34 @@ private: // Single USD pool ammAlice.withdraw(alice, std::nullopt, STAmount{USD, 1, -10}); BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'000), - STAmount{USD, UINT64_C(9'999'9999999999), -10}, - IOUAmount{9'999'999'99999995, -8})); + XRP(10'000), STAmount{USD, UINT64_C(9'999'9999999999), -10}, IOUAmount{9'999'999'99999995, -8})); }); // Withdraw close to entire pool // Equal by tokens testAMM([&](AMM& ammAlice, Env&) { ammAlice.withdraw(alice, IOUAmount{9'999'999'999, -3}); - BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount{1}, STAmount{USD, 1, -6}, IOUAmount{1, -3})); + BEAST_EXPECT(ammAlice.expectBalances(XRPAmount{1}, STAmount{USD, 1, -6}, IOUAmount{1, -3})); }); // USD by tokens testAMM([&](AMM& ammAlice, Env&) { ammAlice.withdraw(alice, IOUAmount{9'999'999}, USD(0)); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'000), STAmount{USD, 1, -10}, IOUAmount{1})); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), STAmount{USD, 1, -10}, IOUAmount{1})); }); // XRP by tokens testAMM([&](AMM& ammAlice, Env&) { ammAlice.withdraw(alice, IOUAmount{9'999'900}, XRP(0)); - BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount{1}, USD(10'000), IOUAmount{100})); + BEAST_EXPECT(ammAlice.expectBalances(XRPAmount{1}, USD(10'000), IOUAmount{100})); }); // USD testAMM([&](AMM& ammAlice, Env&) { - ammAlice.withdraw( - alice, STAmount{USD, UINT64_C(9'999'99999999999), -11}); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10000), STAmount{USD, 1, -11}, IOUAmount{316227765, -9})); + ammAlice.withdraw(alice, STAmount{USD, UINT64_C(9'999'99999999999), -11}); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10000), STAmount{USD, 1, -11}, IOUAmount{316227765, -9})); }); // XRP testAMM([&](AMM& ammAlice, Env&) { ammAlice.withdraw(alice, XRPAmount{9'999'999'999}); - BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount{1}, USD(10'000), IOUAmount{100})); + BEAST_EXPECT(ammAlice.expectBalances(XRPAmount{1}, USD(10'000), IOUAmount{100})); }); } @@ -2615,64 +1867,28 @@ private: testAMM([&](AMM& ammAlice, Env& env) { // Invalid flags - ammAlice.vote( - std::nullopt, - 1'000, - tfWithdrawAll, - std::nullopt, - std::nullopt, - ter(temINVALID_FLAG)); + ammAlice.vote(std::nullopt, 1'000, tfWithdrawAll, std::nullopt, std::nullopt, ter(temINVALID_FLAG)); // Invalid fee. - ammAlice.vote( - std::nullopt, - 1'001, - std::nullopt, - std::nullopt, - std::nullopt, - ter(temBAD_FEE)); + ammAlice.vote(std::nullopt, 1'001, std::nullopt, std::nullopt, std::nullopt, ter(temBAD_FEE)); BEAST_EXPECT(ammAlice.expectTradingFee(0)); // Invalid Account Account bad("bad"); env.memoize(bad); - ammAlice.vote( - bad, - 1'000, - std::nullopt, - seq(1), - std::nullopt, - ter(terNO_ACCOUNT)); + ammAlice.vote(bad, 1'000, std::nullopt, seq(1), std::nullopt, ter(terNO_ACCOUNT)); // Invalid AMM - ammAlice.vote( - alice, - 1'000, - std::nullopt, - std::nullopt, - {{USD, GBP}}, - ter(terNO_AMM)); + ammAlice.vote(alice, 1'000, std::nullopt, std::nullopt, {{USD, GBP}}, ter(terNO_AMM)); // Account is not LP - ammAlice.vote( - carol, - 1'000, - std::nullopt, - std::nullopt, - std::nullopt, - ter(tecAMM_INVALID_TOKENS)); + ammAlice.vote(carol, 1'000, std::nullopt, std::nullopt, std::nullopt, ter(tecAMM_INVALID_TOKENS)); }); // Invalid AMM testAMM([&](AMM& ammAlice, Env& env) { ammAlice.withdrawAll(alice); - ammAlice.vote( - alice, - 1'000, - std::nullopt, - std::nullopt, - std::nullopt, - ter(terNO_AMM)); + ammAlice.vote(alice, 1'000, std::nullopt, std::nullopt, std::nullopt, ter(terNO_AMM)); }); } @@ -2842,8 +2058,7 @@ private: BEAST_EXPECT(amm.expectAuctionSlot(100, 0, IOUAmount{999'999})); // 999'999 tokens are burned, only 1 LPToken is owned by gw - BEAST_EXPECT( - amm.expectBalances(XRP(1'000), USD(1'000), IOUAmount{1})); + BEAST_EXPECT(amm.expectBalances(XRP(1'000), USD(1'000), IOUAmount{1})); // gw owns only 1 LPToken in its balance BEAST_EXPECT(Number{amm.getLPTokensBalance(gw)} == 1); @@ -3038,8 +2253,7 @@ private: env(ammAlice.bid({.account = carol, .bidMin = 110})); BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 0, IOUAmount{110})); // 110 tokens are burned. - BEAST_EXPECT(ammAlice.expectBalances( - XRP(11'000), USD(11'000), IOUAmount{10'999'890, 0})); + BEAST_EXPECT(ammAlice.expectBalances(XRP(11'000), USD(11'000), IOUAmount{10'999'890, 0})); }, std::nullopt, 0, @@ -3051,17 +2265,13 @@ private: [&](AMM& ammAlice, Env& env) { ammAlice.deposit(carol, 1'000'000); // Bid exactly 110. Pay 110 because the pay price is < 110. - env(ammAlice.bid( - {.account = carol, .bidMin = 110, .bidMax = 110})); + env(ammAlice.bid({.account = carol, .bidMin = 110, .bidMax = 110})); BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 0, IOUAmount{110})); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(11'000), USD(11'000), IOUAmount{10'999'890})); + BEAST_EXPECT(ammAlice.expectBalances(XRP(11'000), USD(11'000), IOUAmount{10'999'890})); // Bid exactly 180-200. Pay 180 because the pay price is < 180. - env(ammAlice.bid( - {.account = alice, .bidMin = 180, .bidMax = 200})); + env(ammAlice.bid({.account = alice, .bidMin = 180, .bidMax = 200})); BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 0, IOUAmount{180})); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(11'000), USD(11'000), IOUAmount{10'999'814'5, -1})); + BEAST_EXPECT(ammAlice.expectBalances(XRP(11'000), USD(11'000), IOUAmount{10'999'814'5, -1})); }, std::nullopt, 0, @@ -3080,8 +2290,7 @@ private: ammAlice.deposit(bob, 1'000'000); // Bid, pay the computed price. env(ammAlice.bid({.account = bob})); - BEAST_EXPECT( - ammAlice.expectAuctionSlot(0, 0, IOUAmount(1155, -1))); + BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 0, IOUAmount(1155, -1))); // Bid bidMax fails because the computed price is higher. env(ammAlice.bid({ @@ -3091,8 +2300,7 @@ private: ter(tecAMM_FAILED)); // Bid MaxSlotPrice succeeds - pay computed price env(ammAlice.bid({.account = carol, .bidMax = 600})); - BEAST_EXPECT( - ammAlice.expectAuctionSlot(0, 0, IOUAmount{121'275, -3})); + BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 0, IOUAmount{121'275, -3})); // Bid Min/MaxSlotPrice fails because the computed price is not // in range @@ -3103,10 +2311,8 @@ private: }), ter(tecAMM_FAILED)); // Bid Min/MaxSlotPrice succeeds - pay computed price - env(ammAlice.bid( - {.account = carol, .bidMin = 100, .bidMax = 600})); - BEAST_EXPECT( - ammAlice.expectAuctionSlot(0, 0, IOUAmount{127'33875, -5})); + env(ammAlice.bid({.account = carol, .bidMin = 100, .bidMax = 600})); + BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 0, IOUAmount{127'33875, -5})); }, std::nullopt, 0, @@ -3121,13 +2327,10 @@ private: fund(env, gw, {bob}, {USD(10'000)}, Fund::Acct); ammAlice.deposit(bob, 1'000'000); if (!features[fixAMMv1_3]) - BEAST_EXPECT(ammAlice.expectBalances( - XRP(12'000), USD(12'000), IOUAmount{12'000'000, 0})); + BEAST_EXPECT(ammAlice.expectBalances(XRP(12'000), USD(12'000), IOUAmount{12'000'000, 0})); else - BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount{12'000'000'001}, - USD(12'000), - IOUAmount{12'000'000, 0})); + BEAST_EXPECT( + ammAlice.expectBalances(XRPAmount{12'000'000'001}, USD(12'000), IOUAmount{12'000'000, 0})); // Initial state. Pay bidMin. env(ammAlice.bid({.account = carol, .bidMin = 110})).close(); @@ -3136,39 +2339,27 @@ private: // 1st Interval after close, price for 0th interval. env(ammAlice.bid({.account = bob})); env.close(seconds(AUCTION_SLOT_INTERVAL_DURATION + 1)); - BEAST_EXPECT( - ammAlice.expectAuctionSlot(0, 1, IOUAmount{1'155, -1})); + BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 1, IOUAmount{1'155, -1})); // 10th Interval after close, price for 1st interval. env(ammAlice.bid({.account = carol})); env.close(seconds(10 * AUCTION_SLOT_INTERVAL_DURATION + 1)); - BEAST_EXPECT( - ammAlice.expectAuctionSlot(0, 10, IOUAmount{121'275, -3})); + BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 10, IOUAmount{121'275, -3})); // 20th Interval (expired) after close, price for 10th interval. env(ammAlice.bid({.account = bob})); - env.close(seconds( - AUCTION_SLOT_TIME_INTERVALS * - AUCTION_SLOT_INTERVAL_DURATION + - 1)); - BEAST_EXPECT(ammAlice.expectAuctionSlot( - 0, std::nullopt, IOUAmount{127'33875, -5})); + env.close(seconds(AUCTION_SLOT_TIME_INTERVALS * AUCTION_SLOT_INTERVAL_DURATION + 1)); + BEAST_EXPECT(ammAlice.expectAuctionSlot(0, std::nullopt, IOUAmount{127'33875, -5})); // 0 Interval. env(ammAlice.bid({.account = carol, .bidMin = 110})).close(); - BEAST_EXPECT(ammAlice.expectAuctionSlot( - 0, std::nullopt, IOUAmount{110})); + BEAST_EXPECT(ammAlice.expectAuctionSlot(0, std::nullopt, IOUAmount{110})); // ~321.09 tokens burnt on bidding fees. if (!features[fixAMMv1_3]) - BEAST_EXPECT(ammAlice.expectBalances( - XRP(12'000), - USD(12'000), - IOUAmount{11'999'678'91, -2})); + BEAST_EXPECT(ammAlice.expectBalances(XRP(12'000), USD(12'000), IOUAmount{11'999'678'91, -2})); else - BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount{12'000'000'001}, - USD(12'000), - IOUAmount{11'999'678'91, -2})); + BEAST_EXPECT( + ammAlice.expectBalances(XRPAmount{12'000'000'001}, USD(12'000), IOUAmount{11'999'678'91, -2})); }, std::nullopt, 0, @@ -3198,11 +2389,9 @@ private: ammTokens -= slotPrice; BEAST_EXPECT(ammAlice.expectAuctionSlot(100, 0, slotPrice)); if (!features[fixAMMv1_3]) - BEAST_EXPECT(ammAlice.expectBalances( - XRP(13'000), USD(13'000), ammTokens)); + BEAST_EXPECT(ammAlice.expectBalances(XRP(13'000), USD(13'000), ammTokens)); else - BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount{13'000'000'003}, USD(13'000), ammTokens)); + BEAST_EXPECT(ammAlice.expectBalances(XRPAmount{13'000'000'003}, USD(13'000), ammTokens)); // Discounted trade for (int i = 0; i < 10; ++i) { @@ -3216,43 +2405,25 @@ private: // carol, bob, and ed pay ~0.99USD in fees. if (!features[fixAMMv1_1]) { - BEAST_EXPECT( - env.balance(carol, USD) == - STAmount(USD, UINT64_C(29'499'00572620545), -11)); - BEAST_EXPECT( - env.balance(bob, USD) == - STAmount(USD, UINT64_C(18'999'00572616195), -11)); - BEAST_EXPECT( - env.balance(ed, USD) == - STAmount(USD, UINT64_C(18'999'00572611841), -11)); + BEAST_EXPECT(env.balance(carol, USD) == STAmount(USD, UINT64_C(29'499'00572620545), -11)); + BEAST_EXPECT(env.balance(bob, USD) == STAmount(USD, UINT64_C(18'999'00572616195), -11)); + BEAST_EXPECT(env.balance(ed, USD) == STAmount(USD, UINT64_C(18'999'00572611841), -11)); // USD pool is slightly higher because of the fees. BEAST_EXPECT(ammAlice.expectBalances( - XRP(13'000), - STAmount(USD, UINT64_C(13'002'98282151419), -11), - ammTokens)); + XRP(13'000), STAmount(USD, UINT64_C(13'002'98282151419), -11), ammTokens)); } else { - BEAST_EXPECT( - env.balance(carol, USD) == - STAmount(USD, UINT64_C(29'499'00572620544), -11)); - BEAST_EXPECT( - env.balance(bob, USD) == - STAmount(USD, UINT64_C(18'999'00572616194), -11)); - BEAST_EXPECT( - env.balance(ed, USD) == - STAmount(USD, UINT64_C(18'999'0057261184), -10)); + BEAST_EXPECT(env.balance(carol, USD) == STAmount(USD, UINT64_C(29'499'00572620544), -11)); + BEAST_EXPECT(env.balance(bob, USD) == STAmount(USD, UINT64_C(18'999'00572616194), -11)); + BEAST_EXPECT(env.balance(ed, USD) == STAmount(USD, UINT64_C(18'999'0057261184), -10)); // USD pool is slightly higher because of the fees. if (!features[fixAMMv1_3]) BEAST_EXPECT(ammAlice.expectBalances( - XRP(13'000), - STAmount(USD, UINT64_C(13'002'98282151422), -11), - ammTokens)); + XRP(13'000), STAmount(USD, UINT64_C(13'002'98282151422), -11), ammTokens)); else BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount{13'000'000'003}, - STAmount(USD, UINT64_C(13'002'98282151422), -11), - ammTokens)); + XRPAmount{13'000'000'003}, STAmount(USD, UINT64_C(13'002'98282151422), -11), ammTokens)); } ammTokens = ammAlice.getLPTokensBalance(); // Trade with the fee @@ -3266,82 +2437,54 @@ private: // than the trading fee. if (!features[fixAMMv1_1]) { - BEAST_EXPECT( - env.balance(dan, USD) == - STAmount(USD, UINT64_C(19'490'056722744), -9)); + BEAST_EXPECT(env.balance(dan, USD) == STAmount(USD, UINT64_C(19'490'056722744), -9)); // USD pool gains more in dan's fees. BEAST_EXPECT(ammAlice.expectBalances( - XRP(13'000), - STAmount{USD, UINT64_C(13'012'92609877019), -11}, - ammTokens)); + XRP(13'000), STAmount{USD, UINT64_C(13'012'92609877019), -11}, ammTokens)); // Discounted fee payment ammAlice.deposit(carol, USD(100)); ammTokens = ammAlice.getLPTokensBalance(); BEAST_EXPECT(ammAlice.expectBalances( - XRP(13'000), - STAmount{USD, UINT64_C(13'112'92609877019), -11}, - ammTokens)); - env(pay(carol, bob, USD(100)), - path(~USD), - sendmax(XRP(110))); + XRP(13'000), STAmount{USD, UINT64_C(13'112'92609877019), -11}, ammTokens)); + env(pay(carol, bob, USD(100)), path(~USD), sendmax(XRP(110))); env.close(); // carol pays 100000 drops in fees // 99900668XRP swapped in for 100USD BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount{13'100'000'668}, - STAmount{USD, UINT64_C(13'012'92609877019), -11}, - ammTokens)); + XRPAmount{13'100'000'668}, STAmount{USD, UINT64_C(13'012'92609877019), -11}, ammTokens)); } else { if (!features[fixAMMv1_3]) - BEAST_EXPECT( - env.balance(dan, USD) == - STAmount(USD, UINT64_C(19'490'05672274399), -11)); + BEAST_EXPECT(env.balance(dan, USD) == STAmount(USD, UINT64_C(19'490'05672274399), -11)); else - BEAST_EXPECT( - env.balance(dan, USD) == - STAmount(USD, UINT64_C(19'490'05672274398), -11)); + BEAST_EXPECT(env.balance(dan, USD) == STAmount(USD, UINT64_C(19'490'05672274398), -11)); // USD pool gains more in dan's fees. if (!features[fixAMMv1_3]) BEAST_EXPECT(ammAlice.expectBalances( - XRP(13'000), - STAmount{USD, UINT64_C(13'012'92609877023), -11}, - ammTokens)); + XRP(13'000), STAmount{USD, UINT64_C(13'012'92609877023), -11}, ammTokens)); else BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount{13'000'000'003}, - STAmount{USD, UINT64_C(13'012'92609877024), -11}, - ammTokens)); + XRPAmount{13'000'000'003}, STAmount{USD, UINT64_C(13'012'92609877024), -11}, ammTokens)); // Discounted fee payment ammAlice.deposit(carol, USD(100)); ammTokens = ammAlice.getLPTokensBalance(); if (!features[fixAMMv1_3]) BEAST_EXPECT(ammAlice.expectBalances( - XRP(13'000), - STAmount{USD, UINT64_C(13'112'92609877023), -11}, - ammTokens)); + XRP(13'000), STAmount{USD, UINT64_C(13'112'92609877023), -11}, ammTokens)); else BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount{13'000'000'003}, - STAmount{USD, UINT64_C(13'112'92609877024), -11}, - ammTokens)); - env(pay(carol, bob, USD(100)), - path(~USD), - sendmax(XRP(110))); + XRPAmount{13'000'000'003}, STAmount{USD, UINT64_C(13'112'92609877024), -11}, ammTokens)); + env(pay(carol, bob, USD(100)), path(~USD), sendmax(XRP(110))); env.close(); // carol pays 100000 drops in fees // 99900668XRP swapped in for 100USD if (!features[fixAMMv1_3]) BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount{13'100'000'668}, - STAmount{USD, UINT64_C(13'012'92609877023), -11}, - ammTokens)); + XRPAmount{13'100'000'668}, STAmount{USD, UINT64_C(13'012'92609877023), -11}, ammTokens)); else BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount{13'100'000'671}, - STAmount{USD, UINT64_C(13'012'92609877024), -11}, - ammTokens)); + XRPAmount{13'100'000'671}, STAmount{USD, UINT64_C(13'012'92609877024), -11}, ammTokens)); } // Payment with the trading fee env(pay(alice, carol, XRP(100)), path(~XRP), sendmax(USD(110))); @@ -3352,36 +2495,26 @@ private: if (!features[fixAMMv1_1] && !features[fixAMMv1_3]) { BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount{13'000'000'668}, - STAmount{USD, UINT64_C(13'114'03663047264), -11}, - ammTokens)); + XRPAmount{13'000'000'668}, STAmount{USD, UINT64_C(13'114'03663047264), -11}, ammTokens)); } else if (features[fixAMMv1_1] && !features[fixAMMv1_3]) { BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount{13'000'000'668}, - STAmount{USD, UINT64_C(13'114'03663047269), -11}, - ammTokens)); + XRPAmount{13'000'000'668}, STAmount{USD, UINT64_C(13'114'03663047269), -11}, ammTokens)); } else { BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount{13'000'000'671}, - STAmount{USD, UINT64_C(13'114'03663044937), -11}, - ammTokens)); + XRPAmount{13'000'000'671}, STAmount{USD, UINT64_C(13'114'03663044937), -11}, ammTokens)); } // Auction slot expired, no discounted fee env.close(seconds(TOTAL_TIME_SLOT_SECS + 1)); // clock is parent's based env.close(); if (!features[fixAMMv1_1]) - BEAST_EXPECT( - env.balance(carol, USD) == - STAmount(USD, UINT64_C(29'399'00572620545), -11)); + BEAST_EXPECT(env.balance(carol, USD) == STAmount(USD, UINT64_C(29'399'00572620545), -11)); else if (!features[fixAMMv1_3]) - BEAST_EXPECT( - env.balance(carol, USD) == - STAmount(USD, UINT64_C(29'399'00572620544), -11)); + BEAST_EXPECT(env.balance(carol, USD) == STAmount(USD, UINT64_C(29'399'00572620544), -11)); ammTokens = ammAlice.getLPTokensBalance(); for (int i = 0; i < 10; ++i) { @@ -3392,33 +2525,21 @@ private: // trading fees vs discounted fee. if (!features[fixAMMv1_1] && !features[fixAMMv1_3]) { - BEAST_EXPECT( - env.balance(carol, USD) == - STAmount(USD, UINT64_C(29'389'06197177128), -11)); + BEAST_EXPECT(env.balance(carol, USD) == STAmount(USD, UINT64_C(29'389'06197177128), -11)); BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount{13'000'000'668}, - STAmount{USD, UINT64_C(13'123'98038490681), -11}, - ammTokens)); + XRPAmount{13'000'000'668}, STAmount{USD, UINT64_C(13'123'98038490681), -11}, ammTokens)); } else if (features[fixAMMv1_1] && !features[fixAMMv1_3]) { - BEAST_EXPECT( - env.balance(carol, USD) == - STAmount(USD, UINT64_C(29'389'06197177124), -11)); + BEAST_EXPECT(env.balance(carol, USD) == STAmount(USD, UINT64_C(29'389'06197177124), -11)); BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount{13'000'000'668}, - STAmount{USD, UINT64_C(13'123'98038490689), -11}, - ammTokens)); + XRPAmount{13'000'000'668}, STAmount{USD, UINT64_C(13'123'98038490689), -11}, ammTokens)); } else { - BEAST_EXPECT( - env.balance(carol, USD) == - STAmount(USD, UINT64_C(29'389'06197177129), -11)); + BEAST_EXPECT(env.balance(carol, USD) == STAmount(USD, UINT64_C(29'389'06197177129), -11)); BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount{13'000'000'671}, - STAmount{USD, UINT64_C(13'123'98038488352), -11}, - ammTokens)); + XRPAmount{13'000'000'671}, STAmount{USD, UINT64_C(13'123'98038488352), -11}, ammTokens)); } env(pay(carol, bob, USD(100)), path(~USD), sendmax(XRP(110))); env.close(); @@ -3428,23 +2549,17 @@ private: if (!features[fixAMMv1_1] && !features[fixAMMv1_3]) { BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount(13'100'824'790), - STAmount{USD, UINT64_C(13'023'98038490681), -11}, - ammTokens)); + XRPAmount(13'100'824'790), STAmount{USD, UINT64_C(13'023'98038490681), -11}, ammTokens)); } else if (features[fixAMMv1_1] && !features[fixAMMv1_3]) { BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount(13'100'824'790), - STAmount{USD, UINT64_C(13'023'98038490689), -11}, - ammTokens)); + XRPAmount(13'100'824'790), STAmount{USD, UINT64_C(13'023'98038490689), -11}, ammTokens)); } else { BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount(13'100'824'793), - STAmount{USD, UINT64_C(13'023'98038488352), -11}, - ammTokens)); + XRPAmount(13'100'824'793), STAmount{USD, UINT64_C(13'023'98038488352), -11}, ammTokens)); } }, std::nullopt, @@ -3456,29 +2571,23 @@ private: testAMM( [&](AMM& ammAlice, Env& env) { // Bid a tiny amount - auto const tiny = - Number{STAmount::cMinValue, STAmount::cMinOffset}; - env(ammAlice.bid( - {.account = alice, .bidMin = IOUAmount{tiny}})); + auto const tiny = Number{STAmount::cMinValue, STAmount::cMinOffset}; + env(ammAlice.bid({.account = alice, .bidMin = IOUAmount{tiny}})); // Auction slot purchase price is equal to the tiny amount // since the minSlotPrice is 0 with no trading fee. BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 0, IOUAmount{tiny})); // The purchase price is too small to affect the total tokens - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'000), USD(10'000), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), USD(10'000), ammAlice.tokens())); // Bid the tiny amount env(ammAlice.bid({ .account = alice, - .bidMin = - IOUAmount{STAmount::cMinValue, STAmount::cMinOffset}, + .bidMin = IOUAmount{STAmount::cMinValue, STAmount::cMinOffset}, })); // Pay slightly higher price - BEAST_EXPECT(ammAlice.expectAuctionSlot( - 0, 0, IOUAmount{tiny * Number{105, -2}})); + BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 0, IOUAmount{tiny * Number{105, -2}})); // The purchase price is still too small to affect the total // tokens - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'000), USD(10'000), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), USD(10'000), ammAlice.tokens())); }, std::nullopt, 0, @@ -3528,10 +2637,7 @@ private: // But trades with the discounted fee since she still owns the slot. // Alice pays 10011 drops in fees env(pay(alice, bob, USD(10)), path(~USD), sendmax(XRP(11))); - BEAST_EXPECT(amm.expectBalances( - XRPAmount{1'010'010'011}, - USD(1'000), - IOUAmount{1'004'487'562112089, -9})); + BEAST_EXPECT(amm.expectBalances(XRPAmount{1'010'010'011}, USD(1'000), IOUAmount{1'004'487'562112089, -9})); // Bob pays the full fee ~0.1USD env(pay(bob, alice, XRP(10)), path(~XRP), sendmax(USD(11))); if (!features[fixAMMv1_1]) @@ -3562,12 +2668,7 @@ private: { auto jtx = env.jt(tx, seq(1), fee(baseFee)); env.app().config().features.erase(featureAMM); - PreflightContext pfCtx( - env.app(), - *jtx.stx, - env.current()->rules(), - tapNONE, - env.journal); + PreflightContext pfCtx(env.app(), *jtx.stx, env.current()->rules(), tapNONE, env.journal); auto pf = Transactor::invokePreflight(pfCtx); BEAST_EXPECT(pf == temDISABLED); env.app().config().features.insert(featureAMM); @@ -3577,12 +2678,7 @@ private: auto jtx = env.jt(tx, seq(1), fee(baseFee)); jtx.jv["TxnSignature"] = "deadbeef"; jtx.stx = env.ust(jtx); - PreflightContext pfCtx( - env.app(), - *jtx.stx, - env.current()->rules(), - tapNONE, - env.journal); + PreflightContext pfCtx(env.app(), *jtx.stx, env.current()->rules(), tapNONE, env.journal); auto pf = Transactor::invokePreflight(pfCtx); BEAST_EXPECT(pf != tesSUCCESS); } @@ -3592,12 +2688,7 @@ private: jtx.jv["Asset2"]["currency"] = "XRP"; jtx.jv["Asset2"].removeMember("issuer"); jtx.stx = env.ust(jtx); - PreflightContext pfCtx( - env.app(), - *jtx.stx, - env.current()->rules(), - tapNONE, - env.journal); + PreflightContext pfCtx(env.app(), *jtx.stx, env.current()->rules(), tapNONE, env.journal); auto pf = Transactor::invokePreflight(pfCtx); BEAST_EXPECT(pf == temBAD_AMM_TOKENS); } @@ -3622,14 +2713,11 @@ private: // XRP balance is below reserve AMM ammAlice(env, acct, XRP(10), USD(10)); // Pay below reserve - env(pay(carol, ammAlice.ammAccount(), XRP(10)), - ter(tecNO_PERMISSION)); + env(pay(carol, ammAlice.ammAccount(), XRP(10)), ter(tecNO_PERMISSION)); // Pay above reserve - env(pay(carol, ammAlice.ammAccount(), XRP(300)), - ter(tecNO_PERMISSION)); + env(pay(carol, ammAlice.ammAccount(), XRP(300)), ter(tecNO_PERMISSION)); // Pay IOU - env(pay(carol, ammAlice.ammAccount(), USD(10)), - ter(tecNO_PERMISSION)); + env(pay(carol, ammAlice.ammAccount(), USD(10)), ter(tecNO_PERMISSION)); } { Env env(*this); @@ -3637,11 +2725,9 @@ private: // XRP balance is above reserve AMM ammAlice(env, acct, XRP(1'000'000), USD(100)); // Pay below reserve - env(pay(carol, ammAlice.ammAccount(), XRP(10)), - ter(tecNO_PERMISSION)); + env(pay(carol, ammAlice.ammAccount(), XRP(10)), ter(tecNO_PERMISSION)); // Pay above reserve - env(pay(carol, ammAlice.ammAccount(), XRP(1'000'000)), - ter(tecNO_PERMISSION)); + env(pay(carol, ammAlice.ammAccount(), XRP(1'000'000)), ter(tecNO_PERMISSION)); } } @@ -3660,46 +2746,28 @@ private: testAMM([&](AMM& ammAlice, Env& env) { auto const pk = carol.pk(); auto const settleDelay = 100s; - NetClock::time_point const cancelAfter = - env.current()->header().parentCloseTime + 200s; - env(paychan::create( - carol, - ammAlice.ammAccount(), - XRP(1'000), - settleDelay, - pk, - cancelAfter), + NetClock::time_point const cancelAfter = env.current()->header().parentCloseTime + 200s; + env(paychan::create(carol, ammAlice.ammAccount(), XRP(1'000), settleDelay, pk, cancelAfter), ter(tecNO_PERMISSION)); }); // Can't pay into AMM with checks. testAMM([&](AMM& ammAlice, Env& env) { - env(check::create(env.master.id(), ammAlice.ammAccount(), XRP(100)), - ter(tecNO_PERMISSION)); + env(check::create(env.master.id(), ammAlice.ammAccount(), XRP(100)), ter(tecNO_PERMISSION)); }); // Pay amounts close to one side of the pool testAMM( [&](AMM& ammAlice, Env& env) { // Can't consume whole pool - env(pay(alice, carol, USD(100)), - path(~USD), - sendmax(XRP(1'000'000'000)), - ter(tecPATH_PARTIAL)); - env(pay(alice, carol, XRP(100)), - path(~XRP), - sendmax(USD(1'000'000'000)), - ter(tecPATH_PARTIAL)); + env(pay(alice, carol, USD(100)), path(~USD), sendmax(XRP(1'000'000'000)), ter(tecPATH_PARTIAL)); + env(pay(alice, carol, XRP(100)), path(~XRP), sendmax(USD(1'000'000'000)), ter(tecPATH_PARTIAL)); // Overflow - env(pay(alice, - carol, - STAmount{USD, UINT64_C(99'999999999), -9}), + env(pay(alice, carol, STAmount{USD, UINT64_C(99'999999999), -9}), path(~USD), sendmax(XRP(1'000'000'000)), ter(tecPATH_PARTIAL)); - env(pay(alice, - carol, - STAmount{USD, UINT64_C(999'99999999), -8}), + env(pay(alice, carol, STAmount{USD, UINT64_C(999'99999999), -8}), path(~USD), sendmax(XRP(1'000'000'000)), ter(tecPATH_PARTIAL)); @@ -3708,10 +2776,7 @@ private: sendmax(USD(1'000'000'000)), ter(tecPATH_PARTIAL)); // Sender doesn't have enough funds - env(pay(alice, carol, USD(99.99)), - path(~USD), - sendmax(XRP(1'000'000'000)), - ter(tecPATH_PARTIAL)); + env(pay(alice, carol, USD(99.99)), path(~USD), sendmax(XRP(1'000'000'000)), ter(tecPATH_PARTIAL)); env(pay(alice, carol, STAmount{xrpIssue(), 99'990'000}), path(~XRP), sendmax(USD(1'000'000'000)), @@ -3737,10 +2802,7 @@ private: // Individually frozen AMM testAMM([&](AMM& ammAlice, Env& env) { - env(trust( - gw, - STAmount{Issue{gw["USD"].currency, ammAlice.ammAccount()}, 0}, - tfSetFreeze)); + env(trust(gw, STAmount{Issue{gw["USD"].currency, ammAlice.ammAccount()}, 0}, tfSetFreeze)); env.close(); env(pay(alice, carol, USD(1)), path(~USD), @@ -3775,8 +2837,7 @@ private: // For now, just disable SAV entirely, which locks in the small Number // mantissas - features = features - featureSingleAssetVault - featureLendingProtocol - - featureLendingProtocol; + features = features - featureSingleAssetVault - featureLendingProtocol - featureLendingProtocol; // Payment 100USD for 100XRP. // Force one path with tfNoRippleDirect. @@ -3784,18 +2845,13 @@ private: [&](AMM& ammAlice, Env& env) { env.fund(jtx::XRP(30'000), bob); env.close(); - env(pay(bob, carol, USD(100)), - path(~USD), - sendmax(XRP(100)), - txflags(tfNoRippleDirect)); + env(pay(bob, carol, USD(100)), path(~USD), sendmax(XRP(100)), txflags(tfNoRippleDirect)); env.close(); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'100), USD(10'000), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'100), USD(10'000), ammAlice.tokens())); // Initial balance 30,000 + 100 BEAST_EXPECT(expectHolding(env, carol, USD(30'100))); // Initial balance 30,000 - 100(sendmax) - 10(tx fee) - BEAST_EXPECT(expectLedgerEntryRoot( - env, bob, XRP(30'000) - XRP(100) - txfee(env, 1))); + BEAST_EXPECT(expectLedgerEntryRoot(env, bob, XRP(30'000) - XRP(100) - txfee(env, 1))); }, {{XRP(10'000), USD(10'100)}}, 0, @@ -3809,13 +2865,11 @@ private: env.close(); env(pay(bob, carol, USD(100)), sendmax(XRP(100))); env.close(); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'100), USD(10'000), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'100), USD(10'000), ammAlice.tokens())); // Initial balance 30,000 + 100 BEAST_EXPECT(expectHolding(env, carol, USD(30'100))); // Initial balance 30,000 - 100(sendmax) - 10(tx fee) - BEAST_EXPECT(expectLedgerEntryRoot( - env, bob, XRP(30'000) - XRP(100) - txfee(env, 1))); + BEAST_EXPECT(expectLedgerEntryRoot(env, bob, XRP(30'000) - XRP(100) - txfee(env, 1))); }, {{XRP(10'000), USD(10'100)}}, 0, @@ -3830,13 +2884,11 @@ private: env.close(); env(pay(bob, carol, USD(100)), path(~USD), sendmax(XRP(100))); env.close(); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'100), USD(10'000), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'100), USD(10'000), ammAlice.tokens())); // Initial balance 30,000 + 100 BEAST_EXPECT(expectHolding(env, carol, USD(30'100))); // Initial balance 30,000 - 100(sendmax) - 10(tx fee) - BEAST_EXPECT(expectLedgerEntryRoot( - env, bob, XRP(30'000) - XRP(100) - txfee(env, 1))); + BEAST_EXPECT(expectLedgerEntryRoot(env, bob, XRP(30'000) - XRP(100) - txfee(env, 1))); }, {{XRP(10'000), USD(10'100)}}, 0, @@ -3853,25 +2905,21 @@ private: env(pay(bob, carol, USD(100)), path(~USD), sendmax(XRP(100)), - txflags( - tfNoRippleDirect | tfPartialPayment | tfLimitQuality)); + txflags(tfNoRippleDirect | tfPartialPayment | tfLimitQuality)); env.close(); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'010), USD(10'000), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'010), USD(10'000), ammAlice.tokens())); // Initial balance 30,000 + 10(limited by limitQuality) BEAST_EXPECT(expectHolding(env, carol, USD(30'010))); // Initial balance 30,000 - 10(limited by limitQuality) - 10(tx // fee) - BEAST_EXPECT(expectLedgerEntryRoot( - env, bob, XRP(30'000) - XRP(10) - txfee(env, 1))); + BEAST_EXPECT(expectLedgerEntryRoot(env, bob, XRP(30'000) - XRP(10) - txfee(env, 1))); // Fails because of limitQuality. Would have sent // ~98.91USD/110XRP has it not been for limitQuality. env(pay(bob, carol, USD(100)), path(~USD), sendmax(XRP(100)), - txflags( - tfNoRippleDirect | tfPartialPayment | tfLimitQuality), + txflags(tfNoRippleDirect | tfPartialPayment | tfLimitQuality), ter(tecPATH_DRY)); env.close(); }, @@ -3893,18 +2941,12 @@ private: env(pay(bob, carol, USD(100)), path(~USD), sendmax(XRP(110)), - txflags( - tfNoRippleDirect | tfPartialPayment | tfLimitQuality)); + txflags(tfNoRippleDirect | tfPartialPayment | tfLimitQuality)); env.close(); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'010), USD(10'000), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'010), USD(10'000), ammAlice.tokens())); // 10USD - 10% transfer fee - BEAST_EXPECT(expectHolding( - env, - carol, - STAmount{USD, UINT64_C(30'009'09090909091), -11})); - BEAST_EXPECT(expectLedgerEntryRoot( - env, bob, XRP(30'000) - XRP(10) - txfee(env, 1))); + BEAST_EXPECT(expectHolding(env, carol, STAmount{USD, UINT64_C(30'009'09090909091), -11})); + BEAST_EXPECT(expectLedgerEntryRoot(env, bob, XRP(30'000) - XRP(10) - txfee(env, 1))); }, {{XRP(10'000), USD(10'010)}}, 0, @@ -3933,8 +2975,7 @@ private: // is taken from the offer. { Env env(*this, features); - fund( - env, gw, {alice, carol}, {USD(30'000), EUR(30'000)}, Fund::All); + fund(env, gw, {alice, carol}, {USD(30'000), EUR(30'000)}, Fund::All); env.close(); env.fund(XRP(1'000), bob); env.close(); @@ -3942,15 +2983,10 @@ private: auto ammUSD_EUR = AMM(env, alice, EUR(10'000), USD(10'000)); env(offer(alice, XRP(101), USD(100)), txflags(tfPassive)); env.close(); - env(pay(bob, carol, USD(100)), - path(~EUR, ~USD), - sendmax(XRP(102)), - txflags(tfPartialPayment)); + env(pay(bob, carol, USD(100)), path(~EUR, ~USD), sendmax(XRP(102)), txflags(tfPartialPayment)); env.close(); BEAST_EXPECT(ammEUR_XRP.expectBalances( - XRPAmount(10'030'082'730), - STAmount(EUR, UINT64_C(9'970'007498125468), -12), - ammEUR_XRP.tokens())); + XRPAmount(10'030'082'730), STAmount(EUR, UINT64_C(9'970'007498125468), -12), ammEUR_XRP.tokens())); if (!features[fixAMMv1_1]) { BEAST_EXPECT(ammUSD_EUR.expectBalances( @@ -3959,12 +2995,9 @@ private: ammUSD_EUR.tokens())); // fixReducedOffersV2 changes the expected results slightly. - Amounts const expectedAmounts = - env.closed()->rules().enabled(fixReducedOffersV2) + Amounts const expectedAmounts = env.closed()->rules().enabled(fixReducedOffersV2) ? Amounts{XRPAmount(30'201'749), STAmount(USD, UINT64_C(29'90272233787816), -14)} - : Amounts{ - XRPAmount(30'201'749), - STAmount(USD, UINT64_C(29'90272233787818), -14)}; + : Amounts{XRPAmount(30'201'749), STAmount(USD, UINT64_C(29'90272233787818), -14)}; BEAST_EXPECT(expectOffers(env, alice, 1, {{expectedAmounts}})); } @@ -3976,12 +3009,9 @@ private: ammUSD_EUR.tokens())); // fixReducedOffersV2 changes the expected results slightly. - Amounts const expectedAmounts = - env.closed()->rules().enabled(fixReducedOffersV2) + Amounts const expectedAmounts = env.closed()->rules().enabled(fixReducedOffersV2) ? Amounts{XRPAmount(30'201'749), STAmount(USD, UINT64_C(29'90272233782839), -14)} - : Amounts{ - XRPAmount(30'201'749), - STAmount(USD, UINT64_C(29'90272233782840), -14)}; + : Amounts{XRPAmount(30'201'749), STAmount(USD, UINT64_C(29'90272233782840), -14)}; BEAST_EXPECT(expectOffers(env, alice, 1, {{expectedAmounts}})); } @@ -3989,10 +3019,7 @@ private: BEAST_EXPECT(expectHolding(env, carol, STAmount{USD, 30'100})); // Initial 1,000 - 30082730(AMM pool) - 70798251(offer) - 10(tx fee) BEAST_EXPECT(expectLedgerEntryRoot( - env, - bob, - XRP(1'000) - XRPAmount{30'082'730} - XRPAmount{70'798'251} - - txfee(env, 1))); + env, bob, XRP(1'000) - XRPAmount{30'082'730} - XRPAmount{70'798'251} - txfee(env, 1))); } // Default path (with AMM) has a better quality than a non-default path. @@ -4009,37 +3036,24 @@ private: env.close(); env(offer(alice, EUR(100), USD(100)), txflags(tfPassive)); env.close(); - env(pay(bob, carol, USD(100)), - path(~EUR, ~USD), - sendmax(XRP(102)), - txflags(tfPartialPayment)); + env(pay(bob, carol, USD(100)), path(~EUR, ~USD), sendmax(XRP(102)), txflags(tfPartialPayment)); env.close(); BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount(10'050'238'637), - STAmount(USD, UINT64_C(9'950'01249687578), -11), - ammAlice.tokens())); + XRPAmount(10'050'238'637), STAmount(USD, UINT64_C(9'950'01249687578), -11), ammAlice.tokens())); BEAST_EXPECT(expectOffers( env, alice, 2, - {{Amounts{ - XRPAmount(50'487'378), - STAmount(EUR, UINT64_C(49'98750312422), -11)}, + {{Amounts{XRPAmount(50'487'378), STAmount(EUR, UINT64_C(49'98750312422), -11)}, Amounts{ STAmount(EUR, UINT64_C(49'98750312422), -11), STAmount(USD, UINT64_C(49'98750312422), -11)}}})); // Initial 30,000 + 99.99999999999 - BEAST_EXPECT(expectHolding( - env, - carol, - STAmount{USD, UINT64_C(30'099'99999999999), -11})); + BEAST_EXPECT(expectHolding(env, carol, STAmount{USD, UINT64_C(30'099'99999999999), -11})); // Initial 1,000 - 50238637(AMM pool) - 50512622(offer) - 10(tx // fee) BEAST_EXPECT(expectLedgerEntryRoot( - env, - bob, - XRP(1'000) - XRPAmount{50'238'637} - XRPAmount{50'512'622} - - txfee(env, 1))); + env, bob, XRP(1'000) - XRPAmount{50'238'637} - XRPAmount{50'512'622} - txfee(env, 1))); }, std::nullopt, 0, @@ -4054,35 +3068,24 @@ private: env.close(); env(offer(bob, XRP(100), USD(100)), txflags(tfPassive)); env.close(); - env(pay(alice, carol, USD(200)), - sendmax(XRP(200)), - txflags(tfPartialPayment)); + env(pay(alice, carol, USD(200)), sendmax(XRP(200)), txflags(tfPartialPayment)); env.close(); if (!features[fixAMMv1_1]) { - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'100), USD(10'000), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'100), USD(10'000), ammAlice.tokens())); // Initial 30,000 + 200 BEAST_EXPECT(expectHolding(env, carol, USD(30'200))); } else { BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'100), - STAmount(USD, UINT64_C(10'000'00000000001), -11), - ammAlice.tokens())); - BEAST_EXPECT(expectHolding( - env, - carol, - STAmount(USD, UINT64_C(30'199'99999999999), -11))); + XRP(10'100), STAmount(USD, UINT64_C(10'000'00000000001), -11), ammAlice.tokens())); + BEAST_EXPECT(expectHolding(env, carol, STAmount(USD, UINT64_C(30'199'99999999999), -11))); } // Initial 30,000 - 10000(AMM pool LP) - 100(AMM offer) - // - 100(offer) - 10(tx fee) - one reserve BEAST_EXPECT(expectLedgerEntryRoot( - env, - alice, - XRP(30'000) - XRP(10'000) - XRP(100) - XRP(100) - - ammCrtFee(env) - txfee(env, 1))); + env, alice, XRP(30'000) - XRP(10'000) - XRP(100) - XRP(100) - ammCrtFee(env) - txfee(env, 1))); BEAST_EXPECT(expectOffers(env, bob, 0)); }, {{XRP(10'000), USD(10'100)}}, @@ -4100,12 +3103,9 @@ private: env(offer(bob, XRP(50), USD(150)), txflags(tfPassive)); env.close(); AMM ammAlice(env, alice, XRP(1'000), USD(1'050)); - env(pay(alice, carol, USD(200)), - sendmax(XRP(200)), - txflags(tfPartialPayment)); + env(pay(alice, carol, USD(200)), sendmax(XRP(200)), txflags(tfPartialPayment)); env.close(); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(1'050), USD(1'000), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectBalances(XRP(1'050), USD(1'000), ammAlice.tokens())); BEAST_EXPECT(expectHolding(env, carol, USD(2'200))); BEAST_EXPECT(expectOffers(env, bob, 0)); } @@ -4117,13 +3117,11 @@ private: env.close(); env(offer(bob, USD(100), XRP(100))); env.close(); - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'100), USD(10'000), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'100), USD(10'000), ammAlice.tokens())); // Initial 1,000 + 100 BEAST_EXPECT(expectHolding(env, bob, USD(1'100))); // Initial 30,000 - 100(offer) - 10(tx fee) - BEAST_EXPECT(expectLedgerEntryRoot( - env, bob, XRP(30'000) - XRP(100) - txfee(env, 1))); + BEAST_EXPECT(expectLedgerEntryRoot(env, bob, XRP(30'000) - XRP(100) - txfee(env, 1))); BEAST_EXPECT(expectOffers(env, bob, 0)); }, {{XRP(10'000), USD(10'100)}}, @@ -4144,8 +3142,7 @@ private: env(offer(carol, EUR(100), GBP(100))); env.close(); // No transfer fee - BEAST_EXPECT(ammAlice.expectBalances( - GBP(1'100), EUR(1'000), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectBalances(GBP(1'100), EUR(1'000), ammAlice.tokens())); // Initial 30,000 - 100(offer) - 25% transfer fee BEAST_EXPECT(expectHolding(env, carol, GBP(29'875))); // Initial 30,000 + 100(offer) @@ -4172,10 +3169,8 @@ private: // on higher limit out, which generates a larger offer // with lower quality. Consequently, the offer fails // to cross. - BEAST_EXPECT( - amm.expectBalances(XRP(1'000), USD(500), amm.tokens())); - BEAST_EXPECT(expectOffers( - env, carol, 1, {{Amounts{XRP(100), USD(55)}}})); + BEAST_EXPECT(amm.expectBalances(XRP(1'000), USD(500), amm.tokens())); + BEAST_EXPECT(expectOffers(env, carol, 1, {{Amounts{XRP(100), USD(55)}}})); } else { @@ -4187,21 +3182,12 @@ private: // quality. // AMM offer ~50USD/91XRP BEAST_EXPECT(amm.expectBalances( - XRPAmount(909'090'909), - STAmount{USD, UINT64_C(550'000000055), -9}, - amm.tokens())); + XRPAmount(909'090'909), STAmount{USD, UINT64_C(550'000000055), -9}, amm.tokens())); // Offer ~91XRP/49.99USD - BEAST_EXPECT(expectOffers( - env, - carol, - 1, - {{Amounts{ - XRPAmount{9'090'909}, - STAmount{USD, 4'99999995, -8}}}})); - // Carol pays 0.1% fee on ~50USD =~ 0.05USD BEAST_EXPECT( - env.balance(carol, USD) == - STAmount(USD, UINT64_C(29'949'94999999494), -11)); + expectOffers(env, carol, 1, {{Amounts{XRPAmount{9'090'909}, STAmount{USD, 4'99999995, -8}}}})); + // Carol pays 0.1% fee on ~50USD =~ 0.05USD + BEAST_EXPECT(env.balance(carol, USD) == STAmount(USD, UINT64_C(29'949'94999999494), -11)); } }, {{XRP(1'000), USD(500)}}, @@ -4216,18 +3202,14 @@ private: env.close(); if (!features[fixAMMv1_1]) { - BEAST_EXPECT(amm.expectBalances( - XRP(990), - STAmount{USD, UINT64_C(505'050505050505), -12}, - amm.tokens())); + BEAST_EXPECT( + amm.expectBalances(XRP(990), STAmount{USD, UINT64_C(505'050505050505), -12}, amm.tokens())); BEAST_EXPECT(expectOffers(env, carol, 0)); } else { - BEAST_EXPECT(amm.expectBalances( - XRP(990), - STAmount{USD, UINT64_C(505'0505050505051), -13}, - amm.tokens())); + BEAST_EXPECT( + amm.expectBalances(XRP(990), STAmount{USD, UINT64_C(505'0505050505051), -13}, amm.tokens())); BEAST_EXPECT(expectOffers(env, carol, 0)); } }, @@ -4239,13 +3221,7 @@ private: testAMM( [&](AMM& ammAlice, Env& env) { Account const ed("ed"); - fund( - env, - gw, - {bob, ed}, - XRP(30'000), - {GBP(2'000), EUR(2'000)}, - Fund::Acct); + fund(env, gw, {bob, ed}, XRP(30'000), {GBP(2'000), EUR(2'000)}, Fund::Acct); env(rate(gw, 1.25)); env.close(); // The auto-bridge is worse quality than AMM, is not consumed @@ -4287,15 +3263,9 @@ private: // = 58.825 = ~29941.17 // carol bought ~72.93EUR at the cost of ~70.68GBP // the offer is partially consumed - BEAST_EXPECT(expectHolding( - env, - carol, - STAmount{GBP, UINT64_C(29'941'16770347333), -11})); + BEAST_EXPECT(expectHolding(env, carol, STAmount{GBP, UINT64_C(29'941'16770347333), -11})); // Initial 30,000 + ~49.3(offers = 39.3(AMM) + 10(LOB)) - BEAST_EXPECT(expectHolding( - env, - carol, - STAmount{EUR, UINT64_C(30'049'31517120716), -11})); + BEAST_EXPECT(expectHolding(env, carol, STAmount{EUR, UINT64_C(30'049'31517120716), -11})); } else { @@ -4326,15 +3296,9 @@ private: // = 88.35 = ~29911.64 // carol bought ~72.93EUR at the cost of ~70.68GBP // the offer is partially consumed - BEAST_EXPECT(expectHolding( - env, - carol, - STAmount{GBP, UINT64_C(29'911'64396400896), -11})); + BEAST_EXPECT(expectHolding(env, carol, STAmount{GBP, UINT64_C(29'911'64396400896), -11})); // Initial 30,000 + ~72.93(offers = 62.93(AMM) + 10(LOB)) - BEAST_EXPECT(expectHolding( - env, - carol, - STAmount{EUR, UINT64_C(30'072'93416277865), -11})); + BEAST_EXPECT(expectHolding(env, carol, STAmount{EUR, UINT64_C(30'072'93416277865), -11})); } // Initial 2000 + 10 = 2010 BEAST_EXPECT(expectHolding(env, bob, GBP(2'010))); @@ -4358,13 +3322,9 @@ private: fund(env, gw, {bob}, {GBP(200), EUR(200)}, Fund::Acct); env(rate(gw, 1.25)); env.close(); - env(pay(bob, carol, EUR(100)), - path(~EUR), - sendmax(GBP(125)), - txflags(tfPartialPayment)); + env(pay(bob, carol, EUR(100)), path(~EUR), sendmax(GBP(125)), txflags(tfPartialPayment)); env.close(); - BEAST_EXPECT(ammAlice.expectBalances( - GBP(1'100), EUR(1'000), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectBalances(GBP(1'100), EUR(1'000), ammAlice.tokens())); BEAST_EXPECT(expectHolding(env, bob, GBP(75))); BEAST_EXPECT(expectHolding(env, carol, EUR(30'080))); }, @@ -4405,8 +3365,7 @@ private: env.close(); BEAST_EXPECT(expectHolding(env, bob, CAN(0))); BEAST_EXPECT(expectHolding(env, dan, CAN(356.25), GBP(43.75))); - BEAST_EXPECT(ammAlice.expectBalances( - GBP(10'125), EUR(10'000), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectBalances(GBP(10'125), EUR(10'000), ammAlice.tokens())); BEAST_EXPECT(expectHolding(env, ed, EUR(300), USD(100))); BEAST_EXPECT(expectHolding(env, carol, USD(80))); }, @@ -4448,12 +3407,7 @@ private: { Env env(*this, features); auto const ETH = gw["ETH"]; - fund( - env, - gw, - {alice}, - XRP(100'000), - {EUR(50'000), BTC(50'000), ETH(50'000), USD(50'000)}); + fund(env, gw, {alice}, XRP(100'000), {EUR(50'000), BTC(50'000), ETH(50'000), USD(50'000)}); fund(env, gw, {carol, bob}, XRP(1'000), {USD(200)}, Fund::Acct); AMM xrp_eur(env, alice, XRP(10'100), EUR(10'000)); AMM eur_btc(env, alice, EUR(10'000), BTC(10'200)); @@ -4472,9 +3426,7 @@ private: // XRP-ETH-EUR-USD // This path provides ~26.06USD/26.2XRP BEAST_EXPECT(xrp_eth.expectBalances( - XRPAmount(10'026'208'900), - STAmount{ETH, UINT64_C(10'073'65779244494), -11}, - xrp_eth.tokens())); + XRPAmount(10'026'208'900), STAmount{ETH, UINT64_C(10'073'65779244494), -11}, xrp_eth.tokens())); BEAST_EXPECT(eth_eur.expectBalances( STAmount{ETH, UINT64_C(10'926'34220755506), -11}, STAmount{EUR, UINT64_C(10'973'54232078752), -11}, @@ -4486,16 +3438,12 @@ private: // XRP-USD path // This path provides ~73.9USD/74.1XRP BEAST_EXPECT(xrp_usd.expectBalances( - XRPAmount(10'224'106'246), - STAmount{USD, UINT64_C(10'126'06848287914), -11}, - xrp_usd.tokens())); + XRPAmount(10'224'106'246), STAmount{USD, UINT64_C(10'126'06848287914), -11}, xrp_usd.tokens())); } else { BEAST_EXPECT(xrp_eth.expectBalances( - XRPAmount(10'026'208'900), - STAmount{ETH, UINT64_C(10'073'65779244461), -11}, - xrp_eth.tokens())); + XRPAmount(10'026'208'900), STAmount{ETH, UINT64_C(10'073'65779244461), -11}, xrp_eth.tokens())); BEAST_EXPECT(eth_eur.expectBalances( STAmount{ETH, UINT64_C(10'926'34220755539), -11}, STAmount{EUR, UINT64_C(10'973'5423207872), -10}, @@ -4507,9 +3455,7 @@ private: // XRP-USD path // This path provides ~73.9USD/74.1XRP BEAST_EXPECT(xrp_usd.expectBalances( - XRPAmount(10'224'106'246), - STAmount{USD, UINT64_C(10'126'06848287943), -11}, - xrp_usd.tokens())); + XRPAmount(10'224'106'246), STAmount{USD, UINT64_C(10'126'06848287943), -11}, xrp_usd.tokens())); } // XRP-EUR-BTC-USD @@ -4518,12 +3464,9 @@ private: // shows a different distribution: // XRP-EUR-BTC-USD 11.6USD/11.64XRP, XRP-USD 60.7USD/60.8XRP, // XRP-ETH-EUR-USD 27.6USD/27.6XRP - BEAST_EXPECT(xrp_eur.expectBalances( - XRP(10'100), EUR(10'000), xrp_eur.tokens())); - BEAST_EXPECT(eur_btc.expectBalances( - EUR(10'000), BTC(10'200), eur_btc.tokens())); - BEAST_EXPECT(btc_usd.expectBalances( - BTC(10'100), USD(10'000), btc_usd.tokens())); + BEAST_EXPECT(xrp_eur.expectBalances(XRP(10'100), EUR(10'000), xrp_eur.tokens())); + BEAST_EXPECT(eur_btc.expectBalances(EUR(10'000), BTC(10'200), eur_btc.tokens())); + BEAST_EXPECT(btc_usd.expectBalances(BTC(10'100), USD(10'000), btc_usd.tokens())); BEAST_EXPECT(expectHolding(env, carol, USD(300))); } @@ -4532,42 +3475,28 @@ private: { Env env(*this, features); auto const ETH = gw["ETH"]; - fund( - env, - gw, - {alice}, - XRP(40'000), - {EUR(50'000), BTC(50'000), ETH(50'000), USD(50'000)}); + fund(env, gw, {alice}, XRP(40'000), {EUR(50'000), BTC(50'000), ETH(50'000), USD(50'000)}); fund(env, gw, {carol, bob}, XRP(1000), {USD(200)}, Fund::Acct); AMM xrp_eur(env, alice, XRP(10'100), EUR(10'000)); AMM eur_btc(env, alice, EUR(10'000), BTC(10'200)); AMM btc_usd(env, alice, BTC(10'100), USD(10'000)); AMM xrp_eth(env, alice, XRP(10'000), ETH(10'100)); AMM eth_eur(env, alice, ETH(10'900), EUR(11'000)); - env(pay(bob, carol, USD(100)), - path(~EUR, ~BTC, ~USD), - path(~ETH, ~EUR, ~BTC, ~USD), - sendmax(XRP(200))); + env(pay(bob, carol, USD(100)), path(~EUR, ~BTC, ~USD), path(~ETH, ~EUR, ~BTC, ~USD), sendmax(XRP(200))); if (!features[fixAMMv1_1]) { // XRP-EUR-BTC-USD path provides ~17.8USD/~18.7XRP // XRP-ETH-EUR-BTC-USD path provides ~82.2USD/82.4XRP BEAST_EXPECT(xrp_eur.expectBalances( - XRPAmount(10'118'738'472), - STAmount{EUR, UINT64_C(9'981'544436337968), -12}, - xrp_eur.tokens())); + XRPAmount(10'118'738'472), STAmount{EUR, UINT64_C(9'981'544436337968), -12}, xrp_eur.tokens())); BEAST_EXPECT(eur_btc.expectBalances( STAmount{EUR, UINT64_C(10'101'16096785173), -11}, STAmount{BTC, UINT64_C(10'097'91426968066), -11}, eur_btc.tokens())); BEAST_EXPECT(btc_usd.expectBalances( - STAmount{BTC, UINT64_C(10'202'08573031934), -11}, - USD(9'900), - btc_usd.tokens())); + STAmount{BTC, UINT64_C(10'202'08573031934), -11}, USD(9'900), btc_usd.tokens())); BEAST_EXPECT(xrp_eth.expectBalances( - XRPAmount(10'082'446'397), - STAmount{ETH, UINT64_C(10'017'41072778012), -11}, - xrp_eth.tokens())); + XRPAmount(10'082'446'397), STAmount{ETH, UINT64_C(10'017'41072778012), -11}, xrp_eth.tokens())); BEAST_EXPECT(eth_eur.expectBalances( STAmount{ETH, UINT64_C(10'982'58927221988), -11}, STAmount{EUR, UINT64_C(10'917'2945958103), -10}, @@ -4576,21 +3505,15 @@ private: else { BEAST_EXPECT(xrp_eur.expectBalances( - XRPAmount(10'118'738'472), - STAmount{EUR, UINT64_C(9'981'544436337923), -12}, - xrp_eur.tokens())); + XRPAmount(10'118'738'472), STAmount{EUR, UINT64_C(9'981'544436337923), -12}, xrp_eur.tokens())); BEAST_EXPECT(eur_btc.expectBalances( STAmount{EUR, UINT64_C(10'101'16096785188), -11}, STAmount{BTC, UINT64_C(10'097'91426968059), -11}, eur_btc.tokens())); BEAST_EXPECT(btc_usd.expectBalances( - STAmount{BTC, UINT64_C(10'202'08573031941), -11}, - USD(9'900), - btc_usd.tokens())); + STAmount{BTC, UINT64_C(10'202'08573031941), -11}, USD(9'900), btc_usd.tokens())); BEAST_EXPECT(xrp_eth.expectBalances( - XRPAmount(10'082'446'397), - STAmount{ETH, UINT64_C(10'017'41072777996), -11}, - xrp_eth.tokens())); + XRPAmount(10'082'446'397), STAmount{ETH, UINT64_C(10'017'41072777996), -11}, xrp_eth.tokens())); BEAST_EXPECT(eth_eur.expectBalances( STAmount{ETH, UINT64_C(10'982'58927222004), -11}, STAmount{EUR, UINT64_C(10'917'2945958102), -10}, @@ -4619,27 +3542,16 @@ private: { // Carol gets ~29.91USD because of the AMM offers limit BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'030), - STAmount{USD, UINT64_C(9'970'089730807577), -12}, - ammAlice.tokens())); - BEAST_EXPECT(expectHolding( - env, - carol, - STAmount{USD, UINT64_C(30'029'91026919241), -11})); + XRP(10'030), STAmount{USD, UINT64_C(9'970'089730807577), -12}, ammAlice.tokens())); + BEAST_EXPECT(expectHolding(env, carol, STAmount{USD, UINT64_C(30'029'91026919241), -11})); } else { BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'030), - STAmount{USD, UINT64_C(9'970'089730807827), -12}, - ammAlice.tokens())); - BEAST_EXPECT(expectHolding( - env, - carol, - STAmount{USD, UINT64_C(30'029'91026919217), -11})); + XRP(10'030), STAmount{USD, UINT64_C(9'970'089730807827), -12}, ammAlice.tokens())); + BEAST_EXPECT(expectHolding(env, carol, STAmount{USD, UINT64_C(30'029'91026919217), -11})); } - BEAST_EXPECT( - expectOffers(env, alice, 1, {{{EUR(140), XRP(100)}}})); + BEAST_EXPECT(expectOffers(env, alice, 1, {{{EUR(140), XRP(100)}}})); }, std::nullopt, 0, @@ -4660,26 +3572,18 @@ private: path(~XRP, ~USD), sendmax(EUR(400)), txflags(tfPartialPayment | tfNoRippleDirect)); - BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount{10'101'010'102}, USD(9'900), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectBalances(XRPAmount{10'101'010'102}, USD(9'900), ammAlice.tokens())); if (!features[fixAMMv1_1]) { // Carol gets ~100USD - BEAST_EXPECT(expectHolding( - env, - carol, - STAmount{USD, UINT64_C(30'099'99999999999), -11})); + BEAST_EXPECT(expectHolding(env, carol, STAmount{USD, UINT64_C(30'099'99999999999), -11})); } else { BEAST_EXPECT(expectHolding(env, carol, USD(30'100))); } - BEAST_EXPECT(expectOffers( - env, - alice, - 1, - {{{STAmount{EUR, UINT64_C(39'1858572), -7}, - XRPAmount{27'989'898}}}})); + BEAST_EXPECT( + expectOffers(env, alice, 1, {{{STAmount{EUR, UINT64_C(39'1858572), -7}, XRPAmount{27'989'898}}}})); }, std::nullopt, 0, @@ -4697,28 +3601,16 @@ private: if (!features[fixAMMv1_1]) { BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount{10'049'825'373}, - STAmount{USD, UINT64_C(10'049'92586949302), -11}, - ammAlice.tokens())); + XRPAmount{10'049'825'373}, STAmount{USD, UINT64_C(10'049'92586949302), -11}, ammAlice.tokens())); BEAST_EXPECT(expectOffers( - env, - bob, - 1, - {{{XRPAmount{50'074'629}, - STAmount{USD, UINT64_C(50'07513050698), -11}}}})); + env, bob, 1, {{{XRPAmount{50'074'629}, STAmount{USD, UINT64_C(50'07513050698), -11}}}})); } else { BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount{10'049'825'372}, - STAmount{USD, UINT64_C(10'049'92587049303), -11}, - ammAlice.tokens())); + XRPAmount{10'049'825'372}, STAmount{USD, UINT64_C(10'049'92587049303), -11}, ammAlice.tokens())); BEAST_EXPECT(expectOffers( - env, - bob, - 1, - {{{XRPAmount{50'074'628}, - STAmount{USD, UINT64_C(50'07512950697), -11}}}})); + env, bob, 1, {{{XRPAmount{50'074'628}, STAmount{USD, UINT64_C(50'07512950697), -11}}}})); BEAST_EXPECT(expectHolding(env, carol, USD(30'100))); } } @@ -4752,17 +3644,13 @@ private: auto const baseFee = env.current()->fees().base.drops(); auto const token1 = ammAlice.lptIssue(); auto priceXRP = ammAssetOut( - STAmount{XRPAmount{10'000'000'000}}, - STAmount{token1, 10'000'000}, - STAmount{token1, 5'000'000}, - 0); + STAmount{XRPAmount{10'000'000'000}}, STAmount{token1, 10'000'000}, STAmount{token1, 5'000'000}, 0); // Carol places an order to buy LPTokens env(offer(carol, STAmount{token1, 5'000'000}, priceXRP)); // Alice places an order to sell LPTokens env(offer(alice, priceXRP, STAmount{token1, 5'000'000})); // Pool's LPTokens balance doesn't change - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'000), USD(10'000), IOUAmount{10'000'000})); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), USD(10'000), IOUAmount{10'000'000})); // Carol is Liquidity Provider BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount{5'000'000})); BEAST_EXPECT(ammAlice.expectLPTokens(alice, IOUAmount{5'000'000})); @@ -4775,23 +3663,14 @@ private: env(ammAlice.bid({.account = carol, .bidMin = 100})); BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount{4'999'900})); BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 0, IOUAmount{100})); - BEAST_EXPECT( - accountBalance(env, carol) == - std::to_string(22500000000 - 4 * baseFee)); + BEAST_EXPECT(accountBalance(env, carol) == std::to_string(22500000000 - 4 * baseFee)); priceXRP = ammAssetOut( - STAmount{XRPAmount{10'000'000'000}}, - STAmount{token1, 9'999'900}, - STAmount{token1, 4'999'900}, - 0); + STAmount{XRPAmount{10'000'000'000}}, STAmount{token1, 9'999'900}, STAmount{token1, 4'999'900}, 0); // Carol withdraws ammAlice.withdrawAll(carol, XRP(0)); + BEAST_EXPECT(accountBalance(env, carol) == std::to_string(29999949999 - 5 * baseFee)); BEAST_EXPECT( - accountBalance(env, carol) == - std::to_string(29999949999 - 5 * baseFee)); - BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount{10'000'000'000} - priceXRP, - USD(10'000), - IOUAmount{5'000'000})); + ammAlice.expectBalances(XRPAmount{10'000'000'000} - priceXRP, USD(10'000), IOUAmount{5'000'000})); BEAST_EXPECT(ammAlice.expectLPTokens(alice, IOUAmount{5'000'000})); BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount{0})); }); @@ -4804,8 +3683,7 @@ private: ammAlice1.deposit(carol, 1'000'000); auto const token1 = ammAlice.lptIssue(); auto const token2 = ammAlice1.lptIssue(); - env(offer(alice, STAmount{token1, 100}, STAmount{token2, 100}), - txflags(tfPassive)); + env(offer(alice, STAmount{token1, 100}, STAmount{token2, 100}), txflags(tfPassive)); env.close(); BEAST_EXPECT(expectOffers(env, alice, 1)); env(offer(carol, STAmount{token2, 100}, STAmount{token1, 100})); @@ -4816,8 +3694,7 @@ private: BEAST_EXPECT( expectHolding(env, carol, STAmount{token2, 1'000'100}) && expectHolding(env, carol, STAmount{token1, 999'900})); - BEAST_EXPECT( - expectOffers(env, alice, 0) && expectOffers(env, carol, 0)); + BEAST_EXPECT(expectOffers(env, alice, 0) && expectOffers(env, carol, 0)); }); // LPs pay LPTokens directly. Must trust set because the trust line @@ -4859,8 +3736,7 @@ private: FeatureBitset const all{testable_amendments()}; FeatureBitset const noAMM{all - featureAMM}; FeatureBitset const noNumber{all - fixUniversalNumber}; - FeatureBitset const noAMMAndNumber{ - all - featureAMM - fixUniversalNumber}; + FeatureBitset const noAMMAndNumber{all - featureAMM - fixUniversalNumber}; using namespace jtx; for (auto const& feature : {noAMM, noNumber, noAMMAndNumber}) @@ -4874,8 +3750,7 @@ private: amm.vote(VoteArg{.tfee = 100, .err = ter(temDISABLED)}); amm.withdraw(WithdrawArg{.tokens = 100, .err = ter(temMALFORMED)}); amm.withdraw(WithdrawArg{.err = ter(temDISABLED)}); - amm.deposit( - DepositArg{.asset1In = USD(100), .err = ter(temDISABLED)}); + amm.deposit(DepositArg{.asset1In = USD(100), .err = ter(temDISABLED)}); amm.ammDelete(alice, ter(temDISABLED)); } } @@ -4888,16 +3763,9 @@ private: testAMM([&](AMM& ammAlice, Env& env) { auto const info = env.rpc( - "json", - "account_info", - std::string( - "{\"account\": \"" + to_string(ammAlice.ammAccount()) + - "\"}")); - auto const flags = - info[jss::result][jss::account_data][jss::Flags].asUInt(); - BEAST_EXPECT( - flags == - (lsfDisableMaster | lsfDefaultRipple | lsfDepositAuth)); + "json", "account_info", std::string("{\"account\": \"" + to_string(ammAlice.ammAccount()) + "\"}")); + auto const flags = info[jss::result][jss::account_data][jss::Flags].asUInt(); + BEAST_EXPECT(flags == (lsfDisableMaster | lsfDefaultRipple | lsfDepositAuth)); }); } @@ -4987,9 +3855,7 @@ private: prep( [&](Env& env) { AMM amm(env, LP1, TST(25), XRP(250)); }, [&](Env& env) { - lp2TSTBalance = - getAccountLines(env, LP2, TST)["lines"][0u]["balance"] - .asString(); + lp2TSTBalance = getAccountLines(env, LP2, TST)["lines"][0u]["balance"].asString(); auto const offer = getAccountOffers(env, LP2)["offers"][0u]; lp2TakerGets = offer["taker_gets"].asString(); lp2TakerPays = offer["taker_pays"]["value"].asString(); @@ -4998,27 +3864,17 @@ private: prep( [&](Env& env) { if (!features[fixAMMv1_1]) - env(offer( - LP1, - XRPAmount{18'095'133}, - STAmount{TST, UINT64_C(1'68737984885388), -14}), + env(offer(LP1, XRPAmount{18'095'133}, STAmount{TST, UINT64_C(1'68737984885388), -14}), txflags(tfPassive)); else - env(offer( - LP1, - XRPAmount{18'095'132}, - STAmount{TST, UINT64_C(1'68737976189735), -14}), + env(offer(LP1, XRPAmount{18'095'132}, STAmount{TST, UINT64_C(1'68737976189735), -14}), txflags(tfPassive)); }, [&](Env& env) { - BEAST_EXPECT( - lp2TSTBalance == - getAccountLines(env, LP2, TST)["lines"][0u]["balance"] - .asString()); + BEAST_EXPECT(lp2TSTBalance == getAccountLines(env, LP2, TST)["lines"][0u]["balance"].asString()); auto const offer = getAccountOffers(env, LP2)["offers"][0u]; BEAST_EXPECT(lp2TakerGets == offer["taker_gets"].asString()); - BEAST_EXPECT( - lp2TakerPays == offer["taker_pays"]["value"].asString()); + BEAST_EXPECT(lp2TakerPays == offer["taker_pays"]["value"].asString()); }); } @@ -5043,17 +3899,13 @@ private: // Carol gets fewer LPToken ~994, because of the single deposit // fee ammAlice.deposit(carol, USD(3'000)); - BEAST_EXPECT(ammAlice.expectLPTokens( - carol, IOUAmount{994'981155689671, -12})); + BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount{994'981155689671, -12})); BEAST_EXPECT(expectHolding(env, carol, USD(27'000))); // Set fee to 0 ammAlice.vote(alice, 0); ammAlice.withdrawAll(carol, USD(0)); // Carol gets back less than the original deposit - BEAST_EXPECT(expectHolding( - env, - carol, - STAmount{USD, UINT64_C(29'994'96220068281), -11})); + BEAST_EXPECT(expectHolding(env, carol, STAmount{USD, UINT64_C(29'994'96220068281), -11})); }, {{USD(1'000), EUR(1'000)}}, 0, @@ -5065,8 +3917,7 @@ private: testAMM( [&](AMM& ammAlice, Env& env) { auto const balance = env.balance(carol, USD); - auto tokensFee = ammAlice.deposit( - carol, USD(1'000), std::nullopt, STAmount{USD, 1, -1}); + auto tokensFee = ammAlice.deposit(carol, USD(1'000), std::nullopt, STAmount{USD, 1, -1}); auto const deposit = balance - env.balance(carol, USD); ammAlice.withdrawAll(carol, USD(0)); ammAlice.vote(alice, 0); @@ -5087,8 +3938,7 @@ private: testAMM( [&](AMM& ammAlice, Env& env) { auto const balance = env.balance(carol, USD); - auto const tokensFee = ammAlice.deposit( - carol, USD(200), std::nullopt, STAmount{USD, 2020, -6}); + auto const tokensFee = ammAlice.deposit(carol, USD(200), std::nullopt, STAmount{USD, 2020, -6}); auto const deposit = balance - env.balance(carol, USD); ammAlice.withdrawAll(carol, USD(0)); ammAlice.vote(alice, 0); @@ -5117,10 +3967,7 @@ private: BEAST_EXPECT(ammAlice.expectTradingFee(1'000)); // Single withdrawal. Carol gets ~5USD less than deposited. ammAlice.withdrawAll(carol, USD(0)); - BEAST_EXPECT(expectHolding( - env, - carol, - STAmount{USD, UINT64_C(29'994'97487437186), -11})); + BEAST_EXPECT(expectHolding(env, carol, STAmount{USD, UINT64_C(29'994'97487437186), -11})); }, {{USD(1'000), EUR(1'000)}}, 0, @@ -5131,8 +3978,7 @@ private: testAMM( [&](AMM& ammAlice, Env& env) { ammAlice.deposit(carol, 1'000'000); - auto const tokensFee = ammAlice.withdraw( - carol, USD(100), std::nullopt, IOUAmount{520, 0}); + auto const tokensFee = ammAlice.withdraw(carol, USD(100), std::nullopt, IOUAmount{520, 0}); // carol withdraws ~1,443.44USD auto const balanceAfterWithdraw = [&]() { if (!features[fixAMMv1_1] && !features[fixAMMv1_3]) @@ -5151,28 +3997,19 @@ private: BEAST_EXPECT(ammAlice.expectTradingFee(0)); auto const tokensNoFee = ammAlice.withdraw(carol, deposit); if (!features[fixAMMv1_1] && !features[fixAMMv1_3]) - BEAST_EXPECT( - env.balance(carol, USD) == - STAmount(USD, UINT64_C(30'443'43891402717), -11)); + BEAST_EXPECT(env.balance(carol, USD) == STAmount(USD, UINT64_C(30'443'43891402717), -11)); else if (features[fixAMMv1_1] && !features[fixAMMv1_3]) - BEAST_EXPECT( - env.balance(carol, USD) == - STAmount(USD, UINT64_C(30'443'43891402716), -11)); + BEAST_EXPECT(env.balance(carol, USD) == STAmount(USD, UINT64_C(30'443'43891402716), -11)); else - BEAST_EXPECT( - env.balance(carol, USD) == - STAmount(USD, UINT64_C(30'443'43891402713), -11)); + BEAST_EXPECT(env.balance(carol, USD) == STAmount(USD, UINT64_C(30'443'43891402713), -11)); // carol pays ~4008 LPTokens in fees or ~0.5% of the no-fee // LPTokens if (!features[fixAMMv1_1] && !features[fixAMMv1_3]) - BEAST_EXPECT( - tokensNoFee == IOUAmount(746'579'80779913, -8)); + BEAST_EXPECT(tokensNoFee == IOUAmount(746'579'80779913, -8)); else if (features[fixAMMv1_1] && !features[fixAMMv1_3]) - BEAST_EXPECT( - tokensNoFee == IOUAmount(746'579'80779912, -8)); + BEAST_EXPECT(tokensNoFee == IOUAmount(746'579'80779912, -8)); else - BEAST_EXPECT( - tokensNoFee == IOUAmount(746'579'80779911, -8)); + BEAST_EXPECT(tokensNoFee == IOUAmount(746'579'80779911, -8)); BEAST_EXPECT(tokensFee == IOUAmount(750'588'23529411, -8)); }, std::nullopt, @@ -5183,22 +4020,13 @@ private: // Payment, 1% fee testAMM( [&](AMM& ammAlice, Env& env) { - fund( - env, - gw, - {bob}, - XRP(1'000), - {USD(1'000), EUR(1'000)}, - Fund::Acct); + fund(env, gw, {bob}, XRP(1'000), {USD(1'000), EUR(1'000)}, Fund::Acct); // Alice contributed 1010EUR and 1000USD to the pool BEAST_EXPECT(expectHolding(env, alice, EUR(28'990))); BEAST_EXPECT(expectHolding(env, alice, USD(29'000))); BEAST_EXPECT(expectHolding(env, carol, USD(30'000))); // Carol pays to Alice with no fee - env(pay(carol, alice, EUR(10)), - path(~EUR), - sendmax(USD(10)), - txflags(tfNoRippleDirect)); + env(pay(carol, alice, EUR(10)), path(~EUR), sendmax(USD(10)), txflags(tfNoRippleDirect)); env.close(); // Alice has 10EUR more and Carol has 10USD less BEAST_EXPECT(expectHolding(env, alice, EUR(29'000))); @@ -5209,20 +4037,14 @@ private: ammAlice.vote(alice, 1'000); BEAST_EXPECT(ammAlice.expectTradingFee(1'000)); // Bob pays to Carol with 1% fee - env(pay(bob, carol, USD(10)), - path(~USD), - sendmax(EUR(15)), - txflags(tfNoRippleDirect)); + env(pay(bob, carol, USD(10)), path(~USD), sendmax(EUR(15)), txflags(tfNoRippleDirect)); env.close(); // Bob sends 10.1~EUR to pay 10USD - BEAST_EXPECT(expectHolding( - env, bob, STAmount{EUR, UINT64_C(989'8989898989899), -13})); + BEAST_EXPECT(expectHolding(env, bob, STAmount{EUR, UINT64_C(989'8989898989899), -13})); // Carol got 10USD BEAST_EXPECT(expectHolding(env, carol, USD(30'000))); BEAST_EXPECT(ammAlice.expectBalances( - USD(1'000), - STAmount{EUR, UINT64_C(1'010'10101010101), -11}, - ammAlice.tokens())); + USD(1'000), STAmount{EUR, UINT64_C(1'010'10101010101), -11}, ammAlice.tokens())); }, {{USD(1'000), EUR(1'010)}}, 0, @@ -5247,14 +4069,8 @@ private: env.close(); // Alice gets fewer ~4.97EUR for ~5.02USD, the difference goes // to the pool - BEAST_EXPECT(expectHolding( - env, - carol, - STAmount{USD, UINT64_C(29'995'02512562814), -11})); - BEAST_EXPECT(expectHolding( - env, - carol, - STAmount{EUR, UINT64_C(30'004'97487437186), -11})); + BEAST_EXPECT(expectHolding(env, carol, STAmount{USD, UINT64_C(29'995'02512562814), -11})); + BEAST_EXPECT(expectHolding(env, carol, STAmount{EUR, UINT64_C(30'004'97487437186), -11})); BEAST_EXPECT(expectOffers( env, carol, @@ -5289,33 +4105,21 @@ private: { Env env(*this, features); Account const ed("ed"); - fund( - env, - gw, - {alice, bob, carol, ed}, - XRP(1'000), - {USD(2'000), EUR(2'000)}); + fund(env, gw, {alice, bob, carol, ed}, XRP(1'000), {USD(2'000), EUR(2'000)}); env(offer(carol, EUR(5), USD(5))); AMM ammAlice(env, alice, USD(1'005), EUR(1'000)); - env(pay(bob, ed, USD(10)), - path(~USD), - sendmax(EUR(15)), - txflags(tfNoRippleDirect)); + env(pay(bob, ed, USD(10)), path(~USD), sendmax(EUR(15)), txflags(tfNoRippleDirect)); BEAST_EXPECT(expectHolding(env, ed, USD(2'010))); if (!features[fixAMMv1_1]) { BEAST_EXPECT(expectHolding(env, bob, EUR(1'990))); - BEAST_EXPECT(ammAlice.expectBalances( - USD(1'000), EUR(1'005), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectBalances(USD(1'000), EUR(1'005), ammAlice.tokens())); } else { - BEAST_EXPECT(expectHolding( - env, bob, STAmount(EUR, UINT64_C(1989'999999999999), -12))); + BEAST_EXPECT(expectHolding(env, bob, STAmount(EUR, UINT64_C(1989'999999999999), -12))); BEAST_EXPECT(ammAlice.expectBalances( - USD(1'000), - STAmount(EUR, UINT64_C(1005'000000000001), -12), - ammAlice.tokens())); + USD(1'000), STAmount(EUR, UINT64_C(1005'000000000001), -12), ammAlice.tokens())); } BEAST_EXPECT(expectOffers(env, carol, 0)); } @@ -5325,41 +4129,23 @@ private: { Env env(*this, features); Account const ed("ed"); - fund( - env, - gw, - {alice, bob, carol, ed}, - XRP(1'000), - {USD(2'000), EUR(2'000)}); + fund(env, gw, {alice, bob, carol, ed}, XRP(1'000), {USD(2'000), EUR(2'000)}); env(offer(carol, EUR(5), USD(5))); // Set 0.25% fee AMM ammAlice(env, alice, USD(1'005), EUR(1'000), false, 250); - env(pay(bob, ed, USD(10)), - path(~USD), - sendmax(EUR(15)), - txflags(tfNoRippleDirect)); + env(pay(bob, ed, USD(10)), path(~USD), sendmax(EUR(15)), txflags(tfNoRippleDirect)); BEAST_EXPECT(expectHolding(env, ed, USD(2'010))); if (!features[fixAMMv1_1]) { - BEAST_EXPECT(expectHolding( - env, - bob, - STAmount{EUR, UINT64_C(1'989'987453007618), -12})); + BEAST_EXPECT(expectHolding(env, bob, STAmount{EUR, UINT64_C(1'989'987453007618), -12})); BEAST_EXPECT(ammAlice.expectBalances( - USD(1'000), - STAmount{EUR, UINT64_C(1'005'012546992382), -12}, - ammAlice.tokens())); + USD(1'000), STAmount{EUR, UINT64_C(1'005'012546992382), -12}, ammAlice.tokens())); } else { - BEAST_EXPECT(expectHolding( - env, - bob, - STAmount{EUR, UINT64_C(1'989'987453007628), -12})); + BEAST_EXPECT(expectHolding(env, bob, STAmount{EUR, UINT64_C(1'989'987453007628), -12})); BEAST_EXPECT(ammAlice.expectBalances( - USD(1'000), - STAmount{EUR, UINT64_C(1'005'012546992372), -12}, - ammAlice.tokens())); + USD(1'000), STAmount{EUR, UINT64_C(1'005'012546992372), -12}, ammAlice.tokens())); } BEAST_EXPECT(expectOffers(env, carol, 0)); } @@ -5370,23 +4156,14 @@ private: { Env env(*this, features); Account const ed("ed"); - fund( - env, - gw, - {alice, bob, carol, ed}, - XRP(1'000), - {USD(2'000), EUR(2'000)}); + fund(env, gw, {alice, bob, carol, ed}, XRP(1'000), {USD(2'000), EUR(2'000)}); env(offer(carol, EUR(10), USD(10))); // Set 1% fee AMM ammAlice(env, alice, USD(1'005), EUR(1'000), false, 1'000); - env(pay(bob, ed, USD(10)), - path(~USD), - sendmax(EUR(15)), - txflags(tfNoRippleDirect)); + env(pay(bob, ed, USD(10)), path(~USD), sendmax(EUR(15)), txflags(tfNoRippleDirect)); BEAST_EXPECT(expectHolding(env, ed, USD(2'010))); BEAST_EXPECT(expectHolding(env, bob, EUR(1'990))); - BEAST_EXPECT(ammAlice.expectBalances( - USD(1'005), EUR(1'000), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectBalances(USD(1'005), EUR(1'000), ammAlice.tokens())); BEAST_EXPECT(expectOffers(env, carol, 0)); } @@ -5397,26 +4174,15 @@ private: { Env env(*this, features); Account const ed("ed"); - fund( - env, - gw, - {alice, bob, carol, ed}, - XRP(1'000), - {USD(2'000), EUR(2'000)}); + fund(env, gw, {alice, bob, carol, ed}, XRP(1'000), {USD(2'000), EUR(2'000)}); env(offer(carol, EUR(9), USD(9))); // Set 1% fee AMM ammAlice(env, alice, USD(1'005), EUR(1'000), false, 1'000); - env(pay(bob, ed, USD(10)), - path(~USD), - sendmax(EUR(15)), - txflags(tfNoRippleDirect)); + env(pay(bob, ed, USD(10)), path(~USD), sendmax(EUR(15)), txflags(tfNoRippleDirect)); BEAST_EXPECT(expectHolding(env, ed, USD(2'010))); - BEAST_EXPECT(expectHolding( - env, bob, STAmount{EUR, UINT64_C(1'989'993923296712), -12})); + BEAST_EXPECT(expectHolding(env, bob, STAmount{EUR, UINT64_C(1'989'993923296712), -12})); BEAST_EXPECT(ammAlice.expectBalances( - USD(1'004), - STAmount{EUR, UINT64_C(1'001'006076703288), -12}, - ammAlice.tokens())); + USD(1'004), STAmount{EUR, UINT64_C(1'001'006076703288), -12}, ammAlice.tokens())); BEAST_EXPECT(expectOffers(env, carol, 0)); } } @@ -5438,13 +4204,8 @@ private: Account const chris("chris"); Account const simon("simon"); Account const ben("ben"); - Account const nataly("nataly"); - fund( - env, - gw, - {bob, ed, paul, dan, chris, simon, ben, nataly}, - {USD(1'500'000)}, - Fund::Acct); + Account const natalie("natalie"); + fund(env, gw, {bob, ed, paul, dan, chris, simon, ben, natalie}, {USD(1'500'000)}, Fund::Acct); for (int i = 0; i < 10; ++i) { ammAlice.deposit(ben, STAmount{USD, 1, -10}); @@ -5463,34 +4224,26 @@ private: ammAlice.withdrawAll(ed, USD(0)); ammAlice.deposit(paul, USD(100'000)); ammAlice.withdrawAll(paul, USD(0)); - ammAlice.deposit(nataly, USD(1'000'000)); - ammAlice.withdrawAll(nataly, USD(0)); + ammAlice.deposit(natalie, USD(1'000'000)); + ammAlice.withdrawAll(natalie, USD(0)); } // Due to round off some accounts have a tiny gain, while // other have a tiny loss. The last account to withdraw // gets everything in the pool. if (!features[fixAMMv1_1] && !features[fixAMMv1_3]) BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'000), - STAmount{USD, UINT64_C(10'000'0000000013), -10}, - IOUAmount{10'000'000})); + XRP(10'000), STAmount{USD, UINT64_C(10'000'0000000013), -10}, IOUAmount{10'000'000})); else if (features[fixAMMv1_3]) BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'000), - STAmount{USD, UINT64_C(10'000'0000000003), -10}, - IOUAmount{10'000'000})); + XRP(10'000), STAmount{USD, UINT64_C(10'000'0000000003), -10}, IOUAmount{10'000'000})); else - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'000), USD(10'000), IOUAmount{10'000'000})); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), USD(10'000), IOUAmount{10'000'000})); BEAST_EXPECT(expectHolding(env, ben, USD(1'500'000))); BEAST_EXPECT(expectHolding(env, simon, USD(1'500'000))); BEAST_EXPECT(expectHolding(env, chris, USD(1'500'000))); BEAST_EXPECT(expectHolding(env, dan, USD(1'500'000))); if (!features[fixAMMv1_1] && !features[fixAMMv1_3]) - BEAST_EXPECT(expectHolding( - env, - carol, - STAmount{USD, UINT64_C(30'000'00000000001), -11})); + BEAST_EXPECT(expectHolding(env, carol, STAmount{USD, UINT64_C(30'000'00000000001), -11})); else if (features[fixAMMv1_1] && !features[fixAMMv1_3]) BEAST_EXPECT(expectHolding(env, carol, USD(30'000))); else @@ -5498,37 +4251,23 @@ private: BEAST_EXPECT(expectHolding(env, ed, USD(1'500'000))); BEAST_EXPECT(expectHolding(env, paul, USD(1'500'000))); if (!features[fixAMMv1_1] && !features[fixAMMv1_3]) - BEAST_EXPECT(expectHolding( - env, - nataly, - STAmount{USD, UINT64_C(1'500'000'000000002), -9})); + BEAST_EXPECT(expectHolding(env, natalie, STAmount{USD, UINT64_C(1'500'000'000000002), -9})); else if (features[fixAMMv1_1] && !features[fixAMMv1_3]) - BEAST_EXPECT(expectHolding( - env, - nataly, - STAmount{USD, UINT64_C(1'500'000'000000005), -9})); + BEAST_EXPECT(expectHolding(env, natalie, STAmount{USD, UINT64_C(1'500'000'000000005), -9})); else - BEAST_EXPECT(expectHolding(env, nataly, USD(1'500'000))); + BEAST_EXPECT(expectHolding(env, natalie, USD(1'500'000))); ammAlice.withdrawAll(alice); BEAST_EXPECT(!ammAlice.ammExists()); if (!features[fixAMMv1_1]) - BEAST_EXPECT(expectHolding( - env, - alice, - STAmount{USD, UINT64_C(30'000'0000000013), -10})); + BEAST_EXPECT(expectHolding(env, alice, STAmount{USD, UINT64_C(30'000'0000000013), -10})); else if (features[fixAMMv1_3]) - BEAST_EXPECT(expectHolding( - env, - alice, - STAmount{USD, UINT64_C(30'000'0000000003), -10})); + BEAST_EXPECT(expectHolding(env, alice, STAmount{USD, UINT64_C(30'000'0000000003), -10})); else BEAST_EXPECT(expectHolding(env, alice, USD(30'000))); - // alice XRP balance is 30,000initial - 50 ammcreate fee - + // alice XRP balance is 30,000 initial - 50 AMMCreate fee - // 10drops fee BEAST_EXPECT( - accountBalance(env, alice) == - std::to_string( - 29950000000 - env.current()->fees().base.drops())); + accountBalance(env, alice) == std::to_string(29950000000 - env.current()->fees().base.drops())); }, std::nullopt, 0, @@ -5545,14 +4284,8 @@ private: Account const chris("chris"); Account const simon("simon"); Account const ben("ben"); - Account const nataly("nataly"); - fund( - env, - gw, - {bob, ed, paul, dan, chris, simon, ben, nataly}, - XRP(2'000'000), - {}, - Fund::Acct); + Account const natalie("natalie"); + fund(env, gw, {bob, ed, paul, dan, chris, simon, ben, natalie}, XRP(2'000'000), {}, Fund::Acct); for (int i = 0; i < 10; ++i) { ammAlice.deposit(ben, XRPAmount{1}); @@ -5571,69 +4304,50 @@ private: ammAlice.withdrawAll(ed, XRP(0)); ammAlice.deposit(paul, XRP(100'000)); ammAlice.withdrawAll(paul, XRP(0)); - ammAlice.deposit(nataly, XRP(1'000'000)); - ammAlice.withdrawAll(nataly, XRP(0)); + ammAlice.deposit(natalie, XRP(1'000'000)); + ammAlice.withdrawAll(natalie, XRP(0)); } auto const baseFee = env.current()->fees().base.drops(); if (!features[fixAMMv1_3]) { // No round off with XRP in this test - BEAST_EXPECT(ammAlice.expectBalances( - XRP(10'000), USD(10'000), IOUAmount{10'000'000})); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), USD(10'000), IOUAmount{10'000'000})); ammAlice.withdrawAll(alice); BEAST_EXPECT(!ammAlice.ammExists()); // 20,000 initial - (deposit+withdraw) * 10 - auto const xrpBalance = - (XRP(2'000'000) - txfee(env, 20)).getText(); + auto const xrpBalance = (XRP(2'000'000) - txfee(env, 20)).getText(); BEAST_EXPECT(accountBalance(env, ben) == xrpBalance); BEAST_EXPECT(accountBalance(env, simon) == xrpBalance); BEAST_EXPECT(accountBalance(env, chris) == xrpBalance); BEAST_EXPECT(accountBalance(env, dan) == xrpBalance); // 30,000 initial - (deposit+withdraw) * 10 - BEAST_EXPECT( - accountBalance(env, carol) == - std::to_string(30'000'000'000 - 20 * baseFee)); + BEAST_EXPECT(accountBalance(env, carol) == std::to_string(30'000'000'000 - 20 * baseFee)); BEAST_EXPECT(accountBalance(env, ed) == xrpBalance); BEAST_EXPECT(accountBalance(env, paul) == xrpBalance); - BEAST_EXPECT(accountBalance(env, nataly) == xrpBalance); - // 30,000 initial - 50 ammcreate fee - 10drops withdraw fee - BEAST_EXPECT( - accountBalance(env, alice) == - std::to_string(29'950'000'000 - baseFee)); + BEAST_EXPECT(accountBalance(env, natalie) == xrpBalance); + // 30,000 initial - 50 AMMCreate fee - 10drops withdraw fee + BEAST_EXPECT(accountBalance(env, alice) == std::to_string(29'950'000'000 - baseFee)); } else { // post-amendment the rounding takes place to ensure // AMM invariant - BEAST_EXPECT(ammAlice.expectBalances( - XRPAmount(10'000'000'080), - USD(10'000), - IOUAmount{10'000'000})); + BEAST_EXPECT( + ammAlice.expectBalances(XRPAmount(10'000'000'080), USD(10'000), IOUAmount{10'000'000})); ammAlice.withdrawAll(alice); BEAST_EXPECT(!ammAlice.ammExists()); - auto const xrpBalance = - XRP(2'000'000) - txfee(env, 20) - drops(10); + auto const xrpBalance = XRP(2'000'000) - txfee(env, 20) - drops(10); auto const xrpBalanceText = xrpBalance.getText(); BEAST_EXPECT(accountBalance(env, ben) == xrpBalanceText); BEAST_EXPECT(accountBalance(env, simon) == xrpBalanceText); BEAST_EXPECT(accountBalance(env, chris) == xrpBalanceText); BEAST_EXPECT(accountBalance(env, dan) == xrpBalanceText); - BEAST_EXPECT( - accountBalance(env, carol) == - std::to_string(30'000'000'000 - 20 * baseFee - 10)); - BEAST_EXPECT( - accountBalance(env, ed) == - (xrpBalance + drops(2)).getText()); - BEAST_EXPECT( - accountBalance(env, paul) == - (xrpBalance + drops(3)).getText()); - BEAST_EXPECT( - accountBalance(env, nataly) == - (xrpBalance + drops(5)).getText()); - BEAST_EXPECT( - accountBalance(env, alice) == - std::to_string(29'950'000'000 - baseFee + 80)); + BEAST_EXPECT(accountBalance(env, carol) == std::to_string(30'000'000'000 - 20 * baseFee - 10)); + BEAST_EXPECT(accountBalance(env, ed) == (xrpBalance + drops(2)).getText()); + BEAST_EXPECT(accountBalance(env, paul) == (xrpBalance + drops(3)).getText()); + BEAST_EXPECT(accountBalance(env, natalie) == (xrpBalance + drops(5)).getText()); + BEAST_EXPECT(accountBalance(env, alice) == std::to_string(29'950'000'000 - baseFee + 80)); } }, std::nullopt, @@ -5679,24 +4393,10 @@ private: .bidMin = 1000, }), ter(tecAMM_EMPTY)); - amm.vote( - std::nullopt, - 100, - std::nullopt, - std::nullopt, - std::nullopt, - ter(tecAMM_EMPTY)); - amm.withdraw( - alice, 100, std::nullopt, std::nullopt, ter(tecAMM_EMPTY)); - amm.deposit( - alice, - USD(100), - std::nullopt, - std::nullopt, - std::nullopt, - ter(tecAMM_EMPTY)); - env(trust(alice, STAmount{amm.lptIssue(), 10'000}), - ter(tecAMM_EMPTY)); + amm.vote(std::nullopt, 100, std::nullopt, std::nullopt, std::nullopt, ter(tecAMM_EMPTY)); + amm.withdraw(alice, 100, std::nullopt, std::nullopt, ter(tecAMM_EMPTY)); + amm.deposit(alice, USD(100), std::nullopt, std::nullopt, std::nullopt, ter(tecAMM_EMPTY)); + env(trust(alice, STAmount{amm.lptIssue(), 10'000}), ter(tecAMM_EMPTY)); // Can deposit with tfTwoAssetIfEmpty option amm.deposit( @@ -5709,8 +4409,7 @@ private: std::nullopt, std::nullopt, 1'000); - BEAST_EXPECT( - amm.expectBalances(XRP(10'000), USD(10'000), amm.tokens())); + BEAST_EXPECT(amm.expectBalances(XRP(10'000), USD(10'000), amm.tokens())); BEAST_EXPECT(amm.expectTradingFee(1'000)); BEAST_EXPECT(amm.expectAuctionSlot(100, 0, IOUAmount{0})); @@ -5774,40 +4473,30 @@ private: using namespace jtx; testAMM([&](AMM& amm, Env& env) { amm.setClose(false); - auto const info = env.rpc( - "json", - "account_info", - std::string( - "{\"account\": \"" + to_string(amm.ammAccount()) + "\"}")); + auto const info = + env.rpc("json", "account_info", std::string("{\"account\": \"" + to_string(amm.ammAccount()) + "\"}")); try { - BEAST_EXPECT( - info[jss::result][jss::account_data][jss::AMMID] - .asString() == to_string(amm.ammID())); + BEAST_EXPECT(info[jss::result][jss::account_data][jss::AMMID].asString() == to_string(amm.ammID())); } catch (...) { fail(); } amm.deposit(carol, 1'000); - auto affected = env.meta()->getJson( - JsonOptions::none)[sfAffectedNodes.fieldName]; + auto affected = env.meta()->getJson(JsonOptions::none)[sfAffectedNodes.fieldName]; try { bool found = false; for (auto const& node : affected) { if (node.isMember(sfModifiedNode.fieldName) && - node[sfModifiedNode.fieldName] - [sfLedgerEntryType.fieldName] - .asString() == "AccountRoot" && - node[sfModifiedNode.fieldName][sfFinalFields.fieldName] - [jss::Account] - .asString() == to_string(amm.ammAccount())) + node[sfModifiedNode.fieldName][sfLedgerEntryType.fieldName].asString() == "AccountRoot" && + node[sfModifiedNode.fieldName][sfFinalFields.fieldName][jss::Account].asString() == + to_string(amm.ammAccount())) { - found = node[sfModifiedNode.fieldName] - [sfFinalFields.fieldName][jss::AMMID] - .asString() == to_string(amm.ammID()); + found = node[sfModifiedNode.fieldName][sfFinalFields.fieldName][jss::AMMID].asString() == + to_string(amm.ammID()); break; } } @@ -5837,19 +4526,13 @@ private: auto prep = [&](Env& env, auto gwRate, auto gw1Rate) { fund(env, gw, {alice, carol, bob, ed}, XRP(2'000), {USD(2'000)}); env.fund(XRP(2'000), gw1); - fund( - env, - gw1, - {alice, carol, bob, ed}, - {ETH(2'000), CAN(2'000)}, - Fund::IOUOnly); + fund(env, gw1, {alice, carol, bob, ed}, {ETH(2'000), CAN(2'000)}, Fund::IOUOnly); env(rate(gw, gwRate)); env(rate(gw1, gw1Rate)); env.close(); }; - for (auto const& rates : - {std::make_pair(1.5, 1.9), std::make_pair(1.9, 1.5)}) + for (auto const& rates : {std::make_pair(1.5, 1.9), std::make_pair(1.9, 1.5)}) { // Offer Selection @@ -5875,20 +4558,15 @@ private: } if (i > 0) amm.emplace(env, ed, USD(1'000), ETH(1'000)); - env(pay(carol, bob, USD(100)), - path(~USD), - sendmax(ETH(500))); + env(pay(carol, bob, USD(100)), path(~USD), sendmax(ETH(500))); env.close(); // CLOB and AMM, AMM is not selected if (i == 2) { - BEAST_EXPECT(amm->expectBalances( - USD(1'000), ETH(1'000), amm->tokens())); + BEAST_EXPECT(amm->expectBalances(USD(1'000), ETH(1'000), amm->tokens())); } BEAST_EXPECT(expectHolding(env, bob, USD(2'100))); - q[i] = Quality(Amounts{ - ETH(2'000) - env.balance(carol, ETH), - env.balance(bob, USD) - USD(2'000)}); + q[i] = Quality(Amounts{ETH(2'000) - env.balance(carol, ETH), env.balance(bob, USD) - USD(2'000)}); } // CLOB is better quality than AMM BEAST_EXPECT(q[0] > q[1]); @@ -5917,8 +4595,7 @@ private: // AMM is not selected if (i > 0) { - BEAST_EXPECT(amm->expectBalances( - USD(1'000), ETH(1'000), amm->tokens())); + BEAST_EXPECT(amm->expectBalances(USD(1'000), ETH(1'000), amm->tokens())); } if (i == 0 || i == 2) { @@ -5928,8 +4605,7 @@ private: // Fails to cross because AMM is not selected else { - BEAST_EXPECT(expectOffers( - env, alice, 1, {Amounts{USD(400), ETH(400)}})); + BEAST_EXPECT(expectOffers(env, alice, 1, {Amounts{USD(400), ETH(400)}})); } BEAST_EXPECT(expectOffers(env, ed, 0)); } @@ -5952,15 +4628,12 @@ private: } if (i > 0) amm.emplace(env, ed, USD(1'000), ETH(1'000)); - env(pay(carol, bob, USD(100)), - path(~USD), - sendmax(ETH(500))); + env(pay(carol, bob, USD(100)), path(~USD), sendmax(ETH(500))); env.close(); // AMM and CLOB are selected if (i > 0) { - BEAST_EXPECT(!amm->expectBalances( - USD(1'000), ETH(1'000), amm->tokens())); + BEAST_EXPECT(!amm->expectBalances(USD(1'000), ETH(1'000), amm->tokens())); } if (i == 2 && !features[fixAMMv1_1]) { @@ -5972,28 +4645,16 @@ private: ed, 1, {{Amounts{ - STAmount{ - ETH, - UINT64_C(378'6327949540823), - -13}, - STAmount{ - USD, - UINT64_C(283'9745962155617), - -13}}}})); + STAmount{ETH, UINT64_C(378'6327949540823), -13}, + STAmount{USD, UINT64_C(283'9745962155617), -13}}}})); else BEAST_EXPECT(expectOffers( env, ed, 1, {{Amounts{ - STAmount{ - ETH, - UINT64_C(378'6327949540813), - -13}, - STAmount{ - USD, - UINT64_C(283'974596215561), - -12}}}})); + STAmount{ETH, UINT64_C(378'6327949540813), -13}, + STAmount{USD, UINT64_C(283'974596215561), -12}}}})); } else { @@ -6003,28 +4664,16 @@ private: ed, 1, {{Amounts{ - STAmount{ - ETH, - UINT64_C(325'299461620749), - -12}, - STAmount{ - USD, - UINT64_C(243'9745962155617), - -13}}}})); + STAmount{ETH, UINT64_C(325'299461620749), -12}, + STAmount{USD, UINT64_C(243'9745962155617), -13}}}})); else BEAST_EXPECT(expectOffers( env, ed, 1, {{Amounts{ - STAmount{ - ETH, - UINT64_C(325'299461620748), - -12}, - STAmount{ - USD, - UINT64_C(243'974596215561), - -12}}}})); + STAmount{ETH, UINT64_C(325'299461620748), -12}, + STAmount{USD, UINT64_C(243'974596215561), -12}}}})); } } else if (i == 2) @@ -6036,12 +4685,8 @@ private: ed, 1, {{Amounts{ - STAmount{ - ETH, UINT64_C(378'6327949540812), -13}, - STAmount{ - USD, - UINT64_C(283'9745962155609), - -13}}}})); + STAmount{ETH, UINT64_C(378'6327949540812), -13}, + STAmount{USD, UINT64_C(283'9745962155609), -13}}}})); } else { @@ -6050,18 +4695,12 @@ private: ed, 1, {{Amounts{ - STAmount{ - ETH, UINT64_C(325'2994616207479), -13}, - STAmount{ - USD, - UINT64_C(243'9745962155609), - -13}}}})); + STAmount{ETH, UINT64_C(325'2994616207479), -13}, + STAmount{USD, UINT64_C(243'9745962155609), -13}}}})); } } BEAST_EXPECT(expectHolding(env, bob, USD(2'100))); - q[i] = Quality(Amounts{ - ETH(2'000) - env.balance(carol, ETH), - env.balance(bob, USD) - USD(2'000)}); + q[i] = Quality(Amounts{ETH(2'000) - env.balance(carol, ETH), env.balance(bob, USD) - USD(2'000)}); } // AMM is better quality BEAST_EXPECT(q[1] > q[0]); @@ -6087,8 +4726,7 @@ private: // AMM is selected in both cases if (i > 0) { - BEAST_EXPECT(!amm->expectBalances( - USD(1'000), ETH(1'000), amm->tokens())); + BEAST_EXPECT(!amm->expectBalances(USD(1'000), ETH(1'000), amm->tokens())); } // Partially crosses, AMM is selected, CLOB fails // limitQuality @@ -6098,17 +4736,14 @@ private: { if (!features[fixAMMv1_1]) { - BEAST_EXPECT(expectOffers( - env, ed, 1, {{Amounts{ETH(400), USD(250)}}})); + BEAST_EXPECT(expectOffers(env, ed, 1, {{Amounts{ETH(400), USD(250)}}})); BEAST_EXPECT(expectOffers( env, alice, 1, {{Amounts{ - STAmount{ - USD, UINT64_C(40'5694150420947), -13}, - STAmount{ - ETH, UINT64_C(64'91106406735152), -14}, + STAmount{USD, UINT64_C(40'5694150420947), -13}, + STAmount{ETH, UINT64_C(64'91106406735152), -14}, }}})); } else @@ -6121,10 +4756,8 @@ private: ed, 1, {{Amounts{ - STAmount{ - ETH, UINT64_C(335'0889359326475), -13}, - STAmount{ - USD, UINT64_C(209'4305849579047), -13}, + STAmount{ETH, UINT64_C(335'0889359326475), -13}, + STAmount{USD, UINT64_C(209'4305849579047), -13}, }}})); BEAST_EXPECT(expectOffers(env, alice, 0)); } @@ -6139,10 +4772,8 @@ private: ed, 1, {{Amounts{ - STAmount{ - ETH, UINT64_C(335'0889359326485), -13}, - STAmount{ - USD, UINT64_C(209'4305849579053), -13}, + STAmount{ETH, UINT64_C(335'0889359326485), -13}, + STAmount{USD, UINT64_C(209'4305849579053), -13}, }}})); BEAST_EXPECT(expectOffers(env, alice, 0)); } @@ -6154,10 +4785,8 @@ private: ed, 1, {{Amounts{ - STAmount{ - ETH, UINT64_C(335'0889359326475), -13}, - STAmount{ - USD, UINT64_C(209'4305849579047), -13}, + STAmount{ETH, UINT64_C(335'0889359326475), -13}, + STAmount{USD, UINT64_C(209'4305849579047), -13}, }}})); BEAST_EXPECT(expectOffers(env, alice, 0)); } @@ -6199,10 +4828,7 @@ private: if (i > 0) amm.emplace(env, ed, ETH(1'000), USD(1'000)); - env(pay(carol, bob, USD(100)), - path(~USD), - path(~CAN, ~USD), - sendmax(ETH(600))); + env(pay(carol, bob, USD(100)), path(~USD), path(~CAN, ~USD), sendmax(ETH(600))); env.close(); BEAST_EXPECT(expectHolding(env, bob, USD(2'100))); @@ -6213,15 +4839,12 @@ private: { // Liquidity is consumed from AMM strand only BEAST_EXPECT(amm->expectBalances( - STAmount{ETH, UINT64_C(1'176'66038955758), -11}, - USD(850), - amm->tokens())); + STAmount{ETH, UINT64_C(1'176'66038955758), -11}, USD(850), amm->tokens())); } else { BEAST_EXPECT(amm->expectBalances( - STAmount{ - ETH, UINT64_C(1'179'540094339627), -12}, + STAmount{ETH, UINT64_C(1'179'540094339627), -12}, STAmount{USD, UINT64_C(847'7880529867501), -13}, amm->tokens())); BEAST_EXPECT(expectOffers( @@ -6229,24 +4852,12 @@ private: ed, 2, {{Amounts{ - STAmount{ - ETH, - UINT64_C(343'3179205198749), - -13}, - STAmount{ - CAN, - UINT64_C(343'3179205198749), - -13}, + STAmount{ETH, UINT64_C(343'3179205198749), -13}, + STAmount{CAN, UINT64_C(343'3179205198749), -13}, }, Amounts{ - STAmount{ - CAN, - UINT64_C(362'2119470132499), - -13}, - STAmount{ - USD, - UINT64_C(362'2119470132499), - -13}, + STAmount{CAN, UINT64_C(362'2119470132499), -13}, + STAmount{USD, UINT64_C(362'2119470132499), -13}, }}})); } } @@ -6256,10 +4867,7 @@ private: { // Liquidity is consumed from AMM strand only BEAST_EXPECT(amm->expectBalances( - STAmount{ - ETH, UINT64_C(1'176'660389557593), -12}, - USD(850), - amm->tokens())); + STAmount{ETH, UINT64_C(1'176'660389557593), -12}, USD(850), amm->tokens())); } else { @@ -6272,30 +4880,16 @@ private: ed, 2, {{Amounts{ - STAmount{ - ETH, - UINT64_C(343'3179205198749), - -13}, - STAmount{ - CAN, - UINT64_C(343'3179205198749), - -13}, + STAmount{ETH, UINT64_C(343'3179205198749), -13}, + STAmount{CAN, UINT64_C(343'3179205198749), -13}, }, Amounts{ - STAmount{ - CAN, - UINT64_C(362'2119470132499), - -13}, - STAmount{ - USD, - UINT64_C(362'2119470132499), - -13}, + STAmount{CAN, UINT64_C(362'2119470132499), -13}, + STAmount{USD, UINT64_C(362'2119470132499), -13}, }}})); } } - q[i] = Quality(Amounts{ - ETH(2'000) - env.balance(carol, ETH), - env.balance(bob, USD) - USD(2'000)}); + q[i] = Quality(Amounts{ETH(2'000) - env.balance(carol, ETH), env.balance(bob, USD) - USD(2'000)}); } BEAST_EXPECT(q[1] > q[0]); BEAST_EXPECT(q[2] > q[0] && q[2] < q[1]); @@ -6320,37 +4914,23 @@ private: std::optional extra = std::nullopt) { Env env(*this, features); fund(env, gw, {alice}, XRP(1'000), {USD(10)}); - AMM amm( - env, - gw, - XRP(10), - USD(10), - {.tfee = tfee, .close = closeLedger}); + AMM amm(env, gw, XRP(10), USD(10), {.tfee = tfee, .close = closeLedger}); amm.deposit(alice, USD(10), XRP(10)); amm.vote(VoteArg{.account = alice, .tfee = tfee, .err = ter(err1)}); - amm.withdraw(WithdrawArg{ - .account = gw, .asset1Out = USD(1), .err = ter(err2)}); + amm.withdraw(WithdrawArg{.account = gw, .asset1Out = USD(1), .err = ter(err2)}); // with the amendment disabled and ledger not closed, // second vote succeeds if the first vote sets the trading fee // to non-zero; if the first vote sets the trading fee to >0 && // <9 then the second withdraw succeeds if the second vote sets // the trading fee so that the discounted fee is non-zero amm.vote(VoteArg{.account = alice, .tfee = 20, .err = ter(err3)}); - amm.withdraw(WithdrawArg{ - .account = gw, .asset1Out = USD(2), .err = ter(err4)}); + amm.withdraw(WithdrawArg{.account = gw, .asset1Out = USD(2), .err = ter(err4)}); }; // ledger is closed after each transaction, vote/withdraw don't fail // regardless whether the amendment is enabled or not test(all, tesSUCCESS, tesSUCCESS, tesSUCCESS, tesSUCCESS, 0, true); - test( - all - fixInnerObjTemplate, - tesSUCCESS, - tesSUCCESS, - tesSUCCESS, - tesSUCCESS, - 0, - true); + test(all - fixInnerObjTemplate, tesSUCCESS, tesSUCCESS, tesSUCCESS, tesSUCCESS, 0, true); // ledger is not closed after each transaction // vote/withdraw don't fail if the amendment is enabled test(all, tesSUCCESS, tesSUCCESS, tesSUCCESS, tesSUCCESS, 0, false); @@ -6358,49 +4938,21 @@ private: // second vote/withdraw still fail: second vote fails because // the initial trading fee is 0, consequently second withdraw fails // because the second vote fails - test( - all - fixInnerObjTemplate, - tefEXCEPTION, - tefEXCEPTION, - tefEXCEPTION, - tefEXCEPTION, - 0, - false); + test(all - fixInnerObjTemplate, tefEXCEPTION, tefEXCEPTION, tefEXCEPTION, tefEXCEPTION, 0, false); // if non-zero trading/discounted fee then vote/withdraw // don't fail whether the ledger is closed or not and // the amendment is enabled or not test(all, tesSUCCESS, tesSUCCESS, tesSUCCESS, tesSUCCESS, 10, true); - test( - all - fixInnerObjTemplate, - tesSUCCESS, - tesSUCCESS, - tesSUCCESS, - tesSUCCESS, - 10, - true); + test(all - fixInnerObjTemplate, tesSUCCESS, tesSUCCESS, tesSUCCESS, tesSUCCESS, 10, true); test(all, tesSUCCESS, tesSUCCESS, tesSUCCESS, tesSUCCESS, 10, false); - test( - all - fixInnerObjTemplate, - tesSUCCESS, - tesSUCCESS, - tesSUCCESS, - tesSUCCESS, - 10, - false); + test(all - fixInnerObjTemplate, tesSUCCESS, tesSUCCESS, tesSUCCESS, tesSUCCESS, 10, false); // non-zero trading fee but discounted fee is 0, vote doesn't fail // but withdraw fails test(all, tesSUCCESS, tesSUCCESS, tesSUCCESS, tesSUCCESS, 9, false); // second vote sets the trading fee to non-zero, consequently // second withdraw doesn't fail even if the amendment is not // enabled and the ledger is not closed - test( - all - fixInnerObjTemplate, - tesSUCCESS, - tefEXCEPTION, - tesSUCCESS, - tesSUCCESS, - 9, - false); + test(all - fixInnerObjTemplate, tesSUCCESS, tefEXCEPTION, tesSUCCESS, tesSUCCESS, 9, false); } void @@ -6420,14 +4972,12 @@ private: // side is generated first SucceedShouldFail, // Succeed in pre-fix, fail after fix // due to small quality difference - Fail, // Both fail because the quality can't be matched - Succeed // Both succeed + Fail, // Both fail because the quality can't be matched + Succeed // Both succeed }; using enum Status; - auto const xrpIouAmounts10_100 = - TAmounts{XRPAmount{10}, IOUAmount{100}}; - auto const iouXrpAmounts10_100 = - TAmounts{IOUAmount{10}, XRPAmount{100}}; + auto const xrpIouAmounts10_100 = TAmounts{XRPAmount{10}, IOUAmount{100}}; + auto const iouXrpAmounts10_100 = TAmounts{IOUAmount{10}, XRPAmount{100}}; // clang-format off std::vector> tests = { //Pool In , Pool Out, Quality , Fee, Status @@ -6508,21 +5058,15 @@ private: auto const& quality = std::get(t); auto const tfee = std::get(t); auto const status = std::get(t); - auto const poolInIsXRP = - boost::regex_search(std::get<0>(t), match, rx); - auto const poolOutIsXRP = - boost::regex_search(std::get<1>(t), match, rx); + auto const poolInIsXRP = boost::regex_search(std::get<0>(t), match, rx); + auto const poolOutIsXRP = boost::regex_search(std::get<1>(t), match, rx); assert(!(poolInIsXRP && poolOutIsXRP)); auto const poolIn = getPool(std::get<0>(t), poolInIsXRP); auto const poolOut = getPool(std::get<1>(t), poolOutIsXRP); try { auto const amounts = changeSpotPriceQuality( - Amounts{poolIn, poolOut}, - quality, - tfee, - env.current()->rules(), - env.journal); + Amounts{poolIn, poolOut}, quality, tfee, env.current()->rules(), env.journal); if (amounts) { if (status == SucceedShouldSucceedResize) @@ -6537,24 +5081,19 @@ private: if (!features[fixAMMv1_1]) BEAST_EXPECT( Quality{*amounts} >= quality || - withinRelativeDistance( - Quality{*amounts}, quality, Number{1, -7})); + withinRelativeDistance(Quality{*amounts}, quality, Number{1, -7})); else BEAST_EXPECT(Quality{*amounts} >= quality); } else if (status == FailShouldSucceed) { - BEAST_EXPECT( - features[fixAMMv1_1] && - Quality{*amounts} >= quality); + BEAST_EXPECT(features[fixAMMv1_1] && Quality{*amounts} >= quality); } else if (status == SucceedShouldFail) { BEAST_EXPECT( - !features[fixAMMv1_1] && - Quality{*amounts} < quality && - withinRelativeDistance( - Quality{*amounts}, quality, Number{1, -7})); + !features[fixAMMv1_1] && Quality{*amounts} < quality && + withinRelativeDistance(Quality{*amounts}, quality, Number{1, -7})); } } else @@ -6569,29 +5108,15 @@ private: if (isXRP(poolIn)) { auto const takerPays = STAmount{xrpIssue(), 1}; - return Amounts{ - takerPays, - swapAssetIn( - Amounts{poolIn, poolOut}, - takerPays, - tfee)}; + return Amounts{takerPays, swapAssetIn(Amounts{poolIn, poolOut}, takerPays, tfee)}; } else if (isXRP(poolOut)) { auto const takerGets = STAmount{xrpIssue(), 1}; - return Amounts{ - swapAssetOut( - Amounts{poolIn, poolOut}, - takerGets, - tfee), - takerGets}; + return Amounts{swapAssetOut(Amounts{poolIn, poolOut}, takerGets, tfee), takerGets}; } - auto const takerPays = toAmount( - getIssue(poolIn), Number{1, -10} * poolIn); - return Amounts{ - takerPays, - swapAssetIn( - Amounts{poolIn, poolOut}, takerPays, tfee)}; + auto const takerPays = toAmount(getIssue(poolIn), Number{1, -10} * poolIn); + return Amounts{takerPays, swapAssetIn(Amounts{poolIn, poolOut}, takerPays, tfee)}; }(); BEAST_EXPECT(Quality(tinyOffer) < quality); } @@ -6607,18 +5132,15 @@ private: } catch (std::runtime_error const& e) { - BEAST_EXPECT( - !strcmp(e.what(), "changeSpotPriceQuality failed")); - BEAST_EXPECT( - !features[fixAMMv1_1] && status == FailShouldSucceed); + BEAST_EXPECT(!strcmp(e.what(), "changeSpotPriceQuality failed")); + BEAST_EXPECT(!features[fixAMMv1_1] && status == FailShouldSucceed); } } // Test negative discriminant { // b**2 - 4 * a * c -> 1 * 1 - 4 * 1 * 1 = -3 - auto const res = - solveQuadraticEqSmallest(Number{1}, Number{1}, Number{1}); + auto const res = solveQuadraticEqSmallest(Number{1}, Number{1}, Number{1}); BEAST_EXPECT(!res.has_value()); } } @@ -6918,8 +5440,7 @@ private: }) { testcase(input.testCase); - for (auto const& features : - {all - fixAMMOverflowOffer - fixAMMv1_1 - fixAMMv1_3, all}) + for (auto const& features : {all - fixAMMOverflowOffer - fixAMMv1_1 - fixAMMv1_3, all}) { Env env(*this, features, std::make_unique(&logs)); @@ -6941,21 +5462,13 @@ private: env(pay(bitstamp, trader, usdBIT(100'000))); env.close(); - AMM amm{ - env, - trader, - usdGH(input.poolUsdGH), - usdBIT(input.poolUsdBIT)}; + AMM amm{env, trader, usdGH(input.poolUsdGH), usdBIT(input.poolUsdBIT)}; env.close(); - IOUAmount const preSwapLPTokenBalance = - amm.getLPTokensBalance(); + IOUAmount const preSwapLPTokenBalance = amm.getLPTokensBalance(); env(offer(trader, usdBIT(1), btcGH(input.offer1BtcGH))); - env(offer( - trader, - btcGH(input.offer2BtcGH), - usdGH(input.offer2UsdGH))); + env(offer(trader, btcGH(input.offer2BtcGH), usdGH(input.offer2UsdGH))); env.close(); env(pay(trader, trader, input.sendUsdGH), @@ -6965,37 +5478,28 @@ private: txflags(tfPartialPayment)); env.close(); - auto const failUsdGH = - features[fixAMMv1_1] ? input.failUsdGHr : input.failUsdGH; - auto const failUsdBIT = - features[fixAMMv1_1] ? input.failUsdBITr : input.failUsdBIT; - auto const goodUsdGH = - features[fixAMMv1_1] ? input.goodUsdGHr : input.goodUsdGH; - auto const goodUsdBIT = - features[fixAMMv1_1] ? input.goodUsdBITr : input.goodUsdBIT; - auto const lpTokenBalance = - env.enabled(fixAMMv1_3) && input.lpTokenBalanceAlt + auto const failUsdGH = features[fixAMMv1_1] ? input.failUsdGHr : input.failUsdGH; + auto const failUsdBIT = features[fixAMMv1_1] ? input.failUsdBITr : input.failUsdBIT; + auto const goodUsdGH = features[fixAMMv1_1] ? input.goodUsdGHr : input.goodUsdGH; + auto const goodUsdBIT = features[fixAMMv1_1] ? input.goodUsdBITr : input.goodUsdBIT; + auto const lpTokenBalance = env.enabled(fixAMMv1_3) && input.lpTokenBalanceAlt ? *input.lpTokenBalanceAlt : input.lpTokenBalance; if (!features[fixAMMOverflowOffer]) { - BEAST_EXPECT(amm.expectBalances( - failUsdGH, failUsdBIT, lpTokenBalance)); + BEAST_EXPECT(amm.expectBalances(failUsdGH, failUsdBIT, lpTokenBalance)); } else { - BEAST_EXPECT(amm.expectBalances( - goodUsdGH, goodUsdBIT, lpTokenBalance)); + BEAST_EXPECT(amm.expectBalances(goodUsdGH, goodUsdBIT, lpTokenBalance)); // Invariant: LPToken balance must not change in a // payment or a swap transaction - BEAST_EXPECT( - amm.getLPTokensBalance() == preSwapLPTokenBalance); + BEAST_EXPECT(amm.getLPTokensBalance() == preSwapLPTokenBalance); // Invariant: The square root of (product of the pool // balances) must be at least the LPTokenBalance - Number const sqrtPoolProduct = - root2(goodUsdGH * goodUsdBIT); + Number const sqrtPoolProduct = root2(goodUsdGH * goodUsdBIT); // Include a tiny tolerance for the test cases using // .goodUsdGH{usdGH, uint64_t(35'44113971506987), @@ -7005,9 +5509,7 @@ private: // to 99.99999999999994227040383754105 which gets // internally rounded to 100, due to representation // error. - BEAST_EXPECT( - (sqrtPoolProduct + Number{1, -14} >= - input.lpTokenBalance)); + BEAST_EXPECT((sqrtPoolProduct + Number{1, -14} >= input.lpTokenBalance)); } } } @@ -7023,8 +5525,7 @@ private: STAmount const iouPool{USD, UINT64_C(803040'9987141784), -10}; STAmount const xrpBob{XRP, UINT64_C(1092'878933)}; - STAmount const iouBob{ - USD, UINT64_C(3'988035892323031), -28}; // 3.9...e-13 + STAmount const iouBob{USD, UINT64_C(3'988035892323031), -28}; // 3.9...e-13 testAMM( [&](AMM& amm, Env& env) { @@ -7041,8 +5542,7 @@ private: env.close(); // Assert that AMM is unchanged. - BEAST_EXPECT( - amm.expectBalances(xrpBegin, iouBegin, amm.tokens())); + BEAST_EXPECT(amm.expectBalances(xrpBegin, iouBegin, amm.tokens())); }, {{xrpPool, iouPool}}, 889, @@ -7076,20 +5576,15 @@ private: if (!features[fixAMMv1_1]) { - BEAST_EXPECT(amm.expectBalances( - XRP(200'000), USD(100'000), amm.tokens())); - BEAST_EXPECT(expectOffers( - env, alice, 1, {{Amounts{XRP(1), USD(0.01)}}})); + BEAST_EXPECT(amm.expectBalances(XRP(200'000), USD(100'000), amm.tokens())); + BEAST_EXPECT(expectOffers(env, alice, 1, {{Amounts{XRP(1), USD(0.01)}}})); // Carol's offer is blocked by alice's offer - BEAST_EXPECT(expectOffers( - env, carol, 1, {{Amounts{USD(0.49), XRP(1)}}})); + BEAST_EXPECT(expectOffers(env, carol, 1, {{Amounts{USD(0.49), XRP(1)}}})); } else { - BEAST_EXPECT(amm.expectBalances( - XRPAmount(200'000'980'005), USD(99'999.51), amm.tokens())); - BEAST_EXPECT(expectOffers( - env, alice, 1, {{Amounts{XRP(1), USD(0.01)}}})); + BEAST_EXPECT(amm.expectBalances(XRPAmount(200'000'980'005), USD(99'999.51), amm.tokens())); + BEAST_EXPECT(expectOffers(env, alice, 1, {{Amounts{XRP(1), USD(0.01)}}})); // Carol's offer crosses AMM BEAST_EXPECT(expectOffers(env, carol, 0)); } @@ -7111,8 +5606,7 @@ private: env.close(); // The same result as with the blocking offer - BEAST_EXPECT(amm.expectBalances( - XRPAmount(200'000'980'005), USD(99'999.51), amm.tokens())); + BEAST_EXPECT(amm.expectBalances(XRPAmount(200'000'980'005), USD(99'999.51), amm.tokens())); // Carol's offer crosses AMM BEAST_EXPECT(expectOffers(env, carol, 0)); } @@ -7131,28 +5625,17 @@ private: env.close(); if (!features[fixAMMv1_1]) { - BEAST_EXPECT( - amm.expectBalances(XRP(1'000), USD(500), amm.tokens())); - BEAST_EXPECT(expectOffers( - env, bob, 1, {{Amounts{USD(1), XRPAmount(500)}}})); - BEAST_EXPECT(expectOffers( - env, carol, 1, {{Amounts{XRP(100), USD(55)}}})); + BEAST_EXPECT(amm.expectBalances(XRP(1'000), USD(500), amm.tokens())); + BEAST_EXPECT(expectOffers(env, bob, 1, {{Amounts{USD(1), XRPAmount(500)}}})); + BEAST_EXPECT(expectOffers(env, carol, 1, {{Amounts{XRP(100), USD(55)}}})); } else { BEAST_EXPECT(amm.expectBalances( - XRPAmount(909'090'909), - STAmount{USD, UINT64_C(550'000000055), -9}, - amm.tokens())); - BEAST_EXPECT(expectOffers( - env, - carol, - 1, - {{Amounts{ - XRPAmount{9'090'909}, - STAmount{USD, 4'99999995, -8}}}})); - BEAST_EXPECT(expectOffers( - env, bob, 1, {{Amounts{USD(1), XRPAmount(500)}}})); + XRPAmount(909'090'909), STAmount{USD, UINT64_C(550'000000055), -9}, amm.tokens())); + BEAST_EXPECT( + expectOffers(env, carol, 1, {{Amounts{XRPAmount{9'090'909}, STAmount{USD, 4'99999995, -8}}}})); + BEAST_EXPECT(expectOffers(env, bob, 1, {{Amounts{USD(1), XRPAmount(500)}}})); } } @@ -7165,16 +5648,9 @@ private: AMM amm(env, alice, XRP(1'000), USD(500)); env(offer(carol, XRP(100), USD(55))); env.close(); - BEAST_EXPECT(amm.expectBalances( - XRPAmount(909'090'909), - STAmount{USD, UINT64_C(550'000000055), -9}, - amm.tokens())); - BEAST_EXPECT(expectOffers( - env, - carol, - 1, - {{Amounts{ - XRPAmount{9'090'909}, STAmount{USD, 4'99999995, -8}}}})); + BEAST_EXPECT( + amm.expectBalances(XRPAmount(909'090'909), STAmount{USD, UINT64_C(550'000000055), -9}, amm.tokens())); + BEAST_EXPECT(expectOffers(env, carol, 1, {{Amounts{XRPAmount{9'090'909}, STAmount{USD, 4'99999995, -8}}}})); } } @@ -7188,12 +5664,7 @@ private: { std::string logs; Env env(*this, features, std::make_unique(&logs)); - fund( - env, - gw, - {alice, carol}, - XRP(1'000'000'000), - {USD(1'000'000'000)}); + fund(env, gw, {alice, carol}, XRP(1'000'000'000), {USD(1'000'000'000)}); AMM amm(env, gw, XRP(2), USD(1)); amm.deposit(alice, IOUAmount{1'876123487565916, -15}); amm.deposit(carol, IOUAmount{1'000'000}); @@ -7201,13 +5672,9 @@ private: BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{0})); amm.withdrawAll(carol); BEAST_EXPECT(amm.expectLPTokens(carol, IOUAmount{0})); - auto const lpToken = getAccountLines( - env, gw, amm.lptIssue())[jss::lines][0u][jss::balance]; - auto const lpTokenBalance = - amm.ammRpcInfo()[jss::amm][jss::lp_token][jss::value]; - BEAST_EXPECT( - lpToken == "1414.213562373095" && - lpTokenBalance == "1414.213562373"); + auto const lpToken = getAccountLines(env, gw, amm.lptIssue())[jss::lines][0u][jss::balance]; + auto const lpTokenBalance = amm.ammRpcInfo()[jss::amm][jss::lp_token][jss::value]; + BEAST_EXPECT(lpToken == "1414.213562373095" && lpTokenBalance == "1414.213562373"); if (!features[fixAMMv1_1]) { amm.withdrawAll(gw, std::nullopt, ter(tecAMM_BALANCE)); @@ -7226,24 +5693,15 @@ private: { Env env(*this, features); auto const ABC = gw["ABC"]; - fund( - env, - gw, - {alice, carol, bob}, - XRP(1'000), - {USD(1'000'000'000), ABC(1'000'000'000'000)}); + fund(env, gw, {alice, carol, bob}, XRP(1'000), {USD(1'000'000'000), ABC(1'000'000'000'000)}); AMM amm(env, lp, ABC(2'000'000), USD(1)); amm.deposit(alice, IOUAmount{1'876123487565916, -15}); amm.deposit(carol, IOUAmount{1'000'000}); amm.withdrawAll(alice); amm.withdrawAll(carol); - auto const lpToken = getAccountLines( - env, lp, amm.lptIssue())[jss::lines][0u][jss::balance]; - auto const lpTokenBalance = - amm.ammRpcInfo()[jss::amm][jss::lp_token][jss::value]; - BEAST_EXPECT( - lpToken == "1414.213562373095" && - lpTokenBalance == "1414.213562373"); + auto const lpToken = getAccountLines(env, lp, amm.lptIssue())[jss::lines][0u][jss::balance]; + auto const lpTokenBalance = amm.ammRpcInfo()[jss::amm][jss::lp_token][jss::value]; + BEAST_EXPECT(lpToken == "1414.213562373095" && lpTokenBalance == "1414.213562373"); if (!features[fixAMMv1_1]) { amm.withdrawAll(lp, std::nullopt, ter(tecAMM_BALANCE)); @@ -7263,11 +5721,9 @@ private: fund(env, gw, {alice}, XRP(1'000), {USD(1'000)}); AMM amm(env, gw, XRP(10), USD(10)); amm.deposit(alice, 1'000); - auto res = - isOnlyLiquidityProvider(*env.current(), amm.lptIssue(), gw); + auto res = isOnlyLiquidityProvider(*env.current(), amm.lptIssue(), gw); BEAST_EXPECT(res && !res.value()); - res = - isOnlyLiquidityProvider(*env.current(), amm.lptIssue(), alice); + res = isOnlyLiquidityProvider(*env.current(), amm.lptIssue(), alice); BEAST_EXPECT(res && !res.value()); } // IOU/IOU, issuer of both IOU @@ -7276,11 +5732,9 @@ private: fund(env, gw, {alice}, XRP(1'000), {USD(1'000), EUR(1'000)}); AMM amm(env, gw, EUR(10), USD(10)); amm.deposit(alice, 1'000); - auto res = - isOnlyLiquidityProvider(*env.current(), amm.lptIssue(), gw); + auto res = isOnlyLiquidityProvider(*env.current(), amm.lptIssue(), gw); BEAST_EXPECT(res && !res.value()); - res = - isOnlyLiquidityProvider(*env.current(), amm.lptIssue(), alice); + res = isOnlyLiquidityProvider(*env.current(), amm.lptIssue(), alice); BEAST_EXPECT(res && !res.value()); } // IOU/IOU, issuer of one IOU @@ -7292,8 +5746,7 @@ private: fund(env, gw1, {gw}, XRP(1'000), {YAN(1'000)}, Fund::IOUOnly); AMM amm(env, gw1, YAN(10), USD(10)); amm.deposit(gw, 1'000); - auto res = - isOnlyLiquidityProvider(*env.current(), amm.lptIssue(), gw); + auto res = isOnlyLiquidityProvider(*env.current(), amm.lptIssue(), gw); BEAST_EXPECT(res && !res.value()); res = isOnlyLiquidityProvider(*env.current(), amm.lptIssue(), gw1); BEAST_EXPECT(res && !res.value()); @@ -7342,9 +5795,7 @@ private: // allowed for clawing back from an AMM account. Please notice the // `issuer` subfield represents the account being clawed back, which // is confusing. - auto const error = features[featureSingleAssetVault] - ? ter{tecPSEUDO_ACCOUNT} - : ter{tecAMM_ACCOUNT}; + auto const error = features[featureSingleAssetVault] ? ter{tecPSEUDO_ACCOUNT} : ter{tecAMM_ACCOUNT}; Issue usd(USD.issue().currency, amm.ammAccount()); auto amount = amountFromString(usd, "10"); env(claw(gw, amount), error); @@ -7374,13 +5825,7 @@ private: { Env env(*this, features); testAMMDeposit(env, [&](AMM& amm) { - amm.deposit( - alice, - USD(100), - XRP(100), - std::nullopt, - tfTwoAsset, - ter(tecFROZEN)); + amm.deposit(alice, USD(100), XRP(100), std::nullopt, tfTwoAsset, ter(tecFROZEN)); }); } @@ -7389,13 +5834,7 @@ private: { Env env(*this, features); testAMMDeposit(env, [&](AMM& amm) { - amm.deposit( - alice, - USD(100), - std::nullopt, - std::nullopt, - tfSingleAsset, - ter(tecFROZEN)); + amm.deposit(alice, USD(100), std::nullopt, std::nullopt, tfSingleAsset, ter(tecFROZEN)); }); } @@ -7406,13 +5845,7 @@ private: // when feature AMMClawback is enabled. Env env(*this, features); testAMMDeposit(env, [&](AMM& amm) { - amm.deposit( - alice, - XRP(100), - std::nullopt, - std::nullopt, - tfSingleAsset, - ter(tecFROZEN)); + amm.deposit(alice, XRP(100), std::nullopt, std::nullopt, tfSingleAsset, ter(tecFROZEN)); }); } else @@ -7422,13 +5855,7 @@ private: // when feature AMMClawback is not enabled. Env env(*this, features); testAMMDeposit(env, [&](AMM& amm) { - amm.deposit( - alice, - XRP(100), - std::nullopt, - std::nullopt, - tfSingleAsset, - ter(tesSUCCESS)); + amm.deposit(alice, XRP(100), std::nullopt, std::nullopt, tfSingleAsset, ter(tesSUCCESS)); }); } } @@ -7439,13 +5866,11 @@ private: testcase("Fix Reserve Check On Withdrawal"); using namespace jtx; - auto const err = features[fixAMMv1_2] ? ter(tecINSUFFICIENT_RESERVE) - : ter(tesSUCCESS); + auto const err = features[fixAMMv1_2] ? ter(tecINSUFFICIENT_RESERVE) : ter(tesSUCCESS); auto test = [&](auto&& cb) { Env env(*this, features); - auto const starting_xrp = - reserve(env, 2) + env.current()->fees().base * 5; + auto const starting_xrp = reserve(env, 2) + env.current()->fees().base * 5; env.fund(starting_xrp, gw); env.fund(starting_xrp, alice); env.trust(USD(2'000), alice); @@ -7462,22 +5887,13 @@ private: // Equal withdraw with a limit test([&](AMM& amm) { - amm.withdraw(WithdrawArg{ - .account = alice, - .asset1Out = EUR(0.1), - .asset2Out = USD(0.1), - .err = err}); - amm.withdraw(WithdrawArg{ - .account = alice, - .asset1Out = USD(0.1), - .asset2Out = EUR(0.1), - .err = err}); + amm.withdraw(WithdrawArg{.account = alice, .asset1Out = EUR(0.1), .asset2Out = USD(0.1), .err = err}); + amm.withdraw(WithdrawArg{.account = alice, .asset1Out = USD(0.1), .asset2Out = EUR(0.1), .err = err}); }); // Single withdraw test([&](AMM& amm) { - amm.withdraw(WithdrawArg{ - .account = alice, .asset1Out = EUR(0.1), .err = err}); + amm.withdraw(WithdrawArg{.account = alice, .asset1Out = EUR(0.1), .err = err}); amm.withdraw(WithdrawArg{.account = alice, .asset1Out = USD(0.1)}); }); } @@ -7502,13 +5918,9 @@ private: auto const keylet = keylet::amm(amount.issue(), amount2.issue()); for (int i = 0; i < 256; ++i) { - AccountID const accountId = - xrpl::pseudoAccountAddress(*env.current(), keylet.key); + AccountID const accountId = xrpl::pseudoAccountAddress(*env.current(), keylet.key); - env(pay(env.master.id(), accountId, XRP(1000)), - seq(autofill), - fee(autofill), - sig(autofill)); + env(pay(env.master.id(), accountId, XRP(1000)), seq(autofill), fee(autofill), sig(autofill)); } AMM ammAlice( @@ -7516,15 +5928,11 @@ private: alice, amount, amount2, - features[featureSingleAssetVault] ? ter{terADDRESS_COLLISION} - : ter{tecDUPLICATE}); + features[featureSingleAssetVault] ? ter{terADDRESS_COLLISION} : ter{tecDUPLICATE}); }; - testCase( - "tecDUPLICATE", testable_amendments() - featureSingleAssetVault); - testCase( - "terADDRESS_COLLISION", - testable_amendments() | featureSingleAssetVault); + testCase("tecDUPLICATE", testable_amendments() - featureSingleAssetVault); + testCase("terADDRESS_COLLISION", testable_amendments() | featureSingleAssetVault); } void @@ -7548,20 +5956,16 @@ private: AMM amm(env, gw, xrpBalance, xpmBalance, CreateArg{.tfee = tfee_}); // AMM LPToken balance required to replicate single deposit failure - STAmount lptAMMBalance{ - amm.lptIssue(), UINT64_C(3'234'987'266'485968), -6}; - auto const burn = - IOUAmount{amm.getLPTokensBalance() - lptAMMBalance}; + STAmount lptAMMBalance{amm.lptIssue(), UINT64_C(3'234'987'266'485968), -6}; + auto const burn = IOUAmount{amm.getLPTokensBalance() - lptAMMBalance}; // burn tokens to get to the required AMM state env(amm.bid(BidArg{.account = gw, .bidMin = burn, .bidMax = burn})); cb(amm, env); }; test( [&](AMM& amm, Env& env) { - auto const err = env.enabled(fixAMMv1_3) ? ter(tesSUCCESS) - : ter(tecUNFUNDED_AMM); - amm.deposit(DepositArg{ - .account = alice, .asset1In = amount, .err = err}); + auto const err = env.enabled(fixAMMv1_3) ? ter(tesSUCCESS) : ter(tecUNFUNDED_AMM); + amm.deposit(DepositArg{.account = alice, .asset1In = amount, .err = err}); }, tfee); test( @@ -7569,8 +5973,7 @@ private: auto const [amount, amount2, lptAMM] = amm.balances(XRP, XPM); auto const withdraw = STAmount{XPM, 1, -5}; amm.withdraw(WithdrawArg{.asset1Out = STAmount{XPM, 1, -5}}); - auto const [amount_, amount2_, lptAMM_] = - amm.balances(XRP, XPM); + auto const [amount_, amount2_, lptAMM_] = amm.balances(XRP, XPM); if (!env.enabled(fixAMMv1_3)) BEAST_EXPECT((amount2 - amount2_) > withdraw); else @@ -7580,17 +5983,12 @@ private: } void - invariant( - jtx::AMM& amm, - jtx::Env& env, - std::string const& msg, - bool shouldFail) + invariant(jtx::AMM& amm, jtx::Env& env, std::string const& msg, bool shouldFail) { auto const [amount, amount2, lptBalance] = amm.balances(GBP, EUR); NumberMantissaScaleGuard sg(MantissaRange::small); - NumberRoundModeGuard g( - env.enabled(fixAMMv1_3) ? Number::upward : Number::getround()); + NumberRoundModeGuard g(env.enabled(fixAMMv1_3) ? Number::upward : Number::getround()); auto const res = root2(amount * amount2); if (shouldFail) @@ -7616,23 +6014,11 @@ private: { testAMM( [&](AMM& ammAlice, Env& env) { - fund( - env, - gw, - {bob}, - XRP(10'000'000), - {GBP(100'000), EUR(100'000)}, - Fund::Acct); + fund(env, gw, {bob}, XRP(10'000'000), {GBP(100'000), EUR(100'000)}, Fund::Acct); env.close(); - ammAlice.deposit( - DepositArg{.account = bob, .asset1In = deposit}); - invariant( - ammAlice, - env, - "dep1", - deposit == STAmount{EUR, 1, -3} && - !env.enabled(fixAMMv1_3)); + ammAlice.deposit(DepositArg{.account = bob, .asset1In = deposit}); + invariant(ammAlice, env, "dep1", deposit == STAmount{EUR, 1, -3} && !env.enabled(fixAMMv1_3)); }, {{GBP(30'000), EUR(30'000)}}, 0, @@ -7643,24 +6029,13 @@ private: // Two-asset proportional deposit (1:1 pool ratio) testAMM( [&](AMM& ammAlice, Env& env) { - fund( - env, - gw, - {bob}, - XRP(10'000'000), - {GBP(100'000), EUR(100'000)}, - Fund::Acct); + fund(env, gw, {bob}, XRP(10'000'000), {GBP(100'000), EUR(100'000)}, Fund::Acct); env.close(); - STAmount const depositEuro{ - EUR, UINT64_C(10'1234567890123456), -16}; - STAmount const depositGBP{ - GBP, UINT64_C(10'1234567890123456), -16}; + STAmount const depositEuro{EUR, UINT64_C(10'1234567890123456), -16}; + STAmount const depositGBP{GBP, UINT64_C(10'1234567890123456), -16}; - ammAlice.deposit(DepositArg{ - .account = bob, - .asset1In = depositEuro, - .asset2In = depositGBP}); + ammAlice.deposit(DepositArg{.account = bob, .asset1In = depositEuro, .asset2In = depositGBP}); invariant(ammAlice, env, "dep2", false); }, {{GBP(30'000), EUR(30'000)}}, @@ -7673,27 +6048,14 @@ private: { testAMM( [&](AMM& ammAlice, Env& env) { - fund( - env, - gw, - {bob}, - XRP(10'000'000), - {GBP(100'000), EUR(100'000)}, - Fund::Acct); + fund(env, gw, {bob}, XRP(10'000'000), {GBP(100'000), EUR(100'000)}, Fund::Acct); env.close(); STAmount const depositEuro{EUR, 1, exponent}; STAmount const depositGBP{GBP, 1, exponent}; - ammAlice.deposit(DepositArg{ - .account = bob, - .asset1In = depositEuro, - .asset2In = depositGBP}); - invariant( - ammAlice, - env, - "dep3", - exponent != -3 && !env.enabled(fixAMMv1_3)); + ammAlice.deposit(DepositArg{.account = bob, .asset1In = depositEuro, .asset2In = depositGBP}); + invariant(ammAlice, env, "dep3", exponent != -3 && !env.enabled(fixAMMv1_3)); }, {{GBP(10'000), EUR(30'000)}}, 0, @@ -7704,18 +6066,10 @@ private: // tfLPToken deposit testAMM( [&](AMM& ammAlice, Env& env) { - fund( - env, - gw, - {bob}, - XRP(10'000'000), - {GBP(100'000), EUR(100'000)}, - Fund::Acct); + fund(env, gw, {bob}, XRP(10'000'000), {GBP(100'000), EUR(100'000)}, Fund::Acct); env.close(); - ammAlice.deposit(DepositArg{ - .account = bob, - .tokens = IOUAmount{10'1234567890123456, -16}}); + ammAlice.deposit(DepositArg{.account = bob, .tokens = IOUAmount{10'1234567890123456, -16}}); invariant(ammAlice, env, "dep4", false); }, {{GBP(7'000), EUR(30'000)}}, @@ -7736,19 +6090,10 @@ private: { testAMM( [&](AMM& ammAlice, Env& env) { - fund( - env, - gw, - {bob}, - XRP(10'000'000), - {GBP(100'000), EUR(1'000'000)}, - Fund::Acct); + fund(env, gw, {bob}, XRP(10'000'000), {GBP(100'000), EUR(1'000'000)}, Fund::Acct); env.close(); - ammAlice.deposit(DepositArg{ - .account = bob, - .tokens = tokens, - .asset1In = STAmount{EUR, 1, 6}}); + ammAlice.deposit(DepositArg{.account = bob, .tokens = tokens, .asset1In = STAmount{EUR, 1, 6}}); invariant(ammAlice, env, "dep5", false); }, {{GBP(7'000), EUR(30'000)}}, @@ -7761,17 +6106,10 @@ private: // 1'000 GBP with EP not to exceed 5 (GBP/TokensOut) testAMM( [&](AMM& ammAlice, Env& env) { - fund( - env, - gw, - {bob}, - XRP(10'000'000), - {GBP(100'000), EUR(100'000)}, - Fund::Acct); + fund(env, gw, {bob}, XRP(10'000'000), {GBP(100'000), EUR(100'000)}, Fund::Acct); env.close(); - ammAlice.deposit( - bob, GBP(1'000), std::nullopt, STAmount{GBP, 5}); + ammAlice.deposit(bob, GBP(1'000), std::nullopt, STAmount{GBP, 5}); invariant(ammAlice, env, "dep6", false); }, {{GBP(30'000), EUR(30'000)}}, @@ -7801,8 +6139,7 @@ private: // tfWithdrawAll mode testAMM( [&](AMM& ammAlice, Env& env) { - ammAlice.withdraw( - WithdrawArg{.account = alice, .flags = tfWithdrawAll}); + ammAlice.withdraw(WithdrawArg{.account = alice, .flags = tfWithdrawAll}); invariant(ammAlice, env, "with2", false); }, {{GBP(7'000), EUR(30'000)}}, @@ -7832,10 +6169,8 @@ private: // errors testAMM( [&](AMM& ammAlice, Env& env) { - ammAlice.withdraw(WithdrawArg{ - .account = alice, - .asset1Out = STAmount{GBP, 1'234}, - .flags = tfSingleAsset}); + ammAlice.withdraw( + WithdrawArg{.account = alice, .asset1Out = STAmount{GBP, 1'234}, .flags = tfSingleAsset}); invariant(ammAlice, env, "with4", false); }, {{GBP(7'000), EUR(30'000)}}, @@ -7846,22 +6181,13 @@ private: // tfOneAssetWithdrawAll mode testAMM( [&](AMM& ammAlice, Env& env) { - fund( - env, - gw, - {bob}, - XRP(10'000'000), - {GBP(100'000), EUR(100'000)}, - Fund::Acct); + fund(env, gw, {bob}, XRP(10'000'000), {GBP(100'000), EUR(100'000)}, Fund::Acct); env.close(); - ammAlice.deposit(DepositArg{ - .account = bob, .asset1In = STAmount{GBP, 3'456}}); + ammAlice.deposit(DepositArg{.account = bob, .asset1In = STAmount{GBP, 3'456}}); - ammAlice.withdraw(WithdrawArg{ - .account = bob, - .asset1Out = STAmount{GBP, 1'000}, - .flags = tfOneAssetWithdrawAll}); + ammAlice.withdraw( + WithdrawArg{.account = bob, .asset1Out = STAmount{GBP, 1'000}, .flags = tfOneAssetWithdrawAll}); invariant(ammAlice, env, "with5", false); }, {{GBP(7'000), EUR(30'000)}}, @@ -7873,10 +6199,7 @@ private: testAMM( [&](AMM& ammAlice, Env& env) { ammAlice.withdraw(WithdrawArg{ - .account = alice, - .tokens = 1'000, - .asset1Out = STAmount{GBP, 100}, - .flags = tfOneAssetLPToken}); + .account = alice, .tokens = 1'000, .asset1Out = STAmount{GBP, 100}, .flags = tfOneAssetLPToken}); invariant(ammAlice, env, "with6", false); }, {{GBP(7'000), EUR(30'000)}}, @@ -7888,10 +6211,7 @@ private: testAMM( [&](AMM& ammAlice, Env& env) { ammAlice.withdraw(WithdrawArg{ - .account = alice, - .asset1Out = STAmount{GBP, 100}, - .maxEP = IOUAmount{2}, - .flags = tfLimitLPToken}); + .account = alice, .asset1Out = STAmount{GBP, 100}, .maxEP = IOUAmount{2}, .flags = tfLimitLPToken}); invariant(ammAlice, env, "with7", true); }, {{GBP(7'000), EUR(30'000)}}, @@ -7921,8 +6241,7 @@ private: testBasicPaymentEngine(all); testBasicPaymentEngine(all - fixAMMv1_1 - fixAMMv1_3); testBasicPaymentEngine(all - fixReducedOffersV2); - testBasicPaymentEngine( - all - fixAMMv1_1 - fixAMMv1_3 - fixReducedOffersV2); + testBasicPaymentEngine(all - fixAMMv1_1 - fixAMMv1_3 - fixReducedOffersV2); testAMMTokens(); testAmendment(); testFlags(); @@ -7961,8 +6280,7 @@ private: testAMMDepositWithFrozenAssets(all); testAMMDepositWithFrozenAssets(all - featureAMMClawback); testAMMDepositWithFrozenAssets(all - fixAMMv1_1 - featureAMMClawback); - testAMMDepositWithFrozenAssets( - all - fixAMMv1_1 - fixAMMv1_3 - featureAMMClawback); + testAMMDepositWithFrozenAssets(all - fixAMMv1_1 - fixAMMv1_3 - featureAMMClawback); testFixReserveCheckOnWithdrawal(all); testFixReserveCheckOnWithdrawal(all - fixAMMv1_2); testDepositAndWithdrawRounding(all); diff --git a/src/test/app/AccountDelete_test.cpp b/src/test/app/AccountDelete_test.cpp index 44d484ac7a..7c9a593cae 100644 --- a/src/test/app/AccountDelete_test.cpp +++ b/src/test/app/AccountDelete_test.cpp @@ -17,8 +17,7 @@ private: verifyDeliveredAmount(jtx::Env& env, STAmount const& amount) { // Get the hash for the most recent transaction. - std::string const txHash{ - env.tx()->getJson(JsonOptions::none)[jss::hash].asString()}; + std::string const txHash{env.tx()->getJson(JsonOptions::none)[jss::hash].asString()}; // Verify DeliveredAmount and delivered_amount metadata are correct. // We can't use env.meta() here, because meta() doesn't include @@ -82,9 +81,7 @@ public: env(acctdelete(alice, becky), fee(drops(-1)), ter(temBAD_FEE)); // Invalid flags. - env(acctdelete(alice, becky), - txflags(tfImmediateOrCancel), - ter(temINVALID_FLAG)); + env(acctdelete(alice, becky), txflags(tfImmediateOrCancel), ter(temINVALID_FLAG)); // Account deletion has a high fee. Make sure the fee requirement // behaves as we expect. @@ -92,9 +89,7 @@ public: env(acctdelete(alice, becky), ter(telINSUF_FEE_P)); // Try a fee one drop less than the required amount. - env(acctdelete(alice, becky), - fee(acctDelFee - drops(1)), - ter(telINSUF_FEE_P)); + env(acctdelete(alice, becky), fee(acctDelFee - drops(1)), ter(telINSUF_FEE_P)); // alice's account is created too recently to be deleted. env(acctdelete(alice, becky), fee(acctDelFee), ter(tecTOO_SOON)); @@ -145,9 +140,7 @@ public: BEAST_EXPECT(!env.closed()->exists(keylet::ownerDir(alice.id()))); // Verify that alice's XRP, minus the fee, was transferred to becky. - BEAST_EXPECT( - env.balance(becky) == - aliceOldBalance + beckyOldBalance - acctDelFee); + BEAST_EXPECT(env.balance(becky) == aliceOldBalance + beckyOldBalance - acctDelFee); } // Attempt to delete becky's account but get stopped by the trust line. @@ -179,12 +172,9 @@ public: // pre-authorization, offer, ticket, and signer list exist. BEAST_EXPECT(env.closed()->exists(keylet::account(carol.id()))); BEAST_EXPECT(env.closed()->exists(keylet::ownerDir(carol.id()))); - BEAST_EXPECT(env.closed()->exists( - keylet::depositPreauth(carol.id(), becky.id()))); - BEAST_EXPECT( - env.closed()->exists(keylet::offer(carol.id(), carolOfferSeq))); - BEAST_EXPECT(env.closed()->exists( - keylet::ticket(carol.id(), carolTicketSeq))); + BEAST_EXPECT(env.closed()->exists(keylet::depositPreauth(carol.id(), becky.id()))); + BEAST_EXPECT(env.closed()->exists(keylet::offer(carol.id(), carolOfferSeq))); + BEAST_EXPECT(env.closed()->exists(keylet::ticket(carol.id(), carolTicketSeq))); BEAST_EXPECT(env.closed()->exists(keylet::signers(carol.id()))); // Delete carol's account even with stuff in her directory. Show @@ -196,18 +186,13 @@ public: // Verify that Carol's account, directory, and other stuff are gone. BEAST_EXPECT(!env.closed()->exists(keylet::account(carol.id()))); BEAST_EXPECT(!env.closed()->exists(keylet::ownerDir(carol.id()))); - BEAST_EXPECT(!env.closed()->exists( - keylet::depositPreauth(carol.id(), becky.id()))); - BEAST_EXPECT(!env.closed()->exists( - keylet::offer(carol.id(), carolOfferSeq))); - BEAST_EXPECT(!env.closed()->exists( - keylet::ticket(carol.id(), carolTicketSeq))); + BEAST_EXPECT(!env.closed()->exists(keylet::depositPreauth(carol.id(), becky.id()))); + BEAST_EXPECT(!env.closed()->exists(keylet::offer(carol.id(), carolOfferSeq))); + BEAST_EXPECT(!env.closed()->exists(keylet::ticket(carol.id(), carolTicketSeq))); BEAST_EXPECT(!env.closed()->exists(keylet::signers(carol.id()))); // Verify that Carol's XRP, minus the fee, was transferred to becky. - BEAST_EXPECT( - env.balance(becky) == - carolOldBalance + beckyOldBalance - acctDelFee); + BEAST_EXPECT(env.balance(becky) == carolOldBalance + beckyOldBalance - acctDelFee); // Since becky received an influx of XRP, her lsfPasswordSpent bit // is cleared and she can change her regular key for free again. @@ -328,8 +313,7 @@ public: // Now cancel the escrow, but create a payment channel between // alice and becky. - bool const withTokenEscrow = - env.current()->rules().enabled(featureTokenEscrow); + bool const withTokenEscrow = env.current()->rules().enabled(featureTokenEscrow); if (withTokenEscrow) { Account const gw1("gw1"); @@ -351,9 +335,7 @@ public: incLgrSeqForAccDel(env, gw1); - env(acctdelete(gw1, becky), - fee(acctDelFee), - ter(tecHAS_OBLIGATIONS)); + env(acctdelete(gw1, becky), fee(acctDelFee), ter(tecHAS_OBLIGATIONS)); env.close(); env(escrow::cancel(becky, carol, escrowSeq)); @@ -363,11 +345,9 @@ public: env(escrow::cancel(becky, alice, escrowSeq)); env.close(); - Keylet const alicePayChanKey{ - keylet::payChan(alice, becky, env.seq(alice))}; + Keylet const alicePayChanKey{keylet::payChan(alice, becky, env.seq(alice))}; - env(payChanCreate( - alice, becky, XRP(57), 4s, env.now() + 2s, alice.pk())); + env(payChanCreate(alice, becky, XRP(57), 4s, env.now() + 2s, alice.pk())); env.close(); // With the PayChannel in place becky and alice should not be @@ -381,9 +361,7 @@ public: // in her directory. // Lambda to close a PayChannel. - auto payChanClose = [](jtx::Account const& account, - Keylet const& payChanKeylet, - PublicKey const& pk) { + auto payChanClose = [](jtx::Account const& account, Keylet const& payChanKeylet, PublicKey const& pk) { Json::Value jv; jv[jss::TransactionType] = jss::PaymentChannelClaim; jv[jss::Flags] = tfClose; @@ -483,8 +461,7 @@ public: // alice's offers. for (std::uint32_t i{0}; i < offerCount; ++i) - BEAST_EXPECT( - closed->exists(keylet::offer(alice.id(), offerSeq0 + i))); + BEAST_EXPECT(closed->exists(keylet::offer(alice.id(), offerSeq0 + i))); } // Delete alice's account. Should fail because she has too many @@ -514,13 +491,11 @@ public: // alice's former directory nodes. for (std::uint32_t i{0}; i < ((offerCount / 32) + 1); ++i) - BEAST_EXPECT( - !closed->exists(keylet::page(aliceOwnerDirKey, i))); + BEAST_EXPECT(!closed->exists(keylet::page(aliceOwnerDirKey, i))); // alice's former offers. for (std::uint32_t i{0}; i < offerCount; ++i) - BEAST_EXPECT( - !closed->exists(keylet::offer(alice.id(), offerSeq0 + i))); + BEAST_EXPECT(!closed->exists(keylet::offer(alice.id(), offerSeq0 + i))); } } @@ -600,9 +575,7 @@ public: // // The balance of env.master should not change. auto const masterBalance{env.balance(env.master)}; - env(acctdelete(alice, env.master), - fee(acctDelFee), - ter(terINSUF_FEE_B)); + env(acctdelete(alice, env.master), fee(acctDelFee), ter(terINSUF_FEE_B)); env.close(); { std::shared_ptr const closed{env.closed()}; @@ -647,8 +620,7 @@ public: BEAST_EXPECT(closed->exists(keylet::account(bob.id()))); for (std::uint32_t i = 0; i < 250; ++i) { - BEAST_EXPECT( - closed->exists(keylet::ticket(bob.id(), ticketSeq + i))); + BEAST_EXPECT(closed->exists(keylet::ticket(bob.id(), ticketSeq + i))); } } @@ -667,8 +639,7 @@ public: BEAST_EXPECT(!closed->exists(keylet::account(bob.id()))); for (std::uint32_t i = 0; i < 250; ++i) { - BEAST_EXPECT( - !closed->exists(keylet::ticket(bob.id(), ticketSeq + i))); + BEAST_EXPECT(!closed->exists(keylet::ticket(bob.id(), ticketSeq + i))); } } } @@ -732,8 +703,7 @@ public: testDestinationDepositAuthCredentials() { { - testcase( - "Destination Constraints with DepositPreauth and Credentials"); + testcase("Destination Constraints with DepositPreauth and Credentials"); using namespace test::jtx; @@ -753,8 +723,7 @@ public: env.close(); // get credentials index - auto const jv = - credentials::ledgerEntry(env, becky, carol, credType); + auto const jv = credentials::ledgerEntry(env, becky, carol, credType); std::string const credIdx = jv[jss::result][jss::index].asString(); // Close enough ledgers to be able to delete becky's account. @@ -763,10 +732,7 @@ public: auto const acctDelFee{drops(env.current()->fees().increment)}; // becky use credentials but they aren't accepted - env(acctdelete(becky, alice), - credentials::ids({credIdx}), - fee(acctDelFee), - ter(tecBAD_CREDENTIALS)); + env(acctdelete(becky, alice), credentials::ids({credIdx}), fee(acctDelFee), ter(tecBAD_CREDENTIALS)); env.close(); { @@ -778,10 +744,7 @@ public: } // Fail, credentials still not accepted - env(acctdelete(becky, alice), - credentials::ids({credIdx}), - fee(acctDelFee), - ter(tecBAD_CREDENTIALS)); + env(acctdelete(becky, alice), credentials::ids({credIdx}), fee(acctDelFee), ter(tecBAD_CREDENTIALS)); env.close(); // becky accept the credentials @@ -789,16 +752,10 @@ public: env.close(); // Fail, credentials doesn’t belong to carol - env(acctdelete(carol, alice), - credentials::ids({credIdx}), - fee(acctDelFee), - ter(tecBAD_CREDENTIALS)); + env(acctdelete(carol, alice), credentials::ids({credIdx}), fee(acctDelFee), ter(tecBAD_CREDENTIALS)); // Fail, no depositPreauth for provided credentials - env(acctdelete(becky, alice), - credentials::ids({credIdx}), - fee(acctDelFee), - ter(tecNO_PERMISSION)); + env(acctdelete(becky, alice), credentials::ids({credIdx}), fee(acctDelFee), ter(tecNO_PERMISSION)); env.close(); // alice create DepositPreauth Object @@ -807,38 +764,28 @@ public: // becky attempts to delete her account, but alice won't take her // XRP, so the delete is blocked. - env(acctdelete(becky, alice), - fee(acctDelFee), - ter(tecNO_PERMISSION)); + env(acctdelete(becky, alice), fee(acctDelFee), ter(tecNO_PERMISSION)); // becky use empty credentials and can't delete account - env(acctdelete(becky, alice), - fee(acctDelFee), - credentials::ids({}), - ter(temMALFORMED)); + env(acctdelete(becky, alice), fee(acctDelFee), credentials::ids({}), ter(temMALFORMED)); // becky use bad credentials and can't delete account env(acctdelete(becky, alice), - credentials::ids( - {"48004829F915654A81B11C4AB8218D96FED67F209B58328A72314FB6E" - "A288BE4"}), + credentials::ids({"48004829F915654A81B11C4AB8218D96FED67F209B58328A72314FB6E" + "A288BE4"}), fee(acctDelFee), ter(tecBAD_CREDENTIALS)); env.close(); // becky use credentials and can delete account - env(acctdelete(becky, alice), - credentials::ids({credIdx}), - fee(acctDelFee)); + env(acctdelete(becky, alice), credentials::ids({credIdx}), fee(acctDelFee)); env.close(); { // check that credential object deleted too - auto const jNoCred = - credentials::ledgerEntry(env, becky, carol, credType); + auto const jNoCred = credentials::ledgerEntry(env, becky, carol, credType); BEAST_EXPECT( - jNoCred.isObject() && jNoCred.isMember(jss::result) && - jNoCred[jss::result].isMember(jss::error) && + jNoCred.isObject() && jNoCred.isMember(jss::result) && jNoCred[jss::result].isMember(jss::error) && jNoCred[jss::result][jss::error] == "entryNotFound"); } @@ -849,24 +796,18 @@ public: env(credentials::accept(daria, carol, credType)); env.close(); std::string const credDaria = - credentials::ledgerEntry( - env, daria, carol, credType)[jss::result][jss::index] - .asString(); + credentials::ledgerEntry(env, daria, carol, credType)[jss::result][jss::index].asString(); // daria use valid credentials, which aren't required and can // delete her account - env(acctdelete(daria, carol), - credentials::ids({credDaria}), - fee(acctDelFee)); + env(acctdelete(daria, carol), credentials::ids({credDaria}), fee(acctDelFee)); env.close(); // check that credential object deleted too - auto const jNoCred = - credentials::ledgerEntry(env, daria, carol, credType); + auto const jNoCred = credentials::ledgerEntry(env, daria, carol, credType); BEAST_EXPECT( - jNoCred.isObject() && jNoCred.isMember(jss::result) && - jNoCred[jss::result].isMember(jss::error) && + jNoCred.isObject() && jNoCred.isMember(jss::result) && jNoCred[jss::result].isMember(jss::error) && jNoCred[jss::result][jss::error] == "entryNotFound"); } @@ -882,9 +823,7 @@ public: env(credentials::accept(eaton, carol, credType)); env.close(); std::string const credEaton = - credentials::ledgerEntry( - env, eaton, carol, credType)[jss::result][jss::index] - .asString(); + credentials::ledgerEntry(env, eaton, carol, credType)[jss::result][jss::index].asString(); // fred make pre-authorization through authorized account env(fset(fred, asfDepositAuth)); @@ -898,18 +837,14 @@ public: // eaton use valid credentials, but he already authorized // through "Authorized" field. - env(acctdelete(eaton, fred), - credentials::ids({credEaton}), - fee(acctDelFee)); + env(acctdelete(eaton, fred), credentials::ids({credEaton}), fee(acctDelFee)); env.close(); // check that credential object deleted too - auto const jNoCred = - credentials::ledgerEntry(env, eaton, carol, credType); + auto const jNoCred = credentials::ledgerEntry(env, eaton, carol, credType); BEAST_EXPECT( - jNoCred.isObject() && jNoCred.isMember(jss::result) && - jNoCred[jss::result].isMember(jss::error) && + jNoCred.isObject() && jNoCred.isMember(jss::result) && jNoCred[jss::result].isMember(jss::error) && jNoCred[jss::result][jss::error] == "entryNotFound"); } @@ -921,37 +856,27 @@ public: env.close(); auto jv = credentials::create(john, carol, credType); - uint32_t const t = env.current() - ->header() - .parentCloseTime.time_since_epoch() - .count() + - 20; + uint32_t const t = env.current()->header().parentCloseTime.time_since_epoch().count() + 20; jv[sfExpiration.jsonName] = t; env(jv); env.close(); env(credentials::accept(john, carol, credType)); env.close(); jv = credentials::ledgerEntry(env, john, carol, credType); - std::string const credIdx = - jv[jss::result][jss::index].asString(); + std::string const credIdx = jv[jss::result][jss::index].asString(); incLgrSeqForAccDel(env, john); // credentials are expired // john use credentials but can't delete account - env(acctdelete(john, alice), - credentials::ids({credIdx}), - fee(acctDelFee), - ter(tecEXPIRED)); + env(acctdelete(john, alice), credentials::ids({credIdx}), fee(acctDelFee), ter(tecEXPIRED)); env.close(); { // check that expired credential object deleted - auto jv = - credentials::ledgerEntry(env, john, carol, credType); + auto jv = credentials::ledgerEntry(env, john, carol, credType); BEAST_EXPECT( - jv.isObject() && jv.isMember(jss::result) && - jv[jss::result].isMember(jss::error) && + jv.isObject() && jv.isMember(jss::result) && jv[jss::result].isMember(jss::error) && jv[jss::result][jss::error] == "entryNotFound"); } } @@ -988,10 +913,7 @@ public: env(deposit::auth(alice, becky)); env.close(); - env(acctdelete(becky, alice), - credentials::ids({credIdx}), - fee(acctDelFee), - ter(temDISABLED)); + env(acctdelete(becky, alice), credentials::ids({credIdx}), fee(acctDelFee), ter(temDISABLED)); env.close(); } } @@ -1021,8 +943,7 @@ public: env.close(); // get credentials index - auto const jv = - credentials::ledgerEntry(env, becky, carol, credType); + auto const jv = credentials::ledgerEntry(env, becky, carol, credType); std::string const credIdx = jv[jss::result][jss::index].asString(); // Close enough ledgers to be able to delete carol's account. @@ -1034,11 +955,9 @@ public: { // check that credential object deleted too BEAST_EXPECT(!env.le(credIdx)); - auto const jv = - credentials::ledgerEntry(env, becky, carol, credType); + auto const jv = credentials::ledgerEntry(env, becky, carol, credType); BEAST_EXPECT( - jv.isObject() && jv.isMember(jss::result) && - jv[jss::result].isMember(jss::error) && + jv.isObject() && jv.isMember(jss::result) && jv[jss::result].isMember(jss::error) && jv[jss::result][jss::error] == "entryNotFound"); } } @@ -1065,8 +984,7 @@ public: env.close(); // get credentials index - auto const jv = - credentials::ledgerEntry(env, becky, carol, credType); + auto const jv = credentials::ledgerEntry(env, becky, carol, credType); std::string const credIdx = jv[jss::result][jss::index].asString(); // Close enough ledgers to be able to delete carol's account. @@ -1078,11 +996,9 @@ public: { // check that credential object deleted too BEAST_EXPECT(!env.le(credIdx)); - auto const jv = - credentials::ledgerEntry(env, becky, carol, credType); + auto const jv = credentials::ledgerEntry(env, becky, carol, credType); BEAST_EXPECT( - jv.isObject() && jv.isMember(jss::result) && - jv[jss::result].isMember(jss::error) && + jv.isObject() && jv.isMember(jss::result) && jv[jss::result].isMember(jss::error) && jv[jss::result][jss::error] == "entryNotFound"); } } diff --git a/src/test/app/AccountTxPaging_test.cpp b/src/test/app/AccountTxPaging_test.cpp index 5efe307812..27078f0578 100644 --- a/src/test/app/AccountTxPaging_test.cpp +++ b/src/test/app/AccountTxPaging_test.cpp @@ -13,9 +13,7 @@ class AccountTxPaging_test : public beast::unit_test::suite bool checkTransaction(Json::Value const& tx, int sequence, int ledger) { - return ( - tx[jss::tx][jss::Sequence].asInt() == sequence && - tx[jss::tx][jss::ledger_index].asInt() == ledger); + return (tx[jss::tx][jss::Sequence].asInt() == sequence && tx[jss::tx][jss::ledger_index].asInt() == ledger); } auto diff --git a/src/test/app/AmendmentTable_test.cpp b/src/test/app/AmendmentTable_test.cpp index a320bccfe8..1e4b096927 100644 --- a/src/test/app/AmendmentTable_test.cpp +++ b/src/test/app/AmendmentTable_test.cpp @@ -34,9 +34,7 @@ private: } static Section - makeSection( - std::string const& name, - std::vector const& amendments) + makeSection(std::string const& name, std::vector const& amendments) { Section section(name); for (auto const& a : amendments) @@ -62,17 +60,13 @@ private: makeConfig() { auto cfg = test::jtx::envconfig(); - cfg->section(SECTION_AMENDMENTS) = - makeSection(SECTION_AMENDMENTS, enabled_); - cfg->section(SECTION_VETO_AMENDMENTS) = - makeSection(SECTION_VETO_AMENDMENTS, vetoed_); + cfg->section(SECTION_AMENDMENTS) = makeSection(SECTION_AMENDMENTS, enabled_); + cfg->section(SECTION_VETO_AMENDMENTS) = makeSection(SECTION_VETO_AMENDMENTS, vetoed_); return cfg; } static std::vector - makeFeatureInfo( - std::vector const& amendments, - VoteBehavior voteBehavior) + makeFeatureInfo(std::vector const& amendments, VoteBehavior voteBehavior) { std::vector result; result.reserve(amendments.size()); @@ -92,8 +86,7 @@ private: static std::vector makeDefaultYes(uint256 const amendment) { - std::vector result{ - {to_string(amendment), amendment, VoteBehavior::DefaultYes}}; + std::vector result{{to_string(amendment), amendment, VoteBehavior::DefaultYes}}; return result; } @@ -120,10 +113,7 @@ private: template static void - combine_arg( - std::vector& dest, - std::vector const& src, - Args const&... args) + combine_arg(std::vector& dest, std::vector const& src, Args const&... args) { assert(dest.capacity() >= dest.size() + src.size()); std::copy(src.begin(), src.end(), std::back_inserter(dest)); @@ -151,14 +141,11 @@ private: // Enabled amendments are typically a subset of supported amendments. // Vetoed amendments should be supported but not enabled. // Unsupported amendments may be added to the AmendmentTable. - std::vector const - yes_{"g", "i", "k", "m", "o", "q", "r", "s", "t", "u"}; - std::vector const - enabled_{"b", "d", "f", "h", "j", "l", "n", "p"}; + std::vector const yes_{"g", "i", "k", "m", "o", "q", "r", "s", "t", "u"}; + std::vector const enabled_{"b", "d", "f", "h", "j", "l", "n", "p"}; std::vector const vetoed_{"a", "c", "e"}; std::vector const obsolete_{"0", "1", "2"}; - std::vector const allSupported_{ - combine(yes_, enabled_, vetoed_, obsolete_)}; + std::vector const allSupported_{combine(yes_, enabled_, vetoed_, obsolete_)}; std::vector const unsupported_{"v", "w", "x"}; std::vector const unsupportedMajority_{"y", "z"}; @@ -180,8 +167,7 @@ public: Section const& enabled, Section const& vetoed) { - return make_AmendmentTable( - app, majorityTime, supported, enabled, vetoed, journal_); + return make_AmendmentTable(app, majorityTime, supported, enabled, vetoed, journal_); } std::unique_ptr @@ -198,22 +184,16 @@ public: std::unique_ptr makeTable(test::jtx::Env& env, std::chrono::seconds majorityTime) { - static std::vector const supported = - combine( - makeDefaultYes(yes_), - // Use non-intuitive default votes for "enabled_" and "vetoed_" - // so that when the tests later explicitly enable or veto them, - // we can be certain that they are not simply going by their - // default vote setting. - makeDefaultNo(enabled_), - makeDefaultYes(vetoed_), - makeObsolete(obsolete_)); - return makeTable( - env.app(), - majorityTime, - supported, - makeSection(enabled_), - makeSection(vetoed_)); + static std::vector const supported = combine( + makeDefaultYes(yes_), + // Use non-intuitive default votes for "enabled_" and "vetoed_" + // so that when the tests later explicitly enable or veto them, + // we can be certain that they are not simply going by their + // default vote setting. + makeDefaultNo(enabled_), + makeDefaultYes(vetoed_), + makeObsolete(obsolete_)); + return makeTable(env.app(), majorityTime, supported, makeSection(enabled_), makeSection(vetoed_)); } void @@ -270,16 +250,14 @@ public: // Verify that unsupportedID is not in table. uint256 const unsupportedID = amendmentId(unsupported_[0]); { - Json::Value const unsupp = - table->getJson(unsupportedID, true)[to_string(unsupportedID)]; + Json::Value const unsupp = table->getJson(unsupportedID, true)[to_string(unsupportedID)]; BEAST_EXPECT(unsupp.size() == 0); } // After vetoing unsupportedID verify that it is in table. table->veto(unsupportedID); { - Json::Value const unsupp = - table->getJson(unsupportedID, true)[to_string(unsupportedID)]; + Json::Value const unsupp = table->getJson(unsupportedID, true)[to_string(unsupportedID)]; BEAST_EXPECT(unsupp[jss::vetoed].asBool()); } } @@ -305,8 +283,7 @@ public: } catch (std::exception const& e) { - BEAST_EXPECT( - e.what() == "Invalid entry '" + id + "' in [Test]"); + BEAST_EXPECT(e.what() == "Invalid entry '" + id + "' in [Test]"); } } @@ -322,9 +299,7 @@ public: } catch (std::exception const& e) { - BEAST_EXPECT( - e.what() == - "Invalid entry '" + id + " Test Name' in [Test]"); + BEAST_EXPECT(e.what() == "Invalid entry '" + id + " Test Name' in [Test]"); } } @@ -343,8 +318,7 @@ public: } catch (std::exception const& e) { - BEAST_EXPECT( - e.what() == "Invalid entry '" + sid + " Name' in [Test]"); + BEAST_EXPECT(e.what() == "Invalid entry '" + sid + " Name' in [Test]"); } } @@ -363,8 +337,7 @@ public: } catch (std::exception const& e) { - BEAST_EXPECT( - e.what() == "Invalid entry '" + sid + " Name' in [Test]"); + BEAST_EXPECT(e.what() == "Invalid entry '" + sid + " Name' in [Test]"); } } @@ -384,8 +357,7 @@ public: } catch (std::exception const& e) { - BEAST_EXPECT( - e.what() == "Invalid entry '" + sid + " Name' in [Test]"); + BEAST_EXPECT(e.what() == "Invalid entry '" + sid + " Name' in [Test]"); } } } @@ -416,9 +388,7 @@ public: bool const enabled = table->isEnabled(supportedID); bool const found = allEnabled.find(supportedID) != allEnabled.end(); BEAST_EXPECTS( - enabled == found, - a + (enabled ? " enabled " : " disabled ") + - (found ? " found" : " not found")); + enabled == found, a + (enabled ? " enabled " : " disabled ") + (found ? " found" : " not found")); } // All supported and unVetoed amendments should be returned as desired. @@ -444,9 +414,7 @@ public: BEAST_EXPECT(table->unVeto(unvetoedID)); std::vector const desired = table->getDesired(); - BEAST_EXPECT( - std::find(desired.begin(), desired.end(), unvetoedID) != - desired.end()); + BEAST_EXPECT(std::find(desired.begin(), desired.end(), unvetoedID) != desired.end()); } // Veto all supported amendments. Now desired should be empty. @@ -475,8 +443,7 @@ public: trustedValidators.reserve(num); for (int i = 0; i < num; ++i) { - auto const& back = - ret.emplace_back(randomKeyPair(KeyType::secp256k1)); + auto const& back = ret.emplace_back(randomKeyPair(KeyType::secp256k1)); trustedValidators.insert(back.first); } table->trustChanged(trustedValidators); @@ -534,14 +501,9 @@ public: } auto v = std::make_shared( - xrpl::NetClock::time_point{}, - pub, - sec, - calcNodeID(pub), - [&field](STValidation& v) { + xrpl::NetClock::time_point{}, pub, sec, calcNodeID(pub), [&field](STValidation& v) { if (!field.empty()) - v.setFieldV256( - sfAmendments, STVector256(sfAmendments, field)); + v.setFieldV256(sfAmendments, STVector256(sfAmendments, field)); v.setFieldU32(sfLedgerSequence, 6180339); }); @@ -550,8 +512,7 @@ public: ourVotes = table.doValidation(enabled); - auto actions = - table.doVoting(rules, roundTime, enabled, majority, validations); + auto actions = table.doVoting(rules, roundTime, enabled, majority, validations); for (auto const& [hash, action] : actions) { // This code assumes other validators do as we do @@ -570,15 +531,13 @@ public: case tfGotMajority: if (majority.find(hash) != majority.end()) - Throw( - "got majority while having majority"); + Throw("got majority while having majority"); majority[hash] = roundTime; break; case tfLostMajority: if (majority.find(hash) == majority.end()) - Throw( - "lost majority without majority"); + Throw("lost majority without majority"); majority.erase(hash); break; @@ -597,8 +556,7 @@ public: auto const testAmendment = amendmentId("TestAmendment"); test::jtx::Env env{*this, feat}; - auto table = - makeTable(env, weeks(2), emptyYes_, emptySection_, emptySection_); + auto table = makeTable(env, weeks(2), emptyYes_, emptySection_, emptySection_); auto const validators = makeValidators(10, table); @@ -607,30 +565,20 @@ public: std::set enabled; majorityAmendments_t majority; - doRound( - env.current()->rules(), - *table, - weeks{1}, - validators, - votes, - ourVotes, - enabled, - majority); + doRound(env.current()->rules(), *table, weeks{1}, validators, votes, ourVotes, enabled, majority); BEAST_EXPECT(ourVotes.empty()); BEAST_EXPECT(enabled.empty()); BEAST_EXPECT(majority.empty()); uint256 const unsupportedID = amendmentId(unsupported_[0]); { - Json::Value const unsupp = - table->getJson(unsupportedID, false)[to_string(unsupportedID)]; + Json::Value const unsupp = table->getJson(unsupportedID, false)[to_string(unsupportedID)]; BEAST_EXPECT(unsupp.size() == 0); } table->veto(unsupportedID); { - Json::Value const unsupp = - table->getJson(unsupportedID, false)[to_string(unsupportedID)]; + Json::Value const unsupp = table->getJson(unsupportedID, false)[to_string(unsupportedID)]; BEAST_EXPECT(!unsupp[jss::vetoed].asBool()); } @@ -638,15 +586,7 @@ public: votes.emplace_back(testAmendment, validators.size()); - doRound( - env.current()->rules(), - *table, - weeks{2}, - validators, - votes, - ourVotes, - enabled, - majority); + doRound(env.current()->rules(), *table, weeks{2}, validators, votes, ourVotes, enabled, majority); BEAST_EXPECT(ourVotes.empty()); BEAST_EXPECT(enabled.empty()); @@ -654,15 +594,7 @@ public: // Note that the simulation code assumes others behave as we do, // so the amendment won't get enabled - doRound( - env.current()->rules(), - *table, - weeks{5}, - validators, - votes, - ourVotes, - enabled, - majority); + doRound(env.current()->rules(), *table, weeks{5}, validators, votes, ourVotes, enabled, majority); BEAST_EXPECT(ourVotes.empty()); BEAST_EXPECT(enabled.empty()); } @@ -676,12 +608,7 @@ public: auto const testAmendment = amendmentId("vetoedAmendment"); test::jtx::Env env{*this, feat}; - auto table = makeTable( - env, - weeks(2), - emptyYes_, - emptySection_, - makeSection(testAmendment)); + auto table = makeTable(env, weeks(2), emptyYes_, emptySection_, makeSection(testAmendment)); auto const validators = makeValidators(10, table); @@ -690,44 +617,20 @@ public: std::set enabled; majorityAmendments_t majority; - doRound( - env.current()->rules(), - *table, - weeks{1}, - validators, - votes, - ourVotes, - enabled, - majority); + doRound(env.current()->rules(), *table, weeks{1}, validators, votes, ourVotes, enabled, majority); BEAST_EXPECT(ourVotes.empty()); BEAST_EXPECT(enabled.empty()); BEAST_EXPECT(majority.empty()); votes.emplace_back(testAmendment, validators.size()); - doRound( - env.current()->rules(), - *table, - weeks{2}, - validators, - votes, - ourVotes, - enabled, - majority); + doRound(env.current()->rules(), *table, weeks{2}, validators, votes, ourVotes, enabled, majority); BEAST_EXPECT(ourVotes.empty()); BEAST_EXPECT(enabled.empty()); majority[testAmendment] = hourTime(weeks{1}); - doRound( - env.current()->rules(), - *table, - weeks{5}, - validators, - votes, - ourVotes, - enabled, - majority); + doRound(env.current()->rules(), *table, weeks{5}, validators, votes, ourVotes, enabled, majority); BEAST_EXPECT(ourVotes.empty()); BEAST_EXPECT(enabled.empty()); } @@ -739,8 +642,7 @@ public: testcase("voteEnable"); test::jtx::Env env{*this, feat}; - auto table = makeTable( - env, weeks(2), makeDefaultYes(yes_), emptySection_, emptySection_); + auto table = makeTable(env, weeks(2), makeDefaultYes(yes_), emptySection_, emptySection_); auto const validators = makeValidators(10, table); @@ -750,15 +652,7 @@ public: majorityAmendments_t majority; // Week 1: We should vote for all known amendments not enabled - doRound( - env.current()->rules(), - *table, - weeks{1}, - validators, - votes, - ourVotes, - enabled, - majority); + doRound(env.current()->rules(), *table, weeks{1}, validators, votes, ourVotes, enabled, majority); BEAST_EXPECT(ourVotes.size() == yes_.size()); BEAST_EXPECT(enabled.empty()); for (auto const& i : yes_) @@ -769,15 +663,7 @@ public: votes.emplace_back(amendmentId(i), validators.size()); // Week 2: We should recognize a majority - doRound( - env.current()->rules(), - *table, - weeks{2}, - validators, - votes, - ourVotes, - enabled, - majority); + doRound(env.current()->rules(), *table, weeks{2}, validators, votes, ourVotes, enabled, majority); BEAST_EXPECT(ourVotes.size() == yes_.size()); BEAST_EXPECT(enabled.empty()); @@ -785,27 +671,11 @@ public: BEAST_EXPECT(majority[amendmentId(i)] == hourTime(weeks{2})); // Week 5: We should enable the amendment - doRound( - env.current()->rules(), - *table, - weeks{5}, - validators, - votes, - ourVotes, - enabled, - majority); + doRound(env.current()->rules(), *table, weeks{5}, validators, votes, ourVotes, enabled, majority); BEAST_EXPECT(enabled.size() == yes_.size()); // Week 6: We should remove it from our votes and from having a majority - doRound( - env.current()->rules(), - *table, - weeks{6}, - validators, - votes, - ourVotes, - enabled, - majority); + doRound(env.current()->rules(), *table, weeks{6}, validators, votes, ourVotes, enabled, majority); BEAST_EXPECT(enabled.size() == yes_.size()); BEAST_EXPECT(ourVotes.empty()); for (auto const& i : yes_) @@ -820,12 +690,7 @@ public: auto const testAmendment = amendmentId("detectMajority"); test::jtx::Env env{*this, feat}; - auto table = makeTable( - env, - weeks(2), - makeDefaultYes(testAmendment), - emptySection_, - emptySection_); + auto table = makeTable(env, weeks(2), makeDefaultYes(testAmendment), emptySection_, emptySection_); auto const validators = makeValidators(16, table); @@ -840,15 +705,7 @@ public: if ((i > 0) && (i < 17)) votes.emplace_back(testAmendment, i); - doRound( - env.current()->rules(), - *table, - weeks{i}, - validators, - votes, - ourVotes, - enabled, - majority); + doRound(env.current()->rules(), *table, weeks{i}, validators, votes, ourVotes, enabled, majority); if (i < 13) // 13 => 13/16 = 0.8125 => > 80% { @@ -890,12 +747,7 @@ public: auto const testAmendment = amendmentId("lostMajority"); test::jtx::Env env{*this, feat}; - auto table = makeTable( - env, - weeks(8), - makeDefaultYes(testAmendment), - emptySection_, - emptySection_); + auto table = makeTable(env, weeks(8), makeDefaultYes(testAmendment), emptySection_, emptySection_); auto const validators = makeValidators(16, table); @@ -909,15 +761,7 @@ public: votes.emplace_back(testAmendment, validators.size()); - doRound( - env.current()->rules(), - *table, - weeks{1}, - validators, - votes, - ourVotes, - enabled, - majority); + doRound(env.current()->rules(), *table, weeks{1}, validators, votes, ourVotes, enabled, majority); BEAST_EXPECT(enabled.empty()); BEAST_EXPECT(!majority.empty()); @@ -931,15 +775,7 @@ public: // Gradually reduce support votes.emplace_back(testAmendment, validators.size() - i); - doRound( - env.current()->rules(), - *table, - weeks{i + 1}, - validators, - votes, - ourVotes, - enabled, - majority); + doRound(env.current()->rules(), *table, weeks{i + 1}, validators, votes, ourVotes, enabled, majority); if (i < 4) // 16 - 3 = 13 => 13/16 = 0.8125 => > 80% { // 16 - 4 = 12 => 12/16 = 0.75 => < 80% @@ -966,15 +802,9 @@ public: auto const testAmendment = amendmentId("changedUNL"); test::jtx::Env env{*this, feat}; - auto table = makeTable( - env, - weeks(8), - makeDefaultYes(testAmendment), - emptySection_, - emptySection_); + auto table = makeTable(env, weeks(8), makeDefaultYes(testAmendment), emptySection_, emptySection_); - std::vector> validators = - makeValidators(10, table); + std::vector> validators = makeValidators(10, table); std::set enabled; majorityAmendments_t majority; @@ -986,15 +816,7 @@ public: votes.emplace_back(testAmendment, validators.size() - 2); - doRound( - env.current()->rules(), - *table, - weeks{1}, - validators, - votes, - ourVotes, - enabled, - majority); + doRound(env.current()->rules(), *table, weeks{1}, validators, votes, ourVotes, enabled, majority); BEAST_EXPECT(enabled.empty()); BEAST_EXPECT(majority.empty()); @@ -1005,22 +827,18 @@ public: // A lambda that updates the AmendmentTable with the latest // trusted validators. - auto callTrustChanged = - [](std::vector> const& validators, - std::unique_ptr const& table) { - // We need a hash_set to pass to trustChanged. - hash_set trustedValidators; - trustedValidators.reserve(validators.size()); - std::for_each( - validators.begin(), - validators.end(), - [&trustedValidators](auto const& val) { - trustedValidators.insert(val.first); - }); + auto callTrustChanged = [](std::vector> const& validators, + std::unique_ptr const& table) { + // We need a hash_set to pass to trustChanged. + hash_set trustedValidators; + trustedValidators.reserve(validators.size()); + std::for_each(validators.begin(), validators.end(), [&trustedValidators](auto const& val) { + trustedValidators.insert(val.first); + }); - // Tell the AmendmentTable that the UNL changed. - table->trustChanged(trustedValidators); - }; + // Tell the AmendmentTable that the UNL changed. + table->trustChanged(trustedValidators); + }; // Tell the table that there's been a change in trusted validators. callTrustChanged(validators, table); @@ -1032,15 +850,7 @@ public: votes.emplace_back(testAmendment, validators.size() - 2); - doRound( - env.current()->rules(), - *table, - weeks{2}, - validators, - votes, - ourVotes, - enabled, - majority); + doRound(env.current()->rules(), *table, weeks{2}, validators, votes, ourVotes, enabled, majority); BEAST_EXPECT(enabled.empty()); BEAST_EXPECT(!majority.empty()); @@ -1048,8 +858,7 @@ public: { // One of the validators goes flaky and doesn't send validations // (without the UNL changing) so the amendment loses majority. - std::pair const savedValidator = - validators.front(); + std::pair const savedValidator = validators.front(); validators.erase(validators.begin()); std::vector> votes; @@ -1057,15 +866,7 @@ public: votes.emplace_back(testAmendment, validators.size() - 2); - doRound( - env.current()->rules(), - *table, - weeks{3}, - validators, - votes, - ourVotes, - enabled, - majority); + doRound(env.current()->rules(), *table, weeks{3}, validators, votes, ourVotes, enabled, majority); BEAST_EXPECT(enabled.empty()); BEAST_EXPECT(majority.empty()); @@ -1076,15 +877,7 @@ public: votes.front().second = validators.size() - 2; - doRound( - env.current()->rules(), - *table, - weeks{4}, - validators, - votes, - ourVotes, - enabled, - majority); + doRound(env.current()->rules(), *table, weeks{4}, validators, votes, ourVotes, enabled, majority); BEAST_EXPECT(enabled.empty()); BEAST_EXPECT(!majority.empty()); @@ -1098,15 +891,7 @@ public: votes.front().second = validators.size() - 2; - doRound( - env.current()->rules(), - *table, - weeks{5}, - validators, - votes, - ourVotes, - enabled, - majority); + doRound(env.current()->rules(), *table, weeks{5}, validators, votes, ourVotes, enabled, majority); BEAST_EXPECT(enabled.empty()); BEAST_EXPECT(majority.empty()); @@ -1131,18 +916,12 @@ public: { test::jtx::Env env{*this, feat}; auto const testAmendment = amendmentId("validatorFlapping"); - auto table = makeTable( - env, - weeks(1), - makeDefaultYes(testAmendment), - emptySection_, - emptySection_); + auto table = makeTable(env, weeks(1), makeDefaultYes(testAmendment), emptySection_, emptySection_); // Make two lists of validators, one with a missing validator, to // make it easy to simulate validator flapping. auto const allValidators = makeValidators(11, table); - decltype(allValidators) const mostValidators( - allValidators.begin() + 1, allValidators.end()); + decltype(allValidators) const mostValidators(allValidators.begin() + 1, allValidators.end()); BEAST_EXPECT(allValidators.size() == mostValidators.size() + 1); std::set enabled; @@ -1184,9 +963,7 @@ public: // no flapping. Otherwise we should only have majority // if allValidators vote -- which means there are no // missing validators. - bool const expectMajority = (delay <= 24) - ? true - : &thisHoursValidators == &allValidators; + bool const expectMajority = (delay <= 24) ? true : &thisHoursValidators == &allValidators; BEAST_EXPECT(majority.empty() != expectMajority); } else @@ -1217,9 +994,7 @@ public: std::set enabled; std::for_each( - unsupported_.begin(), - unsupported_.end(), - [&enabled](auto const& s) { enabled.insert(amendmentId(s)); }); + unsupported_.begin(), unsupported_.end(), [&enabled](auto const& s) { enabled.insert(amendmentId(s)); }); majorityAmendments_t majority; table->doValidatedLedger(1, enabled, majority); @@ -1227,18 +1002,14 @@ public: BEAST_EXPECT(!table->firstUnsupportedExpected()); NetClock::duration t{1000s}; - std::for_each( - unsupportedMajority_.begin(), - unsupportedMajority_.end(), - [&majority, &t](auto const& s) { - majority[amendmentId(s)] = NetClock::time_point{--t}; - }); + std::for_each(unsupportedMajority_.begin(), unsupportedMajority_.end(), [&majority, &t](auto const& s) { + majority[amendmentId(s)] = NetClock::time_point{--t}; + }); table->doValidatedLedger(1, enabled, majority); BEAST_EXPECT(table->hasUnsupportedEnabled()); BEAST_EXPECT( - table->firstUnsupportedExpected() && - *table->firstUnsupportedExpected() == NetClock::time_point{t} + w); + table->firstUnsupportedExpected() && *table->firstUnsupportedExpected() == NetClock::time_point{t} + w); // Make sure the table knows when it needs an update. BEAST_EXPECT(!table->needValidatedLedger(256)); diff --git a/src/test/app/Batch_test.cpp b/src/test/app/Batch_test.cpp index 67b0933ae2..a4e00f26db 100644 --- a/src/test/app/Batch_test.cpp +++ b/src/test/app/Batch_test.cpp @@ -2,18 +2,18 @@ #include #include -#include -#include #include #include #include +#include #include #include #include #include #include #include +#include namespace xrpl { namespace test { @@ -57,27 +57,19 @@ class Batch_test : public beast::unit_test::suite } void - validateInnerTxn( - jtx::Env& env, - std::string const& batchID, - TestLedgerData const& ledgerResult) + validateInnerTxn(jtx::Env& env, std::string const& batchID, TestLedgerData const& ledgerResult) { Json::Value const jrr = env.rpc("tx", ledgerResult.txHash)[jss::result]; BEAST_EXPECT(jrr[sfTransactionType.jsonName] == ledgerResult.txType); - BEAST_EXPECT( - jrr[jss::meta][sfTransactionResult.jsonName] == - ledgerResult.result); + BEAST_EXPECT(jrr[jss::meta][sfTransactionResult.jsonName] == ledgerResult.result); BEAST_EXPECT(jrr[jss::meta][sfParentBatchID.jsonName] == batchID); } void - validateClosedLedger( - jtx::Env& env, - std::vector const& ledgerResults) + validateClosedLedger(jtx::Env& env, std::vector const& ledgerResults) { auto const jrr = getLastLedger(env); - auto const transactions = - jrr[jss::result][jss::ledger][jss::transactions]; + auto const transactions = jrr[jss::result][jss::ledger][jss::transactions]; BEAST_EXPECT(transactions.size() == ledgerResults.size()); for (TestLedgerData const& ledgerResult : ledgerResults) { @@ -85,10 +77,8 @@ class Batch_test : public beast::unit_test::suite BEAST_EXPECT(txn[jss::hash].asString() == ledgerResult.txHash); BEAST_EXPECT(txn.isMember(jss::metaData)); Json::Value const meta = txn[jss::metaData]; - BEAST_EXPECT( - txn[sfTransactionType.jsonName] == ledgerResult.txType); - BEAST_EXPECT( - meta[sfTransactionResult.jsonName] == ledgerResult.result); + BEAST_EXPECT(txn[sfTransactionType.jsonName] == ledgerResult.txType); + BEAST_EXPECT(meta[sfTransactionResult.jsonName] == ledgerResult.result); if (ledgerResult.batchID) validateInnerTxn(env, *ledgerResult.batchID, ledgerResult); } @@ -155,10 +145,8 @@ class Batch_test : public beast::unit_test::suite for (bool const withBatch : {true, false}) { - testcase << "enabled: Batch " - << (withBatch ? "enabled" : "disabled") - << ", Inner Sig Fix: " - << (withInnerSigFix ? "enabled" : "disabled"); + testcase << "enabled: Batch " << (withBatch ? "enabled" : "disabled") + << ", Inner Sig Fix: " << (withInnerSigFix ? "enabled" : "disabled"); auto const amend = withBatch ? features : features - featureBatch; @@ -174,8 +162,7 @@ class Batch_test : public beast::unit_test::suite { auto const seq = env.seq(alice); auto const batchFee = batch::calcBatchFee(env, 0, 2); - auto const txResult = - withBatch ? ter(tesSUCCESS) : ter(temDISABLED); + auto const txResult = withBatch ? ter(tesSUCCESS) : ter(temDISABLED); env(batch::outer(alice, seq, batchFee, tfAllOrNothing), batch::inner(pay(alice, bob, XRP(1)), seq + 1), batch::inner(pay(alice, bob, XRP(1)), seq + 2), @@ -188,11 +175,8 @@ class Batch_test : public beast::unit_test::suite // temINVALID_FLAG. If the feature is enabled, the transaction fails // early in checkValidity() { - auto const txResult = - withBatch ? ter(telENV_RPC_FAILED) : ter(temINVALID_FLAG); - env(pay(alice, bob, XRP(1)), - txflags(tfInnerBatchTxn), - txResult); + auto const txResult = withBatch ? ter(telENV_RPC_FAILED) : ter(temINVALID_FLAG); + env(pay(alice, bob, XRP(1)), txflags(tfInnerBatchTxn), txResult); env.close(); } @@ -221,8 +205,7 @@ class Batch_test : public beast::unit_test::suite // temBAD_FEE: preflight1 { - env(batch::outer(alice, env.seq(alice), XRP(-1), tfAllOrNothing), - ter(temBAD_FEE)); + env(batch::outer(alice, env.seq(alice), XRP(-1), tfAllOrNothing), ter(temBAD_FEE)); env.close(); } @@ -231,8 +214,7 @@ class Batch_test : public beast::unit_test::suite { auto const seq = env.seq(alice); auto const batchFee = batch::calcBatchFee(env, 0, 0); - env(batch::outer(alice, seq, batchFee, tfInnerBatchTxn), - ter(telENV_RPC_FAILED)); + env(batch::outer(alice, seq, batchFee, tfInnerBatchTxn), ter(telENV_RPC_FAILED)); env.close(); } @@ -240,8 +222,7 @@ class Batch_test : public beast::unit_test::suite { auto const seq = env.seq(alice); auto const batchFee = batch::calcBatchFee(env, 0, 0); - env(batch::outer(alice, seq, batchFee, tfDisallowXRP), - ter(temINVALID_FLAG)); + env(batch::outer(alice, seq, batchFee, tfDisallowXRP), ter(temINVALID_FLAG)); env.close(); } @@ -259,8 +240,7 @@ class Batch_test : public beast::unit_test::suite { auto const seq = env.seq(alice); auto const batchFee = batch::calcBatchFee(env, 0, 0); - env(batch::outer(alice, seq, batchFee, tfAllOrNothing), - ter(temARRAY_EMPTY)); + env(batch::outer(alice, seq, batchFee, tfAllOrNothing), ter(temARRAY_EMPTY)); env.close(); } @@ -312,8 +292,7 @@ class Batch_test : public beast::unit_test::suite auto const seq = env.seq(alice); auto const batchFee = batch::calcBatchFee(env, 0, 2); env(batch::outer(alice, seq, batchFee, tfAllOrNothing), - batch::inner( - batch::outer(alice, seq, batchFee, tfAllOrNothing), seq), + batch::inner(batch::outer(alice, seq, batchFee, tfAllOrNothing), seq), batch::inner(pay(alice, bob, XRP(1)), seq + 2), ter(telENV_RPC_FAILED)); env.close(); @@ -354,12 +333,9 @@ class Batch_test : public beast::unit_test::suite auto tx1 = pay(alice, bob, XRP(1)); tx1[sfSigners.jsonName] = Json::arrayValue; tx1[sfSigners.jsonName][0U][sfSigner.jsonName] = Json::objectValue; - tx1[sfSigners.jsonName][0U][sfSigner.jsonName][sfAccount.jsonName] = - alice.human(); - tx1[sfSigners.jsonName][0U][sfSigner.jsonName] - [sfSigningPubKey.jsonName] = strHex(alice.pk()); - tx1[sfSigners.jsonName][0U][sfSigner.jsonName] - [sfTxnSignature.jsonName] = "DEADBEEF"; + tx1[sfSigners.jsonName][0U][sfSigner.jsonName][sfAccount.jsonName] = alice.human(); + tx1[sfSigners.jsonName][0U][sfSigner.jsonName][sfSigningPubKey.jsonName] = strHex(alice.pk()); + tx1[sfSigners.jsonName][0U][sfSigner.jsonName][sfTxnSignature.jsonName] = "DEADBEEF"; env(batch::outer(alice, seq, batchFee, tfAllOrNothing), batch::inner(tx1, seq + 1), batch::inner(pay(alice, bob, XRP(1)), seq + 2), @@ -510,17 +486,7 @@ class Batch_test : public beast::unit_test::suite env(batch::outer(alice, seq, batchFee, tfAllOrNothing), batch::inner(pay(alice, bob, XRP(10)), seq + 1), batch::inner(pay(alice, bob, XRP(5)), seq + 2), - batch::sig( - bob, - carol, - alice, - bob, - carol, - alice, - bob, - carol, - alice, - alice), + batch::sig(bob, carol, alice, bob, carol, alice, bob, carol, alice, alice), ter(telENV_RPC_FAILED)); env.close(); } @@ -585,15 +551,11 @@ class Batch_test : public beast::unit_test::suite batch::inner(pay(bob, alice, XRP(5)), bobSeq)); Serializer msg; - serializeBatch( - msg, tfAllOrNothing, jt.stx->getBatchTransactionIDs()); + serializeBatch(msg, tfAllOrNothing, jt.stx->getBatchTransactionIDs()); auto const sig = xrpl::sign(bob.pk(), bob.sk(), msg.slice()); - jt.jv[sfBatchSigners.jsonName][0u][sfBatchSigner.jsonName] - [sfAccount.jsonName] = bob.human(); - jt.jv[sfBatchSigners.jsonName][0u][sfBatchSigner.jsonName] - [sfSigningPubKey.jsonName] = strHex(alice.pk()); - jt.jv[sfBatchSigners.jsonName][0u][sfBatchSigner.jsonName] - [sfTxnSignature.jsonName] = + jt.jv[sfBatchSigners.jsonName][0u][sfBatchSigner.jsonName][sfAccount.jsonName] = bob.human(); + jt.jv[sfBatchSigners.jsonName][0u][sfBatchSigner.jsonName][sfSigningPubKey.jsonName] = strHex(alice.pk()); + jt.jv[sfBatchSigners.jsonName][0u][sfBatchSigner.jsonName][sfTxnSignature.jsonName] = strHex(Slice{sig.data(), sig.size()}); env(jt.jv, ter(temBAD_SIGNATURE)); @@ -1338,16 +1300,15 @@ class Batch_test : public beast::unit_test::suite env.fund(XRP(10000), alice, bob, gw); env.close(); - auto const ammCreate = - [&alice](STAmount const& amount, STAmount const& amount2) { - Json::Value jv; - jv[jss::Account] = alice.human(); - jv[jss::Amount] = amount.getJson(JsonOptions::none); - jv[jss::Amount2] = amount2.getJson(JsonOptions::none); - jv[jss::TradingFee] = 0; - jv[jss::TransactionType] = jss::AMMCreate; - return jv; - }; + auto const ammCreate = [&alice](STAmount const& amount, STAmount const& amount2) { + Json::Value jv; + jv[jss::Account] = alice.human(); + jv[jss::Amount] = amount.getJson(JsonOptions::none); + jv[jss::Amount2] = amount2.getJson(JsonOptions::none); + jv[jss::TradingFee] = 0; + jv[jss::TransactionType] = jss::AMMCreate; + return jv; + }; auto const batchFee = batch::calcBatchFee(env, 0, 2); auto const seq = env.seq(alice); @@ -1415,14 +1376,11 @@ class Batch_test : public beast::unit_test::suite batch::inner(pay(alice, bob, XRP(1)), aliceSeq), batch::inner(pay(alice, bob, XRP(1)), aliceSeq)); - env.app().openLedger().modify( - [&](OpenView& view, beast::Journal j) { - auto const result = - xrpl::apply(env.app(), view, *jt.stx, tapNONE, j); - BEAST_EXPECT( - !result.applied && result.ter == temARRAY_TOO_LARGE); - return result.applied; - }); + env.app().openLedger().modify([&](OpenView& view, beast::Journal j) { + auto const result = xrpl::apply(env.app(), view, *jt.stx, tapNONE, j); + BEAST_EXPECT(!result.applied && result.ter == temARRAY_TOO_LARGE); + return result.applied; + }); } // telENV_RPC_FAILED: Batch: signers array exceeds 8 entries. @@ -1461,14 +1419,11 @@ class Batch_test : public beast::unit_test::suite batch::inner(pay(alice, bob, XRP(5)), aliceSeq + 2), batch::sig(bob, bob, bob, bob, bob, bob, bob, bob, bob, bob)); - env.app().openLedger().modify( - [&](OpenView& view, beast::Journal j) { - auto const result = - xrpl::apply(env.app(), view, *jt.stx, tapNONE, j); - BEAST_EXPECT( - !result.applied && result.ter == temARRAY_TOO_LARGE); - return result.applied; - }); + env.app().openLedger().modify([&](OpenView& view, beast::Journal j) { + auto const result = xrpl::apply(env.app(), view, *jt.stx, tapNONE, j); + BEAST_EXPECT(!result.applied && result.ter == temARRAY_TOO_LARGE); + return result.applied; + }); } } @@ -1799,27 +1754,9 @@ class Batch_test : public beast::unit_test::suite env, tesSUCCESS, batch::outer(alice, seq, batchFee, tfOnlyOne), - batch::inner( - offer( - alice, - alice["USD"](100), - XRP(100), - tfImmediateOrCancel), - seq + 1), - batch::inner( - offer( - alice, - alice["USD"](100), - XRP(100), - tfImmediateOrCancel), - seq + 2), - batch::inner( - offer( - alice, - alice["USD"](100), - XRP(100), - tfImmediateOrCancel), - seq + 3), + batch::inner(offer(alice, alice["USD"](100), XRP(100), tfImmediateOrCancel), seq + 1), + batch::inner(offer(alice, alice["USD"](100), XRP(100), tfImmediateOrCancel), seq + 2), + batch::inner(offer(alice, alice["USD"](100), XRP(100), tfImmediateOrCancel), seq + 3), batch::inner(pay(alice, bob, XRP(100)), seq + 4), batch::inner(pay(alice, carol, XRP(100)), seq + 5), batch::inner(pay(alice, dave, XRP(100)), seq + 6)); @@ -2038,13 +1975,7 @@ class Batch_test : public beast::unit_test::suite batch::outer(alice, seq, batchFee, tfUntilFailure), batch::inner(pay(alice, bob, XRP(100)), seq + 1), batch::inner(pay(alice, carol, XRP(100)), seq + 2), - batch::inner( - offer( - alice, - alice["USD"](100), - XRP(100), - tfImmediateOrCancel), - seq + 3), + batch::inner(offer(alice, alice["USD"](100), XRP(100), tfImmediateOrCancel), seq + 3), batch::inner(pay(alice, dave, XRP(100)), seq + 4)); env.close(); @@ -2232,13 +2163,7 @@ class Batch_test : public beast::unit_test::suite batch::outer(alice, seq, batchFee, tfIndependent), batch::inner(pay(alice, bob, XRP(100)), seq + 1), batch::inner(pay(alice, carol, XRP(100)), seq + 2), - batch::inner( - offer( - alice, - alice["USD"](100), - XRP(100), - tfImmediateOrCancel), - seq + 3)); + batch::inner(offer(alice, alice["USD"](100), XRP(100), tfImmediateOrCancel), seq + 3)); env.close(); std::vector testCases = { @@ -2262,9 +2187,8 @@ class Batch_test : public beast::unit_test::suite std::string const testName = [&]() { std::stringstream ss; - ss << "inner submit rpc: batch " - << (withBatch ? "enabled" : "disabled") << ", inner sig fix: " - << (withInnerSigFix ? "enabled" : "disabled") << ": "; + ss << "inner submit rpc: batch " << (withBatch ? "enabled" : "disabled") + << ", inner sig fix: " << (withInnerSigFix ? "enabled" : "disabled") << ": "; return ss.str(); }(); @@ -2283,45 +2207,37 @@ class Batch_test : public beast::unit_test::suite env.fund(XRP(10000), alice, bob); env.close(); - auto submitAndValidate = - [&](std::string caseName, - Slice const& slice, - int line, - std::optional expectedEnabled = std::nullopt, - std::optional expectedDisabled = std::nullopt, - bool expectInvalidFlag = false) { - testcase << testName << caseName - << (expectInvalidFlag - ? " - Expected to reach tx engine!" - : ""); - auto const jrr = env.rpc("submit", strHex(slice))[jss::result]; - auto const expected = withBatch - ? expectedEnabled.value_or( - "fails local checks: Malformed: Invalid inner batch " - "transaction.") - : expectedDisabled.value_or( - "fails local checks: Empty SigningPubKey."); - if (expectInvalidFlag) - { - expect( - jrr[jss::status] == "success" && - jrr[jss::engine_result] == "temINVALID_FLAG", - pretty(jrr), - __FILE__, - line); - } - else - { - expect( - jrr[jss::status] == "error" && - jrr[jss::error] == "invalidTransaction" && - jrr[jss::error_exception] == expected, - pretty(jrr), - __FILE__, - line); - } - env.close(); - }; + auto submitAndValidate = [&](std::string caseName, + Slice const& slice, + int line, + std::optional expectedEnabled = std::nullopt, + std::optional expectedDisabled = std::nullopt, + bool expectInvalidFlag = false) { + testcase << testName << caseName << (expectInvalidFlag ? " - Expected to reach tx engine!" : ""); + auto const jrr = env.rpc("submit", strHex(slice))[jss::result]; + auto const expected = withBatch ? expectedEnabled.value_or( + "fails local checks: Malformed: Invalid inner batch " + "transaction.") + : expectedDisabled.value_or("fails local checks: Empty SigningPubKey."); + if (expectInvalidFlag) + { + expect( + jrr[jss::status] == "success" && jrr[jss::engine_result] == "temINVALID_FLAG", + pretty(jrr), + __FILE__, + line); + } + else + { + expect( + jrr[jss::status] == "error" && jrr[jss::error] == "invalidTransaction" && + jrr[jss::error_exception] == expected, + pretty(jrr), + __FILE__, + line); + } + env.close(); + }; // Invalid RPC Submission: TxnSignature // + has `TxnSignature` field @@ -2349,11 +2265,7 @@ class Batch_test : public beast::unit_test::suite Serializer s; parsed.object->add(s); submitAndValidate( - "SigningPubKey set", - s.slice(), - __LINE__, - std::nullopt, - "fails local checks: Invalid signature."); + "SigningPubKey set", s.slice(), __LINE__, std::nullopt, "fails local checks: Invalid signature."); } // Invalid RPC Submission: Signers @@ -2368,29 +2280,18 @@ class Batch_test : public beast::unit_test::suite Serializer s; parsed.object->add(s); submitAndValidate( - "Signers set", - s.slice(), - __LINE__, - std::nullopt, - "fails local checks: Invalid Signers array size."); + "Signers set", s.slice(), __LINE__, std::nullopt, "fails local checks: Invalid Signers array size."); } { // Fully signed inner batch transaction - auto const txn = - batch::inner(pay(alice, bob, XRP(1)), env.seq(alice)); + auto const txn = batch::inner(pay(alice, bob, XRP(1)), env.seq(alice)); auto const jt = env.jt(txn.getTxn()); STParsedJSONObject parsed("test", jt.jv); Serializer s; parsed.object->add(s); - submitAndValidate( - "Fully signed", - s.slice(), - __LINE__, - std::nullopt, - std::nullopt, - !withBatch); + submitAndValidate("Fully signed", s.slice(), __LINE__, std::nullopt, std::nullopt, !withBatch); } // Invalid RPC Submission: tfInnerBatchTxn @@ -2418,15 +2319,13 @@ class Batch_test : public beast::unit_test::suite // - has no `Signers` field // + has `tfInnerBatchTxn` flag { - STTx amendTx( - ttAMENDMENT, [seq = env.closed()->header().seq + 1](auto& obj) { - obj.setAccountID(sfAccount, AccountID()); - obj.setFieldH256(sfAmendment, fixBatchInnerSigs); - obj.setFieldU32(sfLedgerSequence, seq); - obj.setFieldU32(sfFlags, tfInnerBatchTxn); - }); - auto txn = batch::inner( - amendTx.getJson(JsonOptions::none), env.seq(alice)); + STTx amendTx(ttAMENDMENT, [seq = env.closed()->header().seq + 1](auto& obj) { + obj.setAccountID(sfAccount, AccountID()); + obj.setFieldH256(sfAmendment, fixBatchInnerSigs); + obj.setFieldU32(sfLedgerSequence, seq); + obj.setFieldU32(sfFlags, tfInnerBatchTxn); + }); + auto txn = batch::inner(amendTx.getJson(JsonOptions::none), env.seq(alice)); STParsedJSONObject parsed("test", txn.getTxn()); Serializer s; parsed.object->add(s); @@ -2434,9 +2333,8 @@ class Batch_test : public beast::unit_test::suite "Pseudo-transaction", s.slice(), __LINE__, - withInnerSigFix - ? "fails local checks: Empty SigningPubKey." - : "fails local checks: Cannot submit pseudo transactions.", + withInnerSigFix ? "fails local checks: Empty SigningPubKey." + : "fails local checks: Cannot submit pseudo transactions.", "fails local checks: Empty SigningPubKey."); } } @@ -2537,8 +2435,7 @@ class Batch_test : public beast::unit_test::suite auto const sle = env.le(keylet::account(alice)); BEAST_EXPECT(sle); - BEAST_EXPECT( - sle->getFieldVL(sfDomain) == Blob(domain.begin(), domain.end())); + BEAST_EXPECT(sle->getFieldVL(sfDomain) == Blob(domain.begin(), domain.end())); // Alice consumes sequences (# of txns) BEAST_EXPECT(env.seq(alice) == seq + 3); @@ -2573,8 +2470,7 @@ class Batch_test : public beast::unit_test::suite auto const preBob = env.balance(bob); auto const seq = env.seq(alice); - auto const batchFee = batch::calcBatchFee(env, 0, 2) + - env.current()->fees().increment; + auto const batchFee = batch::calcBatchFee(env, 0, 2) + env.current()->fees().increment; auto const [txIDs, batchID] = submitBatch( env, tesSUCCESS, @@ -2617,8 +2513,7 @@ class Batch_test : public beast::unit_test::suite env.close(); auto const seq = env.seq(alice); - auto const batchFee = batch::calcBatchFee(env, 0, 2) + - env.current()->fees().increment; + auto const batchFee = batch::calcBatchFee(env, 0, 2) + env.current()->fees().increment; auto const [txIDs, batchID] = submitBatch( env, tesSUCCESS, @@ -2659,8 +2554,7 @@ class Batch_test : public beast::unit_test::suite auto const preBob = env.balance(bob); auto const seq = env.seq(alice); - auto const batchFee = batch::calcBatchFee(env, 0, 2) + - env.current()->fees().increment; + auto const batchFee = batch::calcBatchFee(env, 0, 2) + env.current()->fees().increment; auto const [txIDs, batchID] = submitBatch( env, tesSUCCESS, @@ -2687,17 +2581,14 @@ class Batch_test : public beast::unit_test::suite { testcase("loan"); - bool const lendingBatchEnabled = !std::any_of( - Batch::disabledTxTypes.begin(), - Batch::disabledTxTypes.end(), - [](auto const& disabled) { return disabled == ttLOAN_BROKER_SET; }); + bool const lendingBatchEnabled = + !std::any_of(Batch::disabledTxTypes.begin(), Batch::disabledTxTypes.end(), [](auto const& disabled) { + return disabled == ttLOAN_BROKER_SET; + }); using namespace test::jtx; - test::jtx::Env env{ - *this, - features | featureSingleAssetVault | featureLendingProtocol | - featureMPTokensV1}; + test::jtx::Env env{*this, features | featureSingleAssetVault | featureLendingProtocol | featureMPTokensV1}; Account const issuer{"issuer"}; // For simplicity, lender will be the sole actor for the vault & @@ -2720,18 +2611,15 @@ class Batch_test : public beast::unit_test::suite auto const debtMaximumValue = asset(25'000).value(); auto const coverDepositValue = asset(1000).value(); - auto [tx, vaultKeylet] = - vault.create({.owner = lender, .asset = asset}); + auto [tx, vaultKeylet] = vault.create({.owner = lender, .asset = asset}); env(tx); env.close(); BEAST_EXPECT(env.le(vaultKeylet)); - env(vault.deposit( - {.depositor = lender, .id = vaultKeylet.key, .amount = deposit})); + env(vault.deposit({.depositor = lender, .id = vaultKeylet.key, .amount = deposit})); env.close(); - auto const brokerKeylet = - keylet::loanbroker(lender.id(), env.seq(lender)); + auto const brokerKeylet = keylet::loanbroker(lender.id(), env.seq(lender)); { using namespace loanBroker; @@ -2757,8 +2645,7 @@ class Batch_test : public beast::unit_test::suite { auto const [txIDs, batchID] = submitBatch( env, - lendingBatchEnabled ? temBAD_SIGNATURE - : temINVALID_INNER_BATCH, + lendingBatchEnabled ? temBAD_SIGNATURE : temINVALID_INNER_BATCH, batch::outer(lender, lenderSeq, batchFee, tfAllOrNothing), batch::inner( env.json( @@ -2769,11 +2656,7 @@ class Batch_test : public beast::unit_test::suite fee(none), seq(none)), lenderSeq + 1), - batch::inner( - pay(lender, - loanKeylet.key, - STAmount{asset, asset(500).value()}), - lenderSeq + 2)); + batch::inner(pay(lender, loanKeylet.key, STAmount{asset, asset(500).value()}), lenderSeq + 2)); } { auto const [txIDs, batchID] = submitBatch( @@ -2788,17 +2671,12 @@ class Batch_test : public beast::unit_test::suite fee(none), seq(none)), lenderSeq + 1), - batch::inner( - pay(lender, - loanKeylet.key, - STAmount{asset, asset(500).value()}), - lenderSeq + 2)); + batch::inner(pay(lender, loanKeylet.key, STAmount{asset, asset(500).value()}), lenderSeq + 2)); } { auto const [txIDs, batchID] = submitBatch( env, - lendingBatchEnabled ? temBAD_SIGNER - : temINVALID_INNER_BATCH, + lendingBatchEnabled ? temBAD_SIGNER : temINVALID_INNER_BATCH, batch::outer(lender, lenderSeq, batchFee, tfAllOrNothing), batch::inner( env.json( @@ -2809,11 +2687,7 @@ class Batch_test : public beast::unit_test::suite fee(none), seq(none)), lenderSeq + 1), - batch::inner( - pay(lender, - loanKeylet.key, - STAmount{asset, asset(500).value()}), - lenderSeq + 2)); + batch::inner(pay(lender, loanKeylet.key, STAmount{asset, asset(500).value()}), lenderSeq + 2)); } { // LoanSet normally charges at least 2x base fee, but since the @@ -2822,8 +2696,7 @@ class Batch_test : public beast::unit_test::suite auto const batchFee = batch::calcBatchFee(env, 1, 2); auto const [txIDs, batchID] = submitBatch( env, - lendingBatchEnabled ? TER(tesSUCCESS) - : TER(temINVALID_INNER_BATCH), + lendingBatchEnabled ? TER(tesSUCCESS) : TER(temINVALID_INNER_BATCH), batch::outer(lender, lenderSeq, batchFee, tfAllOrNothing), batch::inner( env.json( @@ -2855,8 +2728,7 @@ class Batch_test : public beast::unit_test::suite auto const batchFee = batch::calcBatchFee(env, 1, 2); auto const [txIDs, batchID] = submitBatch( env, - lendingBatchEnabled ? TER(tesSUCCESS) - : TER(temINVALID_INNER_BATCH), + lendingBatchEnabled ? TER(tesSUCCESS) : TER(temINVALID_INNER_BATCH), batch::outer(lender, lenderSeq, batchFee, tfAllOrNothing), batch::inner( env.json( @@ -2866,16 +2738,13 @@ class Batch_test : public beast::unit_test::suite fee(none), seq(none)), lenderSeq + 1), - batch::inner( - manage(lender, loanKeylet.key, tfLoanImpair), - lenderSeq + 2), + batch::inner(manage(lender, loanKeylet.key, tfLoanImpair), lenderSeq + 2), batch::sig(borrower)); } env.close(); BEAST_EXPECT(env.le(brokerKeylet)); - if (auto const sleLoan = env.le(loanKeylet); lendingBatchEnabled - ? BEAST_EXPECT(sleLoan) - : !BEAST_EXPECT(!sleLoan)) + if (auto const sleLoan = env.le(loanKeylet); + lendingBatchEnabled ? BEAST_EXPECT(sleLoan) : !BEAST_EXPECT(!sleLoan)) { BEAST_EXPECT(sleLoan->isFlag(lsfLoanImpaired)); } @@ -2943,8 +2812,7 @@ class Batch_test : public beast::unit_test::suite BEAST_EXPECT(env.balance(bob) == preBob); // Alice pays USD & Bob receives USD - BEAST_EXPECT( - env.balance(alice, USD.issue()) == preAliceUSD + USD(10)); + BEAST_EXPECT(env.balance(alice, USD.issue()) == preAliceUSD + USD(10)); BEAST_EXPECT(env.balance(bob, USD.issue()) == preBobUSD - USD(10)); } @@ -3478,8 +3346,7 @@ class Batch_test : public beast::unit_test::suite auto const aliceSeq = env.seq(alice); // AccountSet Txn - auto const noopTxn = - env.jt(noop(alice), ticket::use(aliceTicketSeq + 1)); + auto const noopTxn = env.jt(noop(alice), ticket::use(aliceTicketSeq + 1)); auto const noopTxnID = to_string(noopTxn.stx->getTransactionID()); env(noopTxn, ter(tesSUCCESS)); @@ -3537,8 +3404,7 @@ class Batch_test : public beast::unit_test::suite ticket::use(aliceTicketSeq)); // AccountSet Txn - auto const noopTxn = - env.jt(noop(alice), ticket::use(aliceTicketSeq + 1)); + auto const noopTxn = env.jt(noop(alice), ticket::use(aliceTicketSeq + 1)); env(noopTxn); env.close(); @@ -3752,7 +3618,7 @@ class Batch_test : public beast::unit_test::suite // another transaction is part of the batch, the batch might fail // because the sequence is out of order. This is because the canonical // order of transactions is determined by the account first. So in this - // case, alice's batch comes after bobs self submitted transaction even + // case, alice's batch comes after bob's self submitted transaction even // though the payment was submitted after the batch. using namespace test::jtx; @@ -3820,8 +3686,7 @@ class Batch_test : public beast::unit_test::suite BEAST_EXPECT(env.seq(bob) == bobSeq + 2); // Alice pays XRP & Fee; Bob receives XRP & pays Fee - BEAST_EXPECT( - env.balance(alice) == preAlice - XRP(10) - batchFee - baseFee); + BEAST_EXPECT(env.balance(alice) == preAlice - XRP(10) - batchFee - baseFee); BEAST_EXPECT(env.balance(bob) == preBob + XRP(10) - baseFee); } @@ -3837,8 +3702,7 @@ class Batch_test : public beast::unit_test::suite { test::jtx::Env env{ *this, - makeSmallQueueConfig( - {{"minimum_txn_in_ledger_standalone", "2"}}), + makeSmallQueueConfig({{"minimum_txn_in_ledger_standalone", "2"}}), features, nullptr, beast::severities::kError}; @@ -3879,11 +3743,7 @@ class Batch_test : public beast::unit_test::suite // Replace Queued Batch { - env(batch::outer( - alice, - aliceSeq, - openLedgerFee(env, batchFee), - tfAllOrNothing), + env(batch::outer(alice, aliceSeq, openLedgerFee(env, batchFee), tfAllOrNothing), batch::inner(pay(alice, bob, XRP(10)), aliceSeq + 1), batch::inner(pay(bob, alice, XRP(5)), bobSeq), batch::sig(bob), @@ -3898,8 +3758,7 @@ class Batch_test : public beast::unit_test::suite { test::jtx::Env env{ *this, - makeSmallQueueConfig( - {{"minimum_txn_in_ledger_standalone", "2"}}), + makeSmallQueueConfig({{"minimum_txn_in_ledger_standalone", "2"}}), features, nullptr, beast::severities::kError}; @@ -3947,12 +3806,7 @@ class Batch_test : public beast::unit_test::suite using namespace test::jtx; using namespace std::literals; - Env env( - *this, - envconfig(), - features, - nullptr, - beast::severities::kDisabled); + Env env(*this, envconfig(), features, nullptr, beast::severities::kDisabled); auto alice = Account("alice"); auto bob = Account("bob"); @@ -3972,10 +3826,8 @@ class Batch_test : public beast::unit_test::suite Serializer s; jt.stx->add(s); std::string reason; - auto transaction = - std::make_shared(jt.stx, reason, env.app()); - env.app().getOPs().processTransaction( - transaction, false, true, NetworkOPs::FailHard::yes); + auto transaction = std::make_shared(jt.stx, reason, env.app()); + env.app().getOPs().processTransaction(transaction, false, true, NetworkOPs::FailHard::yes); return transaction->getID(); }; @@ -3983,18 +3835,14 @@ class Batch_test : public beast::unit_test::suite { // Submit a tx with tfInnerBatchTxn uint256 const txBad = submitTx(tfInnerBatchTxn); - BEAST_EXPECT( - env.app().getHashRouter().getFlags(txBad) == - HashRouterFlags::UNDEFINED); + BEAST_EXPECT(env.app().getHashRouter().getFlags(txBad) == HashRouterFlags::UNDEFINED); } // Validate: NetworkOPs::processTransaction() { uint256 const txid = processTxn(tfInnerBatchTxn); // HashRouter::getFlags() should return LedgerFlags::BAD - BEAST_EXPECT( - env.app().getHashRouter().getFlags(txid) == - HashRouterFlags::BAD); + BEAST_EXPECT(env.app().getHashRouter().getFlags(txid) == HashRouterFlags::BAD); } } @@ -4167,8 +4015,7 @@ class Batch_test : public beast::unit_test::suite env.close(); // alice gives granular permission to bob of MPTokenIssuanceLock - env(delegate::set( - alice, bob, {"MPTokenIssuanceLock", "MPTokenIssuanceUnlock"})); + env(delegate::set(alice, bob, {"MPTokenIssuanceLock", "MPTokenIssuanceUnlock"})); env.close(); auto const seq = env.seq(alice); @@ -4220,8 +4067,7 @@ class Batch_test : public beast::unit_test::suite env(trust(alice, gw["USD"](50))); env.close(); - env(delegate::set( - gw, bob, {"TrustlineAuthorize", "TrustlineFreeze"})); + env(delegate::set(gw, bob, {"TrustlineAuthorize", "TrustlineFreeze"})); env.close(); auto const seq = env.seq(gw); @@ -4260,8 +4106,7 @@ class Batch_test : public beast::unit_test::suite env(trust(alice, gw["USD"](50))); env.close(); - env(delegate::set( - gw, bob, {"TrustlineAuthorize", "TrustlineFreeze"})); + env(delegate::set(gw, bob, {"TrustlineAuthorize", "TrustlineFreeze"})); env.close(); auto const seq = env.seq(gw); @@ -4316,11 +4161,9 @@ class Batch_test : public beast::unit_test::suite env.close(); BEAST_EXPECT(jr.isMember(jss::account_sequence_available)); - BEAST_EXPECT( - jr[jss::account_sequence_available].asUInt() == aliceSeq + 1); + BEAST_EXPECT(jr[jss::account_sequence_available].asUInt() == aliceSeq + 1); BEAST_EXPECT(jr.isMember(jss::account_sequence_next)); - BEAST_EXPECT( - jr[jss::account_sequence_next].asUInt() == aliceSeq + 1); + BEAST_EXPECT(jr[jss::account_sequence_next].asUInt() == aliceSeq + 1); BEAST_EXPECT(jr.isMember(jss::open_ledger_cost)); BEAST_EXPECT(jr[jss::open_ledger_cost] == to_string(baseFee)); BEAST_EXPECT(jr.isMember(jss::validated_ledger_index)); @@ -4339,11 +4182,9 @@ class Batch_test : public beast::unit_test::suite env.close(); BEAST_EXPECT(jr.isMember(jss::account_sequence_available)); - BEAST_EXPECT( - jr[jss::account_sequence_available].asUInt() == aliceSeq + 1); + BEAST_EXPECT(jr[jss::account_sequence_available].asUInt() == aliceSeq + 1); BEAST_EXPECT(jr.isMember(jss::account_sequence_next)); - BEAST_EXPECT( - jr[jss::account_sequence_next].asUInt() == aliceSeq + 1); + BEAST_EXPECT(jr[jss::account_sequence_next].asUInt() == aliceSeq + 1); BEAST_EXPECT(jr.isMember(jss::open_ledger_cost)); BEAST_EXPECT(jr[jss::open_ledger_cost] == to_string(baseFee)); BEAST_EXPECT(jr.isMember(jss::validated_ledger_index)); @@ -4361,8 +4202,7 @@ class Batch_test : public beast::unit_test::suite env.close(); BEAST_EXPECT(jr.isMember(jss::account_sequence_available)); - BEAST_EXPECT( - jr[jss::account_sequence_available].asUInt() == aliceSeq); + BEAST_EXPECT(jr[jss::account_sequence_available].asUInt() == aliceSeq); BEAST_EXPECT(jr.isMember(jss::account_sequence_next)); BEAST_EXPECT(jr[jss::account_sequence_next].asUInt() == aliceSeq); BEAST_EXPECT(jr.isMember(jss::open_ledger_cost)); @@ -4394,8 +4234,7 @@ class Batch_test : public beast::unit_test::suite XRPAmount const batchFee = batch::calcBatchFee(env, 0, 2); auto jtx = env.jt( batch::outer(alice, seq, batchFee, tfAllOrNothing), - batch::inner( - batch::outer(alice, seq, batchFee, tfAllOrNothing), seq), + batch::inner(batch::outer(alice, seq, batchFee, tfAllOrNothing), seq), batch::inner(pay(alice, bob, XRP(1)), seq + 2)); XRPAmount const txBaseFee = getBaseFee(jtx); BEAST_EXPECT(txBaseFee == XRPAmount(INITIAL_XRP)); @@ -4431,17 +4270,7 @@ class Batch_test : public beast::unit_test::suite batch::outer(alice, seq, batchFee, tfAllOrNothing), batch::inner(pay(alice, bob, XRP(10)), seq + 1), batch::inner(pay(alice, bob, XRP(5)), seq + 2), - batch::sig( - bob, - carol, - alice, - bob, - carol, - alice, - bob, - carol, - alice, - alice)); + batch::sig(bob, carol, alice, bob, carol, alice, bob, carol, alice, alice)); XRPAmount const txBaseFee = getBaseFee(jtx); BEAST_EXPECT(txBaseFee == XRPAmount(INITIAL_XRP)); } diff --git a/src/test/app/Check_test.cpp b/src/test/app/Check_test.cpp index 8eccdc4824..42c600c22b 100644 --- a/src/test/app/Check_test.cpp +++ b/src/test/app/Check_test.cpp @@ -14,8 +14,7 @@ private: std::uint32_t const expiry_; public: - explicit expiration(NetClock::time_point const& expiry) - : expiry_{expiry.time_since_epoch().count()} + explicit expiration(NetClock::time_point const& expiry) : expiry_{expiry.time_since_epoch().count()} { } @@ -78,13 +77,10 @@ class Check_test : public beast::unit_test::suite checksOnAccount(test::jtx::Env& env, test::jtx::Account account) { std::vector> result; - forEachItem( - *env.current(), - account, - [&result](std::shared_ptr const& sle) { - if (sle && sle->getType() == ltCHECK) - result.push_back(sle); - }); + forEachItem(*env.current(), account, [&result](std::shared_ptr const& sle) { + if (sle && sle->getType() == ltCHECK) + result.push_back(sle); + }); return result; } @@ -96,8 +92,7 @@ class Check_test : public beast::unit_test::suite verifyDeliveredAmount(test::jtx::Env& env, STAmount const& amount) { // Get the hash for the most recent transaction. - std::string const txHash{ - env.tx()->getJson(JsonOptions::none)[jss::hash].asString()}; + std::string const txHash{env.tx()->getJson(JsonOptions::none)[jss::hash].asString()}; // Verify DeliveredAmount and delivered_amount metadata are correct. env.close(); @@ -109,11 +104,8 @@ class Check_test : public beast::unit_test::suite // DeliveredAmount and delivered_amount should both be present and // equal amount. - BEAST_EXPECT( - meta[sfDeliveredAmount.jsonName] == - amount.getJson(JsonOptions::none)); - BEAST_EXPECT( - meta[jss::delivered_amount] == amount.getJson(JsonOptions::none)); + BEAST_EXPECT(meta[sfDeliveredAmount.jsonName] == amount.getJson(JsonOptions::none)); + BEAST_EXPECT(meta[jss::delivered_amount] == amount.getJson(JsonOptions::none)); } void @@ -131,16 +123,14 @@ class Check_test : public beast::unit_test::suite env.fund(XRP(1000), alice); env.close(); - uint256 const checkId1{ - getCheckIndex(env.master, env.seq(env.master))}; + uint256 const checkId1{getCheckIndex(env.master, env.seq(env.master))}; env(check::create(env.master, alice, XRP(100))); env.close(); env(check::cash(alice, checkId1, XRP(100))); env.close(); - uint256 const checkId2{ - getCheckIndex(env.master, env.seq(env.master))}; + uint256 const checkId2{getCheckIndex(env.master, env.seq(env.master))}; env(check::create(env.master, alice, XRP(100))); env.close(); @@ -171,8 +161,7 @@ class Check_test : public beast::unit_test::suite // Note that no trust line has been set up for alice, but alice can // still write a check for USD. You don't have to have the funds // necessary to cover a check in order to write a check. - auto writeTwoChecks = [&env, &USD, this]( - Account const& from, Account const& to) { + auto writeTwoChecks = [&env, &USD, this](Account const& from, Account const& to) { std::uint32_t const fromOwnerCount{ownerCount(env, from)}; std::uint32_t const toOwnerCount{ownerCount(env, to)}; @@ -189,8 +178,7 @@ class Check_test : public beast::unit_test::suite BEAST_EXPECT(checksOnAccount(env, to).size() == toCkCount + 2); env.require(owners(from, fromOwnerCount + 2)); - env.require( - owners(to, to == from ? fromOwnerCount + 2 : toOwnerCount)); + env.require(owners(to, to == from ? fromOwnerCount + 2 : toOwnerCount)); }; // from to writeTwoChecks(alice, bob); @@ -241,9 +229,7 @@ class Check_test : public beast::unit_test::suite // alice uses multisigning to create a check. XRPAmount const baseFeeDrops{env.current()->fees().base}; - env(check::create(alice, bob, USD(50)), - msig(bogie, demon), - fee(3 * baseFeeDrops)); + env(check::create(alice, bob, USD(50)), msig(bogie, demon), fee(3 * baseFeeDrops)); env.close(); BEAST_EXPECT(checksOnAccount(env, alice).size() == aliceCount + 7); BEAST_EXPECT(checksOnAccount(env, bob).size() == bobCount + 7); @@ -271,10 +257,7 @@ class Check_test : public beast::unit_test::suite * Attempt to create two checks from `from` to `to` and * require they both result in error/success code `expected` */ - auto writeTwoChecksDI = [&env, &USD, this]( - Account const& from, - Account const& to, - TER expected) { + auto writeTwoChecksDI = [&env, &USD, this](Account const& from, Account const& to, TER expected) { std::uint32_t const fromOwnerCount{ownerCount(env, from)}; std::uint32_t const toOwnerCount{ownerCount(env, to)}; @@ -289,13 +272,11 @@ class Check_test : public beast::unit_test::suite if (expected == tesSUCCESS) { - BEAST_EXPECT( - checksOnAccount(env, from).size() == fromCkCount + 2); + BEAST_EXPECT(checksOnAccount(env, from).size() == fromCkCount + 2); BEAST_EXPECT(checksOnAccount(env, to).size() == toCkCount + 2); env.require(owners(from, fromOwnerCount + 2)); - env.require( - owners(to, to == from ? fromOwnerCount + 2 : toOwnerCount)); + env.require(owners(to, to == from ? fromOwnerCount + 2 : toOwnerCount)); return; } @@ -353,15 +334,11 @@ class Check_test : public beast::unit_test::suite env.close(); // Bad fee. - env(check::create(alice, bob, USD(50)), - fee(drops(-10)), - ter(temBAD_FEE)); + env(check::create(alice, bob, USD(50)), fee(drops(-10)), ter(temBAD_FEE)); env.close(); // Bad flags. - env(check::create(alice, bob, USD(50)), - txflags(tfImmediateOrCancel), - ter(temINVALID_FLAG)); + env(check::create(alice, bob, USD(50)), txflags(tfImmediateOrCancel), ter(temINVALID_FLAG)); env.close(); // Check to self. @@ -393,9 +370,7 @@ class Check_test : public beast::unit_test::suite } // Bad expiration. - env(check::create(alice, bob, USD(50)), - expiration(NetClock::time_point{}), - ter(temBAD_EXPIRATION)); + env(check::create(alice, bob, USD(50)), expiration(NetClock::time_point{}), ter(temBAD_EXPIRATION)); env.close(); // Destination does not exist. @@ -492,9 +467,7 @@ class Check_test : public beast::unit_test::suite } // Expired expiration. - env(check::create(alice, bob, USD(50)), - expiration(env.now()), - ter(tecEXPIRED)); + env(check::create(alice, bob, USD(50)), expiration(env.now()), ter(tecEXPIRED)); env.close(); using namespace std::chrono_literals; @@ -506,9 +479,7 @@ class Check_test : public beast::unit_test::suite env.fund(env.current()->fees().accountReserve(1) - drops(1), cheri); env.close(); - env(check::create(cheri, bob, USD(50)), - fee(drops(env.current()->fees().base)), - ter(tecINSUFFICIENT_RESERVE)); + env(check::create(cheri, bob, USD(50)), fee(drops(env.current()->fees().base)), ter(tecINSUFFICIENT_RESERVE)); env.close(); env(pay(bob, cheri, drops(env.current()->fees().base + 1))); @@ -549,10 +520,8 @@ class Check_test : public beast::unit_test::suite env(check::cash(bob, chkId, XRP(10))); env.close(); - env.require( - balance(alice, startBalance - XRP(10) - drops(baseFeeDrops))); - env.require( - balance(bob, startBalance + XRP(10) - drops(baseFeeDrops))); + env.require(balance(alice, startBalance - XRP(10) - drops(baseFeeDrops))); + env.require(balance(bob, startBalance + XRP(10) - drops(baseFeeDrops))); BEAST_EXPECT(checksOnAccount(env, alice).size() == 0); BEAST_EXPECT(checksOnAccount(env, bob).size() == 0); BEAST_EXPECT(ownerCount(env, alice) == 0); @@ -568,19 +537,15 @@ class Check_test : public beast::unit_test::suite { // Write a check that chews into alice's reserve. STAmount const reserve{env.current()->fees().reserve}; - STAmount const checkAmount{ - startBalance - reserve - drops(baseFeeDrops)}; + STAmount const checkAmount{startBalance - reserve - drops(baseFeeDrops)}; uint256 const chkId{getCheckIndex(alice, env.seq(alice))}; env(check::create(alice, bob, checkAmount)); env.close(); // bob tries to cash for more than the check amount. - env(check::cash(bob, chkId, checkAmount + drops(1)), - ter(tecPATH_PARTIAL)); + env(check::cash(bob, chkId, checkAmount + drops(1)), ter(tecPATH_PARTIAL)); env.close(); - env(check::cash( - bob, chkId, check::DeliverMin(checkAmount + drops(1))), - ter(tecPATH_PARTIAL)); + env(check::cash(bob, chkId, check::DeliverMin(checkAmount + drops(1))), ter(tecPATH_PARTIAL)); env.close(); // bob cashes exactly the check amount. This is successful @@ -589,8 +554,7 @@ class Check_test : public beast::unit_test::suite env(check::cash(bob, chkId, check::DeliverMin(checkAmount))); verifyDeliveredAmount(env, drops(checkAmount.mantissa())); env.require(balance(alice, reserve)); - env.require(balance( - bob, startBalance + checkAmount - drops(baseFeeDrops * 3))); + env.require(balance(bob, startBalance + checkAmount - drops(baseFeeDrops * 3))); BEAST_EXPECT(checksOnAccount(env, alice).size() == 0); BEAST_EXPECT(checksOnAccount(env, bob).size() == 0); BEAST_EXPECT(ownerCount(env, alice) == 0); @@ -606,8 +570,7 @@ class Check_test : public beast::unit_test::suite { // Write a check that goes one drop past what alice can pay. STAmount const reserve{env.current()->fees().reserve}; - STAmount const checkAmount{ - startBalance - reserve - drops(baseFeeDrops - 1)}; + STAmount const checkAmount{startBalance - reserve - drops(baseFeeDrops - 1)}; uint256 const chkId{getCheckIndex(alice, env.seq(alice))}; env(check::create(alice, bob, checkAmount)); env.close(); @@ -621,8 +584,7 @@ class Check_test : public beast::unit_test::suite env(check::cash(bob, chkId, check::DeliverMin(drops(1)))); verifyDeliveredAmount(env, drops(checkAmount.mantissa() - 1)); env.require(balance(alice, reserve)); - env.require(balance( - bob, startBalance + checkAmount - drops(baseFeeDrops * 2 + 1))); + env.require(balance(bob, startBalance + checkAmount - drops(baseFeeDrops * 2 + 1))); BEAST_EXPECT(checksOnAccount(env, alice).size() == 0); BEAST_EXPECT(checksOnAccount(env, bob).size() == 0); BEAST_EXPECT(ownerCount(env, alice) == 0); @@ -630,8 +592,7 @@ class Check_test : public beast::unit_test::suite // Make alice's and bob's balances easy to think about. env(pay(env.master, alice, checkAmount + drops(baseFeeDrops - 1))); - env(pay( - bob, env.master, checkAmount - drops(baseFeeDrops * 3 + 1))); + env(pay(bob, env.master, checkAmount - drops(baseFeeDrops * 3 + 1))); env.close(); env.require(balance(alice, startBalance)); env.require(balance(bob, startBalance)); @@ -821,8 +782,7 @@ class Check_test : public beast::unit_test::suite // bob attempts to cash a check for the amount on the check. // Should fail, since alice doesn't have the funds. - env(check::cash(bob, chkId9, check::DeliverMin(USD(9))), - ter(tecPATH_PARTIAL)); + env(check::cash(bob, chkId9, check::DeliverMin(USD(9))), ter(tecPATH_PARTIAL)); env.close(); // bob sets a DeliverMin of 7 and gets all that alice has. @@ -974,9 +934,7 @@ class Check_test : public beast::unit_test::suite // bob uses multisigning to cash a check. XRPAmount const baseFeeDrops{env.current()->fees().base}; - env(check::cash(bob, chkId2, (USD(2))), - msig(bogie, demon), - fee(3 * baseFeeDrops)); + env(check::cash(bob, chkId2, (USD(2))), msig(bogie, demon), fee(3 * baseFeeDrops)); env.close(); env.require(balance(alice, USD(5))); env.require(balance(bob, USD(3))); @@ -1031,8 +989,7 @@ class Check_test : public beast::unit_test::suite // bob attempts to cash the check for face value. Should fail. env(check::cash(bob, chkId125, USD(125)), ter(tecPATH_PARTIAL)); env.close(); - env(check::cash(bob, chkId125, check::DeliverMin(USD(101))), - ter(tecPATH_PARTIAL)); + env(check::cash(bob, chkId125, check::DeliverMin(USD(101))), ter(tecPATH_PARTIAL)); env.close(); // bob decides that he'll accept anything USD(75) or up. @@ -1092,59 +1049,53 @@ class Check_test : public beast::unit_test::suite // There are two test lambdas: one for a Payment and one for a Check. // This shows whether a Payment and a Check behave the same. - auto testNonIssuerQPay = [&env, &alice, &bob, &USD]( - Account const& truster, - IOU const& iou, - auto const& inOrOut, - double pct, - double amount) { - // Capture bob's and alice's balances so we can test at the end. - STAmount const aliceStart{env.balance(alice, USD.issue()).value()}; - STAmount const bobStart{env.balance(bob, USD.issue()).value()}; + auto testNonIssuerQPay = + [&env, &alice, &bob, &USD]( + Account const& truster, IOU const& iou, auto const& inOrOut, double pct, double amount) { + // Capture bob's and alice's balances so we can test at the end. + STAmount const aliceStart{env.balance(alice, USD.issue()).value()}; + STAmount const bobStart{env.balance(bob, USD.issue()).value()}; - // Set the modified quality. - env(trust(truster, iou(1000)), inOrOut(pct)); - env.close(); + // Set the modified quality. + env(trust(truster, iou(1000)), inOrOut(pct)); + env.close(); - env(pay(alice, bob, USD(amount)), sendmax(USD(10))); - env.close(); - env.require(balance(alice, aliceStart - USD(10))); - env.require(balance(bob, bobStart + USD(10))); + env(pay(alice, bob, USD(amount)), sendmax(USD(10))); + env.close(); + env.require(balance(alice, aliceStart - USD(10))); + env.require(balance(bob, bobStart + USD(10))); - // Return the quality to the unmodified state so it doesn't - // interfere with upcoming tests. - env(trust(truster, iou(1000)), inOrOut(0)); - env.close(); - }; + // Return the quality to the unmodified state so it doesn't + // interfere with upcoming tests. + env(trust(truster, iou(1000)), inOrOut(0)); + env.close(); + }; - auto testNonIssuerQCheck = [&env, &alice, &bob, &USD]( - Account const& truster, - IOU const& iou, - auto const& inOrOut, - double pct, - double amount) { - // Capture bob's and alice's balances so we can test at the end. - STAmount const aliceStart{env.balance(alice, USD.issue()).value()}; - STAmount const bobStart{env.balance(bob, USD.issue()).value()}; + auto testNonIssuerQCheck = + [&env, &alice, &bob, &USD]( + Account const& truster, IOU const& iou, auto const& inOrOut, double pct, double amount) { + // Capture bob's and alice's balances so we can test at the end. + STAmount const aliceStart{env.balance(alice, USD.issue()).value()}; + STAmount const bobStart{env.balance(bob, USD.issue()).value()}; - // Set the modified quality. - env(trust(truster, iou(1000)), inOrOut(pct)); - env.close(); + // Set the modified quality. + env(trust(truster, iou(1000)), inOrOut(pct)); + env.close(); - uint256 const chkId = getCheckIndex(alice, env.seq(alice)); - env(check::create(alice, bob, USD(10))); - env.close(); + uint256 const chkId = getCheckIndex(alice, env.seq(alice)); + env(check::create(alice, bob, USD(10))); + env.close(); - env(check::cash(bob, chkId, USD(amount))); - env.close(); - env.require(balance(alice, aliceStart - USD(10))); - env.require(balance(bob, bobStart + USD(10))); + env(check::cash(bob, chkId, USD(amount))); + env.close(); + env.require(balance(alice, aliceStart - USD(10))); + env.require(balance(bob, bobStart + USD(10))); - // Return the quality to the unmodified state so it doesn't - // interfere with upcoming tests. - env(trust(truster, iou(1000)), inOrOut(0)); - env.close(); - }; + // Return the quality to the unmodified state so it doesn't + // interfere with upcoming tests. + env(trust(truster, iou(1000)), inOrOut(0)); + env.close(); + }; // pct amount testNonIssuerQPay(alice, gw["USD"], qIn, 50, 10); @@ -1341,18 +1292,13 @@ class Check_test : public beast::unit_test::suite env.close(); // Same set of failing cases for both IOU and XRP check cashing. - auto failingCases = [&env, &gw, &alice, &bob]( - uint256 const& chkId, STAmount const& amount) { + auto failingCases = [&env, &gw, &alice, &bob](uint256 const& chkId, STAmount const& amount) { // Bad fee. - env(check::cash(bob, chkId, amount), - fee(drops(-10)), - ter(temBAD_FEE)); + env(check::cash(bob, chkId, amount), fee(drops(-10)), ter(temBAD_FEE)); env.close(); // Bad flags. - env(check::cash(bob, chkId, amount), - txflags(tfImmediateOrCancel), - ter(temINVALID_FLAG)); + env(check::cash(bob, chkId, amount), txflags(tfImmediateOrCancel), ter(temINVALID_FLAG)); env.close(); // Missing both Amount and DeliverMin. @@ -1376,8 +1322,7 @@ class Check_test : public beast::unit_test::suite neg.negate(); env(check::cash(bob, chkId, neg), ter(temBAD_AMOUNT)); env.close(); - env(check::cash(bob, chkId, amount.zeroed()), - ter(temBAD_AMOUNT)); + env(check::cash(bob, chkId, amount.zeroed()), ter(temBAD_AMOUNT)); env.close(); } @@ -1420,8 +1365,7 @@ class Check_test : public beast::unit_test::suite env.close(); // DeliverMin bigger than SendMax. - env(check::cash(bob, chkId, check::DeliverMin(amount + amount)), - ter(tecPATH_PARTIAL)); + env(check::cash(bob, chkId, check::DeliverMin(amount + amount)), ter(tecPATH_PARTIAL)); env.close(); }; @@ -1455,8 +1399,7 @@ class Check_test : public beast::unit_test::suite env(check::cash(bob, chkIdFroz1, USD(1)), ter(tecPATH_PARTIAL)); env.close(); - env(check::cash(bob, chkIdFroz1, check::DeliverMin(USD(0.5))), - ter(tecPATH_PARTIAL)); + env(check::cash(bob, chkIdFroz1, check::DeliverMin(USD(0.5))), ter(tecPATH_PARTIAL)); env.close(); env(fclear(gw, asfGlobalFreeze)); @@ -1473,8 +1416,7 @@ class Check_test : public beast::unit_test::suite env.close(); env(check::cash(bob, chkIdFroz2, USD(2)), ter(tecPATH_PARTIAL)); env.close(); - env(check::cash(bob, chkIdFroz2, check::DeliverMin(USD(1))), - ter(tecPATH_PARTIAL)); + env(check::cash(bob, chkIdFroz2, check::DeliverMin(USD(1))), ter(tecPATH_PARTIAL)); env.close(); // Clear that freeze. Now check cashing works. @@ -1490,8 +1432,7 @@ class Check_test : public beast::unit_test::suite env.close(); env(check::cash(bob, chkIdFroz3, USD(3)), ter(tecFROZEN)); env.close(); - env(check::cash(bob, chkIdFroz3, check::DeliverMin(USD(1))), - ter(tecFROZEN)); + env(check::cash(bob, chkIdFroz3, check::DeliverMin(USD(1))), ter(tecFROZEN)); env.close(); // Clear that freeze. Now check cashing works again. @@ -1508,8 +1449,7 @@ class Check_test : public beast::unit_test::suite env.close(); env(check::cash(bob, chkIdFroz4, USD(4)), ter(terNO_LINE)); env.close(); - env(check::cash(bob, chkIdFroz4, check::DeliverMin(USD(1))), - ter(terNO_LINE)); + env(check::cash(bob, chkIdFroz4, check::DeliverMin(USD(1))), ter(terNO_LINE)); env.close(); // Clear bob's freeze bit and the check should be cashable. @@ -1527,8 +1467,7 @@ class Check_test : public beast::unit_test::suite env.close(); env(check::cash(bob, chkIdNoDest1, USD(1)), ter(tecDST_TAG_NEEDED)); env.close(); - env(check::cash(bob, chkIdNoDest1, check::DeliverMin(USD(0.5))), - ter(tecDST_TAG_NEEDED)); + env(check::cash(bob, chkIdNoDest1, check::DeliverMin(USD(0.5))), ter(tecDST_TAG_NEEDED)); env.close(); // bob can cash a check with a destination tag. @@ -1585,18 +1524,15 @@ class Check_test : public beast::unit_test::suite // Three checks that expire in 10 minutes. using namespace std::chrono_literals; uint256 const chkIdNotExp1{getCheckIndex(alice, env.seq(alice))}; - env(check::create(alice, bob, XRP(10)), - expiration(env.now() + 600s)); + env(check::create(alice, bob, XRP(10)), expiration(env.now() + 600s)); env.close(); uint256 const chkIdNotExp2{getCheckIndex(alice, env.seq(alice))}; - env(check::create(alice, bob, USD(10)), - expiration(env.now() + 600s)); + env(check::create(alice, bob, USD(10)), expiration(env.now() + 600s)); env.close(); uint256 const chkIdNotExp3{getCheckIndex(alice, env.seq(alice))}; - env(check::create(alice, bob, XRP(10)), - expiration(env.now() + 600s)); + env(check::create(alice, bob, XRP(10)), expiration(env.now() + 600s)); env.close(); // Three checks that expire in one second. @@ -1689,9 +1625,7 @@ class Check_test : public beast::unit_test::suite // alice uses multisigning to cancel a check. XRPAmount const baseFeeDrops{env.current()->fees().base}; - env(check::cancel(alice, chkIdMSig), - msig(bogie, demon), - fee(3 * baseFeeDrops)); + env(check::cancel(alice, chkIdMSig), msig(bogie, demon), fee(3 * baseFeeDrops)); env.close(); BEAST_EXPECT(checksOnAccount(env, alice).size() == 2); BEAST_EXPECT(ownerCount(env, alice) == 3); @@ -1726,9 +1660,7 @@ class Check_test : public beast::unit_test::suite env.close(); // Bad fee. - env(check::cancel(bob, getCheckIndex(alice, env.seq(alice))), - fee(drops(-10)), - ter(temBAD_FEE)); + env(check::cancel(bob, getCheckIndex(alice, env.seq(alice))), fee(drops(-10)), ter(temBAD_FEE)); env.close(); // Bad flags. @@ -1738,8 +1670,7 @@ class Check_test : public beast::unit_test::suite env.close(); // Non-existent check. - env(check::cancel(bob, getCheckIndex(alice, env.seq(alice))), - ter(tecNO_ENTRY)); + env(check::cancel(bob, getCheckIndex(alice, env.seq(alice))), ter(tecNO_ENTRY)); env.close(); } @@ -1764,8 +1695,7 @@ class Check_test : public beast::unit_test::suite env(check::cash(bob, chkId, check::DeliverMin(XRP(100)))); // Get the hash for the most recent transaction. - std::string const txHash{ - env.tx()->getJson(JsonOptions::none)[jss::hash].asString()}; + std::string const txHash{env.tx()->getJson(JsonOptions::none)[jss::hash].asString()}; env.close(); Json::Value const meta = env.rpc("tx", txHash)[jss::result][jss::meta]; @@ -1898,11 +1828,7 @@ class Check_test : public beast::unit_test::suite void verifyOwners(std::uint32_t line) const { - suite.expect( - ownerCount(env, acct) == owners, - "Owner count mismatch", - __FILE__, - line); + suite.expect(ownerCount(env, acct) == owners, "Owner count mismatch", __FILE__, line); } // Operators to make using the class more convenient. @@ -1956,8 +1882,7 @@ class Check_test : public beast::unit_test::suite env(check::create(gw1, yui, CK8(99))); env.close(); - env(check::cash(yui, chkId, CK8(99)), - ter(tecNO_LINE_INSUF_RESERVE)); + env(check::cash(yui, chkId, CK8(99)), ter(tecNO_LINE_INSUF_RESERVE)); env.close(); alice.verifyOwners(__LINE__); @@ -1988,14 +1913,9 @@ class Check_test : public beast::unit_test::suite // between the same two accounts but with two different currencies. // The lambda expects the two trust lines to be largely similar. auto cmpTrustLines = [this, &env]( - Account const& acct1, - Account const& acct2, - IOU const& offerIou, - IOU const& checkIou) { - auto const offerLine = - env.le(keylet::line(acct1, acct2, offerIou.currency)); - auto const checkLine = - env.le(keylet::line(acct1, acct2, checkIou.currency)); + Account const& acct1, Account const& acct2, IOU const& offerIou, IOU const& checkIou) { + auto const offerLine = env.le(keylet::line(acct1, acct2, offerIou.currency)); + auto const checkLine = env.le(keylet::line(acct1, acct2, checkIou.currency)); if (offerLine == nullptr || checkLine == nullptr) { BEAST_EXPECT(offerLine == nullptr && checkLine == nullptr); @@ -2008,50 +1928,39 @@ class Check_test : public beast::unit_test::suite // Lambda that compares the contents of required STAmounts // without comparing the currency. - auto cmpReqAmount = - [this, offerLine, checkLine](SF_AMOUNT const& sfield) { - STAmount const offerAmount = offerLine->at(sfield); - STAmount const checkAmount = checkLine->at(sfield); + auto cmpReqAmount = [this, offerLine, checkLine](SF_AMOUNT const& sfield) { + STAmount const offerAmount = offerLine->at(sfield); + STAmount const checkAmount = checkLine->at(sfield); - // Neither STAmount should be native. - if (!BEAST_EXPECT( - !offerAmount.native() && !checkAmount.native())) - return; + // Neither STAmount should be native. + if (!BEAST_EXPECT(!offerAmount.native() && !checkAmount.native())) + return; - BEAST_EXPECT( - offerAmount.issue().account == - checkAmount.issue().account); - BEAST_EXPECT( - offerAmount.negative() == checkAmount.negative()); - BEAST_EXPECT( - offerAmount.mantissa() == checkAmount.mantissa()); - BEAST_EXPECT( - offerAmount.exponent() == checkAmount.exponent()); - }; + BEAST_EXPECT(offerAmount.issue().account == checkAmount.issue().account); + BEAST_EXPECT(offerAmount.negative() == checkAmount.negative()); + BEAST_EXPECT(offerAmount.mantissa() == checkAmount.mantissa()); + BEAST_EXPECT(offerAmount.exponent() == checkAmount.exponent()); + }; cmpReqAmount(sfBalance); cmpReqAmount(sfLowLimit); cmpReqAmount(sfHighLimit); } { // Lambda that compares the contents of optional fields. - auto cmpOptField = - [this, offerLine, checkLine](auto const& sfield) { - // Expect both fields to either be present or absent. - if (!BEAST_EXPECT( - offerLine->isFieldPresent(sfield) == - checkLine->isFieldPresent(sfield))) - return; + auto cmpOptField = [this, offerLine, checkLine](auto const& sfield) { + // Expect both fields to either be present or absent. + if (!BEAST_EXPECT(offerLine->isFieldPresent(sfield) == checkLine->isFieldPresent(sfield))) + return; - // If both fields are absent then there's nothing - // further to check. - if (!offerLine->isFieldPresent(sfield)) - return; + // If both fields are absent then there's nothing + // further to check. + if (!offerLine->isFieldPresent(sfield)) + return; - // Both optional fields are present so we can compare - // them. - BEAST_EXPECT( - offerLine->at(sfield) == checkLine->at(sfield)); - }; + // Both optional fields are present so we can compare + // them. + BEAST_EXPECT(offerLine->at(sfield) == checkLine->at(sfield)); + }; cmpOptField(sfLowNode); cmpOptField(sfLowQualityIn); cmpOptField(sfLowQualityOut); @@ -2076,8 +1985,7 @@ class Check_test : public beast::unit_test::suite IOU const OF1 = gw1["OF1"]; env(offer(gw1, XRP(98), OF1(98))); env.close(); - BEAST_EXPECT( - env.le(keylet::line(gw1, alice, OF1.currency)) == nullptr); + BEAST_EXPECT(env.le(keylet::line(gw1, alice, OF1.currency)) == nullptr); env(offer(alice, OF1(98), XRP(98))); ++alice.owners; env.close(); @@ -2095,8 +2003,7 @@ class Check_test : public beast::unit_test::suite uint256 const chkId{getCheckIndex(gw1, env.seq(gw1))}; env(check::create(gw1, alice, CK1(98))); env.close(); - BEAST_EXPECT( - env.le(keylet::line(gw1, alice, CK1.currency)) == nullptr); + BEAST_EXPECT(env.le(keylet::line(gw1, alice, CK1.currency)) == nullptr); env(check::cash(alice, chkId, CK1(98))); ++alice.owners; verifyDeliveredAmount(env, CK1(98)); @@ -2125,8 +2032,7 @@ class Check_test : public beast::unit_test::suite IOU const OF1 = gw1["OF1"]; env(offer(alice, XRP(97), OF1(97))); env.close(); - BEAST_EXPECT( - env.le(keylet::line(alice, bob, OF1.currency)) == nullptr); + BEAST_EXPECT(env.le(keylet::line(alice, bob, OF1.currency)) == nullptr); env(offer(bob, OF1(97), XRP(97))); ++bob.owners; env.close(); @@ -2150,15 +2056,12 @@ class Check_test : public beast::unit_test::suite uint256 const chkId{getCheckIndex(alice, env.seq(alice))}; env(check::create(alice, bob, CK1(97))); env.close(); - BEAST_EXPECT( - env.le(keylet::line(alice, bob, CK1.currency)) == nullptr); + BEAST_EXPECT(env.le(keylet::line(alice, bob, CK1.currency)) == nullptr); env(check::cash(bob, chkId, CK1(97)), ter(terNO_RIPPLE)); env.close(); - BEAST_EXPECT( - env.le(keylet::line(gw1, bob, OF1.currency)) != nullptr); - BEAST_EXPECT( - env.le(keylet::line(gw1, bob, CK1.currency)) == nullptr); + BEAST_EXPECT(env.le(keylet::line(gw1, bob, OF1.currency)) != nullptr); + BEAST_EXPECT(env.le(keylet::line(gw1, bob, CK1.currency)) == nullptr); // Delete alice's check since it is no longer needed. env(check::cancel(alice, chkId)); @@ -2182,8 +2085,7 @@ class Check_test : public beast::unit_test::suite IOU const OF2 = gw1["OF2"]; env(offer(gw1, XRP(96), OF2(96))); env.close(); - BEAST_EXPECT( - env.le(keylet::line(gw1, alice, OF2.currency)) == nullptr); + BEAST_EXPECT(env.le(keylet::line(gw1, alice, OF2.currency)) == nullptr); env(offer(alice, OF2(96), XRP(96))); ++alice.owners; env.close(); @@ -2201,8 +2103,7 @@ class Check_test : public beast::unit_test::suite uint256 const chkId{getCheckIndex(gw1, env.seq(gw1))}; env(check::create(gw1, alice, CK2(96))); env.close(); - BEAST_EXPECT( - env.le(keylet::line(gw1, alice, CK2.currency)) == nullptr); + BEAST_EXPECT(env.le(keylet::line(gw1, alice, CK2.currency)) == nullptr); env(check::cash(alice, chkId, CK2(96))); ++alice.owners; verifyDeliveredAmount(env, CK2(96)); @@ -2228,8 +2129,7 @@ class Check_test : public beast::unit_test::suite IOU const OF2 = gw1["OF2"]; env(offer(alice, XRP(95), OF2(95))); env.close(); - BEAST_EXPECT( - env.le(keylet::line(alice, bob, OF2.currency)) == nullptr); + BEAST_EXPECT(env.le(keylet::line(alice, bob, OF2.currency)) == nullptr); env(offer(bob, OF2(95), XRP(95))); ++bob.owners; env.close(); @@ -2244,8 +2144,7 @@ class Check_test : public beast::unit_test::suite uint256 const chkId{getCheckIndex(alice, env.seq(alice))}; env(check::create(alice, bob, CK2(95))); env.close(); - BEAST_EXPECT( - env.le(keylet::line(alice, bob, CK2.currency)) == nullptr); + BEAST_EXPECT(env.le(keylet::line(alice, bob, CK2.currency)) == nullptr); env(check::cash(bob, chkId, CK2(95))); ++bob.owners; verifyDeliveredAmount(env, CK2(95)); @@ -2277,8 +2176,7 @@ class Check_test : public beast::unit_test::suite IOU const OF3 = gw1["OF3"]; env(offer(gw1, XRP(94), OF3(94))); env.close(); - BEAST_EXPECT( - env.le(keylet::line(gw1, alice, OF3.currency)) == nullptr); + BEAST_EXPECT(env.le(keylet::line(gw1, alice, OF3.currency)) == nullptr); env(offer(alice, OF3(94), XRP(94))); ++alice.owners; env.close(); @@ -2296,8 +2194,7 @@ class Check_test : public beast::unit_test::suite uint256 const chkId{getCheckIndex(gw1, env.seq(gw1))}; env(check::create(gw1, alice, CK3(94))); env.close(); - BEAST_EXPECT( - env.le(keylet::line(gw1, alice, CK3.currency)) == nullptr); + BEAST_EXPECT(env.le(keylet::line(gw1, alice, CK3.currency)) == nullptr); env(check::cash(alice, chkId, CK3(94))); ++alice.owners; verifyDeliveredAmount(env, CK3(94)); @@ -2323,8 +2220,7 @@ class Check_test : public beast::unit_test::suite IOU const OF3 = gw1["OF3"]; env(offer(alice, XRP(93), OF3(93))); env.close(); - BEAST_EXPECT( - env.le(keylet::line(alice, bob, OF3.currency)) == nullptr); + BEAST_EXPECT(env.le(keylet::line(alice, bob, OF3.currency)) == nullptr); env(offer(bob, OF3(93), XRP(93))); ++bob.owners; env.close(); @@ -2339,8 +2235,7 @@ class Check_test : public beast::unit_test::suite uint256 const chkId{getCheckIndex(alice, env.seq(alice))}; env(check::create(alice, bob, CK3(93))); env.close(); - BEAST_EXPECT( - env.le(keylet::line(alice, bob, CK3.currency)) == nullptr); + BEAST_EXPECT(env.le(keylet::line(alice, bob, CK3.currency)) == nullptr); env(check::cash(bob, chkId, CK3(93))); ++bob.owners; verifyDeliveredAmount(env, CK3(93)); @@ -2366,8 +2261,7 @@ class Check_test : public beast::unit_test::suite IOU const OF4 = gw1["OF4"]; env(offer(gw1, XRP(92), OF4(92)), ter(tecFROZEN)); env.close(); - BEAST_EXPECT( - env.le(keylet::line(gw1, alice, OF4.currency)) == nullptr); + BEAST_EXPECT(env.le(keylet::line(gw1, alice, OF4.currency)) == nullptr); env(offer(alice, OF4(92), XRP(92)), ter(tecFROZEN)); env.close(); @@ -2381,8 +2275,7 @@ class Check_test : public beast::unit_test::suite uint256 const chkId{getCheckIndex(gw1, env.seq(gw1))}; env(check::create(gw1, alice, CK4(92)), ter(tecFROZEN)); env.close(); - BEAST_EXPECT( - env.le(keylet::line(gw1, alice, CK4.currency)) == nullptr); + BEAST_EXPECT(env.le(keylet::line(gw1, alice, CK4.currency)) == nullptr); env(check::cash(alice, chkId, CK4(92)), ter(tecNO_ENTRY)); env.close(); @@ -2393,10 +2286,8 @@ class Check_test : public beast::unit_test::suite // Because gw1 has set lsfGlobalFreeze, neither trust line // is created. - BEAST_EXPECT( - env.le(keylet::line(gw1, alice, OF4.currency)) == nullptr); - BEAST_EXPECT( - env.le(keylet::line(gw1, alice, CK4.currency)) == nullptr); + BEAST_EXPECT(env.le(keylet::line(gw1, alice, OF4.currency)) == nullptr); + BEAST_EXPECT(env.le(keylet::line(gw1, alice, CK4.currency)) == nullptr); } //------------ lsfGlobalFreeze, check written by non-issuer ------------ { @@ -2408,8 +2299,7 @@ class Check_test : public beast::unit_test::suite IOU const OF4 = gw1["OF4"]; env(offer(alice, XRP(91), OF4(91)), ter(tecFROZEN)); env.close(); - BEAST_EXPECT( - env.le(keylet::line(alice, bob, OF4.currency)) == nullptr); + BEAST_EXPECT(env.le(keylet::line(alice, bob, OF4.currency)) == nullptr); env(offer(bob, OF4(91), XRP(91)), ter(tecFROZEN)); env.close(); @@ -2423,8 +2313,7 @@ class Check_test : public beast::unit_test::suite uint256 const chkId{getCheckIndex(alice, env.seq(alice))}; env(check::create(alice, bob, CK4(91)), ter(tecFROZEN)); env.close(); - BEAST_EXPECT( - env.le(keylet::line(alice, bob, CK4.currency)) == nullptr); + BEAST_EXPECT(env.le(keylet::line(alice, bob, CK4.currency)) == nullptr); env(check::cash(bob, chkId, CK4(91)), ter(tecNO_ENTRY)); env.close(); @@ -2435,10 +2324,8 @@ class Check_test : public beast::unit_test::suite // Because gw1 has set lsfGlobalFreeze, neither trust line // is created. - BEAST_EXPECT( - env.le(keylet::line(gw1, bob, OF4.currency)) == nullptr); - BEAST_EXPECT( - env.le(keylet::line(gw1, bob, CK4.currency)) == nullptr); + BEAST_EXPECT(env.le(keylet::line(gw1, bob, OF4.currency)) == nullptr); + BEAST_EXPECT(env.le(keylet::line(gw1, bob, CK4.currency)) == nullptr); } //-------------- lsfRequireAuth, check written by issuer --------------- @@ -2462,8 +2349,7 @@ class Check_test : public beast::unit_test::suite env(offer(gw2, XRP(92), OF5(92))); ++gw2.owners; env.close(); - BEAST_EXPECT( - env.le(keylet::line(gw2, alice, OF5.currency)) == nullptr); + BEAST_EXPECT(env.le(keylet::line(gw2, alice, OF5.currency)) == nullptr); env(offer(alice, OF5(92), XRP(92)), ter(tecNO_LINE)); env.close(); @@ -2485,8 +2371,7 @@ class Check_test : public beast::unit_test::suite env(check::create(gw2, alice, CK5(92))); ++gw2.owners; env.close(); - BEAST_EXPECT( - env.le(keylet::line(gw2, alice, CK5.currency)) == nullptr); + BEAST_EXPECT(env.le(keylet::line(gw2, alice, CK5.currency)) == nullptr); env(check::cash(alice, chkId, CK5(92)), ter(tecNO_AUTH)); env.close(); @@ -2498,10 +2383,8 @@ class Check_test : public beast::unit_test::suite // Because gw2 has set lsfRequireAuth, neither trust line // is created. - BEAST_EXPECT( - env.le(keylet::line(gw2, alice, OF5.currency)) == nullptr); - BEAST_EXPECT( - env.le(keylet::line(gw2, alice, CK5.currency)) == nullptr); + BEAST_EXPECT(env.le(keylet::line(gw2, alice, OF5.currency)) == nullptr); + BEAST_EXPECT(env.le(keylet::line(gw2, alice, CK5.currency)) == nullptr); // Since we don't need it any more, remove gw2's check. env(check::cancel(gw2, chkId)); @@ -2520,8 +2403,7 @@ class Check_test : public beast::unit_test::suite env(offer(alice, XRP(91), OF5(91)), ter(tecUNFUNDED_OFFER)); env.close(); env(offer(bob, OF5(91), XRP(91)), ter(tecNO_LINE)); - BEAST_EXPECT( - env.le(keylet::line(gw2, bob, OF5.currency)) == nullptr); + BEAST_EXPECT(env.le(keylet::line(gw2, bob, OF5.currency)) == nullptr); env.close(); gw2.verifyOwners(__LINE__); @@ -2533,8 +2415,7 @@ class Check_test : public beast::unit_test::suite uint256 const chkId{getCheckIndex(alice, env.seq(alice))}; env(check::create(alice, bob, CK5(91))); env.close(); - BEAST_EXPECT( - env.le(keylet::line(alice, bob, CK5.currency)) == nullptr); + BEAST_EXPECT(env.le(keylet::line(alice, bob, CK5.currency)) == nullptr); env(check::cash(bob, chkId, CK5(91)), ter(tecPATH_PARTIAL)); env.close(); @@ -2549,10 +2430,8 @@ class Check_test : public beast::unit_test::suite // Because gw2 has set lsfRequireAuth, neither trust line // is created. - BEAST_EXPECT( - env.le(keylet::line(gw2, bob, OF5.currency)) == nullptr); - BEAST_EXPECT( - env.le(keylet::line(gw2, bob, CK5.currency)) == nullptr); + BEAST_EXPECT(env.le(keylet::line(gw2, bob, OF5.currency)) == nullptr); + BEAST_EXPECT(env.le(keylet::line(gw2, bob, CK5.currency)) == nullptr); } } diff --git a/src/test/app/Clawback_test.cpp b/src/test/app/Clawback_test.cpp index c8c4aea757..d169e9e165 100644 --- a/src/test/app/Clawback_test.cpp +++ b/src/test/app/Clawback_test.cpp @@ -250,9 +250,7 @@ class Clawback_test : public beast::unit_test::suite env.require(balance(alice, bob["USD"](-10))); // fails due to invalid flag - env(claw(alice, bob["USD"](5)), - txflags(0x00008000), - ter(temINVALID_FLAG)); + env(claw(alice, bob["USD"](5)), txflags(0x00008000), ter(temINVALID_FLAG)); env.close(); // fails due to negative amount diff --git a/src/test/app/Credentials_test.cpp b/src/test/app/Credentials_test.cpp index 7de34e05a1..31c867c24d 100644 --- a/src/test/app/Credentials_test.cpp +++ b/src/test/app/Credentials_test.cpp @@ -39,8 +39,7 @@ struct Credentials_test : public beast::unit_test::suite env.close(); // Test Create credentials - env(credentials::create(subject, issuer, credType), - credentials::uri(uri)); + env(credentials::create(subject, issuer, credType), credentials::uri(uri)); env.close(); { auto const sleCred = env.le(credKey); @@ -55,21 +54,14 @@ struct Credentials_test : public beast::unit_test::suite BEAST_EXPECT(!ownerCount(env, subject)); BEAST_EXPECT(checkVL(sleCred, sfCredentialType, credType)); BEAST_EXPECT(checkVL(sleCred, sfURI, uri)); - auto const jle = - credentials::ledgerEntry(env, subject, issuer, credType); + auto const jle = credentials::ledgerEntry(env, subject, issuer, credType); BEAST_EXPECT( - jle.isObject() && jle.isMember(jss::result) && - !jle[jss::result].isMember(jss::error) && - jle[jss::result].isMember(jss::node) && - jle[jss::result][jss::node].isMember("LedgerEntryType") && - jle[jss::result][jss::node]["LedgerEntryType"] == - jss::Credential && - jle[jss::result][jss::node][jss::Issuer] == - issuer.human() && - jle[jss::result][jss::node][jss::Subject] == - subject.human() && - jle[jss::result][jss::node]["CredentialType"] == - strHex(std::string_view(credType))); + jle.isObject() && jle.isMember(jss::result) && !jle[jss::result].isMember(jss::error) && + jle[jss::result].isMember(jss::node) && jle[jss::result][jss::node].isMember("LedgerEntryType") && + jle[jss::result][jss::node]["LedgerEntryType"] == jss::Credential && + jle[jss::result][jss::node][jss::Issuer] == issuer.human() && + jle[jss::result][jss::node][jss::Subject] == subject.human() && + jle[jss::result][jss::node]["CredentialType"] == strHex(std::string_view(credType))); } env(credentials::accept(subject, issuer, credType)); @@ -99,11 +91,9 @@ struct Credentials_test : public beast::unit_test::suite BEAST_EXPECT(!ownerCount(env, subject)); // check no credential exists anymore - auto const jle = - credentials::ledgerEntry(env, subject, issuer, credType); + auto const jle = credentials::ledgerEntry(env, subject, issuer, credType); BEAST_EXPECT( - jle.isObject() && jle.isMember(jss::result) && - jle[jss::result].isMember(jss::error) && + jle.isObject() && jle.isMember(jss::result) && jle[jss::result].isMember(jss::error) && jle[jss::result][jss::error] == "entryNotFound"); } } @@ -113,8 +103,7 @@ struct Credentials_test : public beast::unit_test::suite auto const credKey = credentials::keylet(issuer, issuer, credType); - env(credentials::create(issuer, issuer, credType), - credentials::uri(uri)); + env(credentials::create(issuer, issuer, credType), credentials::uri(uri)); env.close(); { auto const sleCred = env.le(credKey); @@ -125,27 +114,18 @@ struct Credentials_test : public beast::unit_test::suite BEAST_EXPECT(sleCred->getAccountID(sfSubject) == issuer.id()); BEAST_EXPECT(sleCred->getAccountID(sfIssuer) == issuer.id()); BEAST_EXPECT((sleCred->getFieldU32(sfFlags) & lsfAccepted)); - BEAST_EXPECT( - sleCred->getFieldU64(sfIssuerNode) == - sleCred->getFieldU64(sfSubjectNode)); + BEAST_EXPECT(sleCred->getFieldU64(sfIssuerNode) == sleCred->getFieldU64(sfSubjectNode)); BEAST_EXPECT(ownerCount(env, issuer) == 1); BEAST_EXPECT(checkVL(sleCred, sfCredentialType, credType)); BEAST_EXPECT(checkVL(sleCred, sfURI, uri)); - auto const jle = - credentials::ledgerEntry(env, issuer, issuer, credType); + auto const jle = credentials::ledgerEntry(env, issuer, issuer, credType); BEAST_EXPECT( - jle.isObject() && jle.isMember(jss::result) && - !jle[jss::result].isMember(jss::error) && - jle[jss::result].isMember(jss::node) && - jle[jss::result][jss::node].isMember("LedgerEntryType") && - jle[jss::result][jss::node]["LedgerEntryType"] == - jss::Credential && - jle[jss::result][jss::node][jss::Issuer] == - issuer.human() && - jle[jss::result][jss::node][jss::Subject] == - issuer.human() && - jle[jss::result][jss::node]["CredentialType"] == - strHex(std::string_view(credType))); + jle.isObject() && jle.isMember(jss::result) && !jle[jss::result].isMember(jss::error) && + jle[jss::result].isMember(jss::node) && jle[jss::result][jss::node].isMember("LedgerEntryType") && + jle[jss::result][jss::node]["LedgerEntryType"] == jss::Credential && + jle[jss::result][jss::node][jss::Issuer] == issuer.human() && + jle[jss::result][jss::node][jss::Subject] == issuer.human() && + jle[jss::result][jss::node]["CredentialType"] == strHex(std::string_view(credType))); } env(credentials::deleteCred(issuer, issuer, issuer, credType)); @@ -155,11 +135,9 @@ struct Credentials_test : public beast::unit_test::suite BEAST_EXPECT(!ownerCount(env, issuer)); // check no credential exists anymore - auto const jle = - credentials::ledgerEntry(env, issuer, issuer, credType); + auto const jle = credentials::ledgerEntry(env, issuer, issuer, credType); BEAST_EXPECT( - jle.isObject() && jle.isMember(jss::result) && - jle[jss::result].isMember(jss::error) && + jle.isObject() && jle.isMember(jss::result) && jle[jss::result].isMember(jss::error) && jle[jss::result][jss::error] == "entryNotFound"); } } @@ -205,11 +183,9 @@ struct Credentials_test : public beast::unit_test::suite BEAST_EXPECT(!ownerCount(env, subject)); // check no credential exists anymore - auto const jle = - credentials::ledgerEntry(env, subject, issuer, credType); + auto const jle = credentials::ledgerEntry(env, subject, issuer, credType); BEAST_EXPECT( - jle.isObject() && jle.isMember(jss::result) && - jle[jss::result].isMember(jss::error) && + jle.isObject() && jle.isMember(jss::result) && jle[jss::result].isMember(jss::error) && jle[jss::result][jss::error] == "entryNotFound"); } @@ -243,11 +219,9 @@ struct Credentials_test : public beast::unit_test::suite BEAST_EXPECT(!ownerCount(env, subject)); // check no credential exists anymore - auto const jle = - credentials::ledgerEntry(env, subject, issuer, credType); + auto const jle = credentials::ledgerEntry(env, subject, issuer, credType); BEAST_EXPECT( - jle.isObject() && jle.isMember(jss::result) && - jle[jss::result].isMember(jss::error) && + jle.isObject() && jle.isMember(jss::result) && jle[jss::result].isMember(jss::error) && jle[jss::result][jss::error] == "entryNotFound"); } @@ -279,11 +253,9 @@ struct Credentials_test : public beast::unit_test::suite BEAST_EXPECT(!ownerCount(env, issuer)); // check no credential exists anymore - auto const jle = - credentials::ledgerEntry(env, subject, issuer, credType); + auto const jle = credentials::ledgerEntry(env, subject, issuer, credType); BEAST_EXPECT( - jle.isObject() && jle.isMember(jss::result) && - jle[jss::result].isMember(jss::error) && + jle.isObject() && jle.isMember(jss::result) && jle[jss::result].isMember(jss::error) && jle[jss::result][jss::error] == "entryNotFound"); } @@ -317,11 +289,9 @@ struct Credentials_test : public beast::unit_test::suite BEAST_EXPECT(!ownerCount(env, issuer)); // check no credential exists anymore - auto const jle = - credentials::ledgerEntry(env, subject, issuer, credType); + auto const jle = credentials::ledgerEntry(env, subject, issuer, credType); BEAST_EXPECT( - jle.isObject() && jle.isMember(jss::result) && - jle[jss::result].isMember(jss::error) && + jle.isObject() && jle.isMember(jss::result) && jle[jss::result].isMember(jss::error) && jle[jss::result][jss::error] == "entryNotFound"); } @@ -335,10 +305,7 @@ struct Credentials_test : public beast::unit_test::suite auto const credKey = credentials::keylet(subject, issuer, credType); auto jv = credentials::create(subject, issuer, credType); - uint32_t const t = env.current() - ->header() - .parentCloseTime.time_since_epoch() - .count(); + uint32_t const t = env.current()->header().parentCloseTime.time_since_epoch().count(); jv[sfExpiration.jsonName] = t + 20; env(jv); @@ -358,11 +325,9 @@ struct Credentials_test : public beast::unit_test::suite BEAST_EXPECT(!ownerCount(env, subject)); // check no credential exists anymore - auto const jle = - credentials::ledgerEntry(env, subject, issuer, credType); + auto const jle = credentials::ledgerEntry(env, subject, issuer, credType); BEAST_EXPECT( - jle.isObject() && jle.isMember(jss::result) && - jle[jss::result].isMember(jss::error) && + jle.isObject() && jle.isMember(jss::result) && jle[jss::result].isMember(jss::error) && jle[jss::result][jss::error] == "entryNotFound"); } } @@ -377,16 +342,13 @@ struct Credentials_test : public beast::unit_test::suite env(credentials::deleteCred(subject, subject, issuer, credType)); env.close(); { - auto const credKey = - credentials::keylet(subject, issuer, credType); + auto const credKey = credentials::keylet(subject, issuer, credType); BEAST_EXPECT(!env.le(credKey)); BEAST_EXPECT(!ownerCount(env, subject)); BEAST_EXPECT(!ownerCount(env, issuer)); - auto const jle = - credentials::ledgerEntry(env, subject, issuer, credType); + auto const jle = credentials::ledgerEntry(env, subject, issuer, credType); BEAST_EXPECT( - jle.isObject() && jle.isMember(jss::result) && - jle[jss::result].isMember(jss::error) && + jle.isObject() && jle.isMember(jss::result) && jle[jss::result].isMember(jss::error) && jle[jss::result][jss::error] == "entryNotFound"); } } @@ -399,16 +361,13 @@ struct Credentials_test : public beast::unit_test::suite env(credentials::deleteCred(issuer, subject, issuer, credType)); env.close(); { - auto const credKey = - credentials::keylet(subject, issuer, credType); + auto const credKey = credentials::keylet(subject, issuer, credType); BEAST_EXPECT(!env.le(credKey)); BEAST_EXPECT(!ownerCount(env, subject)); BEAST_EXPECT(!ownerCount(env, issuer)); - auto const jle = - credentials::ledgerEntry(env, subject, issuer, credType); + auto const jle = credentials::ledgerEntry(env, subject, issuer, credType); BEAST_EXPECT( - jle.isObject() && jle.isMember(jss::result) && - jle[jss::result].isMember(jss::error) && + jle.isObject() && jle.isMember(jss::result) && jle[jss::result].isMember(jss::error) && jle[jss::result][jss::error] == "entryNotFound"); } } @@ -481,27 +440,19 @@ struct Credentials_test : public beast::unit_test::suite "WULE" "fv28o37gfwEFB3872TFO8GSDSDVD"; static_assert(longURI.size() > maxCredentialURILength); - env(credentials::create(subject, issuer, credType), - credentials::uri(longURI), - ter(temMALFORMED)); + env(credentials::create(subject, issuer, credType), credentials::uri(longURI), ter(temMALFORMED)); } { testcase("Credentials fail, URI empty."); - env(credentials::create(subject, issuer, credType), - credentials::uri(""), - ter(temMALFORMED)); + env(credentials::create(subject, issuer, credType), credentials::uri(""), ter(temMALFORMED)); } { testcase("Credentials fail, expiration in the past."); auto jv = credentials::create(subject, issuer, credType); // current time in ripple epoch - 1s - uint32_t const t = env.current() - ->header() - .parentCloseTime.time_since_epoch() - .count() - - 1; + uint32_t const t = env.current()->header().parentCloseTime.time_since_epoch().count() - 1; jv[sfExpiration.jsonName] = t; env(jv, ter(tecEXPIRED)); } @@ -523,21 +474,14 @@ struct Credentials_test : public beast::unit_test::suite env.close(); // check credential still present - auto const jle = - credentials::ledgerEntry(env, subject, issuer, credType); + auto const jle = credentials::ledgerEntry(env, subject, issuer, credType); BEAST_EXPECT( - jle.isObject() && jle.isMember(jss::result) && - !jle[jss::result].isMember(jss::error) && - jle[jss::result].isMember(jss::node) && - jle[jss::result][jss::node].isMember("LedgerEntryType") && - jle[jss::result][jss::node]["LedgerEntryType"] == - jss::Credential && - jle[jss::result][jss::node][jss::Issuer] == - issuer.human() && - jle[jss::result][jss::node][jss::Subject] == - subject.human() && - jle[jss::result][jss::node]["CredentialType"] == - strHex(std::string_view(credType))); + jle.isObject() && jle.isMember(jss::result) && !jle[jss::result].isMember(jss::error) && + jle[jss::result].isMember(jss::node) && jle[jss::result][jss::node].isMember("LedgerEntryType") && + jle[jss::result][jss::node]["LedgerEntryType"] == jss::Credential && + jle[jss::result][jss::node][jss::Issuer] == issuer.human() && + jle[jss::result][jss::node][jss::Subject] == subject.human() && + jle[jss::result][jss::node]["CredentialType"] == strHex(std::string_view(credType))); } { @@ -548,10 +492,7 @@ struct Credentials_test : public beast::unit_test::suite // Everything below can only be tested on open ledger. auto const res1 = directory::bumpLastPage( - env, - directory::maximumPageIndex(env), - keylet::ownerDir(issuer.id()), - directory::adjustOwnerNode); + env, directory::maximumPageIndex(env), keylet::ownerDir(issuer.id()), directory::adjustOwnerNode); BEAST_EXPECT(res1); auto const jv = credentials::create(issuer, subject, credType); @@ -562,10 +503,7 @@ struct Credentials_test : public beast::unit_test::suite // Fill subject directory env(ticket::create(subject, 63)); auto const res2 = directory::bumpLastPage( - env, - directory::maximumPageIndex(env), - keylet::ownerDir(subject.id()), - directory::adjustOwnerNode); + env, directory::maximumPageIndex(env), keylet::ownerDir(subject.id()), directory::adjustOwnerNode); BEAST_EXPECT(res2); env(jv, ter(tecDIR_FULL)); @@ -622,8 +560,7 @@ struct Credentials_test : public beast::unit_test::suite { testcase("CredentialsAccept fail, Credential doesn't exist."); - env(credentials::accept(subject, issuer, credType), - ter(tecNO_ENTRY)); + env(credentials::accept(subject, issuer, credType), ter(tecNO_ENTRY)); env.close(); } @@ -636,8 +573,7 @@ struct Credentials_test : public beast::unit_test::suite } { - testcase( - "CredentialsAccept fail, invalid credentialType param."); + testcase("CredentialsAccept fail, invalid credentialType param."); auto jv = credentials::accept(subject, issuer, ""); env(jv, ter(temMALFORMED)); } @@ -655,26 +591,18 @@ struct Credentials_test : public beast::unit_test::suite env(credentials::create(subject, issuer, credType)); env.close(); - env(credentials::accept(subject, issuer, credType), - ter(tecINSUFFICIENT_RESERVE)); + env(credentials::accept(subject, issuer, credType), ter(tecINSUFFICIENT_RESERVE)); env.close(); // check credential still present - auto const jle = - credentials::ledgerEntry(env, subject, issuer, credType); + auto const jle = credentials::ledgerEntry(env, subject, issuer, credType); BEAST_EXPECT( - jle.isObject() && jle.isMember(jss::result) && - !jle[jss::result].isMember(jss::error) && - jle[jss::result].isMember(jss::node) && - jle[jss::result][jss::node].isMember("LedgerEntryType") && - jle[jss::result][jss::node]["LedgerEntryType"] == - jss::Credential && - jle[jss::result][jss::node][jss::Issuer] == - issuer.human() && - jle[jss::result][jss::node][jss::Subject] == - subject.human() && - jle[jss::result][jss::node]["CredentialType"] == - strHex(std::string_view(credType))); + jle.isObject() && jle.isMember(jss::result) && !jle[jss::result].isMember(jss::error) && + jle[jss::result].isMember(jss::node) && jle[jss::result][jss::node].isMember("LedgerEntryType") && + jle[jss::result][jss::node]["LedgerEntryType"] == jss::Credential && + jle[jss::result][jss::node][jss::Issuer] == issuer.human() && + jle[jss::result][jss::node][jss::Subject] == subject.human() && + jle[jss::result][jss::node]["CredentialType"] == strHex(std::string_view(credType))); } } @@ -697,26 +625,18 @@ struct Credentials_test : public beast::unit_test::suite testcase("CredentialsAccept fail, lsfAccepted already set."); env(credentials::accept(subject, issuer, credType)); env.close(); - env(credentials::accept(subject, issuer, credType), - ter(tecDUPLICATE)); + env(credentials::accept(subject, issuer, credType), ter(tecDUPLICATE)); env.close(); // check credential still present - auto const jle = - credentials::ledgerEntry(env, subject, issuer, credType); + auto const jle = credentials::ledgerEntry(env, subject, issuer, credType); BEAST_EXPECT( - jle.isObject() && jle.isMember(jss::result) && - !jle[jss::result].isMember(jss::error) && - jle[jss::result].isMember(jss::node) && - jle[jss::result][jss::node].isMember("LedgerEntryType") && - jle[jss::result][jss::node]["LedgerEntryType"] == - jss::Credential && - jle[jss::result][jss::node][jss::Issuer] == - issuer.human() && - jle[jss::result][jss::node][jss::Subject] == - subject.human() && - jle[jss::result][jss::node]["CredentialType"] == - strHex(std::string_view(credType))); + jle.isObject() && jle.isMember(jss::result) && !jle[jss::result].isMember(jss::error) && + jle[jss::result].isMember(jss::node) && jle[jss::result][jss::node].isMember("LedgerEntryType") && + jle[jss::result][jss::node]["LedgerEntryType"] == jss::Credential && + jle[jss::result][jss::node][jss::Issuer] == issuer.human() && + jle[jss::result][jss::node][jss::Subject] == subject.human() && + jle[jss::result][jss::node]["CredentialType"] == strHex(std::string_view(credType))); } { @@ -724,26 +644,20 @@ struct Credentials_test : public beast::unit_test::suite testcase("CredentialsAccept fail, expired credentials."); auto jv = credentials::create(subject, issuer, credType2); - uint32_t const t = env.current() - ->header() - .parentCloseTime.time_since_epoch() - .count(); + uint32_t const t = env.current()->header().parentCloseTime.time_since_epoch().count(); jv[sfExpiration.jsonName] = t; env(jv); env.close(); // credentials are expired now - env(credentials::accept(subject, issuer, credType2), - ter(tecEXPIRED)); + env(credentials::accept(subject, issuer, credType2), ter(tecEXPIRED)); env.close(); // check that expired credentials were deleted - auto const jDelCred = - credentials::ledgerEntry(env, subject, issuer, credType2); + auto const jDelCred = credentials::ledgerEntry(env, subject, issuer, credType2); BEAST_EXPECT( jDelCred.isObject() && jDelCred.isMember(jss::result) && - jDelCred[jss::result].isMember(jss::error) && - jDelCred[jss::result][jss::error] == "entryNotFound"); + jDelCred[jss::result].isMember(jss::error) && jDelCred[jss::result][jss::error] == "entryNotFound"); BEAST_EXPECT(ownerCount(env, issuer) == 0); BEAST_EXPECT(ownerCount(env, subject) == 1); @@ -776,12 +690,10 @@ struct Credentials_test : public beast::unit_test::suite env.close(); // check that expired credentials were deleted - auto const jDelCred = - credentials::ledgerEntry(env, subject, issuer, credType); + auto const jDelCred = credentials::ledgerEntry(env, subject, issuer, credType); BEAST_EXPECT( jDelCred.isObject() && jDelCred.isMember(jss::result) && - jDelCred[jss::result].isMember(jss::error) && - jDelCred[jss::result][jss::error] == "entryNotFound"); + jDelCred[jss::result].isMember(jss::error) && jDelCred[jss::result][jss::error] == "entryNotFound"); } } } @@ -805,15 +717,13 @@ struct Credentials_test : public beast::unit_test::suite { testcase("CredentialsDelete fail, no Credentials."); - env(credentials::deleteCred(subject, subject, issuer, credType), - ter(tecNO_ENTRY)); + env(credentials::deleteCred(subject, subject, issuer, credType), ter(tecNO_ENTRY)); env.close(); } { testcase("CredentialsDelete fail, invalid Subject account."); - auto jv = - credentials::deleteCred(subject, subject, issuer, credType); + auto jv = credentials::deleteCred(subject, subject, issuer, credType); jv[jss::Subject] = to_string(xrpAccount()); env(jv, ter(temINVALID_ACCOUNT_ID)); env.close(); @@ -821,16 +731,14 @@ struct Credentials_test : public beast::unit_test::suite { testcase("CredentialsDelete fail, invalid Issuer account."); - auto jv = - credentials::deleteCred(subject, subject, issuer, credType); + auto jv = credentials::deleteCred(subject, subject, issuer, credType); jv[jss::Issuer] = to_string(xrpAccount()); env(jv, ter(temINVALID_ACCOUNT_ID)); env.close(); } { - testcase( - "CredentialsDelete fail, invalid credentialType param."); + testcase("CredentialsDelete fail, invalid credentialType param."); auto jv = credentials::deleteCred(subject, subject, issuer, ""); env(jv, ter(temMALFORMED)); } @@ -842,26 +750,18 @@ struct Credentials_test : public beast::unit_test::suite env.close(); // Other account can't delete credentials without expiration - env(credentials::deleteCred(other, subject, issuer, credType2), - ter(tecNO_PERMISSION)); + env(credentials::deleteCred(other, subject, issuer, credType2), ter(tecNO_PERMISSION)); env.close(); // check credential still present - auto const jle = - credentials::ledgerEntry(env, subject, issuer, credType2); + auto const jle = credentials::ledgerEntry(env, subject, issuer, credType2); BEAST_EXPECT( - jle.isObject() && jle.isMember(jss::result) && - !jle[jss::result].isMember(jss::error) && - jle[jss::result].isMember(jss::node) && - jle[jss::result][jss::node].isMember("LedgerEntryType") && - jle[jss::result][jss::node]["LedgerEntryType"] == - jss::Credential && - jle[jss::result][jss::node][jss::Issuer] == - issuer.human() && - jle[jss::result][jss::node][jss::Subject] == - subject.human() && - jle[jss::result][jss::node]["CredentialType"] == - strHex(std::string_view(credType2))); + jle.isObject() && jle.isMember(jss::result) && !jle[jss::result].isMember(jss::error) && + jle[jss::result].isMember(jss::node) && jle[jss::result][jss::node].isMember("LedgerEntryType") && + jle[jss::result][jss::node]["LedgerEntryType"] == jss::Credential && + jle[jss::result][jss::node][jss::Issuer] == issuer.human() && + jle[jss::result][jss::node][jss::Subject] == subject.human() && + jle[jss::result][jss::node]["CredentialType"] == strHex(std::string_view(credType2))); } { @@ -869,43 +769,30 @@ struct Credentials_test : public beast::unit_test::suite auto jv = credentials::create(subject, issuer, credType); // current time in ripple epoch + 1000s - uint32_t const t = env.current() - ->header() - .parentCloseTime.time_since_epoch() - .count() + - 1000; + uint32_t const t = env.current()->header().parentCloseTime.time_since_epoch().count() + 1000; jv[sfExpiration.jsonName] = t; env(jv); env.close(); // Other account can't delete credentials that not expired - env(credentials::deleteCred(other, subject, issuer, credType), - ter(tecNO_PERMISSION)); + env(credentials::deleteCred(other, subject, issuer, credType), ter(tecNO_PERMISSION)); env.close(); // check credential still present - auto const jle = - credentials::ledgerEntry(env, subject, issuer, credType); + auto const jle = credentials::ledgerEntry(env, subject, issuer, credType); BEAST_EXPECT( - jle.isObject() && jle.isMember(jss::result) && - !jle[jss::result].isMember(jss::error) && - jle[jss::result].isMember(jss::node) && - jle[jss::result][jss::node].isMember("LedgerEntryType") && - jle[jss::result][jss::node]["LedgerEntryType"] == - jss::Credential && - jle[jss::result][jss::node][jss::Issuer] == - issuer.human() && - jle[jss::result][jss::node][jss::Subject] == - subject.human() && - jle[jss::result][jss::node]["CredentialType"] == - strHex(std::string_view(credType))); + jle.isObject() && jle.isMember(jss::result) && !jle[jss::result].isMember(jss::error) && + jle[jss::result].isMember(jss::node) && jle[jss::result][jss::node].isMember("LedgerEntryType") && + jle[jss::result][jss::node]["LedgerEntryType"] == jss::Credential && + jle[jss::result][jss::node][jss::Issuer] == issuer.human() && + jle[jss::result][jss::node][jss::Subject] == subject.human() && + jle[jss::result][jss::node]["CredentialType"] == strHex(std::string_view(credType))); } { testcase("CredentialsDelete fail, no Issuer and Subject."); - auto jv = - credentials::deleteCred(subject, subject, issuer, credType); + auto jv = credentials::deleteCred(subject, subject, issuer, credType); jv.removeMember(jss::Subject); jv.removeMember(jss::Issuer); env(jv, ter(temMALFORMED)); @@ -915,8 +802,7 @@ struct Credentials_test : public beast::unit_test::suite { testcase("CredentialsDelete fail, invalid fee."); - auto jv = - credentials::deleteCred(subject, subject, issuer, credType); + auto jv = credentials::deleteCred(subject, subject, issuer, credType); jv[jss::Fee] = -1; env(jv, ter(temBAD_FEE)); env.close(); @@ -924,8 +810,7 @@ struct Credentials_test : public beast::unit_test::suite { testcase("deleteSLE fail, bad SLE."); - auto view = std::make_shared( - env.current().get(), ApplyFlags::tapNONE); + auto view = std::make_shared(env.current().get(), ApplyFlags::tapNONE); auto ter = xrpl::credentials::deleteSLE(*view, {}, env.journal); BEAST_EXPECT(ter == tecNO_ENTRY); } @@ -950,12 +835,9 @@ struct Credentials_test : public beast::unit_test::suite { testcase("Credentials fail, Feature is not enabled."); - env(credentials::create(subject, issuer, credType), - ter(temDISABLED)); - env(credentials::accept(subject, issuer, credType), - ter(temDISABLED)); - env(credentials::deleteCred(subject, subject, issuer, credType), - ter(temDISABLED)); + env(credentials::create(subject, issuer, credType), ter(temDISABLED)); + env(credentials::accept(subject, issuer, credType), ter(temDISABLED)); + env(credentials::deleteCred(subject, subject, issuer, credType), ter(temDISABLED)); } } } @@ -988,16 +870,13 @@ struct Credentials_test : public beast::unit_test::suite { Json::Value params; params[jss::account] = subject.human(); - auto const jv = env.rpc( - "json", "account_tx", to_string(params))[jss::result]; + auto const jv = env.rpc("json", "account_tx", to_string(params))[jss::result]; BEAST_EXPECT(jv[jss::transactions].size() == 4); auto const& tx0(jv[jss::transactions][0u][jss::tx]); - BEAST_EXPECT( - tx0[jss::TransactionType] == jss::CredentialAccept); + BEAST_EXPECT(tx0[jss::TransactionType] == jss::CredentialAccept); auto const& tx1(jv[jss::transactions][1u][jss::tx]); - BEAST_EXPECT( - tx1[jss::TransactionType] == jss::CredentialCreate); + BEAST_EXPECT(tx1[jss::TransactionType] == jss::CredentialCreate); txHash0 = tx0[jss::hash].asString(); txHash1 = tx1[jss::hash].asString(); } @@ -1005,16 +884,13 @@ struct Credentials_test : public beast::unit_test::suite { Json::Value params; params[jss::account] = issuer.human(); - auto const jv = env.rpc( - "json", "account_tx", to_string(params))[jss::result]; + auto const jv = env.rpc("json", "account_tx", to_string(params))[jss::result]; BEAST_EXPECT(jv[jss::transactions].size() == 4); auto const& tx0(jv[jss::transactions][0u][jss::tx]); - BEAST_EXPECT( - tx0[jss::TransactionType] == jss::CredentialAccept); + BEAST_EXPECT(tx0[jss::TransactionType] == jss::CredentialAccept); auto const& tx1(jv[jss::transactions][1u][jss::tx]); - BEAST_EXPECT( - tx1[jss::TransactionType] == jss::CredentialCreate); + BEAST_EXPECT(tx1[jss::TransactionType] == jss::CredentialCreate); BEAST_EXPECT(txHash0 == tx0[jss::hash].asString()); BEAST_EXPECT(txHash1 == tx1[jss::hash].asString()); @@ -1025,28 +901,24 @@ struct Credentials_test : public beast::unit_test::suite { Json::Value params; params[jss::account] = subject.human(); - auto jv = env.rpc( - "json", "account_objects", to_string(params))[jss::result]; + auto jv = env.rpc("json", "account_objects", to_string(params))[jss::result]; BEAST_EXPECT(jv[jss::account_objects].size() == 1); auto const& object(jv[jss::account_objects][0u]); - BEAST_EXPECT( - object["LedgerEntryType"].asString() == jss::Credential); + BEAST_EXPECT(object["LedgerEntryType"].asString() == jss::Credential); objectIdx = object[jss::index].asString(); } { Json::Value params; params[jss::account] = issuer.human(); - auto jv = env.rpc( - "json", "account_objects", to_string(params))[jss::result]; + auto jv = env.rpc("json", "account_objects", to_string(params))[jss::result]; BEAST_EXPECT(jv[jss::account_objects].size() == 1); auto const& object(jv[jss::account_objects][0u]); - BEAST_EXPECT( - object["LedgerEntryType"].asString() == jss::Credential); + BEAST_EXPECT(object["LedgerEntryType"].asString() == jss::Credential); BEAST_EXPECT(objectIdx == object[jss::index].asString()); } } @@ -1058,9 +930,7 @@ struct Credentials_test : public beast::unit_test::suite using namespace test::jtx; bool const enabled = features[fixInvalidTxFlags]; - testcase( - std::string("Test flag, fix ") + - (enabled ? "enabled" : "disabled")); + testcase(std::string("Test flag, fix ") + (enabled ? "enabled" : "disabled")); char const credType[] = "abcde"; Account const issuer{"issuer"}; @@ -1074,17 +944,10 @@ struct Credentials_test : public beast::unit_test::suite env.close(); { - ter const expected( - enabled ? TER(temINVALID_FLAG) : TER(tesSUCCESS)); - env(credentials::create(subject, issuer, credType), - txflags(tfTransferable), - expected); - env(credentials::accept(subject, issuer, credType), - txflags(tfSellNFToken), - expected); - env(credentials::deleteCred(subject, subject, issuer, credType), - txflags(tfPassive), - expected); + ter const expected(enabled ? TER(temINVALID_FLAG) : TER(tesSUCCESS)); + env(credentials::create(subject, issuer, credType), txflags(tfTransferable), expected); + env(credentials::accept(subject, issuer, credType), txflags(tfSellNFToken), expected); + env(credentials::deleteCred(subject, subject, issuer, credType), txflags(tfPassive), expected); } } } diff --git a/src/test/app/CrossingLimits_test.cpp b/src/test/app/CrossingLimits_test.cpp index 8c11dd6737..0451822492 100644 --- a/src/test/app/CrossingLimits_test.cpp +++ b/src/test/app/CrossingLimits_test.cpp @@ -64,15 +64,15 @@ public: int const maxConsumed = 1000; env.fund(XRP(100000000), gw, "alice", "bob", "carol"); - int const bobsOfferCount = maxConsumed + 150; - env.trust(USD(bobsOfferCount), "bob"); - env(pay(gw, "bob", USD(bobsOfferCount))); + int const bobOfferCount = maxConsumed + 150; + env.trust(USD(bobOfferCount), "bob"); + env(pay(gw, "bob", USD(bobOfferCount))); env.close(); - n_offers(env, bobsOfferCount, "bob", XRP(1), USD(1)); + n_offers(env, bobOfferCount, "bob", XRP(1), USD(1)); // Alice offers to buy Bob's offers. However she hits the offer // crossing limit, so she can't buy them all at once. - env(offer("alice", USD(bobsOfferCount), XRP(bobsOfferCount))); + env(offer("alice", USD(bobOfferCount), XRP(bobOfferCount))); env.close(); env.require(balance("alice", USD(maxConsumed))); env.require(balance("bob", USD(150))); @@ -103,19 +103,19 @@ public: // The payment engine allows 1000 offers to cross. int const maxConsumed = 1000; - int const evitasOfferCount{maxConsumed + 49}; + int const evitaOfferCount{maxConsumed + 49}; env.trust(USD(1000), "alice"); env(pay(gw, "alice", USD(1000))); env.trust(USD(1000), "carol"); env(pay(gw, "carol", USD(1))); - env.trust(USD(evitasOfferCount + 1), "evita"); - env(pay(gw, "evita", USD(evitasOfferCount + 1))); + env.trust(USD(evitaOfferCount + 1), "evita"); + env(pay(gw, "evita", USD(evitaOfferCount + 1))); // The payment engine has a limit of 1000 funded or unfunded offers. int const carolsOfferCount{700}; n_offers(env, 400, "alice", XRP(1), USD(1)); n_offers(env, carolsOfferCount, "carol", XRP(1), USD(1)); - n_offers(env, evitasOfferCount, "evita", XRP(1), USD(1)); + n_offers(env, evitaOfferCount, "evita", XRP(1), USD(1)); // Bob offers to buy 1000 XRP for 1000 USD. He takes all 400 USD from // Alice's offers, 1 USD from Carol's and then removes 599 of Carol's @@ -126,8 +126,8 @@ public: env.require(owners("alice", 1)); env.require(balance("carol", USD(0))); env.require(owners("carol", carolsOfferCount - 599)); - env.require(balance("evita", USD(evitasOfferCount + 1))); - env.require(owners("evita", evitasOfferCount + 1)); + env.require(balance("evita", USD(evitaOfferCount + 1))); + env.require(owners("evita", evitaOfferCount + 1)); // Dan offers to buy maxConsumed + 50 XRP USD. He removes all of // Carol's remaining offers as unfunded, then takes @@ -283,8 +283,7 @@ public: // best quality n_offers(env, 2000, alice, EUR(2), XRP(1)); n_offers(env, 100, alice, XRP(1), USD(4)); - n_offers( - env, 801, carol, XRP(1), USD(3)); // only one offer is funded + n_offers(env, 801, carol, XRP(1), USD(3)); // only one offer is funded n_offers(env, 1000, alice, XRP(1), USD(3)); n_offers(env, 1, alice, EUR(500), USD(500)); @@ -341,8 +340,7 @@ public: env.require(balance(alice, USD(2503))); env.require(balance(alice, EUR(1100))); - auto const numAOffers = - 2000 + 100 + 1000 + 1 - (2 * 100 + 2 * 199 + 1 + 1); + auto const numAOffers = 2000 + 100 + 1000 + 1 - (2 * 100 + 2 * 199 + 1 + 1); env.require(offers(alice, numAOffers)); env.require(owners(alice, numAOffers + 2)); @@ -363,8 +361,7 @@ public: n_offers(env, 1, alice, EUR(1), USD(10)); n_offers(env, 2000, alice, EUR(2), XRP(1)); n_offers(env, 100, alice, XRP(1), USD(4)); - n_offers( - env, 801, carol, XRP(1), USD(3)); // only one offer is funded + n_offers(env, 801, carol, XRP(1), USD(3)); // only one offer is funded n_offers(env, 1000, alice, XRP(1), USD(3)); n_offers(env, 1, alice, EUR(499), USD(499)); @@ -414,8 +411,7 @@ public: env.require(balance(alice, USD(2494))); env.require(balance(alice, EUR(1100))); - auto const numAOffers = - 1 + 2000 + 100 + 1000 + 1 - (1 + 2 * 100 + 2 * 199 + 1 + 1); + auto const numAOffers = 1 + 2000 + 100 + 1000 + 1 - (1 + 2 * 100 + 2 * 199 + 1 + 1); env.require(offers(alice, numAOffers)); env.require(owners(alice, numAOffers + 2)); diff --git a/src/test/app/DID_test.cpp b/src/test/app/DID_test.cpp index e7adfee178..f83571deab 100644 --- a/src/test/app/DID_test.cpp +++ b/src/test/app/DID_test.cpp @@ -60,9 +60,7 @@ struct DID_test : public beast::unit_test::suite // Pay alice almost enough to make the reserve for a DID. env(pay(env.master, alice, drops(incReserve + 2 * baseFee - 1))); - BEAST_EXPECT( - env.balance(alice) == - acctReserve + incReserve + drops(baseFee - 1)); + BEAST_EXPECT(env.balance(alice) == acctReserve + incReserve + drops(baseFee - 1)); env.close(); // alice still does not have enough XRP for the reserve of a DID. @@ -113,11 +111,7 @@ struct DID_test : public beast::unit_test::suite BEAST_EXPECT(ownerCount(env, alice) == 0); // all empty fields - env(did::set(alice), - did::uri(""), - did::document(""), - did::data(""), - ter(temEMPTY_DID)); + env(did::set(alice), did::uri(""), did::document(""), did::data(""), ter(temEMPTY_DID)); env.close(); BEAST_EXPECT(ownerCount(env, alice) == 0); @@ -133,19 +127,14 @@ struct DID_test : public beast::unit_test::suite BEAST_EXPECT(ownerCount(env, alice) == 0); // attestation is too long - env(did::set(alice), - did::document("data"), - did::data(longString), - ter(temMALFORMED)); + env(did::set(alice), did::document("data"), did::data(longString), ter(temMALFORMED)); env.close(); BEAST_EXPECT(ownerCount(env, alice) == 0); // some empty fields, some optional fields // pre-fix amendment auto const fixEnabled = env.current()->rules().enabled(fixEmptyDID); - env(did::set(alice), - did::uri(""), - fixEnabled ? ter(tecEMPTY_DID) : ter(tesSUCCESS)); + env(did::set(alice), did::uri(""), fixEnabled ? ter(tecEMPTY_DID) : ter(tesSUCCESS)); env.close(); auto const expectedOwnerReserve = fixEnabled ? 0 : 1; BEAST_EXPECT(ownerCount(env, alice) == expectedOwnerReserve); @@ -231,10 +220,7 @@ struct DID_test : public beast::unit_test::suite BEAST_EXPECT(ownerCount(env, francis) == 1); // URI + DIDDocument + Data - env(did::set(george), - did::uri("uri"), - did::document("data"), - did::data("attest")); + env(did::set(george), did::uri("uri"), did::document("data"), did::data("attest")); BEAST_EXPECT(ownerCount(env, george) == 1); } diff --git a/src/test/app/DNS_test.cpp b/src/test/app/DNS_test.cpp index fc6917e15c..0d41c0f419 100644 --- a/src/test/app/DNS_test.cpp +++ b/src/test/app/DNS_test.cpp @@ -31,14 +31,13 @@ public: void makeRequest(endpoint_type const& lastEndpoint, bool lastStatus) { - auto onFetch = [&](error_code const& errorCode, - endpoint_type const& endpoint, - xrpl::detail::response_type&& resp) { - BEAST_EXPECT(!errorCode); - lastEndpoint_ = endpoint; - resolved_[endpoint.address().to_string()]++; - cv_.notify_all(); - }; + auto onFetch = + [&](error_code const& errorCode, endpoint_type const& endpoint, xrpl::detail::response_type&& resp) { + BEAST_EXPECT(!errorCode); + lastEndpoint_ = endpoint; + resolved_[endpoint.address().to_string()]++; + cv_.notify_all(); + }; auto sp = std::make_shared( pUrl_.domain, @@ -92,8 +91,7 @@ public: for (int i = 1; i <= 4; ++i) { makeRequest(lastEndpoint_, true); - BEAST_EXPECT( - resolved_.size() == 1 && resolved_.begin()->second == i); + BEAST_EXPECT(resolved_.size() == 1 && resolved_.begin()->second == i); } if (!isMultipleEndpoints()) return; diff --git a/src/test/app/Delegate_test.cpp b/src/test/app/Delegate_test.cpp index 4039f60ef0..2207c83148 100644 --- a/src/test/app/Delegate_test.cpp +++ b/src/test/app/Delegate_test.cpp @@ -22,8 +22,7 @@ class Delegate_test : public beast::unit_test::suite env.fund(XRP(1000000), gw, alice, bob); env.close(); - auto res = features[featurePermissionDelegationV1_1] ? ter(tesSUCCESS) - : ter(temDISABLED); + auto res = features[featurePermissionDelegationV1_1] ? ter(tesSUCCESS) : ter(temDISABLED); // can not set Delegate when feature disabled env(delegate::set(gw, alice, {"Payment"}), res); @@ -52,61 +51,42 @@ class Delegate_test : public beast::unit_test::suite auto const entry = delegate::entry(env, gw, alice); BEAST_EXPECT(entry[jss::result][jss::error] == "entryNotFound"); - auto const permissions = std::vector{ - "Payment", - "EscrowCreate", - "EscrowFinish", - "TrustlineAuthorize", - "CheckCreate"}; + auto const permissions = + std::vector{"Payment", "EscrowCreate", "EscrowFinish", "TrustlineAuthorize", "CheckCreate"}; env(delegate::set(gw, alice, permissions)); env.close(); // this lambda function is used to compare the json value of ledger // entry response with the given vector of permissions. - auto comparePermissions = - [&](Json::Value const& jle, - std::vector const& permissions, - Account const& account, - Account const& authorize) { - BEAST_EXPECT( - !jle[jss::result].isMember(jss::error) && - jle[jss::result].isMember(jss::node)); - BEAST_EXPECT( - jle[jss::result][jss::node]["LedgerEntryType"] == - jss::Delegate); - BEAST_EXPECT( - jle[jss::result][jss::node][jss::Account] == - account.human()); - BEAST_EXPECT( - jle[jss::result][jss::node][sfAuthorize.jsonName] == - authorize.human()); + auto comparePermissions = [&](Json::Value const& jle, + std::vector const& permissions, + Account const& account, + Account const& authorize) { + BEAST_EXPECT(!jle[jss::result].isMember(jss::error) && jle[jss::result].isMember(jss::node)); + BEAST_EXPECT(jle[jss::result][jss::node]["LedgerEntryType"] == jss::Delegate); + BEAST_EXPECT(jle[jss::result][jss::node][jss::Account] == account.human()); + BEAST_EXPECT(jle[jss::result][jss::node][sfAuthorize.jsonName] == authorize.human()); - auto const& jPermissions = - jle[jss::result][jss::node][sfPermissions.jsonName]; - unsigned i = 0; - for (auto const& permission : permissions) - { - BEAST_EXPECT( - jPermissions[i][sfPermission.jsonName] - [sfPermissionValue.jsonName] == permission); - i++; - } - }; + auto const& jPermissions = jle[jss::result][jss::node][sfPermissions.jsonName]; + unsigned i = 0; + for (auto const& permission : permissions) + { + BEAST_EXPECT(jPermissions[i][sfPermission.jsonName][sfPermissionValue.jsonName] == permission); + i++; + } + }; // get ledger entry with valid parameter - comparePermissions( - delegate::entry(env, gw, alice), permissions, gw, alice); + comparePermissions(delegate::entry(env, gw, alice), permissions, gw, alice); // gw updates permission - auto const newPermissions = std::vector{ - "Payment", "AMMCreate", "AMMDeposit", "AMMWithdraw"}; + auto const newPermissions = std::vector{"Payment", "AMMCreate", "AMMDeposit", "AMMWithdraw"}; env(delegate::set(gw, alice, newPermissions)); env.close(); // get ledger entry again, permissions should be updated to // newPermissions - comparePermissions( - delegate::entry(env, gw, alice), newPermissions, gw, alice); + comparePermissions(delegate::entry(env, gw, alice), newPermissions, gw, alice); // gw deletes all permissions delegated to alice, this will delete // the @@ -119,8 +99,7 @@ class Delegate_test : public beast::unit_test::suite // alice can delegate permissions to gw as well env(delegate::set(alice, gw, permissions)); env.close(); - comparePermissions( - delegate::entry(env, alice, gw), permissions, alice, gw); + comparePermissions(delegate::entry(env, alice, gw), permissions, alice, gw); auto const response = delegate::entry(env, gw, alice); // alice has not been granted any permissions by gw BEAST_EXPECT(response[jss::result][jss::error] == "entryNotFound"); @@ -199,8 +178,7 @@ class Delegate_test : public beast::unit_test::suite // when authorizing account which does not exist, should return // tecNO_TARGET { - env(delegate::set(gw, Account("unknown"), {"Payment"}), - ter(tecNO_TARGET)); + env(delegate::set(gw, Account("unknown"), {"Payment"}), ter(tecNO_TARGET)); } // non-delegable transaction @@ -209,8 +187,7 @@ class Delegate_test : public beast::unit_test::suite env(delegate::set(gw, alice, {"AccountSet"}), ter(temMALFORMED)); env(delegate::set(gw, alice, {"SignerListSet"}), ter(temMALFORMED)); env(delegate::set(gw, alice, {"DelegateSet"}), ter(temMALFORMED)); - env(delegate::set(gw, alice, {"EnableAmendment"}), - ter(temMALFORMED)); + env(delegate::set(gw, alice, {"EnableAmendment"}), ter(temMALFORMED)); env(delegate::set(gw, alice, {"UNLModify"}), ter(temMALFORMED)); env(delegate::set(gw, alice, {"SetFee"}), ter(temMALFORMED)); env(delegate::set(gw, alice, {"Batch"}), ter(temMALFORMED)); @@ -231,13 +208,11 @@ class Delegate_test : public beast::unit_test::suite Account carol{"carol"}; env.fund(drops(env.current()->fees().accountReserve(0)), alice); - env.fund( - drops(env.current()->fees().accountReserve(1)), bob, carol); + env.fund(drops(env.current()->fees().accountReserve(1)), bob, carol); env.close(); // alice does not have enough reserve to create Delegate - env(delegate::set(alice, bob, {"Payment"}), - ter(tecINSUFFICIENT_RESERVE)); + env(delegate::set(alice, bob, {"Payment"}), ter(tecINSUFFICIENT_RESERVE)); // bob has enough reserve env(delegate::set(bob, alice, {"Payment"})); @@ -245,8 +220,7 @@ class Delegate_test : public beast::unit_test::suite // now bob create another Delegate, he does not have // enough reserve - env(delegate::set(bob, carol, {"Payment"}), - ter(tecINSUFFICIENT_RESERVE)); + env(delegate::set(bob, carol, {"Payment"}), ter(tecINSUFFICIENT_RESERVE)); } // test reserve when sending transaction on behalf of other account @@ -265,10 +239,7 @@ class Delegate_test : public beast::unit_test::suite // bob set DID on behalf of alice, but alice does not have enough // reserve - env(did::set(alice), - did::uri("uri"), - delegate::as(bob), - ter(tecINSUFFICIENT_RESERVE)); + env(did::set(alice), did::uri("uri"), delegate::as(bob), ter(tecINSUFFICIENT_RESERVE)); // bob can set DID for himself because he has enough reserve env(did::set(bob), did::uri("uri")); @@ -295,10 +266,7 @@ class Delegate_test : public beast::unit_test::suite auto bobBalance = env.balance(bob); auto carolBalance = env.balance(carol); - env(pay(alice, carol, XRP(100)), - fee(XRP(2000)), - delegate::as(bob), - ter(terNO_DELEGATE_PERMISSION)); + env(pay(alice, carol, XRP(100)), fee(XRP(2000)), delegate::as(bob), ter(terNO_DELEGATE_PERMISSION)); env.close(); BEAST_EXPECT(env.balance(alice) == aliceBalance); BEAST_EXPECT(env.balance(bob) == bobBalance); @@ -329,10 +297,7 @@ class Delegate_test : public beast::unit_test::suite auto bobBalance = env.balance(bob); auto carolBalance = env.balance(carol); - env(pay(alice, carol, XRP(100)), - fee(XRP(2000)), - delegate::as(bob), - ter(terINSUF_FEE_B)); + env(pay(alice, carol, XRP(100)), fee(XRP(2000)), delegate::as(bob), ter(terINSUF_FEE_B)); env.close(); BEAST_EXPECT(env.balance(alice) == aliceBalance); BEAST_EXPECT(env.balance(bob) == bobBalance); @@ -347,10 +312,7 @@ class Delegate_test : public beast::unit_test::suite auto carolBalance = env.balance(carol); auto const feeAmt = XRP(10); - env(pay(alice, carol, XRP(20000)), - fee(feeAmt), - delegate::as(bob), - ter(tecUNFUNDED_PAYMENT)); + env(pay(alice, carol, XRP(20000)), fee(feeAmt), delegate::as(bob), ter(tecUNFUNDED_PAYMENT)); env.close(); BEAST_EXPECT(env.balance(alice) == aliceBalance); BEAST_EXPECT(env.balance(bob) == bobBalance - feeAmt); @@ -425,8 +387,7 @@ class Delegate_test : public beast::unit_test::suite env(delegate::set(alice, bob, {"Payment"})); env.close(); - BEAST_EXPECT( - env.closed()->exists(keylet::delegate(alice.id(), bob.id()))); + BEAST_EXPECT(env.closed()->exists(keylet::delegate(alice.id(), bob.id()))); for (std::uint32_t i = 0; i < 256; ++i) env.close(); @@ -443,8 +404,7 @@ class Delegate_test : public beast::unit_test::suite BEAST_EXPECT(!env.closed()->exists(keylet::ownerDir(alice.id()))); BEAST_EXPECT(env.balance(bob) == bobBalance + aliceBalance - deleteFee); - BEAST_EXPECT( - !env.closed()->exists(keylet::delegate(alice.id(), bob.id()))); + BEAST_EXPECT(!env.closed()->exists(keylet::delegate(alice.id(), bob.id()))); } void @@ -503,14 +463,10 @@ class Delegate_test : public beast::unit_test::suite env.close(); // bob does not have permission to create check - env(check::create(alice, bob, XRP(10)), - delegate::as(bob), - ter(terNO_DELEGATE_PERMISSION)); + env(check::create(alice, bob, XRP(10)), delegate::as(bob), ter(terNO_DELEGATE_PERMISSION)); // carol does not have permission to create check - env(check::create(alice, bob, XRP(10)), - delegate::as(carol), - ter(terNO_DELEGATE_PERMISSION)); + env(check::create(alice, bob, XRP(10)), delegate::as(carol), ter(terNO_DELEGATE_PERMISSION)); } void @@ -543,9 +499,7 @@ class Delegate_test : public beast::unit_test::suite auto gw2Balance = env.balance(gw2, XRP); // delegate ledger object is not created yet - env(pay(gw, alice, USD(50)), - delegate::as(bob), - ter(terNO_DELEGATE_PERMISSION)); + env(pay(gw, alice, USD(50)), delegate::as(bob), ter(terNO_DELEGATE_PERMISSION)); env.require(balance(bob, bobBalance)); // gw gives bob burn permission @@ -555,9 +509,7 @@ class Delegate_test : public beast::unit_test::suite gwBalance = env.balance(gw, XRP); // bob sends a payment transaction on behalf of gw - env(pay(gw, alice, USD(50)), - delegate::as(bob), - ter(terNO_DELEGATE_PERMISSION)); + env(pay(gw, alice, USD(50)), delegate::as(bob), ter(terNO_DELEGATE_PERMISSION)); env.close(); env.require(balance(bob, bobBalance)); @@ -571,9 +523,7 @@ class Delegate_test : public beast::unit_test::suite gwBalance = env.balance(gw, XRP); // can not send XRP - env(pay(gw, alice, XRP(50)), - delegate::as(bob), - ter(terNO_DELEGATE_PERMISSION)); + env(pay(gw, alice, XRP(50)), delegate::as(bob), ter(terNO_DELEGATE_PERMISSION)); env.close(); env.require(balance(bob, bobBalance)); @@ -658,9 +608,7 @@ class Delegate_test : public beast::unit_test::suite // bob can not mint on behalf of gw because he only has burn // permission - env(pay(gw, alice, USD(50)), - delegate::as(bob), - ter(terNO_DELEGATE_PERMISSION)); + env(pay(gw, alice, USD(50)), delegate::as(bob), ter(terNO_DELEGATE_PERMISSION)); env.close(); env.require(balance(bob, bobBalance)); @@ -767,8 +715,7 @@ class Delegate_test : public beast::unit_test::suite Account const gw{"gateway"}; MPTTester mpt(env, gw, {.holders = {alice, bob}}); - mpt.create( - {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer}); + mpt.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer}); mpt.authorize({.account = alice}); mpt.authorize({.account = bob}); @@ -804,8 +751,7 @@ class Delegate_test : public beast::unit_test::suite // Grant both granular permissions and tx level permission. { - env(delegate::set( - alice, bob, {"PaymentBurn", "PaymentMint", "Payment"})); + env(delegate::set(alice, bob, {"PaymentBurn", "PaymentMint", "Payment"})); env.close(); env(pay(alice, gw, MPT(50)), delegate::as(bob)); BEAST_EXPECT(env.balance(alice, MPT) == aliceMPT - MPT(50)); @@ -838,9 +784,7 @@ class Delegate_test : public beast::unit_test::suite env.close(); // bob can not create trustline on behalf of alice because he only // has unfreeze permission - env(trust(alice, gw["USD"](50)), - delegate::as(bob), - ter(terNO_DELEGATE_PERMISSION)); + env(trust(alice, gw["USD"](50)), delegate::as(bob), ter(terNO_DELEGATE_PERMISSION)); env.close(); // alice creates trustline by herself @@ -852,70 +796,45 @@ class Delegate_test : public beast::unit_test::suite env.close(); // unsupported flags - env(trust(alice, gw["USD"](50), tfSetNoRipple), - delegate::as(bob), - ter(terNO_DELEGATE_PERMISSION)); - env(trust(alice, gw["USD"](50), tfClearNoRipple), - delegate::as(bob), - ter(terNO_DELEGATE_PERMISSION)); - env(trust(gw, gw["USD"](0), alice, tfSetDeepFreeze), - delegate::as(bob), - ter(terNO_DELEGATE_PERMISSION)); - env(trust(gw, gw["USD"](0), alice, tfClearDeepFreeze), - delegate::as(bob), - ter(terNO_DELEGATE_PERMISSION)); + env(trust(alice, gw["USD"](50), tfSetNoRipple), delegate::as(bob), ter(terNO_DELEGATE_PERMISSION)); + env(trust(alice, gw["USD"](50), tfClearNoRipple), delegate::as(bob), ter(terNO_DELEGATE_PERMISSION)); + env(trust(gw, gw["USD"](0), alice, tfSetDeepFreeze), delegate::as(bob), ter(terNO_DELEGATE_PERMISSION)); + env(trust(gw, gw["USD"](0), alice, tfClearDeepFreeze), delegate::as(bob), ter(terNO_DELEGATE_PERMISSION)); env.close(); // supported flags with wrong permission - env(trust(gw, gw["USD"](0), alice, tfSetfAuth), - delegate::as(bob), - ter(terNO_DELEGATE_PERMISSION)); - env(trust(gw, gw["USD"](0), alice, tfSetFreeze), - delegate::as(bob), - ter(terNO_DELEGATE_PERMISSION)); + env(trust(gw, gw["USD"](0), alice, tfSetfAuth), delegate::as(bob), ter(terNO_DELEGATE_PERMISSION)); + env(trust(gw, gw["USD"](0), alice, tfSetFreeze), delegate::as(bob), ter(terNO_DELEGATE_PERMISSION)); env.close(); env(delegate::set(gw, bob, {"TrustlineAuthorize"})); env.close(); - env(trust(gw, gw["USD"](0), alice, tfClearFreeze), - delegate::as(bob), - ter(terNO_DELEGATE_PERMISSION)); + env(trust(gw, gw["USD"](0), alice, tfClearFreeze), delegate::as(bob), ter(terNO_DELEGATE_PERMISSION)); env.close(); // although trustline authorize is granted, bob can not change the // limit number - env(trust(gw, gw["USD"](50), alice, tfSetfAuth), - delegate::as(bob), - ter(terNO_DELEGATE_PERMISSION)); + env(trust(gw, gw["USD"](50), alice, tfSetfAuth), delegate::as(bob), ter(terNO_DELEGATE_PERMISSION)); env.close(); // supported flags with correct permission env(trust(gw, gw["USD"](0), alice, tfSetfAuth), delegate::as(bob)); env.close(); - env(delegate::set( - gw, bob, {"TrustlineAuthorize", "TrustlineFreeze"})); + env(delegate::set(gw, bob, {"TrustlineAuthorize", "TrustlineFreeze"})); env.close(); env(trust(gw, gw["USD"](0), alice, tfSetFreeze), delegate::as(bob)); env.close(); - env(delegate::set( - gw, bob, {"TrustlineAuthorize", "TrustlineUnfreeze"})); + env(delegate::set(gw, bob, {"TrustlineAuthorize", "TrustlineUnfreeze"})); env.close(); - env(trust(gw, gw["USD"](0), alice, tfClearFreeze), - delegate::as(bob)); + env(trust(gw, gw["USD"](0), alice, tfClearFreeze), delegate::as(bob)); env.close(); // but bob can not freeze trustline because he no longer has freeze // permission - env(trust(gw, gw["USD"](0), alice, tfSetFreeze), - delegate::as(bob), - ter(terNO_DELEGATE_PERMISSION)); + env(trust(gw, gw["USD"](0), alice, tfSetFreeze), delegate::as(bob), ter(terNO_DELEGATE_PERMISSION)); // cannot update LimitAmount with granular permission, both high and // low account - env(trust(alice, gw["USD"](100)), - delegate::as(bob), - ter(terNO_DELEGATE_PERMISSION)); - env(trust(gw, alice["USD"](100)), - delegate::as(bob), - ter(terNO_DELEGATE_PERMISSION)); + env(trust(alice, gw["USD"](100)), delegate::as(bob), ter(terNO_DELEGATE_PERMISSION)); + env(trust(gw, alice["USD"](100)), delegate::as(bob), ter(terNO_DELEGATE_PERMISSION)); // can not set QualityIn or QualityOut auto tx = trust(alice, gw["USD"](50)); @@ -956,53 +875,34 @@ class Delegate_test : public beast::unit_test::suite env.close(); // bob does not have permission - env(trust(alice, gw["USD"](50)), - delegate::as(bob), - ter(terNO_DELEGATE_PERMISSION)); - env(delegate::set( - alice, bob, {"TrustlineUnfreeze", "NFTokenCreateOffer"})); + env(trust(alice, gw["USD"](50)), delegate::as(bob), ter(terNO_DELEGATE_PERMISSION)); + env(delegate::set(alice, bob, {"TrustlineUnfreeze", "NFTokenCreateOffer"})); env.close(); // bob still does not have permission - env(trust(alice, gw["USD"](50)), - delegate::as(bob), - ter(terNO_DELEGATE_PERMISSION)); + env(trust(alice, gw["USD"](50)), delegate::as(bob), ter(terNO_DELEGATE_PERMISSION)); // add TrustSet permission and some unrelated permission env(delegate::set( - alice, - bob, - {"TrustlineUnfreeze", - "NFTokenCreateOffer", - "TrustSet", - "AccountTransferRateSet"})); + alice, bob, {"TrustlineUnfreeze", "NFTokenCreateOffer", "TrustSet", "AccountTransferRateSet"})); env.close(); env(trust(alice, gw["USD"](50)), delegate::as(bob)); env.close(); env(delegate::set( - gw, - bob, - {"TrustlineUnfreeze", - "NFTokenCreateOffer", - "TrustSet", - "AccountTransferRateSet"})); + gw, bob, {"TrustlineUnfreeze", "NFTokenCreateOffer", "TrustSet", "AccountTransferRateSet"})); env.close(); // since bob has TrustSet permission, he does not need // TrustlineFreeze granular permission to freeze the trustline env(trust(gw, gw["USD"](0), alice, tfSetFreeze), delegate::as(bob)); - env(trust(gw, gw["USD"](0), alice, tfClearFreeze), - delegate::as(bob)); + env(trust(gw, gw["USD"](0), alice, tfClearFreeze), delegate::as(bob)); // bob can perform all the operations regarding TrustSet env(trust(gw, gw["USD"](0), alice, tfSetFreeze), delegate::as(bob)); - env(trust(gw, gw["USD"](0), alice, tfSetDeepFreeze), - delegate::as(bob)); - env(trust(gw, gw["USD"](0), alice, tfClearDeepFreeze), - delegate::as(bob)); + env(trust(gw, gw["USD"](0), alice, tfSetDeepFreeze), delegate::as(bob)); + env(trust(gw, gw["USD"](0), alice, tfClearDeepFreeze), delegate::as(bob)); env(trust(gw, gw["USD"](0), alice, tfSetfAuth), delegate::as(bob)); env(trust(alice, gw["USD"](50), tfSetNoRipple), delegate::as(bob)); - env(trust(alice, gw["USD"](50), tfClearNoRipple), - delegate::as(bob)); + env(trust(alice, gw["USD"](50), tfClearNoRipple), delegate::as(bob)); } // tfFullyCanonicalSig won't block delegated transaction @@ -1019,9 +919,7 @@ class Delegate_test : public beast::unit_test::suite env(delegate::set(gw, bob, {"TrustlineAuthorize"})); env.close(); - env(trust( - gw, gw["USD"](0), alice, tfSetfAuth | tfFullyCanonicalSig), - delegate::as(bob)); + env(trust(gw, gw["USD"](0), alice, tfSetfAuth | tfFullyCanonicalSig), delegate::as(bob)); } } @@ -1055,8 +953,7 @@ class Delegate_test : public beast::unit_test::suite // add granular permission related to AccountSet but is not the // correct permission for domain set - env(delegate::set( - alice, bob, {"TrustlineUnfreeze", "AccountEmailHashSet"})); + env(delegate::set(alice, bob, {"TrustlineUnfreeze", "AccountEmailHashSet"})); env.close(); env(jt, ter(terNO_DELEGATE_PERMISSION)); @@ -1089,8 +986,7 @@ class Delegate_test : public beast::unit_test::suite env(jt, ter(terNO_DELEGATE_PERMISSION)); // alice give granular permission of AccountEmailHashSet to bob - env(delegate::set( - alice, bob, {"AccountDomainSet", "AccountEmailHashSet"})); + env(delegate::set(alice, bob, {"AccountDomainSet", "AccountEmailHashSet"})); env.close(); env(jt); BEAST_EXPECT(to_string((*env.le(alice))[sfEmailHash]) == mh); @@ -1102,36 +998,24 @@ class Delegate_test : public beast::unit_test::suite env(jt, ter(terNO_DELEGATE_PERMISSION)); // alice give granular permission of AccountMessageKeySet to bob - env(delegate::set( - alice, - bob, - {"AccountDomainSet", - "AccountEmailHashSet", - "AccountMessageKeySet"})); + env(delegate::set(alice, bob, {"AccountDomainSet", "AccountEmailHashSet", "AccountMessageKeySet"})); env.close(); // bob can set message key for alice env(jt); - BEAST_EXPECT( - strHex((*env.le(alice))[sfMessageKey]) == - strHex(rkp.first.slice())); + BEAST_EXPECT(strHex((*env.le(alice))[sfMessageKey]) == strHex(rkp.first.slice())); jt[sfMessageKey] = ""; env(jt); BEAST_EXPECT(!env.le(alice)->isFieldPresent(sfMessageKey)); // bob does not have permission to set transfer rate for alice - env(rate(alice, 2.0), - delegate::as(bob), - ter(terNO_DELEGATE_PERMISSION)); + env(rate(alice, 2.0), delegate::as(bob), ter(terNO_DELEGATE_PERMISSION)); // alice give granular permission of AccountTransferRateSet to bob env(delegate::set( alice, bob, - {"AccountDomainSet", - "AccountEmailHashSet", - "AccountMessageKeySet", - "AccountTransferRateSet"})); + {"AccountDomainSet", "AccountEmailHashSet", "AccountMessageKeySet", "AccountTransferRateSet"})); env.close(); auto jtRate = rate(alice, 2.0); jtRate[sfDelegate] = bob.human(); @@ -1156,18 +1040,14 @@ class Delegate_test : public beast::unit_test::suite BEAST_EXPECT((*env.le(alice))[sfTickSize] == 8); // can not set asfRequireAuth flag for alice - env(fset(alice, asfRequireAuth), - delegate::as(bob), - ter(terNO_DELEGATE_PERMISSION)); + env(fset(alice, asfRequireAuth), delegate::as(bob), ter(terNO_DELEGATE_PERMISSION)); // reset Delegate will delete the Delegate // object env(delegate::set(alice, bob, {})); // bib still does not have permission to set asfRequireAuth for // alice - env(fset(alice, asfRequireAuth), - delegate::as(bob), - ter(terNO_DELEGATE_PERMISSION)); + env(fset(alice, asfRequireAuth), delegate::as(bob), ter(terNO_DELEGATE_PERMISSION)); // alice can set for herself env(fset(alice, asfRequireAuth)); env.require(flags(alice, asfRequireAuth)); @@ -1177,12 +1057,7 @@ class Delegate_test : public beast::unit_test::suite jt[sfTickSize] = 7; env(jt, ter(terNO_DELEGATE_PERMISSION)); - env(delegate::set( - alice, - bob, - {"AccountDomainSet", - "AccountEmailHashSet", - "AccountMessageKeySet"})); + env(delegate::set(alice, bob, {"AccountDomainSet", "AccountEmailHashSet", "AccountMessageKeySet"})); env.close(); // bob does not have permission to set wallet locater for alice @@ -1206,17 +1081,13 @@ class Delegate_test : public beast::unit_test::suite auto testSetClearFlag = [&](std::uint32_t flag) { // bob can not set flag on behalf of alice - env(fset(alice, flag), - delegate::as(bob), - ter(terNO_DELEGATE_PERMISSION)); + env(fset(alice, flag), delegate::as(bob), ter(terNO_DELEGATE_PERMISSION)); // alice set by herself env(fset(alice, flag)); env.close(); env.require(flags(alice, flag)); // bob can not clear on behalf of alice - env(fclear(alice, flag), - delegate::as(bob), - ter(terNO_DELEGATE_PERMISSION)); + env(fclear(alice, flag), delegate::as(bob), ter(terNO_DELEGATE_PERMISSION)); }; // testSetClearFlag(asfNoFreeze); @@ -1224,12 +1095,7 @@ class Delegate_test : public beast::unit_test::suite testSetClearFlag(asfAllowTrustLineClawback); // alice gives some granular permissions to bob - env(delegate::set( - alice, - bob, - {"AccountDomainSet", - "AccountEmailHashSet", - "AccountMessageKeySet"})); + env(delegate::set(alice, bob, {"AccountDomainSet", "AccountEmailHashSet", "AccountMessageKeySet"})); env.close(); testSetClearFlag(asfDefaultRipple); @@ -1243,15 +1109,11 @@ class Delegate_test : public beast::unit_test::suite testSetClearFlag(asfGlobalFreeze); // bob can not set asfAccountTxnID on behalf of alice - env(fset(alice, asfAccountTxnID), - delegate::as(bob), - ter(terNO_DELEGATE_PERMISSION)); + env(fset(alice, asfAccountTxnID), delegate::as(bob), ter(terNO_DELEGATE_PERMISSION)); env(fset(alice, asfAccountTxnID)); env.close(); BEAST_EXPECT(env.le(alice)->isFieldPresent(sfAccountTxnID)); - env(fclear(alice, asfAccountTxnID), - delegate::as(bob), - ter(terNO_DELEGATE_PERMISSION)); + env(fclear(alice, asfAccountTxnID), delegate::as(bob), ter(terNO_DELEGATE_PERMISSION)); // bob can not set asfAuthorizedNFTokenMinter on behalf of alice Json::Value jt = fset(alice, asfAuthorizedNFTokenMinter); @@ -1260,36 +1122,24 @@ class Delegate_test : public beast::unit_test::suite env(jt, ter(terNO_DELEGATE_PERMISSION)); // bob gives alice some permissions - env(delegate::set( - bob, - alice, - {"AccountDomainSet", - "AccountEmailHashSet", - "AccountMessageKeySet"})); + env(delegate::set(bob, alice, {"AccountDomainSet", "AccountEmailHashSet", "AccountMessageKeySet"})); env.close(); // since we can not set asfNoFreeze if asfAllowTrustLineClawback is // set, which can not be clear either. Test alice set asfNoFreeze on // behalf of bob. - env(fset(alice, asfNoFreeze), - delegate::as(bob), - ter(terNO_DELEGATE_PERMISSION)); + env(fset(alice, asfNoFreeze), delegate::as(bob), ter(terNO_DELEGATE_PERMISSION)); env(fset(bob, asfNoFreeze)); env.close(); env.require(flags(bob, asfNoFreeze)); // alice can not clear on behalf of bob - env(fclear(alice, asfNoFreeze), - delegate::as(bob), - ter(terNO_DELEGATE_PERMISSION)); + env(fclear(alice, asfNoFreeze), delegate::as(bob), ter(terNO_DELEGATE_PERMISSION)); // bob can not set asfDisableMaster on behalf of alice Account const bobKey{"bobKey", KeyType::secp256k1}; env(regkey(bob, bobKey)); env.close(); - env(fset(alice, asfDisableMaster), - delegate::as(bob), - sig(bob), - ter(terNO_DELEGATE_PERMISSION)); + env(fset(alice, asfDisableMaster), delegate::as(bob), sig(bob), ter(terNO_DELEGATE_PERMISSION)); } // tfFullyCanonicalSig won't block delegated transaction @@ -1300,8 +1150,7 @@ class Delegate_test : public beast::unit_test::suite env.fund(XRP(10000), alice, bob); env.close(); - env(delegate::set( - alice, bob, {"AccountDomainSet", "AccountEmailHashSet"})); + env(delegate::set(alice, bob, {"AccountDomainSet", "AccountEmailHashSet"})); env.close(); std::string const domain = "example.com"; @@ -1335,34 +1184,21 @@ class Delegate_test : public beast::unit_test::suite env.close(); // delegate ledger object is not created yet - mpt.set( - {.account = alice, - .flags = tfMPTLock, - .delegate = bob, - .err = terNO_DELEGATE_PERMISSION}); + mpt.set({.account = alice, .flags = tfMPTLock, .delegate = bob, .err = terNO_DELEGATE_PERMISSION}); // alice gives granular permission to bob of MPTokenIssuanceUnlock env(delegate::set(alice, bob, {"MPTokenIssuanceUnlock"})); env.close(); // bob does not have lock permission - mpt.set( - {.account = alice, - .flags = tfMPTLock, - .delegate = bob, - .err = terNO_DELEGATE_PERMISSION}); + mpt.set({.account = alice, .flags = tfMPTLock, .delegate = bob, .err = terNO_DELEGATE_PERMISSION}); // bob now has lock permission, but does not have unlock permission env(delegate::set(alice, bob, {"MPTokenIssuanceLock"})); env.close(); mpt.set({.account = alice, .flags = tfMPTLock, .delegate = bob}); - mpt.set( - {.account = alice, - .flags = tfMPTUnlock, - .delegate = bob, - .err = terNO_DELEGATE_PERMISSION}); + mpt.set({.account = alice, .flags = tfMPTUnlock, .delegate = bob, .err = terNO_DELEGATE_PERMISSION}); // now bob can lock and unlock - env(delegate::set( - alice, bob, {"MPTokenIssuanceLock", "MPTokenIssuanceUnlock"})); + env(delegate::set(alice, bob, {"MPTokenIssuanceLock", "MPTokenIssuanceUnlock"})); env.close(); mpt.set({.account = alice, .flags = tfMPTUnlock, .delegate = bob}); mpt.set({.account = alice, .flags = tfMPTLock, .delegate = bob}); @@ -1387,34 +1223,17 @@ class Delegate_test : public beast::unit_test::suite env.close(); mpt.set({.account = alice, .flags = tfMPTLock, .delegate = bob}); // bob does not have unlock permission - mpt.set( - {.account = alice, - .flags = tfMPTUnlock, - .delegate = bob, - .err = terNO_DELEGATE_PERMISSION}); + mpt.set({.account = alice, .flags = tfMPTUnlock, .delegate = bob, .err = terNO_DELEGATE_PERMISSION}); // alice gives bob some unrelated permission with // MPTokenIssuanceLock - env(delegate::set( - alice, - bob, - {"NFTokenMint", "MPTokenIssuanceLock", "NFTokenBurn"})); + env(delegate::set(alice, bob, {"NFTokenMint", "MPTokenIssuanceLock", "NFTokenBurn"})); env.close(); // bob can not unlock - mpt.set( - {.account = alice, - .flags = tfMPTUnlock, - .delegate = bob, - .err = terNO_DELEGATE_PERMISSION}); + mpt.set({.account = alice, .flags = tfMPTUnlock, .delegate = bob, .err = terNO_DELEGATE_PERMISSION}); // alice add MPTokenIssuanceSet to permissions - env(delegate::set( - alice, - bob, - {"NFTokenMint", - "MPTokenIssuanceLock", - "NFTokenBurn", - "MPTokenIssuanceSet"})); + env(delegate::set(alice, bob, {"NFTokenMint", "MPTokenIssuanceLock", "NFTokenBurn", "MPTokenIssuanceSet"})); mpt.set({.account = alice, .flags = tfMPTUnlock, .delegate = bob}); // alice can lock by herself mpt.set({.account = alice, .flags = tfMPTLock}); @@ -1438,10 +1257,7 @@ class Delegate_test : public beast::unit_test::suite // alice gives granular permission to bob of MPTokenIssuanceLock env(delegate::set(alice, bob, {"MPTokenIssuanceLock"})); env.close(); - mpt.set( - {.account = alice, - .flags = tfMPTLock | tfFullyCanonicalSig, - .delegate = bob}); + mpt.set({.account = alice, .flags = tfMPTLock | tfFullyCanonicalSig, .delegate = bob}); } } @@ -1465,10 +1281,7 @@ class Delegate_test : public beast::unit_test::suite auto bobBalance = env.balance(bob); auto carolBalance = env.balance(carol); - env(pay(alice, carol, XRP(100)), - fee(XRP(10)), - delegate::as(bob), - sig(bob)); + env(pay(alice, carol, XRP(100)), fee(XRP(10)), delegate::as(bob), sig(bob)); env.close(); BEAST_EXPECT(env.balance(alice) == aliceBalance - XRP(100)); BEAST_EXPECT(env.balance(bob) == bobBalance - XRP(10)); @@ -1496,11 +1309,7 @@ class Delegate_test : public beast::unit_test::suite auto bobBalance = env.balance(bob); auto carolBalance = env.balance(carol); - env(pay(alice, carol, XRP(100)), - fee(XRP(10)), - delegate::as(bob), - sig(alice), - ter(tefBAD_AUTH)); + env(pay(alice, carol, XRP(100)), fee(XRP(10)), delegate::as(bob), sig(alice), ter(tefBAD_AUTH)); env.close(); BEAST_EXPECT(env.balance(alice) == aliceBalance); BEAST_EXPECT(env.balance(bob) == bobBalance); @@ -1600,10 +1409,7 @@ class Delegate_test : public beast::unit_test::suite auto dariaBalance = env.balance(daria); auto edwardBalance = env.balance(edward); - env(pay(alice, carol, XRP(100)), - fee(XRP(10)), - delegate::as(bob), - msig(daria, edward)); + env(pay(alice, carol, XRP(100)), fee(XRP(10)), delegate::as(bob), msig(daria, edward)); env.close(); BEAST_EXPECT(env.balance(alice) == aliceBalance - XRP(100)); BEAST_EXPECT(env.balance(bob) == bobBalance - XRP(10)); @@ -1640,11 +1446,7 @@ class Delegate_test : public beast::unit_test::suite auto dariaBalance = env.balance(daria); auto edwardBalance = env.balance(edward); - env(pay(alice, carol, XRP(100)), - fee(XRP(10)), - delegate::as(bob), - msig(daria, edward), - ter(tefBAD_QUORUM)); + env(pay(alice, carol, XRP(100)), fee(XRP(10)), delegate::as(bob), msig(daria, edward), ter(tefBAD_QUORUM)); env.close(); BEAST_EXPECT(env.balance(alice) == aliceBalance); BEAST_EXPECT(env.balance(bob) == bobBalance); @@ -1743,8 +1545,7 @@ class Delegate_test : public beast::unit_test::suite // Can not delegate tx if any required feature disabled. { - auto txAmendmentDisabled = [&](FeatureBitset features, - std::string const& tx) { + auto txAmendmentDisabled = [&](FeatureBitset features, std::string const& tx) { BEAST_EXPECT(txRequiredFeatures.contains(tx)); Env env(*this, features - txRequiredFeatures[tx]); diff --git a/src/test/app/DeliverMin_test.cpp b/src/test/app/DeliverMin_test.cpp index c49f83b518..711b29cfa8 100644 --- a/src/test/app/DeliverMin_test.cpp +++ b/src/test/app/DeliverMin_test.cpp @@ -24,25 +24,14 @@ public: env.close(); env.trust(USD(100), "alice", "bob", "carol"); env.close(); - env(pay("alice", "bob", USD(10)), - deliver_min(USD(10)), - ter(temBAD_AMOUNT)); - env(pay("alice", "bob", USD(10)), - deliver_min(USD(-5)), - txflags(tfPartialPayment), - ter(temBAD_AMOUNT)); - env(pay("alice", "bob", USD(10)), - deliver_min(XRP(5)), - txflags(tfPartialPayment), - ter(temBAD_AMOUNT)); + env(pay("alice", "bob", USD(10)), deliver_min(USD(10)), ter(temBAD_AMOUNT)); + env(pay("alice", "bob", USD(10)), deliver_min(USD(-5)), txflags(tfPartialPayment), ter(temBAD_AMOUNT)); + env(pay("alice", "bob", USD(10)), deliver_min(XRP(5)), txflags(tfPartialPayment), ter(temBAD_AMOUNT)); env(pay("alice", "bob", USD(10)), deliver_min(Account("carol")["USD"](5)), txflags(tfPartialPayment), ter(temBAD_AMOUNT)); - env(pay("alice", "bob", USD(10)), - deliver_min(USD(15)), - txflags(tfPartialPayment), - ter(temBAD_AMOUNT)); + env(pay("alice", "bob", USD(10)), deliver_min(USD(15)), txflags(tfPartialPayment), ter(temBAD_AMOUNT)); env(pay(gw, "carol", USD(50))); env(offer("carol", XRP(5), USD(5))); env(pay("alice", "bob", USD(10)), @@ -51,8 +40,7 @@ public: txflags(tfPartialPayment), sendmax(XRP(5)), ter(tecPATH_PARTIAL)); - env.require(balance( - "alice", XRP(10000) - drops(env.current()->fees().base))); + env.require(balance("alice", XRP(10000) - drops(env.current()->fees().base))); env.require(balance("bob", XRP(10000))); } diff --git a/src/test/app/DepositAuth_test.cpp b/src/test/app/DepositAuth_test.cpp index 775d7b1e81..0cd7e7449c 100644 --- a/src/test/app/DepositAuth_test.cpp +++ b/src/test/app/DepositAuth_test.cpp @@ -92,9 +92,7 @@ struct DepositAuth_test : public beast::unit_test::suite // Note that even though alice is paying bob in XRP, the payment // is still not allowed since the payment passes through an offer. - env(pay(alice, bob, drops(1)), - sendmax(USD(1)), - ter(tecNO_PERMISSION)); + env(pay(alice, bob, drops(1)), sendmax(USD(1)), ter(tecNO_PERMISSION)); env.close(); BEAST_EXPECT(bobXrpBalance == env.balance(bob, XRP)); @@ -205,14 +203,12 @@ struct DepositAuth_test : public beast::unit_test::suite // We should be able to pay bob the base reserve one more time. env(pay(alice, bob, reserve(env, 0) + drops(0))); env.close(); - BEAST_EXPECT( - env.balance(bob, XRP) == (reserve(env, 0) + reserve(env, 0))); + BEAST_EXPECT(env.balance(bob, XRP) == (reserve(env, 0) + reserve(env, 0))); // bob's above the threshold again. Any payment should fail. env(pay(alice, bob, drops(1)), ter(tecNO_PERMISSION)); env.close(); - BEAST_EXPECT( - env.balance(bob, XRP) == (reserve(env, 0) + reserve(env, 0))); + BEAST_EXPECT(env.balance(bob, XRP) == (reserve(env, 0) + reserve(env, 0))); // Take bob back down to a zero XRP balance. env(noop(bob), fee(env.balance(bob, XRP))); @@ -262,50 +258,41 @@ struct DepositAuth_test : public beast::unit_test::suite IOU const USD1(gw1["USD"]); IOU const USD2(gw2["USD"]); - auto testIssuer = [&](FeatureBitset const& features, - bool noRipplePrev, - bool noRippleNext, - bool withDepositAuth) { - Env env(*this, features); + auto testIssuer = + [&](FeatureBitset const& features, bool noRipplePrev, bool noRippleNext, bool withDepositAuth) { + Env env(*this, features); - env.fund(XRP(10000), gw1, alice, bob); - env.close(); - env(trust(gw1, alice["USD"](10), noRipplePrev ? tfSetNoRipple : 0)); - env(trust(gw1, bob["USD"](10), noRippleNext ? tfSetNoRipple : 0)); - env.trust(USD1(10), alice, bob); + env.fund(XRP(10000), gw1, alice, bob); + env.close(); + env(trust(gw1, alice["USD"](10), noRipplePrev ? tfSetNoRipple : 0)); + env(trust(gw1, bob["USD"](10), noRippleNext ? tfSetNoRipple : 0)); + env.trust(USD1(10), alice, bob); - env(pay(gw1, alice, USD1(10))); + env(pay(gw1, alice, USD1(10))); - if (withDepositAuth) - env(fset(gw1, asfDepositAuth)); + if (withDepositAuth) + env(fset(gw1, asfDepositAuth)); - TER const result = (noRippleNext && noRipplePrev) ? TER{tecPATH_DRY} - : TER{tesSUCCESS}; - env(pay(alice, bob, USD1(10)), path(gw1), ter(result)); - }; + TER const result = (noRippleNext && noRipplePrev) ? TER{tecPATH_DRY} : TER{tesSUCCESS}; + env(pay(alice, bob, USD1(10)), path(gw1), ter(result)); + }; - auto testNonIssuer = [&](FeatureBitset const& features, - bool noRipplePrev, - bool noRippleNext, - bool withDepositAuth) { - Env env(*this, features); + auto testNonIssuer = + [&](FeatureBitset const& features, bool noRipplePrev, bool noRippleNext, bool withDepositAuth) { + Env env(*this, features); - env.fund(XRP(10000), gw1, gw2, alice); - env.close(); - env(trust(alice, USD1(10), noRipplePrev ? tfSetNoRipple : 0)); - env(trust(alice, USD2(10), noRippleNext ? tfSetNoRipple : 0)); - env(pay(gw2, alice, USD2(10))); + env.fund(XRP(10000), gw1, gw2, alice); + env.close(); + env(trust(alice, USD1(10), noRipplePrev ? tfSetNoRipple : 0)); + env(trust(alice, USD2(10), noRippleNext ? tfSetNoRipple : 0)); + env(pay(gw2, alice, USD2(10))); - if (withDepositAuth) - env(fset(alice, asfDepositAuth)); + if (withDepositAuth) + env(fset(alice, asfDepositAuth)); - TER const result = (noRippleNext && noRipplePrev) ? TER{tecPATH_DRY} - : TER{tesSUCCESS}; - env(pay(gw1, gw2, USD2(10)), - path(alice), - sendmax(USD1(10)), - ter(result)); - }; + TER const result = (noRippleNext && noRipplePrev) ? TER{tecPATH_DRY} : TER{tesSUCCESS}; + env(pay(gw1, gw2, USD2(10)), path(alice), sendmax(USD1(10)), ter(result)); + }; // Test every combo of noRipplePrev, noRippleNext, and withDepositAuth for (int i = 0; i < 8; ++i) @@ -313,17 +300,9 @@ struct DepositAuth_test : public beast::unit_test::suite auto const noRipplePrev = i & 0x1; auto const noRippleNext = i & 0x2; auto const withDepositAuth = i & 0x4; - testIssuer( - testable_amendments(), - noRipplePrev, - noRippleNext, - withDepositAuth); + testIssuer(testable_amendments(), noRipplePrev, noRippleNext, withDepositAuth); - testNonIssuer( - testable_amendments(), - noRipplePrev, - noRippleNext, - withDepositAuth); + testNonIssuer(testable_amendments(), noRipplePrev, noRippleNext, withDepositAuth); } } @@ -346,8 +325,7 @@ ledgerEntryDepositPreauth( Json::Value jvParams; jvParams[jss::ledger_index] = jss::validated; jvParams[jss::deposit_preauth][jss::owner] = acc.human(); - jvParams[jss::deposit_preauth][jss::authorized_credentials] = - Json::arrayValue; + jvParams[jss::deposit_preauth][jss::authorized_credentials] = Json::arrayValue; auto& arr(jvParams[jss::deposit_preauth][jss::authorized_credentials]); for (auto const& o : auth) { @@ -564,8 +542,7 @@ struct DepositPreauth_test : public beast::unit_test::suite env(pay(gw, alice, USD(500))); env.close(); - env(offer(alice, XRP(100), USD(100), tfPassive), - require(offers(alice, 1))); + env(offer(alice, XRP(100), USD(100), tfPassive), require(offers(alice, 1))); env.close(); // becky pays herself USD (10) by consuming part of alice's offer. @@ -578,10 +555,7 @@ struct DepositPreauth_test : public beast::unit_test::suite env.close(); // becky pays herself again. - env(pay(becky, becky, USD(10)), - path(~USD), - sendmax(XRP(10)), - ter(tesSUCCESS)); + env(pay(becky, becky, USD(10)), path(~USD), sendmax(XRP(10)), ter(tesSUCCESS)); env.close(); { @@ -593,11 +567,9 @@ struct DepositPreauth_test : public beast::unit_test::suite bool const supportsCredentials = features[featureCredentials]; - TER const expectTer( - !supportsCredentials ? TER(temDISABLED) : TER(tesSUCCESS)); + TER const expectTer(!supportsCredentials ? TER(temDISABLED) : TER(tesSUCCESS)); - env(deposit::authCredentials(becky, {{carol, credType}}), - ter(expectTer)); + env(deposit::authCredentials(becky, {{carol, credType}}), ter(expectTer)); env.close(); // gw accept credentials @@ -612,9 +584,7 @@ struct DepositPreauth_test : public beast::unit_test::suite : "48004829F915654A81B11C4AB8218D96FED67F209B58328A72314FB6" "EA288BE4"; - env(pay(gw, becky, USD(100)), - credentials::ids({credIdx}), - ter(expectTer)); + env(pay(gw, becky, USD(100)), credentials::ids({credIdx}), ter(expectTer)); env.close(); } } @@ -729,8 +699,7 @@ struct DepositPreauth_test : public beast::unit_test::suite env.close(); // Setup DepositPreauth object failed - amendent is not supported - env(deposit::authCredentials(bob, {{issuer, credType}}), - ter(temDISABLED)); + env(deposit::authCredentials(bob, {{issuer, credType}}), ter(temDISABLED)); env.close(); // But can create old DepositPreauth @@ -742,9 +711,7 @@ struct DepositPreauth_test : public beast::unit_test::suite std::string const invalidIdx = "0E0B04ED60588A758B67E21FBBE95AC5A63598BA951761DC0EC9C08D7E" "01E034"; - env(pay(alice, bob, XRP(10)), - credentials::ids({invalidIdx}), - ter(temDISABLED)); + env(pay(alice, bob, XRP(10)), credentials::ids({invalidIdx}), ter(temDISABLED)); env.close(); } @@ -761,8 +728,7 @@ struct DepositPreauth_test : public beast::unit_test::suite env.close(); // Get the index of the credentials - auto const jv = - credentials::ledgerEntry(env, alice, issuer, credType); + auto const jv = credentials::ledgerEntry(env, alice, issuer, credType); std::string const credIdx = jv[jss::result][jss::index].asString(); // Bob require pre-authorization @@ -774,15 +740,11 @@ struct DepositPreauth_test : public beast::unit_test::suite env(deposit::authCredentials(bob, {{issuer, credType}})); env.close(); - auto const jDP = - ledgerEntryDepositPreauth(env, bob, {{issuer, credType}}); + auto const jDP = ledgerEntryDepositPreauth(env, bob, {{issuer, credType}}); BEAST_EXPECT( - jDP.isObject() && jDP.isMember(jss::result) && - !jDP[jss::result].isMember(jss::error) && - jDP[jss::result].isMember(jss::node) && - jDP[jss::result][jss::node].isMember("LedgerEntryType") && - jDP[jss::result][jss::node]["LedgerEntryType"] == - jss::DepositPreauth); + jDP.isObject() && jDP.isMember(jss::result) && !jDP[jss::result].isMember(jss::error) && + jDP[jss::result].isMember(jss::node) && jDP[jss::result][jss::node].isMember("LedgerEntryType") && + jDP[jss::result][jss::node]["LedgerEntryType"] == jss::DepositPreauth); // Alice can't pay - empty credentials array { @@ -793,9 +755,7 @@ struct DepositPreauth_test : public beast::unit_test::suite } // Alice can't pay - not accepted credentials - env(pay(alice, bob, XRP(100)), - credentials::ids({credIdx}), - ter(tecBAD_CREDENTIALS)); + env(pay(alice, bob, XRP(100)), credentials::ids({credIdx}), ter(tecBAD_CREDENTIALS)); env.close(); // Alice accept the credentials @@ -833,8 +793,7 @@ struct DepositPreauth_test : public beast::unit_test::suite env(credentials::accept(alice, issuer, credType)); env.close(); // Get the index of the credentials - auto const jv = - credentials::ledgerEntry(env, alice, issuer, credType); + auto const jv = credentials::ledgerEntry(env, alice, issuer, credType); std::string const credIdx = jv[jss::result][jss::index].asString(); { @@ -849,15 +808,11 @@ struct DepositPreauth_test : public beast::unit_test::suite { // Fail as destination didn't setup DepositPreauth object - env(pay(alice, bob, XRP(100)), - credentials::ids({credIdx}), - ter(tecNO_PERMISSION)); + env(pay(alice, bob, XRP(100)), credentials::ids({credIdx}), ter(tecNO_PERMISSION)); } // Bob setup DepositPreauth object, duplicates is not allowed - env(deposit::authCredentials( - bob, {{issuer, credType}, {issuer, credType}}), - ter(temMALFORMED)); + env(deposit::authCredentials(bob, {{issuer, credType}, {issuer, credType}}), ter(temMALFORMED)); // Bob setup DepositPreauth object env(deposit::authCredentials(bob, {{issuer, credType}})); @@ -868,16 +823,12 @@ struct DepositPreauth_test : public beast::unit_test::suite "0E0B04ED60588A758B67E21FBBE95AC5A63598BA951761DC0EC9C08D7E" "01E034"; // Alice can't pay with non-existing credentials - env(pay(alice, bob, XRP(100)), - credentials::ids({invalidIdx}), - ter(tecBAD_CREDENTIALS)); + env(pay(alice, bob, XRP(100)), credentials::ids({invalidIdx}), ter(tecBAD_CREDENTIALS)); } { // maria can't pay using valid credentials but issued for // different account - env(pay(maria, bob, XRP(100)), - credentials::ids({credIdx}), - ter(tecBAD_CREDENTIALS)); + env(pay(maria, bob, XRP(100)), credentials::ids({credIdx}), ter(tecBAD_CREDENTIALS)); } { @@ -887,21 +838,15 @@ struct DepositPreauth_test : public beast::unit_test::suite env.close(); env(credentials::accept(alice, issuer, credType2)); env.close(); - auto const jv = - credentials::ledgerEntry(env, alice, issuer, credType2); - std::string const credIdx2 = - jv[jss::result][jss::index].asString(); + auto const jv = credentials::ledgerEntry(env, alice, issuer, credType2); + std::string const credIdx2 = jv[jss::result][jss::index].asString(); // Alice can't pay with invalid set of valid credentials - env(pay(alice, bob, XRP(100)), - credentials::ids({credIdx, credIdx2}), - ter(tecNO_PERMISSION)); + env(pay(alice, bob, XRP(100)), credentials::ids({credIdx, credIdx2}), ter(tecNO_PERMISSION)); } // Error, duplicate credentials - env(pay(alice, bob, XRP(100)), - credentials::ids({credIdx, credIdx}), - ter(temMALFORMED)); + env(pay(alice, bob, XRP(100)), credentials::ids({credIdx, credIdx}), ter(temMALFORMED)); // Alice can pay env(pay(alice, bob, XRP(100)), credentials::ids({credIdx})); @@ -975,8 +920,7 @@ struct DepositPreauth_test : public beast::unit_test::suite auto& arr(jv[sfAuthorizeCredentials.jsonName]); Json::Value cred = Json::objectValue; cred[jss::Issuer] = to_string(xrpAccount()); - cred[sfCredentialType.jsonName] = - strHex(std::string_view(credType)); + cred[sfCredentialType.jsonName] = strHex(std::string_view(credType)); Json::Value credParent; credParent[jss::Credential] = cred; arr.append(std::move(credParent)); @@ -992,20 +936,10 @@ struct DepositPreauth_test : public beast::unit_test::suite { // AuthorizeCredentials is larger than 8 elements - Account const a("a"), b("b"), c("c"), d("d"), e("e"), f("f"), - g("g"), h("h"), i("i"); + Account const a("a"), b("b"), c("c"), d("d"), e("e"), f("f"), g("g"), h("h"), i("i"); auto const& z = credType; auto jv = deposit::authCredentials( - bob, - {{a, z}, - {b, z}, - {c, z}, - {d, z}, - {e, z}, - {f, z}, - {g, z}, - {h, z}, - {i, z}}); + bob, {{a, z}, {b, z}, {c, z}, {d, z}, {e, z}, {f, z}, {g, z}, {h, z}, {i, z}}); env(jv, ter(temARRAY_TOO_LARGE)); } @@ -1028,8 +962,7 @@ struct DepositPreauth_test : public beast::unit_test::suite { // NO deposit object exists - env(deposit::unauthCredentials(bob, {{issuer, credType}}), - ter(tecNO_ENTRY)); + env(deposit::unauthCredentials(bob, {{issuer, credType}}), ter(tecNO_ENTRY)); } // Create DepositPreauth object @@ -1037,45 +970,34 @@ struct DepositPreauth_test : public beast::unit_test::suite env(deposit::authCredentials(bob, {{issuer, credType}})); env.close(); - auto const jDP = - ledgerEntryDepositPreauth(env, bob, {{issuer, credType}}); + auto const jDP = ledgerEntryDepositPreauth(env, bob, {{issuer, credType}}); BEAST_EXPECT( - jDP.isObject() && jDP.isMember(jss::result) && - !jDP[jss::result].isMember(jss::error) && - jDP[jss::result].isMember(jss::node) && - jDP[jss::result][jss::node].isMember("LedgerEntryType") && - jDP[jss::result][jss::node]["LedgerEntryType"] == - jss::DepositPreauth); + jDP.isObject() && jDP.isMember(jss::result) && !jDP[jss::result].isMember(jss::error) && + jDP[jss::result].isMember(jss::node) && jDP[jss::result][jss::node].isMember("LedgerEntryType") && + jDP[jss::result][jss::node]["LedgerEntryType"] == jss::DepositPreauth); // Check object fields - BEAST_EXPECT( - jDP[jss::result][jss::node][jss::Account] == bob.human()); - auto const& credentials( - jDP[jss::result][jss::node]["AuthorizeCredentials"]); + BEAST_EXPECT(jDP[jss::result][jss::node][jss::Account] == bob.human()); + auto const& credentials(jDP[jss::result][jss::node]["AuthorizeCredentials"]); BEAST_EXPECT(credentials.isArray() && credentials.size() == 1); for (auto const& o : credentials) { auto const& c(o[jss::Credential]); BEAST_EXPECT(c[jss::Issuer].asString() == issuer.human()); - BEAST_EXPECT( - c["CredentialType"].asString() == - strHex(std::string_view(credType))); + BEAST_EXPECT(c["CredentialType"].asString() == strHex(std::string_view(credType))); } // can't create duplicate - env(deposit::authCredentials(bob, {{issuer, credType}}), - ter(tecDUPLICATE)); + env(deposit::authCredentials(bob, {{issuer, credType}}), ter(tecDUPLICATE)); } // Delete DepositPreauth object { env(deposit::unauthCredentials(bob, {{issuer, credType}})); env.close(); - auto const jDP = - ledgerEntryDepositPreauth(env, bob, {{issuer, credType}}); + auto const jDP = ledgerEntryDepositPreauth(env, bob, {{issuer, credType}}); BEAST_EXPECT( - jDP.isObject() && jDP.isMember(jss::result) && - jDP[jss::result].isMember(jss::error) && + jDP.isObject() && jDP.isMember(jss::result) && jDP[jss::result].isMember(jss::error) && jDP[jss::result][jss::error] == "entryNotFound"); } } @@ -1106,11 +1028,7 @@ struct DepositPreauth_test : public beast::unit_test::suite auto jv = credentials::create(alice, issuer, credType); // Current time in ripple epoch. // Every time ledger close, unittest timer increase by 10s - uint32_t const t = env.current() - ->header() - .parentCloseTime.time_since_epoch() - .count() + - 60; + uint32_t const t = env.current()->header().parentCloseTime.time_since_epoch().count() + 60; jv[sfExpiration.jsonName] = t; env(jv); env.close(); @@ -1121,11 +1039,7 @@ struct DepositPreauth_test : public beast::unit_test::suite // Create credential which not expired jv = credentials::create(alice, issuer, credType2); - uint32_t const t2 = env.current() - ->header() - .parentCloseTime.time_since_epoch() - .count() + - 1000; + uint32_t const t2 = env.current()->header().parentCloseTime.time_since_epoch().count() + 1000; jv[sfExpiration.jsonName] = t2; env(jv); env.close(); @@ -1145,27 +1059,22 @@ struct DepositPreauth_test : public beast::unit_test::suite env(fset(bob, asfDepositAuth)); env.close(); // Bob setup DepositPreauth object - env(deposit::authCredentials( - bob, {{issuer, credType}, {issuer, credType2}})); + env(deposit::authCredentials(bob, {{issuer, credType}, {issuer, credType2}})); env.close(); { // Alice can pay - env(pay(alice, bob, XRP(100)), - credentials::ids({credIdx, credIdx2})); + env(pay(alice, bob, XRP(100)), credentials::ids({credIdx, credIdx2})); env.close(); env.close(); // Ledger closed, time increased, alice can't pay anymore - env(pay(alice, bob, XRP(100)), - credentials::ids({credIdx, credIdx2}), - ter(tecEXPIRED)); + env(pay(alice, bob, XRP(100)), credentials::ids({credIdx, credIdx2}), ter(tecEXPIRED)); env.close(); { // check that expired credentials were deleted - auto const jDelCred = - credentials::ledgerEntry(env, alice, issuer, credType); + auto const jDelCred = credentials::ledgerEntry(env, alice, issuer, credType); BEAST_EXPECT( jDelCred.isObject() && jDelCred.isMember(jss::result) && jDelCred[jss::result].isMember(jss::error) && @@ -1174,22 +1083,15 @@ struct DepositPreauth_test : public beast::unit_test::suite { // check that non-expired credential still present - auto const jle = - credentials::ledgerEntry(env, alice, issuer, credType2); + auto const jle = credentials::ledgerEntry(env, alice, issuer, credType2); BEAST_EXPECT( - jle.isObject() && jle.isMember(jss::result) && - !jle[jss::result].isMember(jss::error) && + jle.isObject() && jle.isMember(jss::result) && !jle[jss::result].isMember(jss::error) && jle[jss::result].isMember(jss::node) && - jle[jss::result][jss::node].isMember( - "LedgerEntryType") && - jle[jss::result][jss::node]["LedgerEntryType"] == - jss::Credential && - jle[jss::result][jss::node][jss::Issuer] == - issuer.human() && - jle[jss::result][jss::node][jss::Subject] == - alice.human() && - jle[jss::result][jss::node]["CredentialType"] == - strHex(std::string_view(credType2))); + jle[jss::result][jss::node].isMember("LedgerEntryType") && + jle[jss::result][jss::node]["LedgerEntryType"] == jss::Credential && + jle[jss::result][jss::node][jss::Issuer] == issuer.human() && + jle[jss::result][jss::node][jss::Subject] == alice.human() && + jle[jss::result][jss::node]["CredentialType"] == strHex(std::string_view(credType2))); } BEAST_EXPECT(ownerCount(env, issuer) == 0); @@ -1198,11 +1100,7 @@ struct DepositPreauth_test : public beast::unit_test::suite { auto jv = credentials::create(gw, issuer, credType); - uint32_t const t = env.current() - ->header() - .parentCloseTime.time_since_epoch() - .count() + - 40; + uint32_t const t = env.current()->header().parentCloseTime.time_since_epoch().count() + 40; jv[sfExpiration.jsonName] = t; env(jv); env.close(); @@ -1210,8 +1108,7 @@ struct DepositPreauth_test : public beast::unit_test::suite env.close(); jv = credentials::ledgerEntry(env, gw, issuer, credType); - std::string const credIdx = - jv[jss::result][jss::index].asString(); + std::string const credIdx = jv[jss::result][jss::index].asString(); BEAST_EXPECT(ownerCount(env, issuer) == 0); BEAST_EXPECT(ownerCount(env, gw) == 1); @@ -1221,18 +1118,14 @@ struct DepositPreauth_test : public beast::unit_test::suite env.close(); // credentials are expired - env(pay(gw, bob, USD(150)), - credentials::ids({credIdx}), - ter(tecEXPIRED)); + env(pay(gw, bob, USD(150)), credentials::ids({credIdx}), ter(tecEXPIRED)); env.close(); // check that expired credentials were deleted - auto const jDelCred = - credentials::ledgerEntry(env, gw, issuer, credType); + auto const jDelCred = credentials::ledgerEntry(env, gw, issuer, credType); BEAST_EXPECT( jDelCred.isObject() && jDelCred.isMember(jss::result) && - jDelCred[jss::result].isMember(jss::error) && - jDelCred[jss::result][jss::error] == "entryNotFound"); + jDelCred[jss::result].isMember(jss::error) && jDelCred[jss::result][jss::error] == "entryNotFound"); BEAST_EXPECT(ownerCount(env, issuer) == 0); BEAST_EXPECT(ownerCount(env, gw) == 0); @@ -1251,11 +1144,7 @@ struct DepositPreauth_test : public beast::unit_test::suite // Create credentials auto jv = credentials::create(zelda, issuer, credType); - uint32_t const t = env.current() - ->header() - .parentCloseTime.time_since_epoch() - .count() + - 50; + uint32_t const t = env.current()->header().parentCloseTime.time_since_epoch().count() + 50; jv[sfExpiration.jsonName] = t; env(jv); env.close(); @@ -1276,15 +1165,12 @@ struct DepositPreauth_test : public beast::unit_test::suite env.close(); auto const seq = env.seq(alice); - env(escrow::create(alice, bob, XRP(1000)), - escrow::finish_time(env.now() + 1s)); + env(escrow::create(alice, bob, XRP(1000)), escrow::finish_time(env.now() + 1s)); env.close(); // zelda can't finish escrow with invalid credentials { - env(escrow::finish(zelda, alice, seq), - credentials::ids({}), - ter(temMALFORMED)); + env(escrow::finish(zelda, alice, seq), credentials::ids({}), ter(temMALFORMED)); env.close(); } @@ -1294,26 +1180,19 @@ struct DepositPreauth_test : public beast::unit_test::suite "0E0B04ED60588A758B67E21FBBE95AC5A63598BA951761DC0EC9C08D7E" "01E034"; - env(escrow::finish(zelda, alice, seq), - credentials::ids({invalidIdx}), - ter(tecBAD_CREDENTIALS)); + env(escrow::finish(zelda, alice, seq), credentials::ids({invalidIdx}), ter(tecBAD_CREDENTIALS)); env.close(); } { // Ledger closed, time increased, zelda can't finish escrow - env(escrow::finish(zelda, alice, seq), - credentials::ids({credIdx}), - fee(1500), - ter(tecEXPIRED)); + env(escrow::finish(zelda, alice, seq), credentials::ids({credIdx}), fee(1500), ter(tecEXPIRED)); env.close(); } // check that expired credentials were deleted - auto const jDelCred = - credentials::ledgerEntry(env, zelda, issuer, credType); + auto const jDelCred = credentials::ledgerEntry(env, zelda, issuer, credType); BEAST_EXPECT( - jDelCred.isObject() && jDelCred.isMember(jss::result) && - jDelCred[jss::result].isMember(jss::error) && + jDelCred.isObject() && jDelCred.isMember(jss::result) && jDelCred[jss::result].isMember(jss::error) && jDelCred[jss::result][jss::error] == "entryNotFound"); } } @@ -1334,14 +1213,7 @@ struct DepositPreauth_test : public beast::unit_test::suite env.fund(XRP(5000), stock, alice, bob); std::vector credentials = { - {"a", "a"}, - {"b", "b"}, - {"c", "c"}, - {"d", "d"}, - {"e", "e"}, - {"f", "f"}, - {"g", "g"}, - {"h", "h"}}; + {"a", "a"}, {"b", "b"}, {"c", "c"}, {"d", "d"}, {"e", "e"}, {"f", "f"}, {"g", "g"}, {"h", "h"}}; for (auto const& c : credentials) env.fund(XRP(5000), c.issuer); @@ -1362,26 +1234,20 @@ struct DepositPreauth_test : public beast::unit_test::suite env(deposit::authCredentials(stock, credentials)); env.close(); - auto const dp = - ledgerEntryDepositPreauth(env, stock, credentials); - auto const& authCred( - dp[jss::result][jss::node]["AuthorizeCredentials"]); - BEAST_EXPECT( - authCred.isArray() && - authCred.size() == credentials.size()); - std::vector> readedCreds; + auto const dp = ledgerEntryDepositPreauth(env, stock, credentials); + auto const& authCred(dp[jss::result][jss::node]["AuthorizeCredentials"]); + BEAST_EXPECT(authCred.isArray() && authCred.size() == credentials.size()); + std::vector> readCreds; for (auto const& o : authCred) { auto const& c(o[jss::Credential]); auto issuer = c[jss::Issuer].asString(); if (BEAST_EXPECT(pubKey2Acc.contains(issuer))) - readedCreds.emplace_back( - pubKey2Acc.at(issuer), - c["CredentialType"].asString()); + readCreds.emplace_back(pubKey2Acc.at(issuer), c["CredentialType"].asString()); } - BEAST_EXPECT(std::ranges::is_sorted(readedCreds)); + BEAST_EXPECT(std::ranges::is_sorted(readCreds)); env(deposit::unauthCredentials(stock, credentials)); env.close(); @@ -1397,24 +1263,21 @@ struct DepositPreauth_test : public beast::unit_test::suite for (int i = 0; i < 10; ++i) { std::ranges::shuffle(credentials, gen); - env(deposit::authCredentials(stock, credentials), - ter(tecDUPLICATE)); + env(deposit::authCredentials(stock, credentials), ter(tecDUPLICATE)); } } testcase("Check duplicate credentials."); { // check duplicates in depositPreauth params - std::vector copyCredentials( - credentials.begin(), credentials.end() - 1); + std::vector copyCredentials(credentials.begin(), credentials.end() - 1); std::ranges::shuffle(copyCredentials, gen); for (auto const& c : copyCredentials) { auto credentials2 = copyCredentials; credentials2.push_back(c); - env(deposit::authCredentials(stock, credentials2), - ter(temMALFORMED)); + env(deposit::authCredentials(stock, credentials2), ter(temMALFORMED)); } // create batch of credentials and save their hashes @@ -1426,12 +1289,8 @@ struct DepositPreauth_test : public beast::unit_test::suite env(credentials::accept(alice, c.issuer, c.credType)); env.close(); - credentialIDs.push_back(credentials::ledgerEntry( - env, - alice, - c.issuer, - c.credType)[jss::result][jss::index] - .asString()); + credentialIDs.push_back( + credentials::ledgerEntry(env, alice, c.issuer, c.credType)[jss::result][jss::index].asString()); } // check duplicates in payment params @@ -1440,9 +1299,7 @@ struct DepositPreauth_test : public beast::unit_test::suite auto credentialIDs2 = credentialIDs; credentialIDs2.push_back(h); - env(pay(alice, bob, XRP(100)), - credentials::ids(credentialIDs2), - ter(temMALFORMED)); + env(pay(alice, bob, XRP(100)), credentials::ids(credentialIDs2), ter(temMALFORMED)); } } } diff --git a/src/test/app/Discrepancy_test.cpp b/src/test/app/Discrepancy_test.cpp index 0e96f3aa1a..b56cb5b7c6 100644 --- a/src/test/app/Discrepancy_test.cpp +++ b/src/test/app/Discrepancy_test.cpp @@ -69,20 +69,14 @@ class Discrepancy_test : public beast::unit_test::suite env.close(); test::PathSet payPaths{ - test::Path{A2["JPY"], A2}, - test::Path{XRP, A2["JPY"], A2}, - test::Path{A6, XRP, A2["JPY"], A2}}; + test::Path{A2["JPY"], A2}, test::Path{XRP, A2["JPY"], A2}, test::Path{A6, XRP, A2["JPY"], A2}}; - env(pay(A1, A1, A2["JPY"](1000)), - json(payPaths.json()), - txflags(tfPartialPayment), - sendmax(A3["CNY"](56))); + env(pay(A1, A1, A2["JPY"](1000)), json(payPaths.json()), txflags(tfPartialPayment), sendmax(A3["CNY"](56))); env.close(); Json::Value jrq2; jrq2[jss::binary] = false; - jrq2[jss::transaction] = - env.tx()->getJson(JsonOptions::none)[jss::hash]; + jrq2[jss::transaction] = env.tx()->getJson(JsonOptions::none)[jss::hash]; jrq2[jss::id] = 3; auto jrr = env.rpc("json", "tx", to_string(jrq2))[jss::result]; uint64_t fee{jrr[jss::Fee].asUInt()}; @@ -102,19 +96,14 @@ class Discrepancy_test : public beast::unit_test::suite if (node && node[sfLedgerEntryType.fieldName] == jss::AccountRoot) { - Json::Value prevFields = - node.isMember(sfPreviousFields.fieldName) - ? node[sfPreviousFields.fieldName] - : node[sfNewFields.fieldName]; - Json::Value finalFields = node.isMember(sfFinalFields.fieldName) - ? node[sfFinalFields.fieldName] - : node[sfNewFields.fieldName]; + Json::Value prevFields = node.isMember(sfPreviousFields.fieldName) ? node[sfPreviousFields.fieldName] + : node[sfNewFields.fieldName]; + Json::Value finalFields = node.isMember(sfFinalFields.fieldName) ? node[sfFinalFields.fieldName] + : node[sfNewFields.fieldName]; if (prevFields) - sumPrev += beast::lexicalCastThrow( - prevFields[sfBalance.fieldName].asString()); + sumPrev += beast::lexicalCastThrow(prevFields[sfBalance.fieldName].asString()); if (finalFields) - sumFinal += beast::lexicalCastThrow( - finalFields[sfBalance.fieldName].asString()); + sumFinal += beast::lexicalCastThrow(finalFields[sfBalance.fieldName].asString()); } } // the difference in balances (final and prev) should be the diff --git a/src/test/app/EscrowToken_test.cpp b/src/test/app/EscrowToken_test.cpp index 589a8b474e..1f3b3bab70 100644 --- a/src/test/app/EscrowToken_test.cpp +++ b/src/test/app/EscrowToken_test.cpp @@ -19,10 +19,7 @@ namespace test { struct EscrowToken_test : public beast::unit_test::suite { static uint64_t - mptEscrowed( - jtx::Env const& env, - jtx::Account const& account, - jtx::MPT const& mpt) + mptEscrowed(jtx::Env const& env, jtx::Account const& account, jtx::MPT const& mpt) { auto const sle = env.le(keylet::mptoken(mpt.mpt(), account)); if (sle && sle->isFieldPresent(sfLockedAmount)) @@ -40,17 +37,13 @@ struct EscrowToken_test : public beast::unit_test::suite } jtx::PrettyAmount - issuerBalance( - jtx::Env& env, - jtx::Account const& account, - Issue const& issue) + issuerBalance(jtx::Env& env, jtx::Account const& account, Issue const& issue) { Json::Value params; params[jss::account] = account.human(); auto jrr = env.rpc("json", "gateway_balances", to_string(params)); auto const result = jrr[jss::result]; - auto const obligations = - result[jss::obligations][to_string(issue.currency)]; + auto const obligations = result[jss::obligations][to_string(issue.currency)]; if (obligations.isNull()) return {STAmount(issue, 0), account.name()}; STAmount const amount = amountFromString(issue, obligations.asString()); @@ -58,10 +51,7 @@ struct EscrowToken_test : public beast::unit_test::suite } jtx::PrettyAmount - issuerEscrowed( - jtx::Env& env, - jtx::Account const& account, - Issue const& issue) + issuerEscrowed(jtx::Env& env, jtx::Account const& account, Issue const& issue) { Json::Value params; params[jss::account] = account.human(); @@ -84,8 +74,7 @@ struct EscrowToken_test : public beast::unit_test::suite for (bool const withTokenEscrow : {false, true}) { - auto const amend = - withTokenEscrow ? features : features - featureTokenEscrow; + auto const amend = withTokenEscrow ? features : features - featureTokenEscrow; Env env{*this, amend}; auto const baseFee = env.current()->fees().base; auto const alice = Account("alice"); @@ -101,10 +90,8 @@ struct EscrowToken_test : public beast::unit_test::suite env(pay(gw, bob, USD(5000))); env.close(); - auto const createResult = - withTokenEscrow ? ter(tesSUCCESS) : ter(temBAD_AMOUNT); - auto const finishResult = - withTokenEscrow ? ter(tesSUCCESS) : ter(tecNO_TARGET); + auto const createResult = withTokenEscrow ? ter(tesSUCCESS) : ter(temBAD_AMOUNT); + auto const finishResult = withTokenEscrow ? ter(tesSUCCESS) : ter(tecNO_TARGET); auto const seq1 = env.seq(alice); env(escrow::create(alice, bob, USD(1'000)), @@ -134,8 +121,7 @@ struct EscrowToken_test : public beast::unit_test::suite for (bool const withTokenEscrow : {false, true}) { - auto const amend = - withTokenEscrow ? features : features - featureTokenEscrow; + auto const amend = withTokenEscrow ? features : features - featureTokenEscrow; Env env{*this, amend}; auto const baseFee = env.current()->fees().base; auto const alice = Account("alice"); @@ -246,10 +232,7 @@ struct EscrowToken_test : public beast::unit_test::suite auto const USD = gw["USD"]; env.fund(XRP(5000), alice, bob, gw); - env(escrow::create(alice, bob, USD(1)), - escrow::finish_time(env.now() + 1s), - fee(XRP(-1)), - ter(temBAD_FEE)); + env(escrow::create(alice, bob, USD(1)), escrow::finish_time(env.now() + 1s), fee(XRP(-1)), ter(temBAD_FEE)); env.close(); } @@ -559,8 +542,7 @@ struct EscrowToken_test : public beast::unit_test::suite env(pay(gw, bob, USD(1))); env.close(); - bool const largeMantissa = features[featureSingleAssetVault] || - features[featureLendingProtocol]; + bool const largeMantissa = features[featureSingleAssetVault] || features[featureLendingProtocol]; // alice cannot create escrow for 1/10 iou - precision loss env(escrow::create(alice, bob, USD(1)), @@ -770,7 +752,7 @@ struct EscrowToken_test : public beast::unit_test::suite env.trust(USD(1), bob); env.close(); - // alice cannot finish because bobs limit is too low + // alice cannot finish because bob's limit is too low env(escrow::finish(alice, alice, seq1), escrow::condition(escrow::cb1), escrow::fulfillment(escrow::fb1), @@ -807,7 +789,7 @@ struct EscrowToken_test : public beast::unit_test::suite env.trust(USD(1), bob); env.close(); - // bob can finish even if bobs limit is too low + // bob can finish even if bob's limit is too low auto const bobPreLimit = env.limit(bob, USD); env(escrow::finish(bob, alice, seq1), @@ -817,7 +799,7 @@ struct EscrowToken_test : public beast::unit_test::suite ter(tesSUCCESS)); env.close(); - // bobs limit is not changed + // bob's limit is not changed BEAST_EXPECT(env.limit(bob, USD) == bobPreLimit); } } @@ -868,9 +850,7 @@ struct EscrowToken_test : public beast::unit_test::suite env.close(); // alice cannot cancel because she is not authorized - env(escrow::cancel(bob, alice, seq1), - fee(baseFee), - ter(tecNO_AUTH)); + env(escrow::cancel(bob, alice, seq1), fee(baseFee), ter(tecNO_AUTH)); env.close(); } } @@ -914,8 +894,7 @@ struct EscrowToken_test : public beast::unit_test::suite BEAST_EXPECT(env.balance(alice, USD) == preAliceUSD - USD(1'000)); BEAST_EXPECT(env.balance(bob, USD) == preBobUSD); - BEAST_EXPECT( - issuerBalance(env, gw, USD) == outstandingUSD - USD(1'000)); + BEAST_EXPECT(issuerBalance(env, gw, USD) == outstandingUSD - USD(1'000)); BEAST_EXPECT(issuerEscrowed(env, gw, USD) == USD(1'000)); } { @@ -949,8 +928,7 @@ struct EscrowToken_test : public beast::unit_test::suite BEAST_EXPECT(env.balance(alice, USD) == preAliceUSD - USD(1'000)); BEAST_EXPECT(env.balance(bob, USD) == preBobUSD); - BEAST_EXPECT( - issuerBalance(env, gw, USD) == outstandingUSD - USD(1'000)); + BEAST_EXPECT(issuerBalance(env, gw, USD) == outstandingUSD - USD(1'000)); BEAST_EXPECT(issuerEscrowed(env, gw, USD) == USD(1'000)); } { @@ -996,32 +974,26 @@ struct EscrowToken_test : public beast::unit_test::suite env(escrow::create(alice, alice, USD(1'000)), escrow::finish_time(env.now() + 1s), escrow::cancel_time(env.now() + 500s)); - BEAST_EXPECT( - (*env.meta())[sfTransactionResult] == - static_cast(tesSUCCESS)); + BEAST_EXPECT((*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); env.close(5s); auto const aa = env.le(keylet::escrow(alice.id(), aseq)); BEAST_EXPECT(aa); { xrpl::Dir aod(*env.current(), keylet::ownerDir(alice.id())); BEAST_EXPECT(std::distance(aod.begin(), aod.end()) == 2); - BEAST_EXPECT( - std::find(aod.begin(), aod.end(), aa) != aod.end()); + BEAST_EXPECT(std::find(aod.begin(), aod.end(), aa) != aod.end()); } { xrpl::Dir iod(*env.current(), keylet::ownerDir(gw.id())); BEAST_EXPECT(std::distance(iod.begin(), iod.end()) == 4); - BEAST_EXPECT( - std::find(iod.begin(), iod.end(), aa) != iod.end()); + BEAST_EXPECT(std::find(iod.begin(), iod.end(), aa) != iod.end()); } env(escrow::create(bob, bob, USD(1'000)), escrow::finish_time(env.now() + 1s), escrow::cancel_time(env.now() + 2s)); - BEAST_EXPECT( - (*env.meta())[sfTransactionResult] == - static_cast(tesSUCCESS)); + BEAST_EXPECT((*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); env.close(5s); auto const bb = env.le(keylet::escrow(bob.id(), bseq)); BEAST_EXPECT(bb); @@ -1029,58 +1001,47 @@ struct EscrowToken_test : public beast::unit_test::suite { xrpl::Dir bod(*env.current(), keylet::ownerDir(bob.id())); BEAST_EXPECT(std::distance(bod.begin(), bod.end()) == 2); - BEAST_EXPECT( - std::find(bod.begin(), bod.end(), bb) != bod.end()); + BEAST_EXPECT(std::find(bod.begin(), bod.end(), bb) != bod.end()); } { xrpl::Dir iod(*env.current(), keylet::ownerDir(gw.id())); BEAST_EXPECT(std::distance(iod.begin(), iod.end()) == 5); - BEAST_EXPECT( - std::find(iod.begin(), iod.end(), bb) != iod.end()); + BEAST_EXPECT(std::find(iod.begin(), iod.end(), bb) != iod.end()); } env.close(5s); env(escrow::finish(alice, alice, aseq)); { BEAST_EXPECT(!env.le(keylet::escrow(alice.id(), aseq))); - BEAST_EXPECT( - (*env.meta())[sfTransactionResult] == - static_cast(tesSUCCESS)); + BEAST_EXPECT((*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); xrpl::Dir aod(*env.current(), keylet::ownerDir(alice.id())); BEAST_EXPECT(std::distance(aod.begin(), aod.end()) == 1); - BEAST_EXPECT( - std::find(aod.begin(), aod.end(), aa) == aod.end()); + BEAST_EXPECT(std::find(aod.begin(), aod.end(), aa) == aod.end()); xrpl::Dir bod(*env.current(), keylet::ownerDir(bob.id())); BEAST_EXPECT(std::distance(bod.begin(), bod.end()) == 2); - BEAST_EXPECT( - std::find(bod.begin(), bod.end(), bb) != bod.end()); + BEAST_EXPECT(std::find(bod.begin(), bod.end(), bb) != bod.end()); xrpl::Dir iod(*env.current(), keylet::ownerDir(gw.id())); BEAST_EXPECT(std::distance(iod.begin(), iod.end()) == 4); - BEAST_EXPECT( - std::find(iod.begin(), iod.end(), bb) != iod.end()); + BEAST_EXPECT(std::find(iod.begin(), iod.end(), bb) != iod.end()); } env.close(5s); env(escrow::cancel(bob, bob, bseq)); { BEAST_EXPECT(!env.le(keylet::escrow(bob.id(), bseq))); - BEAST_EXPECT( - (*env.meta())[sfTransactionResult] == - static_cast(tesSUCCESS)); + BEAST_EXPECT((*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); xrpl::Dir bod(*env.current(), keylet::ownerDir(bob.id())); BEAST_EXPECT(std::distance(bod.begin(), bod.end()) == 1); - BEAST_EXPECT( - std::find(bod.begin(), bod.end(), bb) == bod.end()); + BEAST_EXPECT(std::find(bod.begin(), bod.end(), bb) == bod.end()); xrpl::Dir iod(*env.current(), keylet::ownerDir(gw.id())); BEAST_EXPECT(std::distance(iod.begin(), iod.end()) == 3); - BEAST_EXPECT( - std::find(iod.begin(), iod.end(), bb) == iod.end()); + BEAST_EXPECT(std::find(iod.begin(), iod.end(), bb) == iod.end()); } } { @@ -1099,18 +1060,13 @@ struct EscrowToken_test : public beast::unit_test::suite auto const aseq = env.seq(alice); auto const bseq = env.seq(bob); - env(escrow::create(alice, bob, USD(1'000)), - escrow::finish_time(env.now() + 1s)); - BEAST_EXPECT( - (*env.meta())[sfTransactionResult] == - static_cast(tesSUCCESS)); + env(escrow::create(alice, bob, USD(1'000)), escrow::finish_time(env.now() + 1s)); + BEAST_EXPECT((*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); env.close(5s); env(escrow::create(bob, carol, USD(1'000)), escrow::finish_time(env.now() + 1s), escrow::cancel_time(env.now() + 2s)); - BEAST_EXPECT( - (*env.meta())[sfTransactionResult] == - static_cast(tesSUCCESS)); + BEAST_EXPECT((*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); env.close(5s); auto const ab = env.le(keylet::escrow(alice.id(), aseq)); @@ -1122,27 +1078,21 @@ struct EscrowToken_test : public beast::unit_test::suite { xrpl::Dir aod(*env.current(), keylet::ownerDir(alice.id())); BEAST_EXPECT(std::distance(aod.begin(), aod.end()) == 2); - BEAST_EXPECT( - std::find(aod.begin(), aod.end(), ab) != aod.end()); + BEAST_EXPECT(std::find(aod.begin(), aod.end(), ab) != aod.end()); xrpl::Dir bod(*env.current(), keylet::ownerDir(bob.id())); BEAST_EXPECT(std::distance(bod.begin(), bod.end()) == 3); - BEAST_EXPECT( - std::find(bod.begin(), bod.end(), ab) != bod.end()); - BEAST_EXPECT( - std::find(bod.begin(), bod.end(), bc) != bod.end()); + BEAST_EXPECT(std::find(bod.begin(), bod.end(), ab) != bod.end()); + BEAST_EXPECT(std::find(bod.begin(), bod.end(), bc) != bod.end()); xrpl::Dir cod(*env.current(), keylet::ownerDir(carol.id())); BEAST_EXPECT(std::distance(cod.begin(), cod.end()) == 2); - BEAST_EXPECT( - std::find(cod.begin(), cod.end(), bc) != cod.end()); + BEAST_EXPECT(std::find(cod.begin(), cod.end(), bc) != cod.end()); xrpl::Dir iod(*env.current(), keylet::ownerDir(gw.id())); BEAST_EXPECT(std::distance(iod.begin(), iod.end()) == 5); - BEAST_EXPECT( - std::find(iod.begin(), iod.end(), ab) != iod.end()); - BEAST_EXPECT( - std::find(iod.begin(), iod.end(), bc) != iod.end()); + BEAST_EXPECT(std::find(iod.begin(), iod.end(), ab) != iod.end()); + BEAST_EXPECT(std::find(iod.begin(), iod.end(), bc) != iod.end()); } env.close(5s); @@ -1153,25 +1103,20 @@ struct EscrowToken_test : public beast::unit_test::suite xrpl::Dir aod(*env.current(), keylet::ownerDir(alice.id())); BEAST_EXPECT(std::distance(aod.begin(), aod.end()) == 1); - BEAST_EXPECT( - std::find(aod.begin(), aod.end(), ab) == aod.end()); + BEAST_EXPECT(std::find(aod.begin(), aod.end(), ab) == aod.end()); xrpl::Dir bod(*env.current(), keylet::ownerDir(bob.id())); BEAST_EXPECT(std::distance(bod.begin(), bod.end()) == 2); - BEAST_EXPECT( - std::find(bod.begin(), bod.end(), ab) == bod.end()); - BEAST_EXPECT( - std::find(bod.begin(), bod.end(), bc) != bod.end()); + BEAST_EXPECT(std::find(bod.begin(), bod.end(), ab) == bod.end()); + BEAST_EXPECT(std::find(bod.begin(), bod.end(), bc) != bod.end()); xrpl::Dir cod(*env.current(), keylet::ownerDir(carol.id())); BEAST_EXPECT(std::distance(cod.begin(), cod.end()) == 2); xrpl::Dir iod(*env.current(), keylet::ownerDir(gw.id())); BEAST_EXPECT(std::distance(iod.begin(), iod.end()) == 4); - BEAST_EXPECT( - std::find(iod.begin(), iod.end(), ab) == iod.end()); - BEAST_EXPECT( - std::find(iod.begin(), iod.end(), bc) != iod.end()); + BEAST_EXPECT(std::find(iod.begin(), iod.end(), ab) == iod.end()); + BEAST_EXPECT(std::find(iod.begin(), iod.end(), bc) != iod.end()); } env.close(5s); @@ -1182,25 +1127,20 @@ struct EscrowToken_test : public beast::unit_test::suite xrpl::Dir aod(*env.current(), keylet::ownerDir(alice.id())); BEAST_EXPECT(std::distance(aod.begin(), aod.end()) == 1); - BEAST_EXPECT( - std::find(aod.begin(), aod.end(), ab) == aod.end()); + BEAST_EXPECT(std::find(aod.begin(), aod.end(), ab) == aod.end()); xrpl::Dir bod(*env.current(), keylet::ownerDir(bob.id())); BEAST_EXPECT(std::distance(bod.begin(), bod.end()) == 1); - BEAST_EXPECT( - std::find(bod.begin(), bod.end(), ab) == bod.end()); - BEAST_EXPECT( - std::find(bod.begin(), bod.end(), bc) == bod.end()); + BEAST_EXPECT(std::find(bod.begin(), bod.end(), ab) == bod.end()); + BEAST_EXPECT(std::find(bod.begin(), bod.end(), bc) == bod.end()); xrpl::Dir cod(*env.current(), keylet::ownerDir(carol.id())); BEAST_EXPECT(std::distance(cod.begin(), cod.end()) == 1); xrpl::Dir iod(*env.current(), keylet::ownerDir(gw.id())); BEAST_EXPECT(std::distance(iod.begin(), iod.end()) == 3); - BEAST_EXPECT( - std::find(iod.begin(), iod.end(), ab) == iod.end()); - BEAST_EXPECT( - std::find(iod.begin(), iod.end(), bc) == iod.end()); + BEAST_EXPECT(std::find(iod.begin(), iod.end(), ab) == iod.end()); + BEAST_EXPECT(std::find(iod.begin(), iod.end(), bc) == iod.end()); } } @@ -1218,12 +1158,9 @@ struct EscrowToken_test : public beast::unit_test::suite env.close(); auto const aseq = env.seq(alice); - env(escrow::create(alice, gw, USD(1'000)), - escrow::finish_time(env.now() + 1s)); + env(escrow::create(alice, gw, USD(1'000)), escrow::finish_time(env.now() + 1s)); - BEAST_EXPECT( - (*env.meta())[sfTransactionResult] == - static_cast(tesSUCCESS)); + BEAST_EXPECT((*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); env.close(5s); env(escrow::create(gw, carol, USD(1'000)), escrow::finish_time(env.now() + 1s), @@ -1237,16 +1174,14 @@ struct EscrowToken_test : public beast::unit_test::suite { xrpl::Dir aod(*env.current(), keylet::ownerDir(alice.id())); BEAST_EXPECT(std::distance(aod.begin(), aod.end()) == 2); - BEAST_EXPECT( - std::find(aod.begin(), aod.end(), ag) != aod.end()); + BEAST_EXPECT(std::find(aod.begin(), aod.end(), ag) != aod.end()); xrpl::Dir cod(*env.current(), keylet::ownerDir(carol.id())); BEAST_EXPECT(std::distance(cod.begin(), cod.end()) == 1); xrpl::Dir iod(*env.current(), keylet::ownerDir(gw.id())); BEAST_EXPECT(std::distance(iod.begin(), iod.end()) == 3); - BEAST_EXPECT( - std::find(iod.begin(), iod.end(), ag) != iod.end()); + BEAST_EXPECT(std::find(iod.begin(), iod.end(), ag) != iod.end()); } env.close(5s); @@ -1256,16 +1191,14 @@ struct EscrowToken_test : public beast::unit_test::suite xrpl::Dir aod(*env.current(), keylet::ownerDir(alice.id())); BEAST_EXPECT(std::distance(aod.begin(), aod.end()) == 1); - BEAST_EXPECT( - std::find(aod.begin(), aod.end(), ag) == aod.end()); + BEAST_EXPECT(std::find(aod.begin(), aod.end(), ag) == aod.end()); xrpl::Dir cod(*env.current(), keylet::ownerDir(carol.id())); BEAST_EXPECT(std::distance(cod.begin(), cod.end()) == 1); xrpl::Dir iod(*env.current(), keylet::ownerDir(gw.id())); BEAST_EXPECT(std::distance(iod.begin(), iod.end()) == 2); - BEAST_EXPECT( - std::find(iod.begin(), iod.end(), ag) == iod.end()); + BEAST_EXPECT(std::find(iod.begin(), iod.end(), ag) == iod.end()); } } } @@ -1495,8 +1428,7 @@ struct EscrowToken_test : public beast::unit_test::suite fee(baseFee * 150)); env.close(); auto const transferRate = escrow::rate(env, alice, seq1); - BEAST_EXPECT( - transferRate.value == std::uint32_t(1'000'000'000 * 1.25)); + BEAST_EXPECT(transferRate.value == std::uint32_t(1'000'000'000 * 1.25)); // bob can finish escrow env(escrow::finish(bob, alice, seq1), @@ -1533,8 +1465,7 @@ struct EscrowToken_test : public beast::unit_test::suite fee(baseFee * 150)); env.close(); auto transferRate = escrow::rate(env, alice, seq1); - BEAST_EXPECT( - transferRate.value == std::uint32_t(1'000'000'000 * 1.25)); + BEAST_EXPECT(transferRate.value == std::uint32_t(1'000'000'000 * 1.25)); // issuer changes rate higher env(rate(gw, 1.26)); @@ -1576,8 +1507,7 @@ struct EscrowToken_test : public beast::unit_test::suite fee(baseFee * 150)); env.close(); auto transferRate = escrow::rate(env, alice, seq1); - BEAST_EXPECT( - transferRate.value == std::uint32_t(1'000'000'000 * 1.25)); + BEAST_EXPECT(transferRate.value == std::uint32_t(1'000'000'000 * 1.25)); // issuer changes rate lower env(rate(gw, 1.00)); @@ -1619,8 +1549,7 @@ struct EscrowToken_test : public beast::unit_test::suite fee(baseFee)); env.close(); auto transferRate = escrow::rate(env, alice, seq1); - BEAST_EXPECT( - transferRate.value == std::uint32_t(1'000'000'000 * 1.25)); + BEAST_EXPECT(transferRate.value == std::uint32_t(1'000'000'000 * 1.25)); // issuer changes rate lower env(rate(gw, 1.00)); @@ -1677,7 +1606,7 @@ struct EscrowToken_test : public beast::unit_test::suite fee(baseFee * 150)); env.close(); auto const postBobLimit = env.limit(bob, USD); - // bobs limit is NOT changed + // bob's limit is NOT changed BEAST_EXPECT(postBobLimit == preBobLimit); } } @@ -1937,8 +1866,7 @@ struct EscrowToken_test : public beast::unit_test::suite env.close(); // clear freeze on alice trustline - env(trust( - gw, USD(10'000), alice, tfClearFreeze | tfClearDeepFreeze)); + env(trust(gw, USD(10'000), alice, tfClearFreeze | tfClearDeepFreeze)); env.close(); // create escrow success @@ -1962,8 +1890,7 @@ struct EscrowToken_test : public beast::unit_test::suite env.close(); // reset freeze on alice and bob trustline - env(trust( - gw, USD(10'000), alice, tfClearFreeze | tfClearDeepFreeze)); + env(trust(gw, USD(10'000), alice, tfClearFreeze | tfClearDeepFreeze)); env(trust(gw, USD(10'000), bob, tfClearFreeze | tfClearDeepFreeze)); env.close(); @@ -1980,14 +1907,12 @@ struct EscrowToken_test : public beast::unit_test::suite env.close(); // bob cancel escrow fails because of deep frozen assets - env(escrow::cancel(bob, alice, seq1), - fee(baseFee), - ter(tesSUCCESS)); + env(escrow::cancel(bob, alice, seq1), fee(baseFee), ter(tesSUCCESS)); env.close(); } } void - testIOUINSF(FeatureBitset features) + testIOUInsufficientFunds(FeatureBitset features) { testcase("IOU Insufficient Funds"); using namespace test::jtx; @@ -2079,8 +2004,7 @@ struct EscrowToken_test : public beast::unit_test::suite env(pay(gw, bob, USD(1))); env.close(); - bool const largeMantissa = features[featureSingleAssetVault] || - features[featureLendingProtocol]; + bool const largeMantissa = features[featureSingleAssetVault] || features[featureLendingProtocol]; // alice cannot create escrow for 1/10 iou - precision loss env(escrow::create(alice, bob, USD(1)), @@ -2117,8 +2041,7 @@ struct EscrowToken_test : public beast::unit_test::suite for (bool const withTokenEscrow : {false, true}) { - auto const amend = - withTokenEscrow ? features : features - featureTokenEscrow; + auto const amend = withTokenEscrow ? features : features - featureTokenEscrow; Env env{*this, amend}; auto const baseFee = env.current()->fees().base; auto const alice = Account("alice"); @@ -2127,19 +2050,14 @@ struct EscrowToken_test : public beast::unit_test::suite env.fund(XRP(5000), bob); MPTTester mptGw(env, gw, {.holders = {alice}}); - mptGw.create( - {.ownerCount = 1, - .holderCount = 0, - .flags = tfMPTCanEscrow | tfMPTCanTransfer}); + mptGw.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); mptGw.authorize({.account = alice}); auto const MPT = mptGw["MPT"]; env(pay(gw, alice, MPT(10'000))); env.close(); - auto const createResult = - withTokenEscrow ? ter(tesSUCCESS) : ter(temBAD_AMOUNT); - auto const finishResult = - withTokenEscrow ? ter(tesSUCCESS) : ter(tecNO_TARGET); + auto const createResult = withTokenEscrow ? ter(tesSUCCESS) : ter(temBAD_AMOUNT); + auto const finishResult = withTokenEscrow ? ter(tesSUCCESS) : ter(tecNO_TARGET); auto const seq1 = env.seq(alice); env(escrow::create(alice, bob, MPT(1'000)), @@ -2176,8 +2094,7 @@ struct EscrowToken_test : public beast::unit_test::suite for (bool const withMPT : {true, false}) { - auto const amend = - withMPT ? features : features - featureMPTokensV1; + auto const amend = withMPT ? features : features - featureMPTokensV1; Env env{*this, amend}; auto const baseFee = env.current()->fees().base; auto const alice = Account("alice"); @@ -2187,16 +2104,11 @@ struct EscrowToken_test : public beast::unit_test::suite Json::Value jv = escrow::create(alice, bob, XRP(1)); jv.removeMember(jss::Amount); - jv[jss::Amount][jss::mpt_issuance_id] = - "00000004A407AF5856CCF3C42619DAA925813FC955C72983"; + jv[jss::Amount][jss::mpt_issuance_id] = "00000004A407AF5856CCF3C42619DAA925813FC955C72983"; jv[jss::Amount][jss::value] = "-1"; auto const result = withMPT ? ter(temBAD_AMOUNT) : ter(temDISABLED); - env(jv, - escrow::condition(escrow::cb1), - escrow::finish_time(env.now() + 1s), - fee(baseFee * 150), - result); + env(jv, escrow::condition(escrow::cb1), escrow::finish_time(env.now() + 1s), fee(baseFee * 150), result); env.close(); } @@ -2209,10 +2121,7 @@ struct EscrowToken_test : public beast::unit_test::suite auto const gw = Account("gw"); MPTTester mptGw(env, gw, {.holders = {alice, bob}}); - mptGw.create( - {.ownerCount = 1, - .holderCount = 0, - .flags = tfMPTCanEscrow | tfMPTCanTransfer}); + mptGw.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = bob}); auto const MPT = mptGw["MPT"]; @@ -2244,10 +2153,7 @@ struct EscrowToken_test : public beast::unit_test::suite auto const gw = Account("gw"); MPTTester mptGw(env, gw, {.holders = {alice}}); - mptGw.create( - {.ownerCount = 1, - .holderCount = 0, - .flags = tfMPTCanEscrow | tfMPTCanTransfer}); + mptGw.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); mptGw.authorize({.account = alice}); auto const MPT = mptGw["MPT"]; env(pay(gw, alice, MPT(10'000))); @@ -2271,11 +2177,9 @@ struct EscrowToken_test : public beast::unit_test::suite env.fund(XRP(10'000), alice, bob, gw); env.close(); - auto const mpt = xrpl::test::jtx::MPT( - alice.name(), makeMptID(env.seq(alice), alice)); + auto const mpt = xrpl::test::jtx::MPT(alice.name(), makeMptID(env.seq(alice), alice)); Json::Value jv = escrow::create(alice, bob, mpt(2)); - jv[jss::Amount][jss::mpt_issuance_id] = - "00000004A407AF5856CCF3C42619DAA925813FC955C72983"; + jv[jss::Amount][jss::mpt_issuance_id] = "00000004A407AF5856CCF3C42619DAA925813FC955C72983"; env(jv, escrow::condition(escrow::cb1), escrow::finish_time(env.now() + 1s), @@ -2293,8 +2197,7 @@ struct EscrowToken_test : public beast::unit_test::suite auto const gw = Account("gw"); MPTTester mptGw(env, gw, {.holders = {alice, bob}}); - mptGw.create( - {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer}); + mptGw.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = bob}); auto const MPT = mptGw["MPT"]; @@ -2319,10 +2222,7 @@ struct EscrowToken_test : public beast::unit_test::suite auto const gw = Account("gw"); MPTTester mptGw(env, gw, {.holders = {alice, bob}}); - mptGw.create( - {.ownerCount = 1, - .holderCount = 0, - .flags = tfMPTCanEscrow | tfMPTCanTransfer}); + mptGw.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); auto const MPT = mptGw["MPT"]; env(escrow::create(alice, bob, MPT(4)), @@ -2343,10 +2243,7 @@ struct EscrowToken_test : public beast::unit_test::suite MPTTester mptGw(env, gw, {.holders = {alice, bob}}); mptGw.create( - {.ownerCount = 1, - .holderCount = 0, - .flags = - tfMPTCanEscrow | tfMPTCanTransfer | tfMPTRequireAuth}); + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer | tfMPTRequireAuth}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = gw, .holder = alice}); auto const MPT = mptGw["MPT"]; @@ -2354,8 +2251,7 @@ struct EscrowToken_test : public beast::unit_test::suite env.close(); // unauthorize account - mptGw.authorize( - {.account = gw, .holder = alice, .flags = tfMPTUnauthorize}); + mptGw.authorize({.account = gw, .holder = alice, .flags = tfMPTUnauthorize}); env(escrow::create(alice, bob, MPT(5)), escrow::condition(escrow::cb1), @@ -2375,10 +2271,7 @@ struct EscrowToken_test : public beast::unit_test::suite MPTTester mptGw(env, gw, {.holders = {alice, bob}}); mptGw.create( - {.ownerCount = 1, - .holderCount = 0, - .flags = - tfMPTCanEscrow | tfMPTCanTransfer | tfMPTRequireAuth}); + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer | tfMPTRequireAuth}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = gw, .holder = alice}); mptGw.authorize({.account = bob}); @@ -2389,8 +2282,7 @@ struct EscrowToken_test : public beast::unit_test::suite env.close(); // unauthorize dest - mptGw.authorize( - {.account = gw, .holder = bob, .flags = tfMPTUnauthorize}); + mptGw.authorize({.account = gw, .holder = bob, .flags = tfMPTUnauthorize}); env(escrow::create(alice, bob, MPT(6)), escrow::condition(escrow::cb1), @@ -2410,9 +2302,7 @@ struct EscrowToken_test : public beast::unit_test::suite MPTTester mptGw(env, gw, {.holders = {alice, bob}}); mptGw.create( - {.ownerCount = 1, - .holderCount = 0, - .flags = tfMPTCanEscrow | tfMPTCanTransfer | tfMPTCanLock}); + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer | tfMPTCanLock}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = bob}); auto const MPT = mptGw["MPT"]; @@ -2441,9 +2331,7 @@ struct EscrowToken_test : public beast::unit_test::suite MPTTester mptGw(env, gw, {.holders = {alice, bob}}); mptGw.create( - {.ownerCount = 1, - .holderCount = 0, - .flags = tfMPTCanEscrow | tfMPTCanTransfer | tfMPTCanLock}); + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer | tfMPTCanLock}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = bob}); auto const MPT = mptGw["MPT"]; @@ -2471,8 +2359,7 @@ struct EscrowToken_test : public beast::unit_test::suite auto const gw = Account("gw"); MPTTester mptGw(env, gw, {.holders = {alice, bob}}); - mptGw.create( - {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow}); + mptGw.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = bob}); auto const MPT = mptGw["MPT"]; @@ -2497,10 +2384,7 @@ struct EscrowToken_test : public beast::unit_test::suite auto const gw = Account("gw"); MPTTester mptGw(env, gw, {.holders = {alice, bob}}); - mptGw.create( - {.ownerCount = 1, - .holderCount = 0, - .flags = tfMPTCanEscrow | tfMPTCanTransfer}); + mptGw.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = bob}); auto const MPT = mptGw["MPT"]; @@ -2524,10 +2408,7 @@ struct EscrowToken_test : public beast::unit_test::suite auto const gw = Account("gw"); MPTTester mptGw(env, gw, {.holders = {alice, bob}}); - mptGw.create( - {.ownerCount = 1, - .holderCount = 0, - .flags = tfMPTCanEscrow | tfMPTCanTransfer}); + mptGw.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = bob}); auto const MPT = mptGw["MPT"]; @@ -2561,10 +2442,7 @@ struct EscrowToken_test : public beast::unit_test::suite MPTTester mptGw(env, gw, {.holders = {alice, bob}}); mptGw.create( - {.ownerCount = 1, - .holderCount = 0, - .flags = - tfMPTCanEscrow | tfMPTCanTransfer | tfMPTRequireAuth}); + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer | tfMPTRequireAuth}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = gw, .holder = alice}); mptGw.authorize({.account = bob}); @@ -2583,8 +2461,7 @@ struct EscrowToken_test : public beast::unit_test::suite env.close(); // unauthorize dest - mptGw.authorize( - {.account = gw, .holder = bob, .flags = tfMPTUnauthorize}); + mptGw.authorize({.account = gw, .holder = bob, .flags = tfMPTUnauthorize}); env(escrow::finish(bob, alice, seq1), escrow::condition(escrow::cb1), @@ -2604,20 +2481,17 @@ struct EscrowToken_test : public beast::unit_test::suite env.close(); auto const seq1 = env.seq(alice); - env.app().openLedger().modify( - [&](OpenView& view, beast::Journal j) { - Sandbox sb(&view, tapNONE); - auto sleNew = - std::make_shared(keylet::escrow(alice, seq1)); - MPTIssue const mpt{ - MPTIssue{makeMptID(1, AccountID(0x4985601))}}; - STAmount amt(mpt, 10); - sleNew->setAccountID(sfDestination, bob); - sleNew->setFieldAmount(sfAmount, amt); - sb.insert(sleNew); - sb.apply(view); - return true; - }); + env.app().openLedger().modify([&](OpenView& view, beast::Journal j) { + Sandbox sb(&view, tapNONE); + auto sleNew = std::make_shared(keylet::escrow(alice, seq1)); + MPTIssue const mpt{MPTIssue{makeMptID(1, AccountID(0x4985601))}}; + STAmount amt(mpt, 10); + sleNew->setAccountID(sfDestination, bob); + sleNew->setFieldAmount(sfAmount, amt); + sb.insert(sleNew); + sb.apply(view); + return true; + }); env(escrow::finish(bob, alice, seq1), escrow::condition(escrow::cb1), @@ -2637,9 +2511,7 @@ struct EscrowToken_test : public beast::unit_test::suite MPTTester mptGw(env, gw, {.holders = {alice, bob}}); mptGw.create( - {.ownerCount = 1, - .holderCount = 0, - .flags = tfMPTCanEscrow | tfMPTCanTransfer | tfMPTCanLock}); + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer | tfMPTCanLock}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = bob}); auto const MPT = mptGw["MPT"]; @@ -2688,10 +2560,7 @@ struct EscrowToken_test : public beast::unit_test::suite env.close(); MPTTester mptGw(env, gw, {.holders = {alice}}); - mptGw.create( - {.ownerCount = 1, - .holderCount = 0, - .flags = tfMPTCanEscrow | tfMPTCanTransfer}); + mptGw.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); mptGw.authorize({.account = alice}); auto const MPT = mptGw["MPT"]; env(pay(gw, alice, MPT(10'000))); @@ -2724,10 +2593,7 @@ struct EscrowToken_test : public beast::unit_test::suite env.close(); MPTTester mptGw(env, gw, {.holders = {alice}}); - mptGw.create( - {.ownerCount = 1, - .holderCount = 0, - .flags = tfMPTCanEscrow | tfMPTCanTransfer}); + mptGw.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); mptGw.authorize({.account = alice}); auto const MPT = mptGw["MPT"]; env(pay(gw, alice, MPT(10'000))); @@ -2761,10 +2627,7 @@ struct EscrowToken_test : public beast::unit_test::suite env.close(); MPTTester mptGw(env, gw, {.holders = {alice}}); - mptGw.create( - {.ownerCount = 1, - .holderCount = 0, - .flags = tfMPTCanEscrow | tfMPTCanTransfer}); + mptGw.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); mptGw.authorize({.account = alice}); auto const MPT = mptGw["MPT"]; env(pay(gw, alice, MPT(10'000))); @@ -2804,10 +2667,7 @@ struct EscrowToken_test : public beast::unit_test::suite MPTTester mptGw(env, gw, {.holders = {alice, bob}}); mptGw.create( - {.ownerCount = 1, - .holderCount = 0, - .flags = - tfMPTCanEscrow | tfMPTCanTransfer | tfMPTRequireAuth}); + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer | tfMPTRequireAuth}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = gw, .holder = alice}); mptGw.authorize({.account = bob}); @@ -2826,8 +2686,7 @@ struct EscrowToken_test : public beast::unit_test::suite env.close(); // unauthorize account - mptGw.authorize( - {.account = gw, .holder = alice, .flags = tfMPTUnauthorize}); + mptGw.authorize({.account = gw, .holder = alice, .flags = tfMPTUnauthorize}); env(escrow::cancel(bob, alice, seq1), ter(tecNO_AUTH)); env.close(); @@ -2842,24 +2701,19 @@ struct EscrowToken_test : public beast::unit_test::suite env.fund(XRP(10'000), alice, bob); auto const seq1 = env.seq(alice); - env.app().openLedger().modify( - [&](OpenView& view, beast::Journal j) { - Sandbox sb(&view, tapNONE); - auto sleNew = - std::make_shared(keylet::escrow(alice, seq1)); - MPTIssue const mpt{ - MPTIssue{makeMptID(1, AccountID(0x4985601))}}; - STAmount amt(mpt, 10); - sleNew->setAccountID(sfDestination, bob); - sleNew->setFieldAmount(sfAmount, amt); - sb.insert(sleNew); - sb.apply(view); - return true; - }); + env.app().openLedger().modify([&](OpenView& view, beast::Journal j) { + Sandbox sb(&view, tapNONE); + auto sleNew = std::make_shared(keylet::escrow(alice, seq1)); + MPTIssue const mpt{MPTIssue{makeMptID(1, AccountID(0x4985601))}}; + STAmount amt(mpt, 10); + sleNew->setAccountID(sfDestination, bob); + sleNew->setFieldAmount(sfAmount, amt); + sb.insert(sleNew); + sb.apply(view); + return true; + }); - env(escrow::cancel(bob, alice, seq1), - fee(baseFee), - ter(tecOBJECT_NOT_FOUND)); + env(escrow::cancel(bob, alice, seq1), fee(baseFee), ter(tecOBJECT_NOT_FOUND)); env.close(); } } @@ -2881,10 +2735,7 @@ struct EscrowToken_test : public beast::unit_test::suite env.fund(XRP(5000), bob); MPTTester mptGw(env, gw, {.holders = {alice, carol}}); - mptGw.create( - {.ownerCount = 1, - .holderCount = 0, - .flags = tfMPTCanEscrow | tfMPTCanTransfer}); + mptGw.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = carol}); auto const MPT = mptGw["MPT"]; @@ -3058,10 +2909,7 @@ struct EscrowToken_test : public beast::unit_test::suite auto const gw = Account("gw"); MPTTester mptGw(env, gw, {.holders = {alice, bob}}); - mptGw.create( - {.ownerCount = 1, - .holderCount = 0, - .flags = tfMPTCanEscrow | tfMPTCanTransfer}); + mptGw.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = bob}); auto const MPT = mptGw["MPT"]; @@ -3095,14 +2943,12 @@ struct EscrowToken_test : public beast::unit_test::suite BEAST_EXPECT(env.balance(alice, MPT) == preAliceMPT - MPT(1)); BEAST_EXPECT(mptEscrowed(env, alice, MPT) == 0); - BEAST_EXPECT(!env.le(keylet::mptoken(MPT.mpt(), alice)) - ->isFieldPresent(sfLockedAmount)); + BEAST_EXPECT(!env.le(keylet::mptoken(MPT.mpt(), alice))->isFieldPresent(sfLockedAmount)); BEAST_EXPECT(env.balance(bob, MPT) == preBobMPT + MPT(1)); BEAST_EXPECT(mptEscrowed(env, bob, MPT) == 0); BEAST_EXPECT(env.balance(gw, MPT) == outstandingMPT); BEAST_EXPECT(issuerMPTEscrowed(env, MPT) == 0); - BEAST_EXPECT(!env.le(keylet::mptIssuance(MPT.mpt())) - ->isFieldPresent(sfLockedAmount)); + BEAST_EXPECT(!env.le(keylet::mptIssuance(MPT.mpt()))->isFieldPresent(sfLockedAmount)); } // Max MPT Amount Issued (Escrow Max MPT) @@ -3114,10 +2960,7 @@ struct EscrowToken_test : public beast::unit_test::suite auto const gw = Account("gw"); MPTTester mptGw(env, gw, {.holders = {alice, bob}}); - mptGw.create( - {.ownerCount = 1, - .holderCount = 0, - .flags = tfMPTCanEscrow | tfMPTCanTransfer}); + mptGw.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = bob}); auto const MPT = mptGw["MPT"]; @@ -3144,8 +2987,7 @@ struct EscrowToken_test : public beast::unit_test::suite fee(baseFee * 150)); env.close(); - BEAST_EXPECT( - env.balance(alice, MPT) == preAliceMPT - MPT(maxMPTokenAmount)); + BEAST_EXPECT(env.balance(alice, MPT) == preAliceMPT - MPT(maxMPTokenAmount)); BEAST_EXPECT(mptEscrowed(env, alice, MPT) == maxMPTokenAmount); BEAST_EXPECT(env.balance(bob, MPT) == preBobMPT); BEAST_EXPECT(mptEscrowed(env, bob, MPT) == 0); @@ -3166,11 +3008,9 @@ struct EscrowToken_test : public beast::unit_test::suite ter(tesSUCCESS)); env.close(); - BEAST_EXPECT( - env.balance(alice, MPT) == preAliceMPT - MPT(maxMPTokenAmount)); + BEAST_EXPECT(env.balance(alice, MPT) == preAliceMPT - MPT(maxMPTokenAmount)); BEAST_EXPECT(mptEscrowed(env, alice, MPT) == 0); - BEAST_EXPECT( - env.balance(bob, MPT) == preBobMPT + MPT(maxMPTokenAmount)); + BEAST_EXPECT(env.balance(bob, MPT) == preBobMPT + MPT(maxMPTokenAmount)); BEAST_EXPECT(mptEscrowed(env, bob, MPT) == 0); BEAST_EXPECT(env.balance(gw, MPT) == outstandingMPT); BEAST_EXPECT(issuerMPTEscrowed(env, MPT) == 0); @@ -3192,10 +3032,7 @@ struct EscrowToken_test : public beast::unit_test::suite Env env{*this, features}; MPTTester mptGw(env, gw, {.holders = {alice, bob}}); - mptGw.create( - {.ownerCount = 1, - .holderCount = 0, - .flags = tfMPTCanEscrow | tfMPTCanTransfer}); + mptGw.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = bob}); auto const MPT = mptGw["MPT"]; @@ -3208,32 +3045,26 @@ struct EscrowToken_test : public beast::unit_test::suite env(escrow::create(alice, alice, MPT(1'000)), escrow::finish_time(env.now() + 1s), escrow::cancel_time(env.now() + 500s)); - BEAST_EXPECT( - (*env.meta())[sfTransactionResult] == - static_cast(tesSUCCESS)); + BEAST_EXPECT((*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); env.close(5s); auto const aa = env.le(keylet::escrow(alice.id(), aseq)); BEAST_EXPECT(aa); { xrpl::Dir aod(*env.current(), keylet::ownerDir(alice.id())); BEAST_EXPECT(std::distance(aod.begin(), aod.end()) == 2); - BEAST_EXPECT( - std::find(aod.begin(), aod.end(), aa) != aod.end()); + BEAST_EXPECT(std::find(aod.begin(), aod.end(), aa) != aod.end()); } { xrpl::Dir iod(*env.current(), keylet::ownerDir(gw.id())); BEAST_EXPECT(std::distance(iod.begin(), iod.end()) == 1); - BEAST_EXPECT( - std::find(iod.begin(), iod.end(), aa) == iod.end()); + BEAST_EXPECT(std::find(iod.begin(), iod.end(), aa) == iod.end()); } env(escrow::create(bob, bob, MPT(1'000)), escrow::finish_time(env.now() + 1s), escrow::cancel_time(env.now() + 2s)); - BEAST_EXPECT( - (*env.meta())[sfTransactionResult] == - static_cast(tesSUCCESS)); + BEAST_EXPECT((*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); env.close(5s); auto const bb = env.le(keylet::escrow(bob.id(), bseq)); BEAST_EXPECT(bb); @@ -3241,41 +3072,33 @@ struct EscrowToken_test : public beast::unit_test::suite { xrpl::Dir bod(*env.current(), keylet::ownerDir(bob.id())); BEAST_EXPECT(std::distance(bod.begin(), bod.end()) == 2); - BEAST_EXPECT( - std::find(bod.begin(), bod.end(), bb) != bod.end()); + BEAST_EXPECT(std::find(bod.begin(), bod.end(), bb) != bod.end()); } env.close(5s); env(escrow::finish(alice, alice, aseq)); { BEAST_EXPECT(!env.le(keylet::escrow(alice.id(), aseq))); - BEAST_EXPECT( - (*env.meta())[sfTransactionResult] == - static_cast(tesSUCCESS)); + BEAST_EXPECT((*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); xrpl::Dir aod(*env.current(), keylet::ownerDir(alice.id())); BEAST_EXPECT(std::distance(aod.begin(), aod.end()) == 1); - BEAST_EXPECT( - std::find(aod.begin(), aod.end(), aa) == aod.end()); + BEAST_EXPECT(std::find(aod.begin(), aod.end(), aa) == aod.end()); xrpl::Dir bod(*env.current(), keylet::ownerDir(bob.id())); BEAST_EXPECT(std::distance(bod.begin(), bod.end()) == 2); - BEAST_EXPECT( - std::find(bod.begin(), bod.end(), bb) != bod.end()); + BEAST_EXPECT(std::find(bod.begin(), bod.end(), bb) != bod.end()); } env.close(5s); env(escrow::cancel(bob, bob, bseq)); { BEAST_EXPECT(!env.le(keylet::escrow(bob.id(), bseq))); - BEAST_EXPECT( - (*env.meta())[sfTransactionResult] == - static_cast(tesSUCCESS)); + BEAST_EXPECT((*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); xrpl::Dir bod(*env.current(), keylet::ownerDir(bob.id())); BEAST_EXPECT(std::distance(bod.begin(), bod.end()) == 1); - BEAST_EXPECT( - std::find(bod.begin(), bod.end(), bb) == bod.end()); + BEAST_EXPECT(std::find(bod.begin(), bod.end(), bb) == bod.end()); } } @@ -3284,10 +3107,7 @@ struct EscrowToken_test : public beast::unit_test::suite Env env{*this, features}; MPTTester mptGw(env, gw, {.holders = {alice, bob, carol}}); - mptGw.create( - {.ownerCount = 1, - .holderCount = 0, - .flags = tfMPTCanEscrow | tfMPTCanTransfer}); + mptGw.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = bob}); mptGw.authorize({.account = carol}); @@ -3299,18 +3119,13 @@ struct EscrowToken_test : public beast::unit_test::suite auto const aseq = env.seq(alice); auto const bseq = env.seq(bob); - env(escrow::create(alice, bob, MPT(1'000)), - escrow::finish_time(env.now() + 1s)); - BEAST_EXPECT( - (*env.meta())[sfTransactionResult] == - static_cast(tesSUCCESS)); + env(escrow::create(alice, bob, MPT(1'000)), escrow::finish_time(env.now() + 1s)); + BEAST_EXPECT((*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); env.close(5s); env(escrow::create(bob, carol, MPT(1'000)), escrow::finish_time(env.now() + 1s), escrow::cancel_time(env.now() + 2s)); - BEAST_EXPECT( - (*env.meta())[sfTransactionResult] == - static_cast(tesSUCCESS)); + BEAST_EXPECT((*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); env.close(5s); auto const ab = env.le(keylet::escrow(alice.id(), aseq)); @@ -3322,20 +3137,16 @@ struct EscrowToken_test : public beast::unit_test::suite { xrpl::Dir aod(*env.current(), keylet::ownerDir(alice.id())); BEAST_EXPECT(std::distance(aod.begin(), aod.end()) == 2); - BEAST_EXPECT( - std::find(aod.begin(), aod.end(), ab) != aod.end()); + BEAST_EXPECT(std::find(aod.begin(), aod.end(), ab) != aod.end()); xrpl::Dir bod(*env.current(), keylet::ownerDir(bob.id())); BEAST_EXPECT(std::distance(bod.begin(), bod.end()) == 3); - BEAST_EXPECT( - std::find(bod.begin(), bod.end(), ab) != bod.end()); - BEAST_EXPECT( - std::find(bod.begin(), bod.end(), bc) != bod.end()); + BEAST_EXPECT(std::find(bod.begin(), bod.end(), ab) != bod.end()); + BEAST_EXPECT(std::find(bod.begin(), bod.end(), bc) != bod.end()); xrpl::Dir cod(*env.current(), keylet::ownerDir(carol.id())); BEAST_EXPECT(std::distance(cod.begin(), cod.end()) == 2); - BEAST_EXPECT( - std::find(cod.begin(), cod.end(), bc) != cod.end()); + BEAST_EXPECT(std::find(cod.begin(), cod.end(), bc) != cod.end()); } env.close(5s); @@ -3346,15 +3157,12 @@ struct EscrowToken_test : public beast::unit_test::suite xrpl::Dir aod(*env.current(), keylet::ownerDir(alice.id())); BEAST_EXPECT(std::distance(aod.begin(), aod.end()) == 1); - BEAST_EXPECT( - std::find(aod.begin(), aod.end(), ab) == aod.end()); + BEAST_EXPECT(std::find(aod.begin(), aod.end(), ab) == aod.end()); xrpl::Dir bod(*env.current(), keylet::ownerDir(bob.id())); BEAST_EXPECT(std::distance(bod.begin(), bod.end()) == 2); - BEAST_EXPECT( - std::find(bod.begin(), bod.end(), ab) == bod.end()); - BEAST_EXPECT( - std::find(bod.begin(), bod.end(), bc) != bod.end()); + BEAST_EXPECT(std::find(bod.begin(), bod.end(), ab) == bod.end()); + BEAST_EXPECT(std::find(bod.begin(), bod.end(), bc) != bod.end()); xrpl::Dir cod(*env.current(), keylet::ownerDir(carol.id())); BEAST_EXPECT(std::distance(cod.begin(), cod.end()) == 2); @@ -3368,15 +3176,12 @@ struct EscrowToken_test : public beast::unit_test::suite xrpl::Dir aod(*env.current(), keylet::ownerDir(alice.id())); BEAST_EXPECT(std::distance(aod.begin(), aod.end()) == 1); - BEAST_EXPECT( - std::find(aod.begin(), aod.end(), ab) == aod.end()); + BEAST_EXPECT(std::find(aod.begin(), aod.end(), ab) == aod.end()); xrpl::Dir bod(*env.current(), keylet::ownerDir(bob.id())); BEAST_EXPECT(std::distance(bod.begin(), bod.end()) == 1); - BEAST_EXPECT( - std::find(bod.begin(), bod.end(), ab) == bod.end()); - BEAST_EXPECT( - std::find(bod.begin(), bod.end(), bc) == bod.end()); + BEAST_EXPECT(std::find(bod.begin(), bod.end(), ab) == bod.end()); + BEAST_EXPECT(std::find(bod.begin(), bod.end(), bc) == bod.end()); xrpl::Dir cod(*env.current(), keylet::ownerDir(carol.id())); BEAST_EXPECT(std::distance(cod.begin(), cod.end()) == 1); @@ -3399,10 +3204,7 @@ struct EscrowToken_test : public beast::unit_test::suite auto const gw = Account("gw"); MPTTester mptGw(env, gw, {.holders = {alice}}); - mptGw.create( - {.ownerCount = 1, - .holderCount = 0, - .flags = tfMPTCanEscrow | tfMPTCanTransfer}); + mptGw.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); mptGw.authorize({.account = alice}); auto const MPT = mptGw["MPT"]; env(pay(gw, alice, MPT(10'000))); @@ -3464,10 +3266,7 @@ struct EscrowToken_test : public beast::unit_test::suite MPTTester mptGw(env, gw, {.holders = {alice, bob}}); mptGw.create( - {.transferFee = 25000, - .ownerCount = 1, - .holderCount = 0, - .flags = tfMPTCanEscrow | tfMPTCanTransfer}); + {.transferFee = 25000, .ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = bob}); auto const MPT = mptGw["MPT"]; @@ -3485,8 +3284,7 @@ struct EscrowToken_test : public beast::unit_test::suite fee(baseFee * 150)); env.close(); auto const transferRate = escrow::rate(env, alice, seq1); - BEAST_EXPECT( - transferRate.value == std::uint32_t(1'000'000'000 * 1.25)); + BEAST_EXPECT(transferRate.value == std::uint32_t(1'000'000'000 * 1.25)); BEAST_EXPECT(mptEscrowed(env, alice, MPT) == 125); BEAST_EXPECT(issuerMPTEscrowed(env, MPT) == 125); @@ -3502,11 +3300,9 @@ struct EscrowToken_test : public beast::unit_test::suite BEAST_EXPECT(env.balance(alice, MPT) == preAlice - delta); BEAST_EXPECT(env.balance(bob, MPT) == MPT(10'100)); - auto const escrowedWithFix = - env.current()->rules().enabled(fixTokenEscrowV1) ? 0 : 25; + auto const escrowedWithFix = env.current()->rules().enabled(fixTokenEscrowV1) ? 0 : 25; auto const outstandingWithFix = - env.current()->rules().enabled(fixTokenEscrowV1) ? MPT(19'975) - : MPT(20'000); + env.current()->rules().enabled(fixTokenEscrowV1) ? MPT(19'975) : MPT(20'000); BEAST_EXPECT(mptEscrowed(env, alice, MPT) == escrowedWithFix); BEAST_EXPECT(issuerMPTEscrowed(env, MPT) == escrowedWithFix); BEAST_EXPECT(env.balance(gw, MPT) == -outstandingWithFix); @@ -3522,10 +3318,7 @@ struct EscrowToken_test : public beast::unit_test::suite MPTTester mptGw(env, gw, {.holders = {alice, bob}}); mptGw.create( - {.transferFee = 25000, - .ownerCount = 1, - .holderCount = 0, - .flags = tfMPTCanEscrow | tfMPTCanTransfer}); + {.transferFee = 25000, .ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = bob}); auto const MPT = mptGw["MPT"]; @@ -3545,8 +3338,7 @@ struct EscrowToken_test : public beast::unit_test::suite fee(baseFee * 150)); env.close(); auto const transferRate = escrow::rate(env, alice, seq1); - BEAST_EXPECT( - transferRate.value == std::uint32_t(1'000'000'000 * 1.25)); + BEAST_EXPECT(transferRate.value == std::uint32_t(1'000'000'000 * 1.25)); // alice can cancel escrow env(escrow::cancel(alice, alice, seq1), fee(baseFee)); @@ -3569,10 +3361,7 @@ struct EscrowToken_test : public beast::unit_test::suite MPTTester mptGw(env, gw, {.holders = {alice, bob}}); mptGw.create( - {.transferFee = 25000, - .ownerCount = 1, - .holderCount = 0, - .flags = tfMPTCanEscrow | tfMPTCanTransfer}); + {.transferFee = 25000, .ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = bob}); auto const MPT = mptGw["MPT"]; @@ -3590,8 +3379,7 @@ struct EscrowToken_test : public beast::unit_test::suite fee(baseFee * 150)); env.close(); auto const transferRate = escrow::rate(env, alice, seq1); - BEAST_EXPECT( - transferRate.value == std::uint32_t(1'000'000'000 * 1.25)); + BEAST_EXPECT(transferRate.value == std::uint32_t(1'000'000'000 * 1.25)); BEAST_EXPECT(mptEscrowed(env, alice, MPT) == 125); BEAST_EXPECT(issuerMPTEscrowed(env, MPT) == 125); @@ -3626,9 +3414,7 @@ struct EscrowToken_test : public beast::unit_test::suite MPTTester mptGw(env, gw, {.holders = {alice, bob}}); mptGw.create( - {.ownerCount = 1, - .holderCount = 0, - .flags = tfMPTCanEscrow | tfMPTCanTransfer | tfMPTRequireAuth}); + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer | tfMPTRequireAuth}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = gw, .holder = alice}); mptGw.authorize({.account = bob}); @@ -3668,10 +3454,7 @@ struct EscrowToken_test : public beast::unit_test::suite auto const gw = Account("gw"); MPTTester mptGw(env, gw, {.holders = {alice, bob}}); - mptGw.create( - {.ownerCount = 1, - .holderCount = 0, - .flags = tfMPTCanEscrow | tfMPTCanTransfer | tfMPTCanLock}); + mptGw.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer | tfMPTCanLock}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = bob}); auto const MPT = mptGw["MPT"]; @@ -3719,8 +3502,7 @@ struct EscrowToken_test : public beast::unit_test::suite auto const gw = Account("gw"); MPTTester mptGw(env, gw, {.holders = {alice, bob}}); - mptGw.create( - {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow}); + mptGw.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = bob}); auto const MPT = mptGw["MPT"]; @@ -3788,10 +3570,7 @@ struct EscrowToken_test : public beast::unit_test::suite auto const gw = Account("gw"); MPTTester mptGw(env, gw, {.holders = {alice, bob}}); - mptGw.create( - {.ownerCount = 1, - .holderCount = 0, - .flags = tfMPTCanEscrow | tfMPTCanTransfer}); + mptGw.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); mptGw.authorize({.account = alice}); mptGw.authorize({.account = bob}); auto const MPT = mptGw["MPT"]; @@ -3815,10 +3594,7 @@ struct EscrowToken_test : public beast::unit_test::suite BEAST_EXPECT(mptEscrowed(env, bob, MPT) == 0); BEAST_EXPECT(env.balance(gw, MPT) == MPT(-10)); mptGw.authorize({.account = bob, .flags = tfMPTUnauthorize}); - mptGw.destroy( - {.id = mptGw.issuanceID(), - .ownerCount = 1, - .err = tecHAS_OBLIGATIONS}); + mptGw.destroy({.id = mptGw.issuanceID(), .ownerCount = 1, .err = tecHAS_OBLIGATIONS}); env(escrow::finish(bob, alice, seq1), escrow::condition(escrow::cb1), @@ -3842,10 +3618,7 @@ struct EscrowToken_test : public beast::unit_test::suite env.close(); MPTTester mptGw(env, gw, {.holders = {alice}}); - mptGw.create( - {.ownerCount = 1, - .holderCount = 0, - .flags = tfMPTCanEscrow | tfMPTCanTransfer}); + mptGw.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanEscrow | tfMPTCanTransfer}); mptGw.authorize({.account = alice}); auto const MPT = mptGw["MPT"]; env(pay(gw, alice, MPT(10'000))); @@ -3864,10 +3637,7 @@ struct EscrowToken_test : public beast::unit_test::suite BEAST_EXPECT(env.balance(alice, MPT) == MPT(0)); BEAST_EXPECT(mptEscrowed(env, alice, MPT) == 10); - mptGw.authorize( - {.account = alice, - .flags = tfMPTUnauthorize, - .err = tecHAS_OBLIGATIONS}); + mptGw.authorize({.account = alice, .flags = tfMPTUnauthorize, .err = tecHAS_OBLIGATIONS}); env(escrow::finish(bob, alice, seq1), escrow::condition(escrow::cb1), @@ -3901,7 +3671,7 @@ struct EscrowToken_test : public beast::unit_test::suite testIOULimitAmount(features); testIOURequireAuth(features); testIOUFreeze(features); - testIOUINSF(features); + testIOUInsufficientFunds(features); testIOUPrecisionLoss(features); } @@ -3930,8 +3700,7 @@ public: { using namespace test::jtx; FeatureBitset const all{testable_amendments()}; - for (FeatureBitset const& feats : - {all - featureSingleAssetVault - featureLendingProtocol, all}) + for (FeatureBitset const& feats : {all - featureSingleAssetVault - featureLendingProtocol, all}) { testIOUWithFeats(feats); testMPTWithFeats(feats); diff --git a/src/test/app/Escrow_test.cpp b/src/test/app/Escrow_test.cpp index 2b7297009a..652049270f 100644 --- a/src/test/app/Escrow_test.cpp +++ b/src/test/app/Escrow_test.cpp @@ -27,8 +27,7 @@ struct Escrow_test : public beast::unit_test::suite Env env(*this, features); auto const baseFee = env.current()->fees().base; env.fund(XRP(5000), "alice", "bob"); - env(escrow::create("alice", "bob", XRP(1000)), - escrow::finish_time(env.now() + 1s)); + env(escrow::create("alice", "bob", XRP(1000)), escrow::finish_time(env.now() + 1s)); env.close(); auto const seq1 = env.seq("alice"); @@ -71,15 +70,12 @@ struct Escrow_test : public beast::unit_test::suite auto const ts = env.now() + 97s; auto const seq = env.seq("alice"); - env(escrow::create("alice", "bob", XRP(1000)), - escrow::finish_time(ts)); + env(escrow::create("alice", "bob", XRP(1000)), escrow::finish_time(ts)); // Advance the ledger, verifying that the finish won't complete // prematurely. for (; env.now() < ts; env.close()) - env(escrow::finish("bob", "alice", seq), - fee(baseFee * 150), - ter(tecNO_PERMISSION)); + env(escrow::finish("bob", "alice", seq), fee(baseFee * 150), ter(tecNO_PERMISSION)); env(escrow::finish("bob", "alice", seq), fee(baseFee * 150)); } @@ -95,16 +91,12 @@ struct Escrow_test : public beast::unit_test::suite auto const ts = env.now() + 117s; auto const seq = env.seq("alice"); - env(escrow::create("alice", "bob", XRP(1000)), - escrow::condition(escrow::cb1), - escrow::cancel_time(ts)); + env(escrow::create("alice", "bob", XRP(1000)), escrow::condition(escrow::cb1), escrow::cancel_time(ts)); // Advance the ledger, verifying that the cancel won't complete // prematurely. for (; env.now() < ts; env.close()) - env(escrow::cancel("bob", "alice", seq), - fee(baseFee * 150), - ter(tecNO_PERMISSION)); + env(escrow::cancel("bob", "alice", seq), fee(baseFee * 150), ter(tecNO_PERMISSION)); // Verify that a finish won't work anymore. env(escrow::finish("bob", "alice", seq), @@ -129,26 +121,18 @@ struct Escrow_test : public beast::unit_test::suite auto const cts = env.now() + 192s; auto const seq = env.seq("alice"); - env(escrow::create("alice", "bob", XRP(1000)), - escrow::finish_time(fts), - escrow::cancel_time(cts)); + env(escrow::create("alice", "bob", XRP(1000)), escrow::finish_time(fts), escrow::cancel_time(cts)); // Advance the ledger, verifying that the finish and cancel won't // complete prematurely. for (; env.now() < fts; env.close()) { - env(escrow::finish("bob", "alice", seq), - fee(baseFee * 150), - ter(tecNO_PERMISSION)); - env(escrow::cancel("bob", "alice", seq), - fee(baseFee * 150), - ter(tecNO_PERMISSION)); + env(escrow::finish("bob", "alice", seq), fee(baseFee * 150), ter(tecNO_PERMISSION)); + env(escrow::cancel("bob", "alice", seq), fee(baseFee * 150), ter(tecNO_PERMISSION)); } // Verify that a cancel still won't work - env(escrow::cancel("bob", "alice", seq), - fee(baseFee * 150), - ter(tecNO_PERMISSION)); + env(escrow::cancel("bob", "alice", seq), fee(baseFee * 150), ter(tecNO_PERMISSION)); // And verify that a finish will env(escrow::finish("bob", "alice", seq), fee(baseFee * 150)); @@ -166,34 +150,24 @@ struct Escrow_test : public beast::unit_test::suite auto const cts = env.now() + 184s; auto const seq = env.seq("alice"); - env(escrow::create("alice", "bob", XRP(1000)), - escrow::finish_time(fts), - escrow::cancel_time(cts)); + env(escrow::create("alice", "bob", XRP(1000)), escrow::finish_time(fts), escrow::cancel_time(cts)); // Advance the ledger, verifying that the finish and cancel won't // complete prematurely. for (; env.now() < fts; env.close()) { - env(escrow::finish("bob", "alice", seq), - fee(baseFee * 150), - ter(tecNO_PERMISSION)); - env(escrow::cancel("bob", "alice", seq), - fee(baseFee * 150), - ter(tecNO_PERMISSION)); + env(escrow::finish("bob", "alice", seq), fee(baseFee * 150), ter(tecNO_PERMISSION)); + env(escrow::cancel("bob", "alice", seq), fee(baseFee * 150), ter(tecNO_PERMISSION)); } // Continue advancing, verifying that the cancel won't complete // prematurely. At this point a finish would succeed. for (; env.now() < cts; env.close()) - env(escrow::cancel("bob", "alice", seq), - fee(baseFee * 150), - ter(tecNO_PERMISSION)); + env(escrow::cancel("bob", "alice", seq), fee(baseFee * 150), ter(tecNO_PERMISSION)); // Verify that finish will no longer work, since we are past the // cancel activation time. - env(escrow::finish("bob", "alice", seq), - fee(baseFee * 150), - ter(tecNO_PERMISSION)); + env(escrow::finish("bob", "alice", seq), fee(baseFee * 150), ter(tecNO_PERMISSION)); // And verify that a cancel will succeed. env(escrow::cancel("bob", "alice", seq), fee(baseFee * 150)); @@ -218,17 +192,12 @@ struct Escrow_test : public beast::unit_test::suite // Check to make sure that we correctly detect if tags are really // required: env(fset(bob, asfRequireDest)); - env(escrow::create(alice, bob, XRP(1000)), - escrow::finish_time(env.now() + 1s), - ter(tecDST_TAG_NEEDED)); + env(escrow::create(alice, bob, XRP(1000)), escrow::finish_time(env.now() + 1s), ter(tecDST_TAG_NEEDED)); // set source and dest tags auto const seq = env.seq(alice); - env(escrow::create(alice, bob, XRP(1000)), - escrow::finish_time(env.now() + 1s), - stag(1), - dtag(2)); + env(escrow::create(alice, bob, XRP(1000)), escrow::finish_time(env.now() + 1s), stag(1), dtag(2)); auto const sle = env.le(keylet::escrow(alice.id(), seq)); BEAST_EXPECT(sle); @@ -259,8 +228,7 @@ struct Escrow_test : public beast::unit_test::suite env.fund(XRP(5000), "bob", "george"); env(fset("george", asfDisallowXRP)); - env(escrow::create("bob", "george", XRP(10)), - escrow::finish_time(env.now() + 1s)); + env(escrow::create("bob", "george", XRP(10)), escrow::finish_time(env.now() + 1s)); } } @@ -307,9 +275,7 @@ struct Escrow_test : public beast::unit_test::suite fee(baseFee * 150)); env.close(); env(escrow::finish("carol", "alice", seqFt), fee(150 * baseFee)); - BEAST_EXPECT( - env.balance("bob") == - XRP(5200)); // 5100 (from last transaction) + 100 + BEAST_EXPECT(env.balance("bob") == XRP(5200)); // 5100 (from last transaction) + 100 } void @@ -332,9 +298,7 @@ struct Escrow_test : public beast::unit_test::suite ter(temINVALID_FLAG)); // Finish time is in the past - env(escrow::create("alice", "bob", XRP(1000)), - escrow::finish_time(env.now() - 5s), - ter(tecNO_PERMISSION)); + env(escrow::create("alice", "bob", XRP(1000)), escrow::finish_time(env.now() - 5s), ter(tecNO_PERMISSION)); // Cancel time is in the past env(escrow::create("alice", "bob", XRP(1000)), @@ -343,45 +307,33 @@ struct Escrow_test : public beast::unit_test::suite ter(tecNO_PERMISSION)); // no destination account - env(escrow::create("alice", "carol", XRP(1000)), - escrow::finish_time(env.now() + 1s), - ter(tecNO_DST)); + env(escrow::create("alice", "carol", XRP(1000)), escrow::finish_time(env.now() + 1s), ter(tecNO_DST)); env.fund(XRP(5000), "carol"); // Using non-XRP: - bool const withTokenEscrow = - env.current()->rules().enabled(featureTokenEscrow); + bool const withTokenEscrow = env.current()->rules().enabled(featureTokenEscrow); { // tecNO_PERMISSION: token escrow is enabled but the issuer did not // set the asfAllowTrustLineLocking flag - auto const txResult = - withTokenEscrow ? ter(tecNO_PERMISSION) : ter(temBAD_AMOUNT); + auto const txResult = withTokenEscrow ? ter(tecNO_PERMISSION) : ter(temBAD_AMOUNT); env(escrow::create("alice", "carol", Account("alice")["USD"](500)), escrow::finish_time(env.now() + 5s), txResult); } // Sending zero or no XRP: - env(escrow::create("alice", "carol", XRP(0)), - escrow::finish_time(env.now() + 1s), - ter(temBAD_AMOUNT)); - env(escrow::create("alice", "carol", XRP(-1000)), - escrow::finish_time(env.now() + 1s), - ter(temBAD_AMOUNT)); + env(escrow::create("alice", "carol", XRP(0)), escrow::finish_time(env.now() + 1s), ter(temBAD_AMOUNT)); + env(escrow::create("alice", "carol", XRP(-1000)), escrow::finish_time(env.now() + 1s), ter(temBAD_AMOUNT)); // Fail if neither CancelAfter nor FinishAfter are specified: env(escrow::create("alice", "carol", XRP(1)), ter(temBAD_EXPIRATION)); // Fail if neither a FinishTime nor a condition are attached: - env(escrow::create("alice", "carol", XRP(1)), - escrow::cancel_time(env.now() + 1s), - ter(temMALFORMED)); + env(escrow::create("alice", "carol", XRP(1)), escrow::cancel_time(env.now() + 1s), ter(temMALFORMED)); // Fail if FinishAfter has already passed: - env(escrow::create("alice", "carol", XRP(1)), - escrow::finish_time(env.now() - 1s), - ter(tecNO_PERMISSION)); + env(escrow::create("alice", "carol", XRP(1)), escrow::finish_time(env.now() - 1s), ter(tecNO_PERMISSION)); // If both CancelAfter and FinishAfter are set, then CancelAfter must // be strictly later than FinishAfter. @@ -414,18 +366,13 @@ struct Escrow_test : public beast::unit_test::suite { // Fail if the sender wants to send more than he has: auto const accountReserve = drops(env.current()->fees().reserve); - auto const accountIncrement = - drops(env.current()->fees().increment); + auto const accountIncrement = drops(env.current()->fees().increment); env.fund(accountReserve + accountIncrement + XRP(50), "daniel"); - env(escrow::create("daniel", "bob", XRP(51)), - escrow::finish_time(env.now() + 1s), - ter(tecUNFUNDED)); + env(escrow::create("daniel", "bob", XRP(51)), escrow::finish_time(env.now() + 1s), ter(tecUNFUNDED)); env.fund(accountReserve + accountIncrement + XRP(50), "evan"); - env(escrow::create("evan", "bob", XRP(50)), - escrow::finish_time(env.now() + 1s), - ter(tecUNFUNDED)); + env(escrow::create("evan", "bob", XRP(50)), escrow::finish_time(env.now() + 1s), ter(tecUNFUNDED)); env.fund(accountReserve, "frank"); env(escrow::create("frank", "bob", XRP(1)), @@ -436,21 +383,16 @@ struct Escrow_test : public beast::unit_test::suite { // Specify incorrect sequence number env.fund(XRP(5000), "hannah"); auto const seq = env.seq("hannah"); - env(escrow::create("hannah", "hannah", XRP(10)), - escrow::finish_time(env.now() + 1s), - fee(150 * baseFee)); + env(escrow::create("hannah", "hannah", XRP(10)), escrow::finish_time(env.now() + 1s), fee(150 * baseFee)); env.close(); - env(escrow::finish("hannah", "hannah", seq + 7), - fee(150 * baseFee), - ter(tecNO_TARGET)); + env(escrow::finish("hannah", "hannah", seq + 7), fee(150 * baseFee), ter(tecNO_TARGET)); } { // Try to specify a condition for a non-conditional payment env.fund(XRP(5000), "ivan"); auto const seq = env.seq("ivan"); - env(escrow::create("ivan", "ivan", XRP(10)), - escrow::finish_time(env.now() + 1s)); + env(escrow::create("ivan", "ivan", XRP(10)), escrow::finish_time(env.now() + 1s)); env.close(); env(escrow::finish("ivan", "ivan", seq), escrow::condition(escrow::cb1), @@ -474,8 +416,7 @@ struct Escrow_test : public beast::unit_test::suite auto const baseFee = env.current()->fees().base; env.fund(XRP(5000), "alice", "bob"); auto const seq = env.seq("alice"); - env(escrow::create("alice", "alice", XRP(1000)), - escrow::finish_time(env.now() + 5s)); + env(escrow::create("alice", "alice", XRP(1000)), escrow::finish_time(env.now() + 5s)); env.require(balance("alice", XRP(4000) - drops(baseFee))); // Not enough time has elapsed for a finish and canceling isn't @@ -499,8 +440,7 @@ struct Escrow_test : public beast::unit_test::suite auto const baseFee = env.current()->fees().base; env.fund(XRP(5000), "alice", "bob", "zelda"); auto const seq = env.seq("alice"); - env(escrow::create("alice", "bob", XRP(1000)), - escrow::finish_time(env.now() + 5s)); + env(escrow::create("alice", "bob", XRP(1000)), escrow::finish_time(env.now() + 5s)); env.require(balance("alice", XRP(4000) - drops(baseFee))); // Not enough time has elapsed for a finish and canceling isn't @@ -530,8 +470,7 @@ struct Escrow_test : public beast::unit_test::suite env.close(); auto const seq = env.seq("alice"); - env(escrow::create("alice", "bob", XRP(1000)), - escrow::finish_time(env.now() + 5s)); + env(escrow::create("alice", "bob", XRP(1000)), escrow::finish_time(env.now() + 5s)); env.require(balance("alice", XRP(4000) - drops(baseFee))); // Not enough time has elapsed for a finish and canceling isn't @@ -571,8 +510,7 @@ struct Escrow_test : public beast::unit_test::suite env.close(); auto const seq = env.seq("alice"); - env(escrow::create("alice", "bob", XRP(1000)), - escrow::finish_time(env.now() + 5s)); + env(escrow::create("alice", "bob", XRP(1000)), escrow::finish_time(env.now() + 5s)); env.require(balance("alice", XRP(4000) - drops(baseFee))); env.close(); @@ -620,10 +558,8 @@ struct Escrow_test : public beast::unit_test::suite // requires the fulfillment associated with the escrow. env(escrow::cancel("alice", "alice", seq), ter(tecNO_PERMISSION)); env(escrow::cancel("bob", "alice", seq), ter(tecNO_PERMISSION)); - env(escrow::finish("bob", "alice", seq), - ter(tecCRYPTOCONDITION_ERROR)); - env(escrow::finish("alice", "alice", seq), - ter(tecCRYPTOCONDITION_ERROR)); + env(escrow::finish("bob", "alice", seq), ter(tecCRYPTOCONDITION_ERROR)); + env(escrow::finish("alice", "alice", seq), ter(tecCRYPTOCONDITION_ERROR)); env.close(); env(escrow::finish("bob", "alice", seq), @@ -645,10 +581,8 @@ struct Escrow_test : public beast::unit_test::suite env.close(); // Finish is now possible but requires the cryptocondition. - env(escrow::finish("bob", "alice", seq), - ter(tecCRYPTOCONDITION_ERROR)); - env(escrow::finish("alice", "alice", seq), - ter(tecCRYPTOCONDITION_ERROR)); + env(escrow::finish("bob", "alice", seq), ter(tecCRYPTOCONDITION_ERROR)); + env(escrow::finish("alice", "alice", seq), ter(tecCRYPTOCONDITION_ERROR)); // Enable deposit authorization. After this only Alice can finish // the escrow. @@ -689,12 +623,9 @@ struct Escrow_test : public beast::unit_test::suite env.close(); // Finish is now possible but requires the cryptocondition. - env(escrow::finish("alice", "alice", seq), - ter(tecCRYPTOCONDITION_ERROR)); - env(escrow::finish("bob", "alice", seq), - ter(tecCRYPTOCONDITION_ERROR)); - env(escrow::finish("zelda", "alice", seq), - ter(tecCRYPTOCONDITION_ERROR)); + env(escrow::finish("alice", "alice", seq), ter(tecCRYPTOCONDITION_ERROR)); + env(escrow::finish("bob", "alice", seq), ter(tecCRYPTOCONDITION_ERROR)); + env(escrow::finish("zelda", "alice", seq), ter(tecCRYPTOCONDITION_ERROR)); // Alice enables deposit authorization. After this only Alice or // Zelda (because Zelda is preauthorized) can finish the escrow. @@ -742,8 +673,7 @@ struct Escrow_test : public beast::unit_test::suite BEAST_EXPECT((*env.le("alice"))[sfOwnerCount] == 1); // Attempt to finish without a fulfillment - env(escrow::finish("bob", "alice", seq), - ter(tecCRYPTOCONDITION_ERROR)); + env(escrow::finish("bob", "alice", seq), ter(tecCRYPTOCONDITION_ERROR)); BEAST_EXPECT((*env.le("alice"))[sfOwnerCount] == 1); // Attempt to finish with a condition instead of a fulfillment @@ -1079,12 +1009,8 @@ struct Escrow_test : public beast::unit_test::suite // Assemble finish that is missing the Condition or the Fulfillment // since either both must be present, or neither can: - env(escrow::finish("bob", "alice", seq), - escrow::condition(escrow::cb3), - ter(temMALFORMED)); - env(escrow::finish("bob", "alice", seq), - escrow::fulfillment(escrow::fb3), - ter(temMALFORMED)); + env(escrow::finish("bob", "alice", seq), escrow::condition(escrow::cb3), ter(temMALFORMED)); + env(escrow::finish("bob", "alice", seq), escrow::fulfillment(escrow::fb3), ter(temMALFORMED)); // Now finish it. env(escrow::finish("bob", "alice", seq), @@ -1099,12 +1025,10 @@ struct Escrow_test : public beast::unit_test::suite Env env(*this, features); env.fund(XRP(5000), "alice", "bob"); - std::array cb = { - {0xA2, 0x2B, 0x80, 0x20, 0x42, 0x4A, 0x70, 0x49, 0x49, - 0x52, 0x92, 0x67, 0xB6, 0x21, 0xB3, 0xD7, 0x91, 0x19, - 0xD7, 0x29, 0xB2, 0x38, 0x2C, 0xED, 0x8B, 0x29, 0x6C, - 0x3C, 0x02, 0x8F, 0xA9, 0x7D, 0x35, 0x0F, 0x6D, 0x07, - 0x81, 0x03, 0x06, 0x34, 0xD2, 0x82, 0x02, 0x03, 0xC8}}; + std::array cb = {{0xA2, 0x2B, 0x80, 0x20, 0x42, 0x4A, 0x70, 0x49, 0x49, 0x52, 0x92, 0x67, + 0xB6, 0x21, 0xB3, 0xD7, 0x91, 0x19, 0xD7, 0x29, 0xB2, 0x38, 0x2C, 0xED, + 0x8B, 0x29, 0x6C, 0x3C, 0x02, 0x8F, 0xA9, 0x7D, 0x35, 0x0F, 0x6D, 0x07, + 0x81, 0x03, 0x06, 0x34, 0xD2, 0x82, 0x02, 0x03, 0xC8}}; // FIXME: this transaction should, eventually, return temDISABLED // instead of temMALFORMED. @@ -1136,9 +1060,7 @@ struct Escrow_test : public beast::unit_test::suite env(escrow::create(alice, alice, XRP(1000)), escrow::finish_time(env.now() + 1s), escrow::cancel_time(env.now() + 500s)); - BEAST_EXPECT( - (*env.meta())[sfTransactionResult] == - static_cast(tesSUCCESS)); + BEAST_EXPECT((*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); env.close(5s); auto const aa = env.le(keylet::escrow(alice.id(), aseq)); BEAST_EXPECT(aa); @@ -1146,16 +1068,13 @@ struct Escrow_test : public beast::unit_test::suite { xrpl::Dir aod(*env.current(), keylet::ownerDir(alice.id())); BEAST_EXPECT(std::distance(aod.begin(), aod.end()) == 1); - BEAST_EXPECT( - std::find(aod.begin(), aod.end(), aa) != aod.end()); + BEAST_EXPECT(std::find(aod.begin(), aod.end(), aa) != aod.end()); } env(escrow::create(bruce, bruce, XRP(1000)), escrow::finish_time(env.now() + 1s), escrow::cancel_time(env.now() + 2s)); - BEAST_EXPECT( - (*env.meta())[sfTransactionResult] == - static_cast(tesSUCCESS)); + BEAST_EXPECT((*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); env.close(5s); auto const bb = env.le(keylet::escrow(bruce.id(), bseq)); BEAST_EXPECT(bb); @@ -1163,41 +1082,33 @@ struct Escrow_test : public beast::unit_test::suite { xrpl::Dir bod(*env.current(), keylet::ownerDir(bruce.id())); BEAST_EXPECT(std::distance(bod.begin(), bod.end()) == 1); - BEAST_EXPECT( - std::find(bod.begin(), bod.end(), bb) != bod.end()); + BEAST_EXPECT(std::find(bod.begin(), bod.end(), bb) != bod.end()); } env.close(5s); env(escrow::finish(alice, alice, aseq)); { BEAST_EXPECT(!env.le(keylet::escrow(alice.id(), aseq))); - BEAST_EXPECT( - (*env.meta())[sfTransactionResult] == - static_cast(tesSUCCESS)); + BEAST_EXPECT((*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); xrpl::Dir aod(*env.current(), keylet::ownerDir(alice.id())); BEAST_EXPECT(std::distance(aod.begin(), aod.end()) == 0); - BEAST_EXPECT( - std::find(aod.begin(), aod.end(), aa) == aod.end()); + BEAST_EXPECT(std::find(aod.begin(), aod.end(), aa) == aod.end()); xrpl::Dir bod(*env.current(), keylet::ownerDir(bruce.id())); BEAST_EXPECT(std::distance(bod.begin(), bod.end()) == 1); - BEAST_EXPECT( - std::find(bod.begin(), bod.end(), bb) != bod.end()); + BEAST_EXPECT(std::find(bod.begin(), bod.end(), bb) != bod.end()); } env.close(5s); env(escrow::cancel(bruce, bruce, bseq)); { BEAST_EXPECT(!env.le(keylet::escrow(bruce.id(), bseq))); - BEAST_EXPECT( - (*env.meta())[sfTransactionResult] == - static_cast(tesSUCCESS)); + BEAST_EXPECT((*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); xrpl::Dir bod(*env.current(), keylet::ownerDir(bruce.id())); BEAST_EXPECT(std::distance(bod.begin(), bod.end()) == 0); - BEAST_EXPECT( - std::find(bod.begin(), bod.end(), bb) == bod.end()); + BEAST_EXPECT(std::find(bod.begin(), bod.end(), bb) == bod.end()); } } { @@ -1208,18 +1119,13 @@ struct Escrow_test : public beast::unit_test::suite auto const aseq = env.seq(alice); auto const bseq = env.seq(bruce); - env(escrow::create(alice, bruce, XRP(1000)), - escrow::finish_time(env.now() + 1s)); - BEAST_EXPECT( - (*env.meta())[sfTransactionResult] == - static_cast(tesSUCCESS)); + env(escrow::create(alice, bruce, XRP(1000)), escrow::finish_time(env.now() + 1s)); + BEAST_EXPECT((*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); env.close(5s); env(escrow::create(bruce, carol, XRP(1000)), escrow::finish_time(env.now() + 1s), escrow::cancel_time(env.now() + 2s)); - BEAST_EXPECT( - (*env.meta())[sfTransactionResult] == - static_cast(tesSUCCESS)); + BEAST_EXPECT((*env.meta())[sfTransactionResult] == static_cast(tesSUCCESS)); env.close(5s); auto const ab = env.le(keylet::escrow(alice.id(), aseq)); @@ -1231,20 +1137,16 @@ struct Escrow_test : public beast::unit_test::suite { xrpl::Dir aod(*env.current(), keylet::ownerDir(alice.id())); BEAST_EXPECT(std::distance(aod.begin(), aod.end()) == 1); - BEAST_EXPECT( - std::find(aod.begin(), aod.end(), ab) != aod.end()); + BEAST_EXPECT(std::find(aod.begin(), aod.end(), ab) != aod.end()); xrpl::Dir bod(*env.current(), keylet::ownerDir(bruce.id())); BEAST_EXPECT(std::distance(bod.begin(), bod.end()) == 2); - BEAST_EXPECT( - std::find(bod.begin(), bod.end(), ab) != bod.end()); - BEAST_EXPECT( - std::find(bod.begin(), bod.end(), bc) != bod.end()); + BEAST_EXPECT(std::find(bod.begin(), bod.end(), ab) != bod.end()); + BEAST_EXPECT(std::find(bod.begin(), bod.end(), bc) != bod.end()); xrpl::Dir cod(*env.current(), keylet::ownerDir(carol.id())); BEAST_EXPECT(std::distance(cod.begin(), cod.end()) == 1); - BEAST_EXPECT( - std::find(cod.begin(), cod.end(), bc) != cod.end()); + BEAST_EXPECT(std::find(cod.begin(), cod.end(), bc) != cod.end()); } env.close(5s); @@ -1255,15 +1157,12 @@ struct Escrow_test : public beast::unit_test::suite xrpl::Dir aod(*env.current(), keylet::ownerDir(alice.id())); BEAST_EXPECT(std::distance(aod.begin(), aod.end()) == 0); - BEAST_EXPECT( - std::find(aod.begin(), aod.end(), ab) == aod.end()); + BEAST_EXPECT(std::find(aod.begin(), aod.end(), ab) == aod.end()); xrpl::Dir bod(*env.current(), keylet::ownerDir(bruce.id())); BEAST_EXPECT(std::distance(bod.begin(), bod.end()) == 1); - BEAST_EXPECT( - std::find(bod.begin(), bod.end(), ab) == bod.end()); - BEAST_EXPECT( - std::find(bod.begin(), bod.end(), bc) != bod.end()); + BEAST_EXPECT(std::find(bod.begin(), bod.end(), ab) == bod.end()); + BEAST_EXPECT(std::find(bod.begin(), bod.end(), bc) != bod.end()); xrpl::Dir cod(*env.current(), keylet::ownerDir(carol.id())); BEAST_EXPECT(std::distance(cod.begin(), cod.end()) == 1); @@ -1277,15 +1176,12 @@ struct Escrow_test : public beast::unit_test::suite xrpl::Dir aod(*env.current(), keylet::ownerDir(alice.id())); BEAST_EXPECT(std::distance(aod.begin(), aod.end()) == 0); - BEAST_EXPECT( - std::find(aod.begin(), aod.end(), ab) == aod.end()); + BEAST_EXPECT(std::find(aod.begin(), aod.end(), ab) == aod.end()); xrpl::Dir bod(*env.current(), keylet::ownerDir(bruce.id())); BEAST_EXPECT(std::distance(bod.begin(), bod.end()) == 0); - BEAST_EXPECT( - std::find(bod.begin(), bod.end(), ab) == bod.end()); - BEAST_EXPECT( - std::find(bod.begin(), bod.end(), bc) == bod.end()); + BEAST_EXPECT(std::find(bod.begin(), bod.end(), ab) == bod.end()); + BEAST_EXPECT(std::find(bod.begin(), bod.end(), bc) == bod.end()); xrpl::Dir cod(*env.current(), keylet::ownerDir(carol.id())); BEAST_EXPECT(std::distance(cod.begin(), cod.end()) == 0); @@ -1309,16 +1205,8 @@ struct Escrow_test : public beast::unit_test::suite { auto const jtx = env.jt( - escrow::create("alice", "carol", XRP(1000)), - escrow::finish_time(env.now() + 1s), - seq(1), - fee(baseFee)); - auto const pf = preflight( - env.app(), - env.current()->rules(), - *jtx.stx, - tapNONE, - env.journal); + escrow::create("alice", "carol", XRP(1000)), escrow::finish_time(env.now() + 1s), seq(1), fee(baseFee)); + auto const pf = preflight(env.app(), env.current()->rules(), *jtx.stx, tapNONE, env.journal); BEAST_EXPECT(pf.ter == tesSUCCESS); BEAST_EXPECT(!pf.consequences.isBlocker()); BEAST_EXPECT(pf.consequences.fee() == drops(baseFee)); @@ -1326,14 +1214,8 @@ struct Escrow_test : public beast::unit_test::suite } { - auto const jtx = - env.jt(escrow::cancel("bob", "alice", 3), seq(1), fee(baseFee)); - auto const pf = preflight( - env.app(), - env.current()->rules(), - *jtx.stx, - tapNONE, - env.journal); + auto const jtx = env.jt(escrow::cancel("bob", "alice", 3), seq(1), fee(baseFee)); + auto const pf = preflight(env.app(), env.current()->rules(), *jtx.stx, tapNONE, env.journal); BEAST_EXPECT(pf.ter == tesSUCCESS); BEAST_EXPECT(!pf.consequences.isBlocker()); BEAST_EXPECT(pf.consequences.fee() == drops(baseFee)); @@ -1341,14 +1223,8 @@ struct Escrow_test : public beast::unit_test::suite } { - auto const jtx = - env.jt(escrow::finish("bob", "alice", 3), seq(1), fee(baseFee)); - auto const pf = preflight( - env.app(), - env.current()->rules(), - *jtx.stx, - tapNONE, - env.journal); + auto const jtx = env.jt(escrow::finish("bob", "alice", 3), seq(1), fee(baseFee)); + auto const pf = preflight(env.app(), env.current()->rules(), *jtx.stx, tapNONE, env.journal); BEAST_EXPECT(pf.ter == tesSUCCESS); BEAST_EXPECT(!pf.consequences.isBlocker()); BEAST_EXPECT(pf.consequences.fee() == drops(baseFee)); @@ -1396,9 +1272,7 @@ struct Escrow_test : public beast::unit_test::suite auto const ts = env.now() + 97s; std::uint32_t const escrowSeq = aliceTicket; - env(escrow::create(alice, bob, XRP(1000)), - escrow::finish_time(ts), - ticket::use(aliceTicket)); + env(escrow::create(alice, bob, XRP(1000)), escrow::finish_time(ts), ticket::use(aliceTicket)); BEAST_EXPECT(env.seq(alice) == aliceRootSeq); env.require(tickets(alice, 0)); env.require(tickets(bob, bobTicketCount)); @@ -1415,15 +1289,10 @@ struct Escrow_test : public beast::unit_test::suite } // bob tries to re-use a ticket, which is rejected. - env(escrow::finish(bob, alice, escrowSeq), - fee(150 * baseFee), - ticket::use(bobTicket), - ter(tefNO_TICKET)); + env(escrow::finish(bob, alice, escrowSeq), fee(150 * baseFee), ticket::use(bobTicket), ter(tefNO_TICKET)); // bob uses one of his remaining tickets. Success! - env(escrow::finish(bob, alice, escrowSeq), - fee(150 * baseFee), - ticket::use(--bobTicket)); + env(escrow::finish(bob, alice, escrowSeq), fee(150 * baseFee), ticket::use(--bobTicket)); env.close(); BEAST_EXPECT(env.seq(bob) == bobRootSeq); } @@ -1485,9 +1354,7 @@ struct Escrow_test : public beast::unit_test::suite BEAST_EXPECT(env.seq(bob) == bobRootSeq); // Verify that the cancel succeeds. - env(escrow::cancel(bob, alice, escrowSeq), - fee(150 * baseFee), - ticket::use(bobTicket++)); + env(escrow::cancel(bob, alice, escrowSeq), fee(150 * baseFee), ticket::use(bobTicket++)); env.close(); BEAST_EXPECT(env.seq(bob) == bobRootSeq); @@ -1519,8 +1386,7 @@ struct Escrow_test : public beast::unit_test::suite env.close(); auto const seq = env.seq(alice); - env(escrow::create(alice, bob, XRP(1000)), - escrow::finish_time(env.now() + 1s)); + env(escrow::create(alice, bob, XRP(1000)), escrow::finish_time(env.now() + 1s)); env.close(); env(fset(bob, asfDepositAuth)); @@ -1531,9 +1397,7 @@ struct Escrow_test : public beast::unit_test::suite std::string const credIdx = "48004829F915654A81B11C4AB8218D96FED67F209B58328A72314FB6EA288B" "E4"; - env(escrow::finish(bob, alice, seq), - credentials::ids({credIdx}), - ter(temDISABLED)); + env(escrow::finish(bob, alice, seq), credentials::ids({credIdx}), ter(temDISABLED)); } { @@ -1544,13 +1408,11 @@ struct Escrow_test : public beast::unit_test::suite env(credentials::create(carol, zelda, credType)); env.close(); - auto const jv = - credentials::ledgerEntry(env, carol, zelda, credType); + auto const jv = credentials::ledgerEntry(env, carol, zelda, credType); std::string const credIdx = jv[jss::result][jss::index].asString(); auto const seq = env.seq(alice); - env(escrow::create(alice, bob, XRP(1000)), - escrow::finish_time(env.now() + 50s)); + env(escrow::create(alice, bob, XRP(1000)), escrow::finish_time(env.now() + 50s)); env.close(); // Bob require pre-authorization @@ -1558,9 +1420,7 @@ struct Escrow_test : public beast::unit_test::suite env.close(); // Fail, credentials not accepted - env(escrow::finish(carol, alice, seq), - credentials::ids({credIdx}), - ter(tecBAD_CREDENTIALS)); + env(escrow::finish(carol, alice, seq), credentials::ids({credIdx}), ter(tecBAD_CREDENTIALS)); env.close(); @@ -1568,14 +1428,10 @@ struct Escrow_test : public beast::unit_test::suite env.close(); // Fail, credentials doesn’t belong to root account - env(escrow::finish(dillon, alice, seq), - credentials::ids({credIdx}), - ter(tecBAD_CREDENTIALS)); + env(escrow::finish(dillon, alice, seq), credentials::ids({credIdx}), ter(tecBAD_CREDENTIALS)); // Fail, no depositPreauth - env(escrow::finish(carol, alice, seq), - credentials::ids({credIdx}), - ter(tecNO_PERMISSION)); + env(escrow::finish(carol, alice, seq), credentials::ids({credIdx}), ter(tecNO_PERMISSION)); env(deposit::authCredentials(bob, {{zelda, credType}})); env.close(); @@ -1599,13 +1455,11 @@ struct Escrow_test : public beast::unit_test::suite env.close(); env(credentials::accept(carol, zelda, credType)); env.close(); - auto const jv = - credentials::ledgerEntry(env, carol, zelda, credType); + auto const jv = credentials::ledgerEntry(env, carol, zelda, credType); std::string const credIdx = jv[jss::result][jss::index].asString(); auto const seq = env.seq(alice); - env(escrow::create(alice, bob, XRP(1000)), - escrow::finish_time(env.now() + 50s)); + env(escrow::create(alice, bob, XRP(1000)), escrow::finish_time(env.now() + 50s)); // time advance env.close(); env.close(); @@ -1626,13 +1480,10 @@ struct Escrow_test : public beast::unit_test::suite env(credentials::accept(bob, zelda, credType2)); env.close(); auto const credIdxBob = - credentials::ledgerEntry( - env, bob, zelda, credType2)[jss::result][jss::index] - .asString(); + credentials::ledgerEntry(env, bob, zelda, credType2)[jss::result][jss::index].asString(); auto const seq = env.seq(alice); - env(escrow::create(alice, bob, XRP(1000)), - escrow::finish_time(env.now() + 1s)); + env(escrow::create(alice, bob, XRP(1000)), escrow::finish_time(env.now() + 1s)); env.close(); // Bob require pre-authorization @@ -1642,8 +1493,7 @@ struct Escrow_test : public beast::unit_test::suite env.close(); // Use any valid credentials if account == dst - env(escrow::finish(bob, alice, seq), - credentials::ids({credIdxBob})); + env(escrow::finish(bob, alice, seq), credentials::ids({credIdxBob})); env.close(); } } diff --git a/src/test/app/FeeVote_test.cpp b/src/test/app/FeeVote_test.cpp index c7f33544f9..15dd385d65 100644 --- a/src/test/app/FeeVote_test.cpp +++ b/src/test/app/FeeVote_test.cpp @@ -27,10 +27,7 @@ struct FeeSettingsFields }; STTx -createFeeTx( - Rules const& rules, - std::uint32_t seq, - FeeSettingsFields const& fields) +createFeeTx(Rules const& rules, std::uint32_t seq, FeeSettingsFields const& fields) { auto fill = [&](auto& obj) { obj.setAccountID(sfAccount, AccountID()); @@ -39,30 +36,18 @@ createFeeTx( if (rules.enabled(featureXRPFees)) { // New XRPFees format - all three fields are REQUIRED + obj.setFieldAmount(sfBaseFeeDrops, fields.baseFeeDrops ? *fields.baseFeeDrops : XRPAmount{0}); + obj.setFieldAmount(sfReserveBaseDrops, fields.reserveBaseDrops ? *fields.reserveBaseDrops : XRPAmount{0}); obj.setFieldAmount( - sfBaseFeeDrops, - fields.baseFeeDrops ? *fields.baseFeeDrops : XRPAmount{0}); - obj.setFieldAmount( - sfReserveBaseDrops, - fields.reserveBaseDrops ? *fields.reserveBaseDrops - : XRPAmount{0}); - obj.setFieldAmount( - sfReserveIncrementDrops, - fields.reserveIncrementDrops ? *fields.reserveIncrementDrops - : XRPAmount{0}); + sfReserveIncrementDrops, fields.reserveIncrementDrops ? *fields.reserveIncrementDrops : XRPAmount{0}); } else { // Legacy format - all four fields are REQUIRED obj.setFieldU64(sfBaseFee, fields.baseFee ? *fields.baseFee : 0); - obj.setFieldU32( - sfReserveBase, fields.reserveBase ? *fields.reserveBase : 0); - obj.setFieldU32( - sfReserveIncrement, - fields.reserveIncrement ? *fields.reserveIncrement : 0); - obj.setFieldU32( - sfReferenceFeeUnits, - fields.referenceFeeUnits ? *fields.referenceFeeUnits : 0); + obj.setFieldU32(sfReserveBase, fields.reserveBase ? *fields.reserveBase : 0); + obj.setFieldU32(sfReserveIncrement, fields.reserveIncrement ? *fields.reserveIncrement : 0); + obj.setFieldU32(sfReferenceFeeUnits, fields.referenceFeeUnits ? *fields.referenceFeeUnits : 0); } }; return STTx(ttFEE, fill); @@ -122,16 +107,12 @@ createInvalidFeeTx( bool applyFeeAndTestResult(jtx::Env& env, OpenView& view, STTx const& tx) { - auto const res = - apply(env.app(), view, tx, ApplyFlags::tapNONE, env.journal); + auto const res = apply(env.app(), view, tx, ApplyFlags::tapNONE, env.journal); return res.ter == tesSUCCESS; } bool -verifyFeeObject( - std::shared_ptr const& ledger, - Rules const& rules, - FeeSettingsFields const& expected) +verifyFeeObject(std::shared_ptr const& ledger, Rules const& rules, FeeSettingsFields const& expected) { auto const feeObject = ledger->read(keylet::fees()); if (!feeObject) @@ -145,28 +126,20 @@ verifyFeeObject( if (rules.enabled(featureXRPFees)) { - if (feeObject->isFieldPresent(sfBaseFee) || - feeObject->isFieldPresent(sfReserveBase) || - feeObject->isFieldPresent(sfReserveIncrement) || - feeObject->isFieldPresent(sfReferenceFeeUnits)) + if (feeObject->isFieldPresent(sfBaseFee) || feeObject->isFieldPresent(sfReserveBase) || + feeObject->isFieldPresent(sfReserveIncrement) || feeObject->isFieldPresent(sfReferenceFeeUnits)) return false; - if (!checkEquality( - sfBaseFeeDrops, expected.baseFeeDrops.value_or(XRPAmount{0}))) + if (!checkEquality(sfBaseFeeDrops, expected.baseFeeDrops.value_or(XRPAmount{0}))) return false; - if (!checkEquality( - sfReserveBaseDrops, - expected.reserveBaseDrops.value_or(XRPAmount{0}))) + if (!checkEquality(sfReserveBaseDrops, expected.reserveBaseDrops.value_or(XRPAmount{0}))) return false; - if (!checkEquality( - sfReserveIncrementDrops, - expected.reserveIncrementDrops.value_or(XRPAmount{0}))) + if (!checkEquality(sfReserveIncrementDrops, expected.reserveIncrementDrops.value_or(XRPAmount{0}))) return false; } else { - if (feeObject->isFieldPresent(sfBaseFeeDrops) || - feeObject->isFieldPresent(sfReserveBaseDrops) || + if (feeObject->isFieldPresent(sfBaseFeeDrops) || feeObject->isFieldPresent(sfReserveBaseDrops) || feeObject->isFieldPresent(sfReserveIncrementDrops)) return false; @@ -213,10 +186,7 @@ class FeeVote_test : public beast::unit_test::suite } { Section config; - config.append( - {"reference_fee = 50", - "account_reserve = 1234567", - "owner_reserve = 1234"}); + config.append({"reference_fee = 50", "account_reserve = 1234567", "owner_reserve = 1234"}); auto setup = setup_FeeVote(config); BEAST_EXPECT(setup.reference_fee == 50); BEAST_EXPECT(setup.account_reserve == 1234567); @@ -224,10 +194,7 @@ class FeeVote_test : public beast::unit_test::suite } { Section config; - config.append( - {"reference_fee = blah", - "account_reserve = yada", - "owner_reserve = foo"}); + config.append({"reference_fee = blah", "account_reserve = yada", "owner_reserve = foo"}); // Illegal values are ignored, and the defaults left unchanged auto setup = setup_FeeVote(config); BEAST_EXPECT(setup.reference_fee == defaultSetup.reference_fee); @@ -236,28 +203,18 @@ class FeeVote_test : public beast::unit_test::suite } { Section config; - config.append( - {"reference_fee = -50", - "account_reserve = -1234567", - "owner_reserve = -1234"}); + config.append({"reference_fee = -50", "account_reserve = -1234567", "owner_reserve = -1234"}); // Illegal values are ignored, and the defaults left unchanged auto setup = setup_FeeVote(config); BEAST_EXPECT(setup.reference_fee == defaultSetup.reference_fee); - BEAST_EXPECT( - setup.account_reserve == static_cast(-1234567)); - BEAST_EXPECT( - setup.owner_reserve == static_cast(-1234)); + BEAST_EXPECT(setup.account_reserve == static_cast(-1234567)); + BEAST_EXPECT(setup.owner_reserve == static_cast(-1234)); } { - auto const big64 = std::to_string( - static_cast( - std::numeric_limits::max()) + - 1); + auto const big64 = + std::to_string(static_cast(std::numeric_limits::max()) + 1); Section config; - config.append( - {"reference_fee = " + big64, - "account_reserve = " + big64, - "owner_reserve = " + big64}); + config.append({"reference_fee = " + big64, "account_reserve = " + big64, "owner_reserve = " + big64}); // Illegal values are ignored, and the defaults left unchanged auto setup = setup_FeeVote(config); BEAST_EXPECT(setup.reference_fee == defaultSetup.reference_fee); @@ -275,22 +232,15 @@ class FeeVote_test : public beast::unit_test::suite { jtx::Env env(*this, jtx::testable_amendments() - featureXRPFees); auto ledger = std::make_shared( - create_genesis, - env.app().config(), - std::vector{}, - env.app().getNodeFamily()); + create_genesis, env.app().config(), std::vector{}, env.app().getNodeFamily()); // Create the next ledger to apply transaction to - ledger = std::make_shared( - *ledger, env.app().timeKeeper().closeTime()); + ledger = std::make_shared(*ledger, env.app().timeKeeper().closeTime()); // Test successful fee transaction with legacy fields FeeSettingsFields fields{ - .baseFee = 10, - .reserveBase = 200000, - .reserveIncrement = 50000, - .referenceFeeUnits = 10}; + .baseFee = 10, .reserveBase = 200000, .reserveIncrement = 50000, .referenceFeeUnits = 10}; auto feeTx = createFeeTx(ledger->rules(), ledger->seq(), fields); OpenView accum(ledger.get()); @@ -305,14 +255,10 @@ class FeeVote_test : public beast::unit_test::suite { jtx::Env env(*this, jtx::testable_amendments() | featureXRPFees); auto ledger = std::make_shared( - create_genesis, - env.app().config(), - std::vector{}, - env.app().getNodeFamily()); + create_genesis, env.app().config(), std::vector{}, env.app().getNodeFamily()); // Create the next ledger to apply transaction to - ledger = std::make_shared( - *ledger, env.app().timeKeeper().closeTime()); + ledger = std::make_shared(*ledger, env.app().timeKeeper().closeTime()); FeeSettingsFields fields{ .baseFeeDrops = XRPAmount{10}, @@ -338,48 +284,36 @@ class FeeVote_test : public beast::unit_test::suite { jtx::Env env(*this, jtx::testable_amendments() - featureXRPFees); auto ledger = std::make_shared( - create_genesis, - env.app().config(), - std::vector{}, - env.app().getNodeFamily()); + create_genesis, env.app().config(), std::vector{}, env.app().getNodeFamily()); // Create the next ledger to apply transaction to - ledger = std::make_shared( - *ledger, env.app().timeKeeper().closeTime()); + ledger = std::make_shared(*ledger, env.app().timeKeeper().closeTime()); // Test transaction with missing required legacy fields - auto invalidTx = createInvalidFeeTx( - ledger->rules(), ledger->seq(), true, false, 1); + auto invalidTx = createInvalidFeeTx(ledger->rules(), ledger->seq(), true, false, 1); OpenView accum(ledger.get()); BEAST_EXPECT(!applyFeeAndTestResult(env, accum, invalidTx)); // Test transaction with new format fields when XRPFees is disabled - auto disallowedTx = createInvalidFeeTx( - ledger->rules(), ledger->seq(), false, true, 2); + auto disallowedTx = createInvalidFeeTx(ledger->rules(), ledger->seq(), false, true, 2); BEAST_EXPECT(!applyFeeAndTestResult(env, accum, disallowedTx)); } { jtx::Env env(*this, jtx::testable_amendments() | featureXRPFees); auto ledger = std::make_shared( - create_genesis, - env.app().config(), - std::vector{}, - env.app().getNodeFamily()); + create_genesis, env.app().config(), std::vector{}, env.app().getNodeFamily()); // Create the next ledger to apply transaction to - ledger = std::make_shared( - *ledger, env.app().timeKeeper().closeTime()); + ledger = std::make_shared(*ledger, env.app().timeKeeper().closeTime()); // Test transaction with missing required new fields - auto invalidTx = createInvalidFeeTx( - ledger->rules(), ledger->seq(), true, false, 3); + auto invalidTx = createInvalidFeeTx(ledger->rules(), ledger->seq(), true, false, 3); OpenView accum(ledger.get()); BEAST_EXPECT(!applyFeeAndTestResult(env, accum, invalidTx)); // Test transaction with legacy fields when XRPFees is enabled - auto disallowedTx = createInvalidFeeTx( - ledger->rules(), ledger->seq(), false, true, 4); + auto disallowedTx = createInvalidFeeTx(ledger->rules(), ledger->seq(), false, true, 4); BEAST_EXPECT(!applyFeeAndTestResult(env, accum, disallowedTx)); } } @@ -391,14 +325,10 @@ class FeeVote_test : public beast::unit_test::suite jtx::Env env(*this, jtx::testable_amendments()); auto ledger = std::make_shared( - create_genesis, - env.app().config(), - std::vector{}, - env.app().getNodeFamily()); + create_genesis, env.app().config(), std::vector{}, env.app().getNodeFamily()); // Create the next ledger to apply transaction to - ledger = std::make_shared( - *ledger, env.app().timeKeeper().closeTime()); + ledger = std::make_shared(*ledger, env.app().timeKeeper().closeTime()); auto feeTx = createFeeTx( ledger->rules(), @@ -430,13 +360,9 @@ class FeeVote_test : public beast::unit_test::suite jtx::Env env(*this, jtx::testable_amendments() | featureXRPFees); auto ledger = std::make_shared( - create_genesis, - env.app().config(), - std::vector{}, - env.app().getNodeFamily()); + create_genesis, env.app().config(), std::vector{}, env.app().getNodeFamily()); - ledger = std::make_shared( - *ledger, env.app().timeKeeper().closeTime()); + ledger = std::make_shared(*ledger, env.app().timeKeeper().closeTime()); FeeSettingsFields fields1{ .baseFeeDrops = XRPAmount{10}, @@ -453,8 +379,7 @@ class FeeVote_test : public beast::unit_test::suite BEAST_EXPECT(verifyFeeObject(ledger, ledger->rules(), fields1)); // Apply second fee transaction with different values - ledger = std::make_shared( - *ledger, env.app().timeKeeper().closeTime()); + ledger = std::make_shared(*ledger, env.app().timeKeeper().closeTime()); FeeSettingsFields fields2{ .baseFeeDrops = XRPAmount{20}, @@ -479,13 +404,9 @@ class FeeVote_test : public beast::unit_test::suite jtx::Env env(*this, jtx::testable_amendments() | featureXRPFees); auto ledger = std::make_shared( - create_genesis, - env.app().config(), - std::vector{}, - env.app().getNodeFamily()); + create_genesis, env.app().config(), std::vector{}, env.app().getNodeFamily()); - ledger = std::make_shared( - *ledger, env.app().timeKeeper().closeTime()); + ledger = std::make_shared(*ledger, env.app().timeKeeper().closeTime()); // Test transaction with wrong ledger sequence auto feeTx = createFeeTx( @@ -510,13 +431,9 @@ class FeeVote_test : public beast::unit_test::suite jtx::Env env(*this, jtx::testable_amendments() | featureXRPFees); auto ledger = std::make_shared( - create_genesis, - env.app().config(), - std::vector{}, - env.app().getNodeFamily()); + create_genesis, env.app().config(), std::vector{}, env.app().getNodeFamily()); - ledger = std::make_shared( - *ledger, env.app().timeKeeper().closeTime()); + ledger = std::make_shared(*ledger, env.app().timeKeeper().closeTime()); FeeSettingsFields fields1{ .baseFeeDrops = XRPAmount{10}, @@ -532,13 +449,10 @@ class FeeVote_test : public beast::unit_test::suite BEAST_EXPECT(verifyFeeObject(ledger, ledger->rules(), fields1)); - ledger = std::make_shared( - *ledger, env.app().timeKeeper().closeTime()); + ledger = std::make_shared(*ledger, env.app().timeKeeper().closeTime()); // Apply partial update (only some fields) - FeeSettingsFields fields2{ - .baseFeeDrops = XRPAmount{20}, - .reserveBaseDrops = XRPAmount{200000}}; + FeeSettingsFields fields2{.baseFeeDrops = XRPAmount{20}, .reserveBaseDrops = XRPAmount{200000}}; auto feeTx2 = createFeeTx(ledger->rules(), ledger->seq(), fields2); { @@ -558,20 +472,15 @@ class FeeVote_test : public beast::unit_test::suite jtx::Env env(*this, jtx::testable_amendments() | featureXRPFees); auto ledger = std::make_shared( - create_genesis, - env.app().config(), - std::vector{}, - env.app().getNodeFamily()); + create_genesis, env.app().config(), std::vector{}, env.app().getNodeFamily()); - ledger = std::make_shared( - *ledger, env.app().timeKeeper().closeTime()); + ledger = std::make_shared(*ledger, env.app().timeKeeper().closeTime()); // Test invalid transaction with non-zero account - this should fail // validation auto invalidTx = STTx(ttFEE, [&](auto& obj) { - obj.setAccountID( - sfAccount, - AccountID(1)); // Should be zero (this makes it invalid) + obj.setAccountID(sfAccount, + AccountID(1)); // Should be zero (this makes it invalid) obj.setFieldU32(sfLedgerSequence, ledger->seq()); obj.setFieldAmount(sfBaseFeeDrops, XRPAmount{10}); obj.setFieldAmount(sfReserveBaseDrops, XRPAmount{200000}); @@ -600,20 +509,13 @@ class FeeVote_test : public beast::unit_test::suite auto feeVote = make_FeeVote(setup, env.app().journal("FeeVote")); auto ledger = std::make_shared( - create_genesis, - env.app().config(), - std::vector{}, - env.app().getNodeFamily()); + create_genesis, env.app().config(), std::vector{}, env.app().getNodeFamily()); auto sec = randomSecretKey(); auto pub = derivePublicKey(KeyType::secp256k1, sec); auto val = std::make_shared( - env.app().timeKeeper().now(), - pub, - sec, - calcNodeID(pub), - [](STValidation& v) { + env.app().timeKeeper().now(), pub, sec, calcNodeID(pub), [](STValidation& v) { v.setFieldU32(sfLedgerSequence, 12345); }); @@ -624,9 +526,7 @@ class FeeVote_test : public beast::unit_test::suite feeVote->doValidation(currentFees, ledger->rules(), *val); BEAST_EXPECT(val->isFieldPresent(sfBaseFeeDrops)); - BEAST_EXPECT( - val->getFieldAmount(sfBaseFeeDrops) == - XRPAmount(setup.reference_fee)); + BEAST_EXPECT(val->getFieldAmount(sfBaseFeeDrops) == XRPAmount(setup.reference_fee)); } // Test with XRPFees disabled (legacy format) @@ -635,20 +535,13 @@ class FeeVote_test : public beast::unit_test::suite auto feeVote = make_FeeVote(setup, env.app().journal("FeeVote")); auto ledger = std::make_shared( - create_genesis, - env.app().config(), - std::vector{}, - env.app().getNodeFamily()); + create_genesis, env.app().config(), std::vector{}, env.app().getNodeFamily()); auto sec = randomSecretKey(); auto pub = derivePublicKey(KeyType::secp256k1, sec); auto val = std::make_shared( - env.app().timeKeeper().now(), - pub, - sec, - calcNodeID(pub), - [](STValidation& v) { + env.app().timeKeeper().now(), pub, sec, calcNodeID(pub), [](STValidation& v) { v.setFieldU32(sfLedgerSequence, 12345); }); @@ -677,24 +570,19 @@ class FeeVote_test : public beast::unit_test::suite Env env(*this, testable_amendments() | featureXRPFees); // establish what the current fees are - BEAST_EXPECT( - env.current()->fees().base == XRPAmount{UNIT_TEST_REFERENCE_FEE}); + BEAST_EXPECT(env.current()->fees().base == XRPAmount{UNIT_TEST_REFERENCE_FEE}); BEAST_EXPECT(env.current()->fees().reserve == XRPAmount{200'000'000}); BEAST_EXPECT(env.current()->fees().increment == XRPAmount{50'000'000}); auto feeVote = make_FeeVote(setup, env.app().journal("FeeVote")); auto ledger = std::make_shared( - create_genesis, - env.app().config(), - std::vector{}, - env.app().getNodeFamily()); + create_genesis, env.app().config(), std::vector{}, env.app().getNodeFamily()); // doVoting requires a flag ledger (every 256th ledger) // We need to create a ledger at sequence 256 to make it a flag ledger for (int i = 0; i < 256 - 1; ++i) { - ledger = std::make_shared( - *ledger, env.app().timeKeeper().closeTime()); + ledger = std::make_shared(*ledger, env.app().timeKeeper().closeTime()); } BEAST_EXPECT(ledger->isFlagLedger()); @@ -707,28 +595,19 @@ class FeeVote_test : public beast::unit_test::suite auto pub = derivePublicKey(KeyType::secp256k1, sec); auto val = std::make_shared( - env.app().timeKeeper().now(), - pub, - sec, - calcNodeID(pub), - [&](STValidation& v) { + env.app().timeKeeper().now(), pub, sec, calcNodeID(pub), [&](STValidation& v) { v.setFieldU32(sfLedgerSequence, ledger->seq()); // Vote for different fees than current - v.setFieldAmount( - sfBaseFeeDrops, XRPAmount{setup.reference_fee}); - v.setFieldAmount( - sfReserveBaseDrops, XRPAmount{setup.account_reserve}); - v.setFieldAmount( - sfReserveIncrementDrops, - XRPAmount{setup.owner_reserve}); + v.setFieldAmount(sfBaseFeeDrops, XRPAmount{setup.reference_fee}); + v.setFieldAmount(sfReserveBaseDrops, XRPAmount{setup.account_reserve}); + v.setFieldAmount(sfReserveIncrementDrops, XRPAmount{setup.owner_reserve}); }); if (i % 2) val->setTrusted(); validations.push_back(val); } - auto txSet = std::make_shared( - SHAMapType::TRANSACTION, env.app().getNodeFamily()); + auto txSet = std::make_shared(SHAMapType::TRANSACTION, env.app().getNodeFamily()); // This should not throw since we have a flag ledger feeVote->doVoting(ledger, validations, txSet); @@ -753,15 +632,9 @@ class FeeVote_test : public beast::unit_test::suite BEAST_EXPECT(!feeTx.isFieldPresent(sfReferenceFeeUnits)); // Check the values - BEAST_EXPECT( - feeTx.getFieldAmount(sfBaseFeeDrops) == - XRPAmount{setup.reference_fee}); - BEAST_EXPECT( - feeTx.getFieldAmount(sfReserveBaseDrops) == - XRPAmount{setup.account_reserve}); - BEAST_EXPECT( - feeTx.getFieldAmount(sfReserveIncrementDrops) == - XRPAmount{setup.owner_reserve}); + BEAST_EXPECT(feeTx.getFieldAmount(sfBaseFeeDrops) == XRPAmount{setup.reference_fee}); + BEAST_EXPECT(feeTx.getFieldAmount(sfReserveBaseDrops) == XRPAmount{setup.account_reserve}); + BEAST_EXPECT(feeTx.getFieldAmount(sfReserveIncrementDrops) == XRPAmount{setup.owner_reserve}); } void diff --git a/src/test/app/FixNFTokenPageLinks_test.cpp b/src/test/app/FixNFTokenPageLinks_test.cpp index ad457cc58b..88f368e9cf 100644 --- a/src/test/app/FixNFTokenPageLinks_test.cpp +++ b/src/test/app/FixNFTokenPageLinks_test.cpp @@ -40,9 +40,7 @@ class FixNFTokenPageLinks_test : public beast::unit_test::suite // creation of NFT pages that are completely full. This lambda // tells us the taxon value we should pass in in order for the // internal representation to match the passed in value. - auto internalTaxon = [this, &env]( - Account const& acct, - std::uint32_t taxon) -> std::uint32_t { + auto internalTaxon = [this, &env](Account const& acct, std::uint32_t taxon) -> std::uint32_t { std::uint32_t tokenSeq = [this, &env, &acct]() { auto const le = env.le(acct); if (BEAST_EXPECT(le)) @@ -51,9 +49,7 @@ class FixNFTokenPageLinks_test : public beast::unit_test::suite }(); // We must add FirstNFTokenSequence. - tokenSeq += env.le(acct) - ->at(~sfFirstNFTokenSequence) - .value_or(env.seq(acct)); + tokenSeq += env.le(acct)->at(~sfFirstNFTokenSequence).value_or(env.seq(acct)); return toUInt32(nft::cipheredTaxon(tokenSeq, nft::toTaxon(taxon))); }; @@ -68,8 +64,7 @@ class FixNFTokenPageLinks_test : public beast::unit_test::suite // populated. std::uint32_t const intTaxon = (i / 16) + (i & 0b10000 ? 2 : 0); uint32_t const extTaxon = internalTaxon(owner, intTaxon); - nfts.push_back( - token::getNextID(env, owner, extTaxon, tfTransferable)); + nfts.push_back(token::getNextID(env, owner, extTaxon, tfTransferable)); env(token::mint(owner, extTaxon), txflags(tfTransferable)); env.close(); } @@ -85,15 +80,13 @@ class FixNFTokenPageLinks_test : public beast::unit_test::suite params[jss::account] = owner.human(); auto resp = env.rpc("json", "account_objects", to_string(params)); - Json::Value const& acctObjs = - resp[jss::result][jss::account_objects]; + Json::Value const& acctObjs = resp[jss::result][jss::account_objects]; int pageCount = 0; for (Json::UInt i = 0; i < acctObjs.size(); ++i) { if (BEAST_EXPECT( - acctObjs[i].isMember(sfNFTokens.jsonName) && - acctObjs[i][sfNFTokens.jsonName].isArray())) + acctObjs[i].isMember(sfNFTokens.jsonName) && acctObjs[i][sfNFTokens.jsonName].isArray())) { BEAST_EXPECT(acctObjs[i][sfNFTokens.jsonName].size() == 32); ++pageCount; @@ -122,9 +115,7 @@ class FixNFTokenPageLinks_test : public beast::unit_test::suite env.fund(XRP(1000), alice); auto const linkFixFee = drops(env.current()->fees().increment); - env(ledgerStateFix::nftPageLinks(alice, alice), - fee(linkFixFee), - ter(temDISABLED)); + env(ledgerStateFix::nftPageLinks(alice, alice), fee(linkFixFee), ter(temDISABLED)); } Env env{*this, testable_amendments()}; @@ -147,10 +138,7 @@ class FixNFTokenPageLinks_test : public beast::unit_test::suite // Invalid flags. auto const linkFixFee = drops(env.current()->fees().increment); - env(ledgerStateFix::nftPageLinks(alice, alice), - fee(linkFixFee), - txflags(tfPassive), - ter(temINVALID_FLAG)); + env(ledgerStateFix::nftPageLinks(alice, alice), fee(linkFixFee), txflags(tfPassive), ter(temINVALID_FLAG)); { // ledgerStateFix::nftPageLinks requires an Owner field. @@ -171,9 +159,7 @@ class FixNFTokenPageLinks_test : public beast::unit_test::suite // Preclaim Account const carol("carol"); env.memoize(carol); - env(ledgerStateFix::nftPageLinks(alice, carol), - fee(linkFixFee), - ter(tecOBJECT_NOT_FOUND)); + env(ledgerStateFix::nftPageLinks(alice, carol), fee(linkFixFee), ter(tecOBJECT_NOT_FOUND)); } void @@ -194,17 +180,13 @@ class FixNFTokenPageLinks_test : public beast::unit_test::suite // Owner has no pages to fix. auto const linkFixFee = drops(env.current()->fees().increment); - env(ledgerStateFix::nftPageLinks(alice, alice), - fee(linkFixFee), - ter(tecFAILED_PROCESSING)); + env(ledgerStateFix::nftPageLinks(alice, alice), fee(linkFixFee), ter(tecFAILED_PROCESSING)); // Alice has only one page. env(token::mint(alice), txflags(tfTransferable)); env.close(); - env(ledgerStateFix::nftPageLinks(alice, alice), - fee(linkFixFee), - ter(tecFAILED_PROCESSING)); + env(ledgerStateFix::nftPageLinks(alice, alice), fee(linkFixFee), ter(tecFAILED_PROCESSING)); // Alice has at least three pages. for (std::uint32_t i = 0; i < 64; ++i) @@ -213,9 +195,7 @@ class FixNFTokenPageLinks_test : public beast::unit_test::suite env.close(); } - env(ledgerStateFix::nftPageLinks(alice, alice), - fee(linkFixFee), - ter(tecFAILED_PROCESSING)); + env(ledgerStateFix::nftPageLinks(alice, alice), fee(linkFixFee), ter(tecFAILED_PROCESSING)); } void @@ -280,15 +260,13 @@ class FixNFTokenPageLinks_test : public beast::unit_test::suite // alice's "middle" page is still present, but has no links. { - auto aliceMiddleNFTokenPage = env.le(keylet::nftpage( - keylet::nftpage_min(alice), aliceMiddleNFTokenPageIndex)); + auto aliceMiddleNFTokenPage = + env.le(keylet::nftpage(keylet::nftpage_min(alice), aliceMiddleNFTokenPageIndex)); if (!BEAST_EXPECT(aliceMiddleNFTokenPage)) return; - BEAST_EXPECT( - !aliceMiddleNFTokenPage->isFieldPresent(sfPreviousPageMin)); - BEAST_EXPECT( - !aliceMiddleNFTokenPage->isFieldPresent(sfNextPageMin)); + BEAST_EXPECT(!aliceMiddleNFTokenPage->isFieldPresent(sfPreviousPageMin)); + BEAST_EXPECT(!aliceMiddleNFTokenPage->isFieldPresent(sfNextPageMin)); } //********************************************************************** @@ -325,13 +303,11 @@ class FixNFTokenPageLinks_test : public beast::unit_test::suite // bob's "middle" page is still present, but has lost the // NextPageMin field. { - auto bobMiddleNFTokenPage = env.le(keylet::nftpage( - keylet::nftpage_min(bob), bobMiddleNFTokenPageIndex)); + auto bobMiddleNFTokenPage = env.le(keylet::nftpage(keylet::nftpage_min(bob), bobMiddleNFTokenPageIndex)); if (!BEAST_EXPECT(bobMiddleNFTokenPage)) return; - BEAST_EXPECT( - bobMiddleNFTokenPage->isFieldPresent(sfPreviousPageMin)); + BEAST_EXPECT(bobMiddleNFTokenPage->isFieldPresent(sfPreviousPageMin)); BEAST_EXPECT(!bobMiddleNFTokenPage->isFieldPresent(sfNextPageMin)); } @@ -356,10 +332,8 @@ class FixNFTokenPageLinks_test : public beast::unit_test::suite dariaNFTs.reserve(32); for (int i = 0; i < 32; ++i) { - uint256 const offerIndex = - keylet::nftoffer(carol, env.seq(carol)).key; - env(token::createOffer(carol, carolNFTs.back(), XRP(0)), - txflags(tfSellNFToken)); + uint256 const offerIndex = keylet::nftoffer(carol, env.seq(carol)).key; + env(token::createOffer(carol, carolNFTs.back(), XRP(0)), txflags(tfSellNFToken)); env.close(); env(token::acceptSellOffer(daria, offerIndex)); @@ -378,8 +352,7 @@ class FixNFTokenPageLinks_test : public beast::unit_test::suite // carol's "middle" page is still present, but has lost the // NextPageMin field. - auto carolMiddleNFTokenPage = env.le(keylet::nftpage( - keylet::nftpage_min(carol), carolMiddleNFTokenPageIndex)); + auto carolMiddleNFTokenPage = env.le(keylet::nftpage(keylet::nftpage_min(carol), carolMiddleNFTokenPageIndex)); if (!BEAST_EXPECT(carolMiddleNFTokenPage)) return; @@ -392,8 +365,7 @@ class FixNFTokenPageLinks_test : public beast::unit_test::suite // back from daria. for (uint256 const& nft : dariaNFTs) { - uint256 const offerIndex = - keylet::nftoffer(carol, env.seq(carol)).key; + uint256 const offerIndex = keylet::nftoffer(carol, env.seq(carol)).key; env(token::createOffer(carol, nft, drops(1)), token::owner(daria)); env.close(); @@ -410,22 +382,19 @@ class FixNFTokenPageLinks_test : public beast::unit_test::suite // carol's "middle" page is present and still has no NextPageMin field. { - auto carolMiddleNFTokenPage = env.le(keylet::nftpage( - keylet::nftpage_min(carol), carolMiddleNFTokenPageIndex)); + auto carolMiddleNFTokenPage = + env.le(keylet::nftpage(keylet::nftpage_min(carol), carolMiddleNFTokenPageIndex)); if (!BEAST_EXPECT(carolMiddleNFTokenPage)) return; - BEAST_EXPECT( - carolMiddleNFTokenPage->isFieldPresent(sfPreviousPageMin)); - BEAST_EXPECT( - !carolMiddleNFTokenPage->isFieldPresent(sfNextPageMin)); + BEAST_EXPECT(carolMiddleNFTokenPage->isFieldPresent(sfPreviousPageMin)); + BEAST_EXPECT(!carolMiddleNFTokenPage->isFieldPresent(sfNextPageMin)); } // carol has a "last" page again, but it has no PreviousPageMin field. { auto carolLastNFTokenPage = env.le(keylet::nftpage_max(carol)); - BEAST_EXPECT( - !carolLastNFTokenPage->isFieldPresent(sfPreviousPageMin)); + BEAST_EXPECT(!carolLastNFTokenPage->isFieldPresent(sfPreviousPageMin)); BEAST_EXPECT(!carolLastNFTokenPage->isFieldPresent(sfNextPageMin)); } @@ -434,9 +403,7 @@ class FixNFTokenPageLinks_test : public beast::unit_test::suite //********************************************************************** // Verify that the LedgerStateFix transaction is not enabled. auto const linkFixFee = drops(env.current()->fees().increment); - env(ledgerStateFix::nftPageLinks(daria, alice), - fee(linkFixFee), - ter(temDISABLED)); + env(ledgerStateFix::nftPageLinks(daria, alice), fee(linkFixFee), ter(temDISABLED)); // Wait 15 ledgers so the LedgerStateFix transaction is no longer // retried. @@ -457,15 +424,13 @@ class FixNFTokenPageLinks_test : public beast::unit_test::suite // alice's "middle" page is still present and has no links. { - auto aliceMiddleNFTokenPage = env.le(keylet::nftpage( - keylet::nftpage_min(alice), aliceMiddleNFTokenPageIndex)); + auto aliceMiddleNFTokenPage = + env.le(keylet::nftpage(keylet::nftpage_min(alice), aliceMiddleNFTokenPageIndex)); if (!BEAST_EXPECT(aliceMiddleNFTokenPage)) return; - BEAST_EXPECT( - !aliceMiddleNFTokenPage->isFieldPresent(sfPreviousPageMin)); - BEAST_EXPECT( - !aliceMiddleNFTokenPage->isFieldPresent(sfNextPageMin)); + BEAST_EXPECT(!aliceMiddleNFTokenPage->isFieldPresent(sfPreviousPageMin)); + BEAST_EXPECT(!aliceMiddleNFTokenPage->isFieldPresent(sfNextPageMin)); } // The server "remembers" daria's failed nftPageLinks transaction @@ -477,20 +442,18 @@ class FixNFTokenPageLinks_test : public beast::unit_test::suite env(ledgerStateFix::nftPageLinks(daria, alice), fee(linkFixFee)); env.close(); - // alices's last page should now be present and include no links. + // alice's last page should now be present and include no links. { auto aliceLastNFTokenPage = env.le(keylet::nftpage_max(alice)); if (!BEAST_EXPECT(aliceLastNFTokenPage)) return; - BEAST_EXPECT( - !aliceLastNFTokenPage->isFieldPresent(sfPreviousPageMin)); + BEAST_EXPECT(!aliceLastNFTokenPage->isFieldPresent(sfPreviousPageMin)); BEAST_EXPECT(!aliceLastNFTokenPage->isFieldPresent(sfNextPageMin)); } // alice's middle page should be gone. - BEAST_EXPECT(!env.le(keylet::nftpage( - keylet::nftpage_min(alice), aliceMiddleNFTokenPageIndex))); + BEAST_EXPECT(!env.le(keylet::nftpage(keylet::nftpage_min(alice), aliceMiddleNFTokenPageIndex))); BEAST_EXPECT(nftCount(env, alice) == 32); BEAST_EXPECT(ownerCount(env, alice) == 1); @@ -506,13 +469,11 @@ class FixNFTokenPageLinks_test : public beast::unit_test::suite // bob's "middle" page is still present and missing NextPageMin. { - auto bobMiddleNFTokenPage = env.le(keylet::nftpage( - keylet::nftpage_min(bob), bobMiddleNFTokenPageIndex)); + auto bobMiddleNFTokenPage = env.le(keylet::nftpage(keylet::nftpage_min(bob), bobMiddleNFTokenPageIndex)); if (!BEAST_EXPECT(bobMiddleNFTokenPage)) return; - BEAST_EXPECT( - bobMiddleNFTokenPage->isFieldPresent(sfPreviousPageMin)); + BEAST_EXPECT(bobMiddleNFTokenPage->isFieldPresent(sfPreviousPageMin)); BEAST_EXPECT(!bobMiddleNFTokenPage->isFieldPresent(sfNextPageMin)); } @@ -529,28 +490,22 @@ class FixNFTokenPageLinks_test : public beast::unit_test::suite return; BEAST_EXPECT(bobLastNFTokenPage->isFieldPresent(sfPreviousPageMin)); - BEAST_EXPECT( - bobLastNFTokenPage->at(sfPreviousPageMin) != - bobMiddleNFTokenPageIndex); + BEAST_EXPECT(bobLastNFTokenPage->at(sfPreviousPageMin) != bobMiddleNFTokenPageIndex); BEAST_EXPECT(!bobLastNFTokenPage->isFieldPresent(sfNextPageMin)); - auto const bobNewFirstNFTokenPage = env.le(keylet::nftpage( - keylet::nftpage_min(bob), - bobLastNFTokenPage->at(sfPreviousPageMin))); + auto const bobNewFirstNFTokenPage = + env.le(keylet::nftpage(keylet::nftpage_min(bob), bobLastNFTokenPage->at(sfPreviousPageMin))); if (!BEAST_EXPECT(bobNewFirstNFTokenPage)) return; BEAST_EXPECT( bobNewFirstNFTokenPage->isFieldPresent(sfNextPageMin) && - bobNewFirstNFTokenPage->at(sfNextPageMin) == - lastPageKeylet.key); - BEAST_EXPECT( - !bobNewFirstNFTokenPage->isFieldPresent(sfPreviousPageMin)); + bobNewFirstNFTokenPage->at(sfNextPageMin) == lastPageKeylet.key); + BEAST_EXPECT(!bobNewFirstNFTokenPage->isFieldPresent(sfPreviousPageMin)); } // bob's middle page should be gone. - BEAST_EXPECT(!env.le(keylet::nftpage( - keylet::nftpage_min(bob), bobMiddleNFTokenPageIndex))); + BEAST_EXPECT(!env.le(keylet::nftpage(keylet::nftpage_min(bob), bobMiddleNFTokenPageIndex))); BEAST_EXPECT(nftCount(env, bob) == 64); BEAST_EXPECT(ownerCount(env, bob) == 2); @@ -563,22 +518,19 @@ class FixNFTokenPageLinks_test : public beast::unit_test::suite // carol's "middle" page is present and has no NextPageMin field. { - auto carolMiddleNFTokenPage = env.le(keylet::nftpage( - keylet::nftpage_min(carol), carolMiddleNFTokenPageIndex)); + auto carolMiddleNFTokenPage = + env.le(keylet::nftpage(keylet::nftpage_min(carol), carolMiddleNFTokenPageIndex)); if (!BEAST_EXPECT(carolMiddleNFTokenPage)) return; - BEAST_EXPECT( - carolMiddleNFTokenPage->isFieldPresent(sfPreviousPageMin)); - BEAST_EXPECT( - !carolMiddleNFTokenPage->isFieldPresent(sfNextPageMin)); + BEAST_EXPECT(carolMiddleNFTokenPage->isFieldPresent(sfPreviousPageMin)); + BEAST_EXPECT(!carolMiddleNFTokenPage->isFieldPresent(sfNextPageMin)); } // carol has a "last" page, but it has no PreviousPageMin field. { auto carolLastNFTokenPage = env.le(keylet::nftpage_max(carol)); - BEAST_EXPECT( - !carolLastNFTokenPage->isFieldPresent(sfPreviousPageMin)); + BEAST_EXPECT(!carolLastNFTokenPage->isFieldPresent(sfPreviousPageMin)); BEAST_EXPECT(!carolLastNFTokenPage->isFieldPresent(sfNextPageMin)); } @@ -589,17 +541,15 @@ class FixNFTokenPageLinks_test : public beast::unit_test::suite { // carol's "middle" page is present and now has a NextPageMin field. auto const lastPageKeylet = keylet::nftpage_max(carol); - auto carolMiddleNFTokenPage = env.le(keylet::nftpage( - keylet::nftpage_min(carol), carolMiddleNFTokenPageIndex)); + auto carolMiddleNFTokenPage = + env.le(keylet::nftpage(keylet::nftpage_min(carol), carolMiddleNFTokenPageIndex)); if (!BEAST_EXPECT(carolMiddleNFTokenPage)) return; - BEAST_EXPECT( - carolMiddleNFTokenPage->isFieldPresent(sfPreviousPageMin)); + BEAST_EXPECT(carolMiddleNFTokenPage->isFieldPresent(sfPreviousPageMin)); BEAST_EXPECT( carolMiddleNFTokenPage->isFieldPresent(sfNextPageMin) && - carolMiddleNFTokenPage->at(sfNextPageMin) == - lastPageKeylet.key); + carolMiddleNFTokenPage->at(sfNextPageMin) == lastPageKeylet.key); // carol has a "last" page that includes a PreviousPageMin field. auto carolLastNFTokenPage = env.le(lastPageKeylet); @@ -608,23 +558,19 @@ class FixNFTokenPageLinks_test : public beast::unit_test::suite BEAST_EXPECT( carolLastNFTokenPage->isFieldPresent(sfPreviousPageMin) && - carolLastNFTokenPage->at(sfPreviousPageMin) == - carolMiddleNFTokenPageIndex); + carolLastNFTokenPage->at(sfPreviousPageMin) == carolMiddleNFTokenPageIndex); BEAST_EXPECT(!carolLastNFTokenPage->isFieldPresent(sfNextPageMin)); // carol also has a "first" page that includes a NextPageMin field. - auto carolFirstNFTokenPage = env.le(keylet::nftpage( - keylet::nftpage_min(carol), - carolMiddleNFTokenPage->at(sfPreviousPageMin))); + auto carolFirstNFTokenPage = + env.le(keylet::nftpage(keylet::nftpage_min(carol), carolMiddleNFTokenPage->at(sfPreviousPageMin))); if (!BEAST_EXPECT(carolFirstNFTokenPage)) return; BEAST_EXPECT( carolFirstNFTokenPage->isFieldPresent(sfNextPageMin) && - carolFirstNFTokenPage->at(sfNextPageMin) == - carolMiddleNFTokenPageIndex); - BEAST_EXPECT( - !carolFirstNFTokenPage->isFieldPresent(sfPreviousPageMin)); + carolFirstNFTokenPage->at(sfNextPageMin) == carolMiddleNFTokenPageIndex); + BEAST_EXPECT(!carolFirstNFTokenPage->isFieldPresent(sfPreviousPageMin)); } // With the link repair, the server knows that carol has 96 NFTs. diff --git a/src/test/app/Flow_test.cpp b/src/test/app/Flow_test.cpp index 8c5a9615fa..551bd117d8 100644 --- a/src/test/app/Flow_test.cpp +++ b/src/test/app/Flow_test.cpp @@ -14,16 +14,11 @@ namespace xrpl { namespace test { bool -getNoRippleFlag( - jtx::Env const& env, - jtx::Account const& src, - jtx::Account const& dst, - Currency const& cur) +getNoRippleFlag(jtx::Env const& env, jtx::Account const& src, jtx::Account const& dst, Currency const& cur) { if (auto sle = env.le(keylet::line(src, dst, cur))) { - auto const flag = - (src.id() > dst.id()) ? lsfHighNoRipple : lsfLowNoRipple; + auto const flag = (src.id() > dst.id()) ? lsfHighNoRipple : lsfLowNoRipple; return sle->isFlag(flag); } Throw("No line in getTrustFlag"); @@ -80,9 +75,7 @@ struct Flow_test : public beast::unit_test::suite env(pay(gw, alice, USD(100))); env(pay(alice, bob, USD(110)), paths(USD), ter(tecPATH_PARTIAL)); env.require(balance(bob, USD(0))); - env(pay(alice, bob, USD(110)), - paths(USD), - txflags(tfPartialPayment)); + env(pay(alice, bob, USD(110)), paths(USD), txflags(tfPartialPayment)); env.require(balance(bob, USD(100))); } { @@ -95,10 +88,7 @@ struct Flow_test : public beast::unit_test::suite env.trust(USDB(10), carol); env.trust(USDC(10), dan); env(pay(alice, dan, USDC(10)), paths(USDA)); - env.require( - balance(bob, USDA(10)), - balance(carol, USDB(10)), - balance(dan, USDC(10))); + env.require(balance(bob, USDA(10)), balance(carol, USDB(10)), balance(dan, USDC(10))); } { // Pay by rippling through accounts, specify path @@ -114,10 +104,7 @@ struct Flow_test : public beast::unit_test::suite // alice will redeem to bob; a transfer fee will be charged env(pay(bob, alice, USDB(6))); - env(pay(alice, dan, USDC(5)), - path(bob, carol), - sendmax(USDA(6)), - txflags(tfNoRippleDirect)); + env(pay(alice, dan, USDC(5)), path(bob, carol), sendmax(USDA(6)), txflags(tfNoRippleDirect)); env.require(balance(dan, USDC(5))); env.require(balance(alice, USDB(0.5))); } @@ -133,10 +120,7 @@ struct Flow_test : public beast::unit_test::suite env.trust(USDC(10), dan); env(rate(bob, 1.1)); - env(pay(alice, dan, USDC(5)), - path(bob, carol), - sendmax(USDA(6)), - txflags(tfNoRippleDirect)); + env(pay(alice, dan, USDC(5)), path(bob, carol), sendmax(USDA(6)), txflags(tfNoRippleDirect)); env.require(balance(dan, USDC(5))); env.require(balance(bob, USDA(5))); } @@ -156,10 +140,7 @@ struct Flow_test : public beast::unit_test::suite // Pay alice so she redeems to carol and a transfer fee is charged env(pay(carol, alice, USDC(10))); - env(pay(alice, erin, USDD(5)), - path(carol, dan), - path(bob, dan), - txflags(tfNoRippleDirect)); + env(pay(alice, erin, USDD(5)), path(carol, dan), path(bob, dan), txflags(tfNoRippleDirect)); env.require(balance(erin, USDD(5))); env.require(balance(dan, USDB(5))); @@ -180,9 +161,7 @@ struct Flow_test : public beast::unit_test::suite ter(tecPATH_DRY)); env.require(balance(carol, USDB(0))); - env(pay(alice, carol, USDB(5)), - sendmax(USDA(4)), - txflags(tfPartialPayment)); + env(pay(alice, carol, USDB(5)), sendmax(USDA(4)), txflags(tfPartialPayment)); env.require(balance(carol, USDB(4))); } } @@ -215,15 +194,10 @@ struct Flow_test : public beast::unit_test::suite env(pay(alice, bob, USDA(100))); env.require(balance(bob, USDA(100))); - env(pay(dan, carol, USDA(10)), - path(bob), - sendmax(USDD(100)), - txflags(tfNoRippleDirect)); + env(pay(dan, carol, USDA(10)), path(bob), sendmax(USDD(100)), txflags(tfNoRippleDirect)); env.require(balance(bob, USDA(90))); if (bobAliceQOut > bobDanQIn) - env.require(balance( - bob, - USDD(10.0 * double(bobAliceQOut) / double(bobDanQIn)))); + env.require(balance(bob, USDD(10.0 * double(bobAliceQOut) / double(bobDanQIn)))); else env.require(balance(bob, USDD(10))); env.require(balance(carol, USDA(10))); @@ -242,8 +216,7 @@ struct Flow_test : public beast::unit_test::suite env(pay(alice, bob, USDA(10))); env.require(balance(bob, USDA(10))); env(pay(bob, carol, USDA(5)), sendmax(USDA(10))); - auto const effectiveQ = - carolAliceQIn > 100 ? 1.0 : carolAliceQIn / 100.0; + auto const effectiveQ = carolAliceQIn > 100 ? 1.0 : carolAliceQIn / 100.0; env.require(balance(bob, USDA(10.0 - 5.0 / effectiveQ))); } @@ -391,10 +364,7 @@ struct Flow_test : public beast::unit_test::suite BEAST_EXPECT(isOffer(env, bob, BTC(40), EUR(50))); BEAST_EXPECT(isOffer(env, bob, EUR(50), USD(50))); - env(pay(alice, carol, USD(50)), - path(~USD), - path(~EUR, ~USD), - sendmax(BTC(60))); + env(pay(alice, carol, USD(50)), path(~USD), path(~EUR, ~USD), sendmax(BTC(60))); env.require(balance(alice, BTC(10))); env.require(balance(bob, BTC(50))); @@ -480,17 +450,16 @@ struct Flow_test : public beast::unit_test::suite }(); BEAST_EXPECT(flowResult.removableOffers.size() == 1); - env.app().openLedger().modify( - [&](OpenView& view, beast::Journal j) { - if (flowResult.removableOffers.empty()) - return false; - Sandbox sb(&view, tapNONE); - for (auto const& o : flowResult.removableOffers) - if (auto ok = sb.peek(keylet::offer(o))) - offerDelete(sb, ok, flowJournal); - sb.apply(view); - return true; - }); + env.app().openLedger().modify([&](OpenView& view, beast::Journal j) { + if (flowResult.removableOffers.empty()) + return false; + Sandbox sb(&view, tapNONE); + for (auto const& o : flowResult.removableOffers) + if (auto ok = sb.peek(keylet::offer(o))) + offerDelete(sb, ok, flowJournal); + sb.apply(view); + return true; + }); // used in payment, but since payment failed should be untouched BEAST_EXPECT(isOffer(env, bob, BTC(50), USD(50))); @@ -526,8 +495,7 @@ struct Flow_test : public beast::unit_test::suite // USD(0.5) of bob's USD offer. If we provide 1 drop for less // than USD(0.5), then the remaining fractional offer would // block the order book. - TER const expectedTER = - reducedOffersV2 ? TER(tecPATH_DRY) : TER(tesSUCCESS); + TER const expectedTER = reducedOffersV2 ? TER(tecPATH_DRY) : TER(tesSUCCESS); env(pay(alice, carol, EUR(1)), path(~XRP, ~EUR), sendmax(USD(0.4)), @@ -547,13 +515,11 @@ struct Flow_test : public beast::unit_test::suite std::uint64_t const bookRate = [&usdOffer]() { // Extract the least significant 64 bits from the // book page. That's where the quality is stored. - std::string bookDirStr = - to_string(usdOffer->at(sfBookDirectory)); + std::string bookDirStr = to_string(usdOffer->at(sfBookDirectory)); bookDirStr.erase(0, 48); return std::stoull(bookDirStr, nullptr, 16); }(); - std::uint64_t const actualRate = getRate( - usdOffer->at(sfTakerGets), usdOffer->at(sfTakerPays)); + std::uint64_t const actualRate = getRate(usdOffer->at(sfTakerGets), usdOffer->at(sfTakerPays)); // We expect the actual rate of the offer to be worse // (larger) than the rate of the book page holding the @@ -589,9 +555,7 @@ struct Flow_test : public beast::unit_test::suite env.trust(USD(1000), alice, bob); env(offer(gw, XRP(125), USD(125))); env(pay(alice, bob, USD(100)), sendmax(XRP(200))); - env.require( - balance(alice, xrpMinusFee(env, 10000 - 125)), - balance(bob, USD(100))); + env.require(balance(alice, xrpMinusFee(env, 10000 - 125)), balance(bob, USD(100))); } void @@ -687,13 +651,10 @@ struct Flow_test : public beast::unit_test::suite offersOnAccount(jtx::Env& env, jtx::Account account) { std::vector> result; - forEachItem( - *env.current(), - account, - [&result](std::shared_ptr const& sle) { - if (sle->getType() == ltOFFER) - result.push_back(sle); - }); + forEachItem(*env.current(), account, [&result](std::shared_ptr const& sle) { + if (sle->getType() == ltOFFER) + result.push_back(sle); + }); return result; } @@ -751,9 +712,7 @@ struct Flow_test : public beast::unit_test::suite BEAST_EXPECT(offer[sfTakerPays] == USD(500)); } - env(pay(alice, alice, EUR(600)), - sendmax(USD(500)), - txflags(tfPartialPayment)); + env(pay(alice, alice, EUR(600)), sendmax(USD(500)), txflags(tfPartialPayment)); env.close(); env.require(owners(alice, 3)); @@ -822,9 +781,7 @@ struct Flow_test : public beast::unit_test::suite BEAST_EXPECT(offer[sfTakerPays] == USD(500)); } - env(pay(alice, alice, EUR(60)), - sendmax(USD(50)), - txflags(tfPartialPayment)); + env(pay(alice, alice, EUR(60)), sendmax(USD(50)), txflags(tfPartialPayment)); env.close(); env.require(owners(alice, 3)); @@ -867,10 +824,7 @@ struct Flow_test : public beast::unit_test::suite // Consuming the offer changes the owner count, which could also cause // liquidity to decrease in the forward pass auto const toSend = consumeOffer ? USD(10) : USD(9); - env(pay(alice, alice, toSend), - path(~USD), - sendmax(XRP(20000)), - txflags(tfPartialPayment | tfNoRippleDirect)); + env(pay(alice, alice, toSend), path(~USD), sendmax(XRP(20000)), txflags(tfPartialPayment | tfNoRippleDirect)); } void @@ -892,24 +846,11 @@ struct Flow_test : public beast::unit_test::suite env.close(); env(trust(bob, USD(20))); - STAmount tinyAmt1{ - USD.issue(), - 9000000000000000ll, - -17, - false, - STAmount::unchecked{}}; - STAmount tinyAmt3{ - USD.issue(), - 9000000000000003ll, - -17, - false, - STAmount::unchecked{}}; + STAmount tinyAmt1{USD.issue(), 9000000000000000ll, -17, false, STAmount::unchecked{}}; + STAmount tinyAmt3{USD.issue(), 9000000000000003ll, -17, false, STAmount::unchecked{}}; env(offer(gw, drops(9000000000), tinyAmt3)); - env(pay(alice, bob, tinyAmt1), - path(~USD), - sendmax(drops(9000000000)), - txflags(tfNoRippleDirect)); + env(pay(alice, bob, tinyAmt1), path(~USD), sendmax(drops(9000000000)), txflags(tfNoRippleDirect)); BEAST_EXPECT(!isOffer(env, gw, XRP(0), USD(0))); } @@ -926,26 +867,13 @@ struct Flow_test : public beast::unit_test::suite env.close(); env(trust(alice, USD(20))); - STAmount tinyAmt1{ - USD.issue(), - 9000000000000000ll, - -17, - false, - STAmount::unchecked{}}; - STAmount tinyAmt3{ - USD.issue(), - 9000000000000003ll, - -17, - false, - STAmount::unchecked{}}; + STAmount tinyAmt1{USD.issue(), 9000000000000000ll, -17, false, STAmount::unchecked{}}; + STAmount tinyAmt3{USD.issue(), 9000000000000003ll, -17, false, STAmount::unchecked{}}; env(pay(gw, alice, tinyAmt1)); env(offer(gw, tinyAmt3, drops(9000000000))); - env(pay(alice, bob, drops(9000000000)), - path(~XRP), - sendmax(USD(1)), - txflags(tfNoRippleDirect)); + env(pay(alice, bob, drops(9000000000)), path(~XRP), sendmax(USD(1)), txflags(tfNoRippleDirect)); BEAST_EXPECT(!isOffer(env, gw, USD(0), XRP(0))); } @@ -972,45 +900,37 @@ struct Flow_test : public beast::unit_test::suite BEAST_EXPECT(!getNoRippleFlag(env, gw, alice, usdC)); - env(pay( - gw, - alice, - // 12.55.... - STAmount{ - USD.issue(), std::uint64_t(1255555555555555ull), -14, false})); + env( + pay(gw, + alice, + // 12.55.... + STAmount{USD.issue(), std::uint64_t(1255555555555555ull), -14, false})); env(offer( gw, // 5.0... - STAmount{ - USD.issue(), std::uint64_t(5000000000000000ull), -15, false}, + STAmount{USD.issue(), std::uint64_t(5000000000000000ull), -15, false}, XRP(1000))); env(offer( gw, // .555... - STAmount{ - USD.issue(), std::uint64_t(5555555555555555ull), -16, false}, + STAmount{USD.issue(), std::uint64_t(5555555555555555ull), -16, false}, XRP(10))); env(offer( gw, // 4.44.... - STAmount{ - USD.issue(), std::uint64_t(4444444444444444ull), -15, false}, + STAmount{USD.issue(), std::uint64_t(4444444444444444ull), -15, false}, XRP(.1))); env(offer( alice, // 17 - STAmount{ - USD.issue(), std::uint64_t(1700000000000000ull), -14, false}, + STAmount{USD.issue(), std::uint64_t(1700000000000000ull), -14, false}, XRP(.001))); - env(pay(alice, bob, XRP(10000)), - path(~XRP), - sendmax(USD(100)), - txflags(tfPartialPayment | tfNoRippleDirect)); + env(pay(alice, bob, XRP(10000)), path(~XRP), sendmax(USD(100)), txflags(tfPartialPayment | tfNoRippleDirect)); } void @@ -1136,9 +1056,7 @@ struct Flow_test : public beast::unit_test::suite env.close(); // This payment caused the assert. - env(pay(ann, ann, CTB(0.687)), - sendmax(drops(20000000000)), - txflags(tfPartialPayment)); + env(pay(ann, ann, CTB(0.687)), sendmax(drops(20000000000)), txflags(tfPartialPayment)); } void @@ -1154,9 +1072,7 @@ struct Flow_test : public beast::unit_test::suite env.fund(XRP(10000), alice); env.close(); - env(pay(alice, alice, alice["USD"](100)), - path(~alice["USD"]), - ter(temBAD_PATH)); + env(pay(alice, alice, alice["USD"](100)), path(~alice["USD"]), ter(temBAD_PATH)); } void @@ -1270,8 +1186,7 @@ struct Flow_test : public beast::unit_test::suite env(pay(alice, bob, XRP(1000)), ticket::use(ticketSeq)); env.close(); env.require(balance(bob, XRP(1000))); - env.require( - balance(alice, XRP(9000) - (env.current()->fees().base * 2))); + env.require(balance(alice, XRP(9000) - (env.current()->fees().base * 2))); } void diff --git a/src/test/app/Freeze_test.cpp b/src/test/app/Freeze_test.cpp index 85c2b5a924..9d7db52e56 100644 --- a/src/test/app/Freeze_test.cpp +++ b/src/test/app/Freeze_test.cpp @@ -69,15 +69,11 @@ class Freeze_test : public beast::unit_test::suite // Is created via a TrustSet with SetFreeze flag // test: sets LowFreeze | HighFreeze flags env(trust(G1, bob["USD"](0), tfSetFreeze)); - auto affected = env.meta()->getJson( - JsonOptions::none)[sfAffectedNodes.fieldName]; + auto affected = env.meta()->getJson(JsonOptions::none)[sfAffectedNodes.fieldName]; if (!BEAST_EXPECT(checkArraySize(affected, 2u))) return; - auto ff = - affected[1u][sfModifiedNode.fieldName][sfFinalFields.fieldName]; - BEAST_EXPECT( - ff[sfLowLimit.fieldName] == - G1["USD"](0).value().getJson(JsonOptions::none)); + auto ff = affected[1u][sfModifiedNode.fieldName][sfFinalFields.fieldName]; + BEAST_EXPECT(ff[sfLowLimit.fieldName] == G1["USD"](0).value().getJson(JsonOptions::none)); BEAST_EXPECT(ff[jss::Flags].asUInt() & lsfLowFreeze); BEAST_EXPECT(!(ff[jss::Flags].asUInt() & lsfHighFreeze)); env.close(); @@ -87,18 +83,12 @@ class Freeze_test : public beast::unit_test::suite // Account with line frozen by issuer // test: can buy more assets on that line env(offer(bob, G1["USD"](5), XRP(25))); - auto affected = env.meta()->getJson( - JsonOptions::none)[sfAffectedNodes.fieldName]; + auto affected = env.meta()->getJson(JsonOptions::none)[sfAffectedNodes.fieldName]; if (!BEAST_EXPECT(checkArraySize(affected, 5u))) return; - auto ff = - affected[3u][sfModifiedNode.fieldName][sfFinalFields.fieldName]; - BEAST_EXPECT( - ff[sfHighLimit.fieldName] == - bob["USD"](100).value().getJson(JsonOptions::none)); - auto amt = STAmount{Issue{to_currency("USD"), noAccount()}, -15} - .value() - .getJson(JsonOptions::none); + auto ff = affected[3u][sfModifiedNode.fieldName][sfFinalFields.fieldName]; + BEAST_EXPECT(ff[sfHighLimit.fieldName] == bob["USD"](100).value().getJson(JsonOptions::none)); + auto amt = STAmount{Issue{to_currency("USD"), noAccount()}, -15}.value().getJson(JsonOptions::none); BEAST_EXPECT(ff[sfBalance.fieldName] == amt); env.close(); } @@ -155,15 +145,11 @@ class Freeze_test : public beast::unit_test::suite // Is cleared via a TrustSet with ClearFreeze flag // test: sets LowFreeze | HighFreeze flags env(trust(G1, bob["USD"](0), tfClearFreeze)); - auto affected = env.meta()->getJson( - JsonOptions::none)[sfAffectedNodes.fieldName]; + auto affected = env.meta()->getJson(JsonOptions::none)[sfAffectedNodes.fieldName]; if (!BEAST_EXPECT(checkArraySize(affected, 2u))) return; - auto ff = - affected[1u][sfModifiedNode.fieldName][sfFinalFields.fieldName]; - BEAST_EXPECT( - ff[sfLowLimit.fieldName] == - G1["USD"](0).value().getJson(JsonOptions::none)); + auto ff = affected[1u][sfModifiedNode.fieldName][sfFinalFields.fieldName]; + BEAST_EXPECT(ff[sfLowLimit.fieldName] == G1["USD"](0).value().getJson(JsonOptions::none)); BEAST_EXPECT(!(ff[jss::Flags].asUInt() & lsfLowFreeze)); BEAST_EXPECT(!(ff[jss::Flags].asUInt() & lsfHighFreeze)); env.close(); @@ -211,8 +197,7 @@ class Freeze_test : public beast::unit_test::suite } // test: Issuer deep freezing not already frozen line must fail - env(trust(G1, A1["USD"](0), tfSetDeepFreeze), - ter(tecNO_PERMISSION)); + env(trust(G1, A1["USD"](0), tfSetDeepFreeze), ter(tecNO_PERMISSION)); env(trust(G1, A1["USD"](0), tfSetFreeze)); env.close(); @@ -258,8 +243,7 @@ class Freeze_test : public beast::unit_test::suite env(trust(G1, A1["USD"](0), tfSetDeepFreeze), ter(temINVALID_FLAG)); // test: clearing deep freeze before amendment fails - env(trust(G1, A1["USD"](0), tfClearDeepFreeze), - ter(temINVALID_FLAG)); + env(trust(G1, A1["USD"](0), tfClearDeepFreeze), ter(temINVALID_FLAG)); } } @@ -295,8 +279,7 @@ class Freeze_test : public beast::unit_test::suite // test: cannot create deep frozen trustline without normal freeze if (features[featureDeepFreeze]) { - env(trust(G1, A1["USD"](1000), tfSetDeepFreeze), - ter(tecNO_PERMISSION)); + env(trust(G1, A1["USD"](1000), tfSetDeepFreeze), ter(tecNO_PERMISSION)); env.close(); env.require(lines(A1, 0)); } @@ -334,14 +317,10 @@ class Freeze_test : public beast::unit_test::suite { // test: can't have both set and clear flag families in the same // transaction - env(trust(G1, A1["USD"](0), tfSetFreeze | tfClearFreeze), - ter(tecNO_PERMISSION)); - env(trust(G1, A1["USD"](0), tfSetFreeze | tfClearDeepFreeze), - ter(tecNO_PERMISSION)); - env(trust(G1, A1["USD"](0), tfSetDeepFreeze | tfClearFreeze), - ter(tecNO_PERMISSION)); - env(trust(G1, A1["USD"](0), tfSetDeepFreeze | tfClearDeepFreeze), - ter(tecNO_PERMISSION)); + env(trust(G1, A1["USD"](0), tfSetFreeze | tfClearFreeze), ter(tecNO_PERMISSION)); + env(trust(G1, A1["USD"](0), tfSetFreeze | tfClearDeepFreeze), ter(tecNO_PERMISSION)); + env(trust(G1, A1["USD"](0), tfSetDeepFreeze | tfClearFreeze), ter(tecNO_PERMISSION)); + env(trust(G1, A1["USD"](0), tfSetDeepFreeze | tfClearDeepFreeze), ter(tecNO_PERMISSION)); } else { @@ -349,10 +328,8 @@ class Freeze_test : public beast::unit_test::suite // trust line env(trust(G1, A1["USD"](0), tfSetFreeze | tfClearFreeze)); { - auto affected = env.meta()->getJson( - JsonOptions::none)[sfAffectedNodes.fieldName]; - BEAST_EXPECT(checkArraySize( - affected, 1u)); // means no trustline changes + auto affected = env.meta()->getJson(JsonOptions::none)[sfAffectedNodes.fieldName]; + BEAST_EXPECT(checkArraySize(affected, 1u)); // means no trustline changes } } } @@ -411,10 +388,7 @@ class Freeze_test : public beast::unit_test::suite { // Account without GlobalFreeze (proving operations normally work) // test: visible offers where taker_pays is unfrozen issuer - auto offers = env.rpc( - "book_offers", - std::string("USD/") + G1.human(), - "XRP")[jss::result][jss::offers]; + auto offers = env.rpc("book_offers", std::string("USD/") + G1.human(), "XRP")[jss::result][jss::offers]; if (!BEAST_EXPECT(checkArraySize(offers, 2u))) return; std::set accounts; @@ -426,10 +400,7 @@ class Freeze_test : public beast::unit_test::suite BEAST_EXPECT(accounts.find(G1.human()) != std::end(accounts)); // test: visible offers where taker_gets is unfrozen issuer - offers = env.rpc( - "book_offers", - "XRP", - std::string("USD/") + G1.human())[jss::result][jss::offers]; + offers = env.rpc("book_offers", "XRP", std::string("USD/") + G1.human())[jss::result][jss::offers]; if (!BEAST_EXPECT(checkArraySize(offers, 2u))) return; accounts.clear(); @@ -487,17 +458,11 @@ class Freeze_test : public beast::unit_test::suite // test: book_offers shows offers // (should these actually be filtered?) - offers = env.rpc( - "book_offers", - "XRP", - std::string("USD/") + G1.human())[jss::result][jss::offers]; + offers = env.rpc("book_offers", "XRP", std::string("USD/") + G1.human())[jss::result][jss::offers]; if (!BEAST_EXPECT(checkArraySize(offers, 2u))) return; - offers = env.rpc( - "book_offers", - std::string("USD/") + G1.human(), - "XRP")[jss::result][jss::offers]; + offers = env.rpc("book_offers", std::string("USD/") + G1.human(), "XRP")[jss::result][jss::offers]; if (!BEAST_EXPECT(checkArraySize(offers, 2u))) return; } @@ -553,8 +518,7 @@ class Freeze_test : public beast::unit_test::suite } if (features[featureDeepFreeze]) { - env(trust( - G1, deepFrozenAcc["USD"](0), tfSetFreeze | tfSetDeepFreeze)); + env(trust(G1, deepFrozenAcc["USD"](0), tfSetFreeze | tfSetDeepFreeze)); { auto const flags = getTrustlineFlags(env, 2u, 1u); BEAST_EXPECT(!(flags & (lsfLowFreeze | lsfLowDeepFreeze))); @@ -593,21 +557,18 @@ class Freeze_test : public beast::unit_test::suite // test: cannot deep freeze already frozen line when no freeze // enacted - env(trust(G1, frozenAcc["USD"](0), tfSetDeepFreeze), - ter(tecNO_PERMISSION)); + env(trust(G1, frozenAcc["USD"](0), tfSetDeepFreeze), ter(tecNO_PERMISSION)); } else { // test: previous functionality, checking there's no changes to a // trust line env(trust(G1, A1["USD"](0), tfSetFreeze)); - auto affected = env.meta()->getJson( - JsonOptions::none)[sfAffectedNodes.fieldName]; + auto affected = env.meta()->getJson(JsonOptions::none)[sfAffectedNodes.fieldName]; if (!BEAST_EXPECT(checkArraySize(affected, 1u))) return; - auto let = affected[0u][sfModifiedNode.fieldName] - [sfLedgerEntryType.fieldName]; + auto let = affected[0u][sfModifiedNode.fieldName][sfLedgerEntryType.fieldName]; BEAST_EXPECT(let == jss::AccountRoot); } @@ -668,9 +629,7 @@ class Freeze_test : public beast::unit_test::suite auto offers = getAccountOffers(env, A3)[jss::offers]; if (!BEAST_EXPECT(checkArraySize(offers, 1u))) return; - BEAST_EXPECT( - offers[0u][jss::taker_gets] == - G1["USD"](999).value().getJson(JsonOptions::none)); + BEAST_EXPECT(offers[0u][jss::taker_gets] == G1["USD"](999).value().getJson(JsonOptions::none)); // test: someone else creates an offer providing liquidity env(offer(A4, XRP(999), G1["USD"](999))); @@ -678,15 +637,11 @@ class Freeze_test : public beast::unit_test::suite // test: owner of partially consumed offers line is frozen env(trust(G1, A3["USD"](0), tfSetFreeze)); - auto affected = - env.meta()->getJson(JsonOptions::none)[sfAffectedNodes.fieldName]; + auto affected = env.meta()->getJson(JsonOptions::none)[sfAffectedNodes.fieldName]; if (!BEAST_EXPECT(checkArraySize(affected, 2u))) return; - auto ff = - affected[1u][sfModifiedNode.fieldName][sfFinalFields.fieldName]; - BEAST_EXPECT( - ff[sfHighLimit.fieldName] == - G1["USD"](0).value().getJson(JsonOptions::none)); + auto ff = affected[1u][sfModifiedNode.fieldName][sfFinalFields.fieldName]; + BEAST_EXPECT(ff[sfHighLimit.fieldName] == G1["USD"](0).value().getJson(JsonOptions::none)); BEAST_EXPECT(!(ff[jss::Flags].asUInt() & lsfLowFreeze)); BEAST_EXPECT(ff[jss::Flags].asUInt() & lsfHighFreeze); env.close(); @@ -708,27 +663,22 @@ class Freeze_test : public beast::unit_test::suite // removal buy successful OfferCreate // test: freeze the new offer env(trust(G1, A4["USD"](0), tfSetFreeze)); - affected = - env.meta()->getJson(JsonOptions::none)[sfAffectedNodes.fieldName]; + affected = env.meta()->getJson(JsonOptions::none)[sfAffectedNodes.fieldName]; if (!BEAST_EXPECT(checkArraySize(affected, 2u))) return; ff = affected[0u][sfModifiedNode.fieldName][sfFinalFields.fieldName]; - BEAST_EXPECT( - ff[sfLowLimit.fieldName] == - G1["USD"](0).value().getJson(JsonOptions::none)); + BEAST_EXPECT(ff[sfLowLimit.fieldName] == G1["USD"](0).value().getJson(JsonOptions::none)); BEAST_EXPECT(ff[jss::Flags].asUInt() & lsfLowFreeze); BEAST_EXPECT(!(ff[jss::Flags].asUInt() & lsfHighFreeze)); env.close(); // test: can no longer create a crossing offer env(offer(A2, G1["USD"](999), XRP(999))); - affected = - env.meta()->getJson(JsonOptions::none)[sfAffectedNodes.fieldName]; + affected = env.meta()->getJson(JsonOptions::none)[sfAffectedNodes.fieldName]; if (!BEAST_EXPECT(checkArraySize(affected, 8u))) return; auto created = affected[0u][sfCreatedNode.fieldName]; - BEAST_EXPECT( - created[sfNewFields.fieldName][jss::Account] == A2.human()); + BEAST_EXPECT(created[sfNewFields.fieldName][jss::Account] == A2.human()); env.close(); // test: offer was removed by offer_create @@ -800,20 +750,15 @@ class Freeze_test : public beast::unit_test::suite // test: can still buy from A2 env(offer(A1, USD(1), XRP(2)), txflags(tfFillOrKill)); env.close(); - env.require( - balance(A1, USD(1001)), balance(A2, USD(998)), offers(A1, 0)); + env.require(balance(A1, USD(1001)), balance(A2, USD(998)), offers(A1, 0)); // test: cannot create passive sell offer - env(offer(A1, XRP(2), USD(1)), - txflags(tfPassive), - ter(tecUNFUNDED_OFFER)); + env(offer(A1, XRP(2), USD(1)), txflags(tfPassive), ter(tecUNFUNDED_OFFER)); env.close(); env.require(balance(A1, USD(1001)), offers(A1, 0)); // test: cannot sell to A3 - env(offer(A1, XRP(1), USD(1)), - txflags(tfFillOrKill), - ter(tecUNFUNDED_OFFER)); + env(offer(A1, XRP(1), USD(1)), txflags(tfFillOrKill), ter(tecUNFUNDED_OFFER)); env.close(); env.require(balance(A1, USD(1001)), offers(A1, 0)); @@ -829,27 +774,19 @@ class Freeze_test : public beast::unit_test::suite env.close(); // test: cannot create passive buy offer - env(offer(A1, USD(1), XRP(0.5)), - txflags(tfPassive), - ter(tecFROZEN)); + env(offer(A1, USD(1), XRP(0.5)), txflags(tfPassive), ter(tecFROZEN)); env.close(); // test: cannot buy from A2 - env(offer(A1, USD(1), XRP(2)), - txflags(tfFillOrKill), - ter(tecFROZEN)); + env(offer(A1, USD(1), XRP(2)), txflags(tfFillOrKill), ter(tecFROZEN)); env.close(); // test: cannot create passive sell offer - env(offer(A1, XRP(2), USD(1)), - txflags(tfPassive), - ter(tecUNFUNDED_OFFER)); + env(offer(A1, XRP(2), USD(1)), txflags(tfPassive), ter(tecUNFUNDED_OFFER)); env.close(); // test: cannot sell to A3 - env(offer(A1, XRP(1), USD(1)), - txflags(tfFillOrKill), - ter(tecUNFUNDED_OFFER)); + env(offer(A1, XRP(1), USD(1)), txflags(tfFillOrKill), ter(tecUNFUNDED_OFFER)); env.close(); env(trust(G1, A1["USD"](0), tfClearFreeze | tfClearDeepFreeze)); @@ -873,18 +810,13 @@ class Freeze_test : public beast::unit_test::suite env.require(balance(A1, USD(1001)), balance(A2, USD(998))); env(offer(A2, XRP(1.1), USD(1)), txflags(tfFillOrKill)); env.close(); - env.require( - balance(A1, USD(1002)), balance(A2, USD(997)), offers(A1, 1)); + env.require(balance(A1, USD(1002)), balance(A2, USD(997)), offers(A1, 1)); // test: A3 wants to buy from A1, must fail - env.require( - balance(A1, USD(1002)), balance(A3, USD(1)), offers(A1, 1)); - env(offer(A3, USD(1), XRP(1.9)), - txflags(tfFillOrKill), - ter(tecKILLED)); + env.require(balance(A1, USD(1002)), balance(A3, USD(1)), offers(A1, 1)); + env(offer(A3, USD(1), XRP(1.9)), txflags(tfFillOrKill), ter(tecKILLED)); env.close(); - env.require( - balance(A1, USD(1002)), balance(A3, USD(1)), offers(A1, 0)); + env.require(balance(A1, USD(1002)), balance(A3, USD(1)), offers(A1, 0)); env(trust(G1, A1["USD"](0), tfClearFreeze)); env.close(); @@ -905,22 +837,15 @@ class Freeze_test : public beast::unit_test::suite // test: A2 wants to sell to A1, must fail env.require(balance(A1, USD(1002)), balance(A2, USD(997))); - env(offer(A2, XRP(1.1), USD(1)), - txflags(tfFillOrKill), - ter(tecKILLED)); + env(offer(A2, XRP(1.1), USD(1)), txflags(tfFillOrKill), ter(tecKILLED)); env.close(); - env.require( - balance(A1, USD(1002)), balance(A2, USD(997)), offers(A1, 1)); + env.require(balance(A1, USD(1002)), balance(A2, USD(997)), offers(A1, 1)); // test: A3 wants to buy from A1, must fail - env.require( - balance(A1, USD(1002)), balance(A3, USD(1)), offers(A1, 1)); - env(offer(A3, USD(1), XRP(1.9)), - txflags(tfFillOrKill), - ter(tecKILLED)); + env.require(balance(A1, USD(1002)), balance(A3, USD(1)), offers(A1, 1)); + env(offer(A3, USD(1), XRP(1.9)), txflags(tfFillOrKill), ter(tecKILLED)); env.close(); - env.require( - balance(A1, USD(1002)), balance(A3, USD(1)), offers(A1, 0)); + env.require(balance(A1, USD(1002)), balance(A3, USD(1)), offers(A1, 0)); env(trust(G1, A1["USD"](0), tfClearFreeze | tfClearDeepFreeze)); env.close(); @@ -942,12 +867,9 @@ class Freeze_test : public beast::unit_test::suite env.close(); // test: A1 wants to buy, must fail - env(offer(A1, USD(1), XRP(2)), - txflags(tfFillOrKill), - ter(tecKILLED)); + env(offer(A1, USD(1), XRP(2)), txflags(tfFillOrKill), ter(tecKILLED)); env.close(); - env.require( - balance(A1, USD(1002)), balance(A2, USD(997)), offers(A1, 0)); + env.require(balance(A1, USD(1002)), balance(A2, USD(997)), offers(A1, 0)); // test: A1 can create passive sell offer env(offer(A1, XRP(2), USD(1)), txflags(tfPassive)); @@ -975,27 +897,19 @@ class Freeze_test : public beast::unit_test::suite env.close(); // test: A1 cannot create passive buy offer - env(offer(A1, USD(1), XRP(0.5)), - txflags(tfPassive), - ter(tecFROZEN)); + env(offer(A1, USD(1), XRP(0.5)), txflags(tfPassive), ter(tecFROZEN)); env.close(); // test: A1 cannot buy, must fail - env(offer(A1, USD(1), XRP(2)), - txflags(tfFillOrKill), - ter(tecFROZEN)); + env(offer(A1, USD(1), XRP(2)), txflags(tfFillOrKill), ter(tecFROZEN)); env.close(); // test: A1 cannot create passive sell offer - env(offer(A1, XRP(2), USD(1)), - txflags(tfPassive), - ter(tecUNFUNDED_OFFER)); + env(offer(A1, XRP(2), USD(1)), txflags(tfPassive), ter(tecUNFUNDED_OFFER)); env.close(); // test: A1 cannot sell to A3 - env(offer(A1, XRP(1), USD(1)), - txflags(tfFillOrKill), - ter(tecUNFUNDED_OFFER)); + env(offer(A1, XRP(1), USD(1)), txflags(tfFillOrKill), ter(tecUNFUNDED_OFFER)); env.close(); env(trust(A1, limit, tfClearFreeze | tfClearDeepFreeze)); @@ -1036,19 +950,11 @@ class Freeze_test : public beast::unit_test::suite env.close(); // test: A1 cannot send USD using XRP through A2 offer - env(pay(A1, G1, USD(10)), - path(~USD), - sendmax(XRP(11)), - txflags(tfNoRippleDirect), - ter(tecPATH_PARTIAL)); + env(pay(A1, G1, USD(10)), path(~USD), sendmax(XRP(11)), txflags(tfNoRippleDirect), ter(tecPATH_PARTIAL)); env.close(); // test: G1 cannot send USD using XRP through A2 offer - env(pay(G1, A1, USD(10)), - path(~USD), - sendmax(XRP(11)), - txflags(tfNoRippleDirect), - ter(tecPATH_PARTIAL)); + env(pay(G1, A1, USD(10)), path(~USD), sendmax(XRP(11)), txflags(tfNoRippleDirect), ter(tecPATH_PARTIAL)); env.close(); env(trust(G1, A2["USD"](0), tfClearFreeze)); @@ -1062,19 +968,11 @@ class Freeze_test : public beast::unit_test::suite env.close(); // test: A1 cannot send USD using XRP through A2 offer - env(pay(A1, G1, USD(10)), - path(~USD), - sendmax(XRP(11)), - txflags(tfNoRippleDirect), - ter(tecPATH_PARTIAL)); + env(pay(A1, G1, USD(10)), path(~USD), sendmax(XRP(11)), txflags(tfNoRippleDirect), ter(tecPATH_PARTIAL)); env.close(); // test: G1 cannot send USD using XRP through A2 offer - env(pay(G1, A1, USD(10)), - path(~USD), - sendmax(XRP(11)), - txflags(tfNoRippleDirect), - ter(tecPATH_PARTIAL)); + env(pay(G1, A1, USD(10)), path(~USD), sendmax(XRP(11)), txflags(tfNoRippleDirect), ter(tecPATH_PARTIAL)); env.close(); env(trust(G1, A2["USD"](0), tfClearFreeze | tfClearDeepFreeze)); @@ -1088,17 +986,11 @@ class Freeze_test : public beast::unit_test::suite env.close(); // test: A1 can send USD using XRP through A2 offer - env(pay(A1, G1, USD(10)), - path(~USD), - sendmax(XRP(11)), - txflags(tfNoRippleDirect)); + env(pay(A1, G1, USD(10)), path(~USD), sendmax(XRP(11)), txflags(tfNoRippleDirect)); env.close(); // test: G1 can send USD using XRP through A2 offer - env(pay(G1, A1, USD(10)), - path(~USD), - sendmax(XRP(11)), - txflags(tfNoRippleDirect)); + env(pay(G1, A1, USD(10)), path(~USD), sendmax(XRP(11)), txflags(tfNoRippleDirect)); env.close(); env(trust(A2, limit, tfClearFreeze)); @@ -1113,19 +1005,11 @@ class Freeze_test : public beast::unit_test::suite env.close(); // test: A1 cannot send USD using XRP through A2 offer - env(pay(A1, G1, USD(10)), - path(~USD), - sendmax(XRP(11)), - txflags(tfNoRippleDirect), - ter(tecPATH_PARTIAL)); + env(pay(A1, G1, USD(10)), path(~USD), sendmax(XRP(11)), txflags(tfNoRippleDirect), ter(tecPATH_PARTIAL)); env.close(); // test: G1 cannot send USD using XRP through A2 offer - env(pay(G1, A1, USD(10)), - path(~USD), - sendmax(XRP(11)), - txflags(tfNoRippleDirect), - ter(tecPATH_PARTIAL)); + env(pay(G1, A1, USD(10)), path(~USD), sendmax(XRP(11)), txflags(tfNoRippleDirect), ter(tecPATH_PARTIAL)); env.close(); env(trust(A2, limit, tfClearFreeze | tfClearDeepFreeze)); @@ -1146,17 +1030,11 @@ class Freeze_test : public beast::unit_test::suite env.close(); // test: A1 can send XRP using USD through A2 offer - env(pay(A1, G1, XRP(10)), - path(~XRP), - sendmax(USD(11)), - txflags(tfNoRippleDirect)); + env(pay(A1, G1, XRP(10)), path(~XRP), sendmax(USD(11)), txflags(tfNoRippleDirect)); env.close(); // test: G1 can send XRP using USD through A2 offer - env(pay(G1, A1, XRP(10)), - path(~XRP), - sendmax(USD(11)), - txflags(tfNoRippleDirect)); + env(pay(G1, A1, XRP(10)), path(~XRP), sendmax(USD(11)), txflags(tfNoRippleDirect)); env.close(); env(trust(G1, A2["USD"](0), tfClearFreeze)); @@ -1171,19 +1049,11 @@ class Freeze_test : public beast::unit_test::suite env.close(); // test: A1 cannot send XRP using USD through A2 offer - env(pay(A1, G1, XRP(10)), - path(~XRP), - sendmax(USD(11)), - txflags(tfNoRippleDirect), - ter(tecPATH_PARTIAL)); + env(pay(A1, G1, XRP(10)), path(~XRP), sendmax(USD(11)), txflags(tfNoRippleDirect), ter(tecPATH_PARTIAL)); env.close(); // test: G1 cannot send XRP using USD through A2 offer - env(pay(G1, A1, XRP(10)), - path(~XRP), - sendmax(USD(11)), - txflags(tfNoRippleDirect), - ter(tecPATH_PARTIAL)); + env(pay(G1, A1, XRP(10)), path(~XRP), sendmax(USD(11)), txflags(tfNoRippleDirect), ter(tecPATH_PARTIAL)); env.close(); env(trust(G1, A2["USD"](0), tfClearFreeze | tfClearDeepFreeze)); @@ -1197,17 +1067,11 @@ class Freeze_test : public beast::unit_test::suite env.close(); // test: A1 can send XRP using USD through A2 offer - env(pay(A1, G1, XRP(10)), - path(~XRP), - sendmax(USD(11)), - txflags(tfNoRippleDirect)); + env(pay(A1, G1, XRP(10)), path(~XRP), sendmax(USD(11)), txflags(tfNoRippleDirect)); env.close(); // test: G1 can send XRP using USD through A2 offer - env(pay(G1, A1, XRP(10)), - path(~XRP), - sendmax(USD(11)), - txflags(tfNoRippleDirect)); + env(pay(G1, A1, XRP(10)), path(~XRP), sendmax(USD(11)), txflags(tfNoRippleDirect)); env.close(); env(trust(A2, limit, tfClearFreeze)); @@ -1222,19 +1086,11 @@ class Freeze_test : public beast::unit_test::suite env.close(); // test: A1 cannot send XRP using USD through A2 offer - env(pay(A1, G1, XRP(10)), - path(~XRP), - sendmax(USD(11)), - txflags(tfNoRippleDirect), - ter(tecPATH_PARTIAL)); + env(pay(A1, G1, XRP(10)), path(~XRP), sendmax(USD(11)), txflags(tfNoRippleDirect), ter(tecPATH_PARTIAL)); env.close(); // test: G1 cannot send XRP using USD through A2 offer - env(pay(G1, A1, XRP(10)), - path(~XRP), - sendmax(USD(11)), - txflags(tfNoRippleDirect), - ter(tecPATH_PARTIAL)); + env(pay(G1, A1, XRP(10)), path(~XRP), sendmax(USD(11)), txflags(tfNoRippleDirect), ter(tecPATH_PARTIAL)); env.close(); env(trust(A2, limit, tfClearFreeze | tfClearDeepFreeze)); @@ -1696,32 +1552,19 @@ class Freeze_test : public beast::unit_test::suite env.close(); // test: can still use XRP to make payment - env(pay(A1, A2, USD(10)), - path(~USD), - sendmax(XRP(11)), - txflags(tfNoRippleDirect)); + env(pay(A1, A2, USD(10)), path(~USD), sendmax(XRP(11)), txflags(tfNoRippleDirect)); env.close(); // test: cannot use USD to make payment - env(pay(A1, A2, XRP(10)), - path(~XRP), - sendmax(USD(11)), - txflags(tfNoRippleDirect), - ter(tecPATH_DRY)); + env(pay(A1, A2, XRP(10)), path(~XRP), sendmax(USD(11)), txflags(tfNoRippleDirect), ter(tecPATH_DRY)); env.close(); // test: can still receive USD payments. - env(pay(A2, A1, USD(10)), - path(~USD), - sendmax(XRP(11)), - txflags(tfNoRippleDirect)); + env(pay(A2, A1, USD(10)), path(~USD), sendmax(XRP(11)), txflags(tfNoRippleDirect)); env.close(); // test: can still receive XRP payments. - env(pay(A2, A1, XRP(10)), - path(~XRP), - sendmax(USD(11)), - txflags(tfNoRippleDirect)); + env(pay(A2, A1, XRP(10)), path(~XRP), sendmax(USD(11)), txflags(tfNoRippleDirect)); env.close(); env(trust(G1, A1["USD"](0), tfClearFreeze)); @@ -1736,33 +1579,19 @@ class Freeze_test : public beast::unit_test::suite env.close(); // test: can still use XRP to make payment - env(pay(A1, A2, USD(10)), - path(~USD), - sendmax(XRP(11)), - txflags(tfNoRippleDirect)); + env(pay(A1, A2, USD(10)), path(~USD), sendmax(XRP(11)), txflags(tfNoRippleDirect)); env.close(); // test: cannot use USD to make payment - env(pay(A1, A2, XRP(10)), - path(~XRP), - sendmax(USD(11)), - txflags(tfNoRippleDirect), - ter(tecPATH_DRY)); + env(pay(A1, A2, XRP(10)), path(~XRP), sendmax(USD(11)), txflags(tfNoRippleDirect), ter(tecPATH_DRY)); env.close(); // test: cannot receive USD payments. - env(pay(A2, A1, USD(10)), - path(~USD), - sendmax(XRP(11)), - txflags(tfNoRippleDirect), - ter(tecPATH_DRY)); + env(pay(A2, A1, USD(10)), path(~USD), sendmax(XRP(11)), txflags(tfNoRippleDirect), ter(tecPATH_DRY)); env.close(); // test: can still receive XRP payments. - env(pay(A2, A1, XRP(10)), - path(~XRP), - sendmax(USD(11)), - txflags(tfNoRippleDirect)); + env(pay(A2, A1, XRP(10)), path(~XRP), sendmax(USD(11)), txflags(tfNoRippleDirect)); env.close(); env(trust(G1, A1["USD"](0), tfClearFreeze | tfClearDeepFreeze)); @@ -1830,8 +1659,7 @@ class Freeze_test : public beast::unit_test::suite env.close(); // test: A2 cannot send USD for NFT - env(token::acceptSellOffer(A2, sellOfferIndex), - ter(tecINSUFFICIENT_FUNDS)); + env(token::acceptSellOffer(A2, sellOfferIndex), ter(tecINSUFFICIENT_FUNDS)); env.close(); env(trust(G1, A2["USD"](0), tfClearFreeze)); @@ -1846,8 +1674,7 @@ class Freeze_test : public beast::unit_test::suite env.close(); // test: A2 cannot send USD for NFT - env(token::acceptSellOffer(A2, sellOfferIndex), - ter(tecINSUFFICIENT_FUNDS)); + env(token::acceptSellOffer(A2, sellOfferIndex), ter(tecINSUFFICIENT_FUNDS)); env.close(); env(trust(G1, A2["USD"](0), tfClearFreeze | tfClearDeepFreeze)); @@ -1855,8 +1682,7 @@ class Freeze_test : public beast::unit_test::suite } // Testing A1 nft buy offer when A2 deep frozen by issuer - if (features[featureDeepFreeze] && - features[fixEnforceNFTokenTrustlineV2]) + if (features[featureDeepFreeze] && features[fixEnforceNFTokenTrustlineV2]) { env(trust(G1, A2["USD"](0), tfSetFreeze | tfSetDeepFreeze)); env.close(); @@ -1931,8 +1757,7 @@ class Freeze_test : public beast::unit_test::suite env.close(); // test: A2 cannot send USD for NFT - env(token::acceptSellOffer(A2, sellOfferIndex), - ter(tecINSUFFICIENT_FUNDS)); + env(token::acceptSellOffer(A2, sellOfferIndex), ter(tecINSUFFICIENT_FUNDS)); env.close(); env(trust(A2, limit, tfClearFreeze | tfClearDeepFreeze)); @@ -1940,8 +1765,7 @@ class Freeze_test : public beast::unit_test::suite } // Testing brokered offer acceptance - if (features[featureDeepFreeze] && - features[fixEnforceNFTokenTrustlineV2]) + if (features[featureDeepFreeze] && features[fixEnforceNFTokenTrustlineV2]) { Account broker{"broker"}; env.fund(XRP(10000), broker); @@ -1960,15 +1784,12 @@ class Freeze_test : public beast::unit_test::suite env(token::createOffer(A1, nftID, USD(11)), token::owner(A2)); env.close(); - env(token::brokerOffers(broker, buyIdx, sellIdx), - token::brokerFee(USD(1)), - ter(tecFROZEN)); + env(token::brokerOffers(broker, buyIdx, sellIdx), token::brokerFee(USD(1)), ter(tecFROZEN)); env.close(); } // Testing transfer fee - if (features[featureDeepFreeze] && - features[fixEnforceNFTokenTrustlineV2]) + if (features[featureDeepFreeze] && features[fixEnforceNFTokenTrustlineV2]) { Account minter{"minter"}; env.fund(XRP(10000), minter); @@ -1976,24 +1797,18 @@ class Freeze_test : public beast::unit_test::suite env(trust(G1, minter["USD"](1000))); env.close(); - uint256 const nftID{ - token::getNextID(env, minter, 0u, tfTransferable, 1u)}; - env(token::mint(minter, 0), - token::xferFee(1u), - txflags(tfTransferable)); + uint256 const nftID{token::getNextID(env, minter, 0u, tfTransferable, 1u)}; + env(token::mint(minter, 0), token::xferFee(1u), txflags(tfTransferable)); env.close(); - uint256 const minterSellIdx = - keylet::nftoffer(minter, env.seq(minter)).key; - env(token::createOffer(minter, nftID, drops(1)), - txflags(tfSellNFToken)); + uint256 const minterSellIdx = keylet::nftoffer(minter, env.seq(minter)).key; + env(token::createOffer(minter, nftID, drops(1)), txflags(tfSellNFToken)); env.close(); env(token::acceptSellOffer(A2, minterSellIdx)); env.close(); uint256 const sellIdx = keylet::nftoffer(A2, env.seq(A2)).key; - env(token::createOffer(A2, nftID, USD(100)), - txflags(tfSellNFToken)); + env(token::createOffer(A2, nftID, USD(100)), txflags(tfSellNFToken)); env.close(); env(trust(G1, minter["USD"](1000), tfSetFreeze | tfSetDeepFreeze)); env.close(); @@ -2004,28 +1819,19 @@ class Freeze_test : public beast::unit_test::suite // Helper function to extract trustline flags from open ledger uint32_t - getTrustlineFlags( - test::jtx::Env& env, - size_t expectedArraySize, - size_t expectedArrayIndex, - bool modified = true) + getTrustlineFlags(test::jtx::Env& env, size_t expectedArraySize, size_t expectedArrayIndex, bool modified = true) { using namespace test::jtx; - auto const affected = - env.meta()->getJson(JsonOptions::none)[sfAffectedNodes.fieldName]; + auto const affected = env.meta()->getJson(JsonOptions::none)[sfAffectedNodes.fieldName]; if (!BEAST_EXPECT(checkArraySize(affected, expectedArraySize))) return 0; if (modified) { - return affected[expectedArrayIndex][sfModifiedNode.fieldName] - [sfFinalFields.fieldName][jss::Flags] - .asUInt(); + return affected[expectedArrayIndex][sfModifiedNode.fieldName][sfFinalFields.fieldName][jss::Flags].asUInt(); } - return affected[expectedArrayIndex][sfCreatedNode.fieldName] - [sfNewFields.fieldName][jss::Flags] - .asUInt(); + return affected[expectedArrayIndex][sfCreatedNode.fieldName][sfNewFields.fieldName][jss::Flags].asUInt(); } // Helper function that returns the index of the next check on account @@ -2036,20 +1842,15 @@ class Freeze_test : public beast::unit_test::suite } uint256 - createNFTSellOffer( - test::jtx::Env& env, - test::jtx::Account const& account, - test::jtx::PrettyAmount const& currency) + createNFTSellOffer(test::jtx::Env& env, test::jtx::Account const& account, test::jtx::PrettyAmount const& currency) { using namespace test::jtx; uint256 const nftID{token::getNextID(env, account, 0u, tfTransferable)}; env(token::mint(account, 0), txflags(tfTransferable)); env.close(); - uint256 const sellOfferIndex = - keylet::nftoffer(account, env.seq(account)).key; - env(token::createOffer(account, nftID, currency), - txflags(tfSellNFToken)); + uint256 const sellOfferIndex = keylet::nftoffer(account, env.seq(account)).key; + env(token::createOffer(account, nftID, currency), txflags(tfSellNFToken)); env.close(); return sellOfferIndex; @@ -2076,9 +1877,7 @@ public: }; using namespace test::jtx; auto const sa = testable_amendments(); - testAll( - sa - featureDeepFreeze - featurePermissionedDEX - - fixEnforceNFTokenTrustlineV2); + testAll(sa - featureDeepFreeze - featurePermissionedDEX - fixEnforceNFTokenTrustlineV2); testAll(sa - featurePermissionedDEX - fixEnforceNFTokenTrustlineV2); testAll(sa - featureDeepFreeze - featurePermissionedDEX); testAll(sa - featurePermissionedDEX); diff --git a/src/test/app/HashRouter_test.cpp b/src/test/app/HashRouter_test.cpp index 2d1d37c3e3..753922a67d 100644 --- a/src/test/app/HashRouter_test.cpp +++ b/src/test/app/HashRouter_test.cpp @@ -1,8 +1,9 @@ -#include +#include #include #include #include +#include namespace xrpl { namespace test { @@ -368,9 +369,7 @@ class HashRouter_test : public beast::unit_test::suite HF f2 = HF::SAVED; HF combined = f1 | f2; - BEAST_EXPECT( - static_cast(combined) == - (static_cast(f1) | static_cast(f2))); + BEAST_EXPECT(static_cast(combined) == (static_cast(f1) | static_cast(f2))); HF temp = f1; temp |= f2; diff --git a/src/test/app/Invariants_test.cpp b/src/test/app/Invariants_test.cpp index 9f70538778..7558c951b0 100644 --- a/src/test/app/Invariants_test.cpp +++ b/src/test/app/Invariants_test.cpp @@ -29,18 +29,18 @@ class Invariants_test : public beast::unit_test::suite // on the ledger after creating two accounts, but before closing it, and // before the Precheck function. These should only be valid functions, and // not direct manipulations. Preclose is not commonly used. - using Preclose = std::function; + using Preclose = std::function; // this is common setup/method for running a failing invariant check. The // precheck function is used to manipulate the ApplyContext with view // changes that will cause the check to fail. - using Precheck = std::function; + using Precheck = std::function; + + static FeatureBitset + defaultAmendments() + { + return xrpl::test::jtx::testable_amendments() | featureInvariantsV1_1 | featureSingleAssetVault; + } /** Run a specific test case to put the ledger into a state that will be * detected by an invariant. Simulates the actions of a transaction that @@ -65,15 +65,26 @@ class Invariants_test : public beast::unit_test::suite Precheck const& precheck, XRPAmount fee = XRPAmount{}, STTx tx = STTx{ttACCOUNT_SET, [](STObject&) {}}, - std::initializer_list ters = - {tecINVARIANT_FAILED, tefINVARIANT_FAILED}, + std::initializer_list ters = {tecINVARIANT_FAILED, tefINVARIANT_FAILED}, + Preclose const& preclose = {}, + TxAccount setTxAccount = TxAccount::None) + { + return doInvariantCheck( + test::jtx::Env(*this, defaultAmendments()), expect_logs, precheck, fee, tx, ters, preclose, setTxAccount); + } + + void + doInvariantCheck( + test::jtx::Env&& env, + std::vector const& expect_logs, + Precheck const& precheck, + XRPAmount fee = XRPAmount{}, + STTx tx = STTx{ttACCOUNT_SET, [](STObject&) {}}, + std::initializer_list ters = {tecINVARIANT_FAILED, tefINVARIANT_FAILED}, Preclose const& preclose = {}, TxAccount setTxAccount = TxAccount::None) { using namespace test::jtx; - FeatureBitset amendments = testable_amendments() | - featureInvariantsV1_1 | featureSingleAssetVault; - Env env{*this, amendments}; Account const A1{"A1"}; Account const A2{"A2"}; @@ -82,20 +93,29 @@ class Invariants_test : public beast::unit_test::suite BEAST_EXPECT(preclose(A1, A2, env)); env.close(); + if (setTxAccount != TxAccount::None) + tx.setAccountID(sfAccount, setTxAccount == TxAccount::A1 ? A1.id() : A2.id()); + + return doInvariantCheck(std::move(env), A1, A2, expect_logs, precheck, fee, tx, ters); + } + + void + doInvariantCheck( + test::jtx::Env&& env, + test::jtx::Account const& A1, + test::jtx::Account const& A2, + std::vector const& expect_logs, + Precheck const& precheck, + XRPAmount fee = XRPAmount{}, + STTx tx = STTx{ttACCOUNT_SET, [](STObject&) {}}, + std::initializer_list ters = {tecINVARIANT_FAILED, tefINVARIANT_FAILED}) + { + using namespace test::jtx; + OpenView ov{*env.current()}; test::StreamSink sink{beast::severities::kWarning}; beast::Journal jlog{sink}; - if (setTxAccount != TxAccount::None) - tx.setAccountID( - sfAccount, setTxAccount == TxAccount::A1 ? A1.id() : A2.id()); - ApplyContext ac{ - env.app(), - ov, - tx, - tesSUCCESS, - env.current()->fees().base, - tapNONE, - jlog}; + ApplyContext ac{env.app(), ov, tx, tesSUCCESS, env.current()->fees().base, tapNONE, jlog}; BEAST_EXPECT(precheck(A1, A2, ac)); @@ -107,20 +127,21 @@ class Invariants_test : public beast::unit_test::suite for (TER const& terExpect : ters) { terActual = ac.checkInvariants(terActual, fee); - BEAST_EXPECT(terExpect == terActual); + BEAST_EXPECTS(terExpect == terActual, std::to_string(TERtoInt(terActual))); auto const messages = sink.messages().str(); - BEAST_EXPECT( - messages.starts_with("Invariant failed:") || - messages.starts_with("Transaction caused an exception")); + + if (terActual != tesSUCCESS) + { + BEAST_EXPECTS( + messages.starts_with("Invariant failed:") || + messages.starts_with("Transaction caused an exception"), + messages); + } + // std::cerr << messages << '\n'; for (auto const& m : expect_logs) { - if (messages.find(m) == std::string::npos) - { - // uncomment if you want to log the invariant failure - // std::cerr << " --> " << m << std::endl; - fail(); - } + BEAST_EXPECTS(messages.find(m) != std::string::npos, m); } } } @@ -131,8 +152,7 @@ class Invariants_test : public beast::unit_test::suite using namespace test::jtx; testcase << "XRP created"; doInvariantCheck( - {{"XRP net change was positive: 500"}}, - [](Account const& A1, Account const&, ApplyContext& ac) { + {{"XRP net change was positive: 500"}}, [](Account const& A1, Account const&, ApplyContext& ac) { // put a single account in the view and "manufacture" some XRP auto const sle = ac.view().peek(keylet::account(A1.id())); if (!sle) @@ -151,20 +171,18 @@ class Invariants_test : public beast::unit_test::suite testcase << "account root removed"; // An account was deleted, but not by an AccountDelete transaction. - doInvariantCheck( - {{"an account root was deleted"}}, - [](Account const& A1, Account const&, ApplyContext& ac) { - // remove an account from the view - auto sle = ac.view().peek(keylet::account(A1.id())); - if (!sle) - return false; - // Clear the balance so the "account deletion left behind a - // non-zero balance" check doesn't trip earlier than the desired - // check. - sle->at(sfBalance) = beast::zero; - ac.view().erase(sle); - return true; - }); + doInvariantCheck({{"an account root was deleted"}}, [](Account const& A1, Account const&, ApplyContext& ac) { + // remove an account from the view + auto sle = ac.view().peek(keylet::account(A1.id())); + if (!sle) + return false; + // Clear the balance so the "account deletion left behind a + // non-zero balance" check doesn't trip earlier than the desired + // check. + sle->at(sfBalance) = beast::zero; + ac.view().erase(sle); + return true; + }); // Successful AccountDelete transaction that didn't delete an account. // @@ -173,9 +191,7 @@ class Invariants_test : public beast::unit_test::suite // After a discussion with the team, we believe that's okay. doInvariantCheck( {{"account deletion succeeded without deleting an account"}}, - [](Account const&, Account const&, ApplyContext& ac) { - return true; - }, + [](Account const&, Account const&, ApplyContext& ac) { return true; }, XRPAmount{}, STTx{ttACCOUNT_DELETE, [](STObject& tx) {}}, {tecINVARIANT_FAILED, tecINVARIANT_FAILED}); @@ -262,8 +278,7 @@ class Invariants_test : public beast::unit_test::suite using namespace std::string_literals; doInvariantCheck( - {{"account deletion left behind a "s + type.c_str() + - " object"}}, + {{"account deletion left behind a "s + type.c_str() + " object"}}, [&](Account const& A1, Account const& A2, ApplyContext& ac) { // Add an object to the ledger for account A1, then delete // A1 @@ -364,9 +379,7 @@ class Invariants_test : public beast::unit_test::suite BEAST_EXPECT(sle->at(~sfAMMID)); BEAST_EXPECT(sle->at(~sfAMMID) == ammKey); - for (auto const& trustKeylet : - {keylet::line(ammAcctID, A1["USD"]), - keylet::line(A1, ammIssue)}) + for (auto const& trustKeylet : {keylet::line(ammAcctID, A1["USD"]), keylet::line(A1, ammIssue)}) { if (auto const line = ac.view().peek(trustKeylet); !line) { @@ -377,12 +390,8 @@ class Invariants_test : public beast::unit_test::suite STAmount const lowLimit = line->at(sfLowLimit); STAmount const highLimit = line->at(sfHighLimit); BEAST_EXPECT( - trustDelete( - ac.view(), - line, - lowLimit.getIssuer(), - highLimit.getIssuer(), - ac.journal) == tesSUCCESS); + trustDelete(ac.view(), line, lowLimit.getIssuer(), highLimit.getIssuer(), ac.journal) == + tesSUCCESS); } } @@ -391,11 +400,8 @@ class Invariants_test : public beast::unit_test::suite return false; auto const ownerDirKeylet = keylet::ownerDir(ammAcctID); - BEAST_EXPECT(ac.view().dirRemove( - ownerDirKeylet, ammSle->at(sfOwnerNode), ammKey, false)); - BEAST_EXPECT( - !ac.view().exists(ownerDirKeylet) || - ac.view().emptyDirDelete(ownerDirKeylet)); + BEAST_EXPECT(ac.view().dirRemove(ownerDirKeylet, ammSle->at(sfOwnerNode), ammKey, false)); + BEAST_EXPECT(!ac.view().exists(ownerDirKeylet) || ac.view().emptyDirDelete(ownerDirKeylet)); // Clear the balance so the "account deletion left behind a // non-zero balance" check doesn't trip earlier than the desired @@ -426,8 +432,7 @@ class Invariants_test : public beast::unit_test::suite using namespace test::jtx; testcase << "ledger entry types don't match"; doInvariantCheck( - {{"ledger entry type mismatch"}, - {"XRP net change of -1000000000 doesn't match fee 0"}}, + {{"ledger entry type mismatch"}, {"XRP net change of -1000000000 doesn't match fee 0"}}, [](Account const& A1, Account const&, ApplyContext& ac) { // replace an entry in the table with an SLE of a different type auto const sle = ac.view().peek(keylet::account(A1.id())); @@ -439,8 +444,7 @@ class Invariants_test : public beast::unit_test::suite }); doInvariantCheck( - {{"invalid ledger entry type added"}}, - [](Account const& A1, Account const&, ApplyContext& ac) { + {{"invalid ledger entry type added"}}, [](Account const& A1, Account const&, ApplyContext& ac) { // add an entry in the table with an SLE of an invalid type auto const sle = ac.view().peek(keylet::account(A1.id())); if (!sle) @@ -449,8 +453,7 @@ class Invariants_test : public beast::unit_test::suite // make a dummy escrow ledger entry, then change the type to an // unsupported value so that the valid type invariant check // will fail. - auto const sleNew = std::make_shared( - keylet::escrow(A1, (*sle)[sfSequence] + 2)); + auto const sleNew = std::make_shared(keylet::escrow(A1, (*sle)[sfSequence] + 2)); // We don't use ltNICKNAME directly since it's marked deprecated // to prevent accidental use elsewhere. @@ -466,11 +469,9 @@ class Invariants_test : public beast::unit_test::suite using namespace test::jtx; testcase << "trust lines with XRP not allowed"; doInvariantCheck( - {{"an XRP trust line was created"}}, - [](Account const& A1, Account const& A2, ApplyContext& ac) { + {{"an XRP trust line was created"}}, [](Account const& A1, Account const& A2, ApplyContext& ac) { // create simple trust SLE with xrp currency - auto const sleNew = std::make_shared( - keylet::line(A1, A2, xrpIssue().currency)); + auto const sleNew = std::make_shared(keylet::line(A1, A2, xrpIssue().currency)); ac.view().insert(sleNew); return true; }); @@ -486,8 +487,7 @@ class Invariants_test : public beast::unit_test::suite {{"a trust line with deep freeze flag without normal freeze was " "created"}}, [](Account const& A1, Account const& A2, ApplyContext& ac) { - auto const sleNew = std::make_shared( - keylet::line(A1, A2, A1["USD"].currency)); + auto const sleNew = std::make_shared(keylet::line(A1, A2, A1["USD"].currency)); sleNew->setFieldAmount(sfLowLimit, A1["USD"](0)); sleNew->setFieldAmount(sfHighLimit, A1["USD"](0)); @@ -502,8 +502,7 @@ class Invariants_test : public beast::unit_test::suite {{"a trust line with deep freeze flag without normal freeze was " "created"}}, [](Account const& A1, Account const& A2, ApplyContext& ac) { - auto const sleNew = std::make_shared( - keylet::line(A1, A2, A1["USD"].currency)); + auto const sleNew = std::make_shared(keylet::line(A1, A2, A1["USD"].currency)); sleNew->setFieldAmount(sfLowLimit, A1["USD"](0)); sleNew->setFieldAmount(sfHighLimit, A1["USD"](0)); std::uint32_t uFlags = 0u; @@ -517,8 +516,7 @@ class Invariants_test : public beast::unit_test::suite {{"a trust line with deep freeze flag without normal freeze was " "created"}}, [](Account const& A1, Account const& A2, ApplyContext& ac) { - auto const sleNew = std::make_shared( - keylet::line(A1, A2, A1["USD"].currency)); + auto const sleNew = std::make_shared(keylet::line(A1, A2, A1["USD"].currency)); sleNew->setFieldAmount(sfLowLimit, A1["USD"](0)); sleNew->setFieldAmount(sfHighLimit, A1["USD"](0)); std::uint32_t uFlags = 0u; @@ -532,8 +530,7 @@ class Invariants_test : public beast::unit_test::suite {{"a trust line with deep freeze flag without normal freeze was " "created"}}, [](Account const& A1, Account const& A2, ApplyContext& ac) { - auto const sleNew = std::make_shared( - keylet::line(A1, A2, A1["USD"].currency)); + auto const sleNew = std::make_shared(keylet::line(A1, A2, A1["USD"].currency)); sleNew->setFieldAmount(sfLowLimit, A1["USD"](0)); sleNew->setFieldAmount(sfHighLimit, A1["USD"](0)); std::uint32_t uFlags = 0u; @@ -547,8 +544,7 @@ class Invariants_test : public beast::unit_test::suite {{"a trust line with deep freeze flag without normal freeze was " "created"}}, [](Account const& A1, Account const& A2, ApplyContext& ac) { - auto const sleNew = std::make_shared( - keylet::line(A1, A2, A1["USD"].currency)); + auto const sleNew = std::make_shared(keylet::line(A1, A2, A1["USD"].currency)); sleNew->setFieldAmount(sfLowLimit, A1["USD"](0)); sleNew->setFieldAmount(sfHighLimit, A1["USD"](0)); std::uint32_t uFlags = 0u; @@ -567,55 +563,49 @@ class Invariants_test : public beast::unit_test::suite Account G1{"G1"}; // Helper function to establish the trustlines - auto const createTrustlines = - [&](Account const& A1, Account const& A2, Env& env) { - // Preclose callback to establish trust lines with gateway - env.fund(XRP(1000), G1); + auto const createTrustlines = [&](Account const& A1, Account const& A2, Env& env) { + // Preclose callback to establish trust lines with gateway + env.fund(XRP(1000), G1); - env.trust(G1["USD"](10000), A1); - env.trust(G1["USD"](10000), A2); - env.close(); + env.trust(G1["USD"](10000), A1); + env.trust(G1["USD"](10000), A2); + env.close(); - env(pay(G1, A1, G1["USD"](1000))); - env(pay(G1, A2, G1["USD"](1000))); - env.close(); + env(pay(G1, A1, G1["USD"](1000))); + env(pay(G1, A2, G1["USD"](1000))); + env.close(); - return true; - }; - - auto const A1FrozenByIssuer = - [&](Account const& A1, Account const& A2, Env& env) { - createTrustlines(A1, A2, env); - env(trust(G1, A1["USD"](10000), tfSetFreeze)); - env.close(); - - return true; - }; - - auto const A1DeepFrozenByIssuer = - [&](Account const& A1, Account const& A2, Env& env) { - A1FrozenByIssuer(A1, A2, env); - env(trust(G1, A1["USD"](10000), tfSetDeepFreeze)); - env.close(); - - return true; - }; - - auto const changeBalances = [&](Account const& A1, - Account const& A2, - ApplyContext& ac, - int A1Balance, - int A2Balance) { - auto const sleA1 = ac.view().peek(keylet::line(A1, G1["USD"])); - auto const sleA2 = ac.view().peek(keylet::line(A2, G1["USD"])); - - sleA1->setFieldAmount(sfBalance, G1["USD"](A1Balance)); - sleA2->setFieldAmount(sfBalance, G1["USD"](A2Balance)); - - ac.view().update(sleA1); - ac.view().update(sleA2); + return true; }; + auto const A1FrozenByIssuer = [&](Account const& A1, Account const& A2, Env& env) { + createTrustlines(A1, A2, env); + env(trust(G1, A1["USD"](10000), tfSetFreeze)); + env.close(); + + return true; + }; + + auto const A1DeepFrozenByIssuer = [&](Account const& A1, Account const& A2, Env& env) { + A1FrozenByIssuer(A1, A2, env); + env(trust(G1, A1["USD"](10000), tfSetDeepFreeze)); + env.close(); + + return true; + }; + + auto const changeBalances = + [&](Account const& A1, Account const& A2, ApplyContext& ac, int A1Balance, int A2Balance) { + auto const sleA1 = ac.view().peek(keylet::line(A1, G1["USD"])); + auto const sleA2 = ac.view().peek(keylet::line(A2, G1["USD"])); + + sleA1->setFieldAmount(sfBalance, G1["USD"](A1Balance)); + sleA2->setFieldAmount(sfBalance, G1["USD"](A2Balance)); + + ac.view().update(sleA1); + ac.view().update(sleA2); + }; + // test: imitating frozen A1 making a payment to A2. doInvariantCheck( {{"Attempting to move frozen funds"}}, @@ -673,8 +663,7 @@ class Invariants_test : public beast::unit_test::suite }); doInvariantCheck( - {{"incorrect account XRP balance"}, - {"XRP net change was positive: 99999999000000001"}}, + {{"incorrect account XRP balance"}, {"XRP net change was positive: 99999999000000001"}}, [this](Account const& A1, Account const&, ApplyContext& ac) { // balance exceeds genesis amount auto const sle = ac.view().peek(keylet::account(A1.id())); @@ -689,8 +678,7 @@ class Invariants_test : public beast::unit_test::suite }); doInvariantCheck( - {{"incorrect account XRP balance"}, - {"XRP net change of -1000000001 doesn't match fee 0"}}, + {{"incorrect account XRP balance"}, {"XRP net change of -1000000001 doesn't match fee 0"}}, [this](Account const& A1, Account const&, ApplyContext& ac) { // balance is negative auto const sle = ac.view().peek(keylet::account(A1.id())); @@ -711,26 +699,21 @@ class Invariants_test : public beast::unit_test::suite testcase << "Transaction fee checks"; doInvariantCheck( - {{"fee paid was negative: -1"}, - {"XRP net change of 0 doesn't match fee -1"}}, + {{"fee paid was negative: -1"}, {"XRP net change of 0 doesn't match fee -1"}}, [](Account const&, Account const&, ApplyContext&) { return true; }, XRPAmount{-1}); doInvariantCheck( {{"fee paid exceeds system limit: "s + to_string(INITIAL_XRP)}, - {"XRP net change of 0 doesn't match fee "s + - to_string(INITIAL_XRP)}}, + {"XRP net change of 0 doesn't match fee "s + to_string(INITIAL_XRP)}}, [](Account const&, Account const&, ApplyContext&) { return true; }, XRPAmount{INITIAL_XRP}); doInvariantCheck( - {{"fee paid is 20 exceeds fee specified in transaction."}, - {"XRP net change of 0 doesn't match fee 20"}}, + {{"fee paid is 20 exceeds fee specified in transaction."}, {"XRP net change of 0 doesn't match fee 20"}}, [](Account const&, Account const&, ApplyContext&) { return true; }, XRPAmount{20}, - STTx{ttACCOUNT_SET, [](STObject& tx) { - tx.setFieldAmount(sfFee, XRPAmount{10}); - }}); + STTx{ttACCOUNT_SET, [](STObject& tx) { tx.setFieldAmount(sfFee, XRPAmount{10}); }}); } void @@ -739,55 +722,46 @@ class Invariants_test : public beast::unit_test::suite using namespace test::jtx; testcase << "no bad offers"; - doInvariantCheck( - {{"offer with a bad amount"}}, - [](Account const& A1, Account const&, ApplyContext& ac) { - // offer with negative takerpays - auto const sle = ac.view().peek(keylet::account(A1.id())); - if (!sle) - return false; - auto sleNew = std::make_shared( - keylet::offer(A1.id(), (*sle)[sfSequence])); - sleNew->setAccountID(sfAccount, A1.id()); - sleNew->setFieldU32(sfSequence, (*sle)[sfSequence]); - sleNew->setFieldAmount(sfTakerPays, XRP(-1)); - ac.view().insert(sleNew); - return true; - }); + doInvariantCheck({{"offer with a bad amount"}}, [](Account const& A1, Account const&, ApplyContext& ac) { + // offer with negative takerpays + auto const sle = ac.view().peek(keylet::account(A1.id())); + if (!sle) + return false; + auto sleNew = std::make_shared(keylet::offer(A1.id(), (*sle)[sfSequence])); + sleNew->setAccountID(sfAccount, A1.id()); + sleNew->setFieldU32(sfSequence, (*sle)[sfSequence]); + sleNew->setFieldAmount(sfTakerPays, XRP(-1)); + ac.view().insert(sleNew); + return true; + }); - doInvariantCheck( - {{"offer with a bad amount"}}, - [](Account const& A1, Account const&, ApplyContext& ac) { - // offer with negative takergets - auto const sle = ac.view().peek(keylet::account(A1.id())); - if (!sle) - return false; - auto sleNew = std::make_shared( - keylet::offer(A1.id(), (*sle)[sfSequence])); - sleNew->setAccountID(sfAccount, A1.id()); - sleNew->setFieldU32(sfSequence, (*sle)[sfSequence]); - sleNew->setFieldAmount(sfTakerPays, A1["USD"](10)); - sleNew->setFieldAmount(sfTakerGets, XRP(-1)); - ac.view().insert(sleNew); - return true; - }); + doInvariantCheck({{"offer with a bad amount"}}, [](Account const& A1, Account const&, ApplyContext& ac) { + // offer with negative takergets + auto const sle = ac.view().peek(keylet::account(A1.id())); + if (!sle) + return false; + auto sleNew = std::make_shared(keylet::offer(A1.id(), (*sle)[sfSequence])); + sleNew->setAccountID(sfAccount, A1.id()); + sleNew->setFieldU32(sfSequence, (*sle)[sfSequence]); + sleNew->setFieldAmount(sfTakerPays, A1["USD"](10)); + sleNew->setFieldAmount(sfTakerGets, XRP(-1)); + ac.view().insert(sleNew); + return true; + }); - doInvariantCheck( - {{"offer with a bad amount"}}, - [](Account const& A1, Account const&, ApplyContext& ac) { - // offer XRP to XRP - auto const sle = ac.view().peek(keylet::account(A1.id())); - if (!sle) - return false; - auto sleNew = std::make_shared( - keylet::offer(A1.id(), (*sle)[sfSequence])); - sleNew->setAccountID(sfAccount, A1.id()); - sleNew->setFieldU32(sfSequence, (*sle)[sfSequence]); - sleNew->setFieldAmount(sfTakerPays, XRP(10)); - sleNew->setFieldAmount(sfTakerGets, XRP(11)); - ac.view().insert(sleNew); - return true; - }); + doInvariantCheck({{"offer with a bad amount"}}, [](Account const& A1, Account const&, ApplyContext& ac) { + // offer XRP to XRP + auto const sle = ac.view().peek(keylet::account(A1.id())); + if (!sle) + return false; + auto sleNew = std::make_shared(keylet::offer(A1.id(), (*sle)[sfSequence])); + sleNew->setAccountID(sfAccount, A1.id()); + sleNew->setFieldU32(sfSequence, (*sle)[sfSequence]); + sleNew->setFieldAmount(sfTakerPays, XRP(10)); + sleNew->setFieldAmount(sfTakerGets, XRP(11)); + ac.view().insert(sleNew); + return true; + }); } void @@ -797,30 +771,26 @@ class Invariants_test : public beast::unit_test::suite testcase << "no zero escrow"; doInvariantCheck( - {{"XRP net change of -1000000 doesn't match fee 0"}, - {"escrow specifies invalid amount"}}, + {{"XRP net change of -1000000 doesn't match fee 0"}, {"escrow specifies invalid amount"}}, [](Account const& A1, Account const&, ApplyContext& ac) { // escrow with negative amount auto const sle = ac.view().peek(keylet::account(A1.id())); if (!sle) return false; - auto sleNew = std::make_shared( - keylet::escrow(A1, (*sle)[sfSequence] + 2)); + auto sleNew = std::make_shared(keylet::escrow(A1, (*sle)[sfSequence] + 2)); sleNew->setFieldAmount(sfAmount, XRP(-1)); ac.view().insert(sleNew); return true; }); doInvariantCheck( - {{"XRP net change was positive: 100000000000000001"}, - {"escrow specifies invalid amount"}}, + {{"XRP net change was positive: 100000000000000001"}, {"escrow specifies invalid amount"}}, [](Account const& A1, Account const&, ApplyContext& ac) { // escrow with too-large amount auto const sle = ac.view().peek(keylet::account(A1.id())); if (!sle) return false; - auto sleNew = std::make_shared( - keylet::escrow(A1, (*sle)[sfSequence] + 2)); + auto sleNew = std::make_shared(keylet::escrow(A1, (*sle)[sfSequence] + 2)); // Use `drops(1)` to bypass a call to STAmount::canonicalize // with an invalid value sleNew->setFieldAmount(sfAmount, INITIAL_XRP + drops(1)); @@ -830,17 +800,14 @@ class Invariants_test : public beast::unit_test::suite // IOU < 0 doInvariantCheck( - {{"escrow specifies invalid amount"}}, - [](Account const& A1, Account const&, ApplyContext& ac) { + {{"escrow specifies invalid amount"}}, [](Account const& A1, Account const&, ApplyContext& ac) { // escrow with too-little iou auto const sle = ac.view().peek(keylet::account(A1.id())); if (!sle) return false; - auto sleNew = std::make_shared( - keylet::escrow(A1, (*sle)[sfSequence] + 2)); + auto sleNew = std::make_shared(keylet::escrow(A1, (*sle)[sfSequence] + 2)); - Issue const usd{ - Currency(0x5553440000000000), AccountID(0x4985601)}; + Issue const usd{Currency(0x5553440000000000), AccountID(0x4985601)}; STAmount amt(usd, -1); sleNew->setFieldAmount(sfAmount, amt); ac.view().insert(sleNew); @@ -849,14 +816,12 @@ class Invariants_test : public beast::unit_test::suite // IOU bad currency doInvariantCheck( - {{"escrow specifies invalid amount"}}, - [](Account const& A1, Account const&, ApplyContext& ac) { + {{"escrow specifies invalid amount"}}, [](Account const& A1, Account const&, ApplyContext& ac) { // escrow with bad iou currency auto const sle = ac.view().peek(keylet::account(A1.id())); if (!sle) return false; - auto sleNew = std::make_shared( - keylet::escrow(A1, (*sle)[sfSequence] + 2)); + auto sleNew = std::make_shared(keylet::escrow(A1, (*sle)[sfSequence] + 2)); Issue const bad{badCurrency(), AccountID(0x4985601)}; STAmount amt(bad, 1); @@ -867,17 +832,14 @@ class Invariants_test : public beast::unit_test::suite // MPT < 0 doInvariantCheck( - {{"escrow specifies invalid amount"}}, - [](Account const& A1, Account const&, ApplyContext& ac) { + {{"escrow specifies invalid amount"}}, [](Account const& A1, Account const&, ApplyContext& ac) { // escrow with too-little mpt auto const sle = ac.view().peek(keylet::account(A1.id())); if (!sle) return false; - auto sleNew = std::make_shared( - keylet::escrow(A1, (*sle)[sfSequence] + 2)); + auto sleNew = std::make_shared(keylet::escrow(A1, (*sle)[sfSequence] + 2)); - MPTIssue const mpt{ - MPTIssue{makeMptID(1, AccountID(0x4985601))}}; + MPTIssue const mpt{MPTIssue{makeMptID(1, AccountID(0x4985601))}}; STAmount amt(mpt, -1); sleNew->setFieldAmount(sfAmount, amt); ac.view().insert(sleNew); @@ -886,17 +848,14 @@ class Invariants_test : public beast::unit_test::suite // MPT OutstandingAmount < 0 doInvariantCheck( - {{"escrow specifies invalid amount"}}, - [](Account const& A1, Account const&, ApplyContext& ac) { + {{"escrow specifies invalid amount"}}, [](Account const& A1, Account const&, ApplyContext& ac) { // mptissuance outstanding is negative auto const sle = ac.view().peek(keylet::account(A1.id())); if (!sle) return false; - MPTIssue const mpt{ - MPTIssue{makeMptID(1, AccountID(0x4985601))}}; - auto sleNew = - std::make_shared(keylet::mptIssuance(mpt.getMptID())); + MPTIssue const mpt{MPTIssue{makeMptID(1, AccountID(0x4985601))}}; + auto sleNew = std::make_shared(keylet::mptIssuance(mpt.getMptID())); sleNew->setFieldU64(sfOutstandingAmount, -1); ac.view().insert(sleNew); return true; @@ -904,17 +863,14 @@ class Invariants_test : public beast::unit_test::suite // MPT LockedAmount < 0 doInvariantCheck( - {{"escrow specifies invalid amount"}}, - [](Account const& A1, Account const&, ApplyContext& ac) { + {{"escrow specifies invalid amount"}}, [](Account const& A1, Account const&, ApplyContext& ac) { // mptissuance locked is less than locked auto const sle = ac.view().peek(keylet::account(A1.id())); if (!sle) return false; - MPTIssue const mpt{ - MPTIssue{makeMptID(1, AccountID(0x4985601))}}; - auto sleNew = - std::make_shared(keylet::mptIssuance(mpt.getMptID())); + MPTIssue const mpt{MPTIssue{makeMptID(1, AccountID(0x4985601))}}; + auto sleNew = std::make_shared(keylet::mptIssuance(mpt.getMptID())); sleNew->setFieldU64(sfLockedAmount, -1); ac.view().insert(sleNew); return true; @@ -922,17 +878,14 @@ class Invariants_test : public beast::unit_test::suite // MPT OutstandingAmount < LockedAmount doInvariantCheck( - {{"escrow specifies invalid amount"}}, - [](Account const& A1, Account const&, ApplyContext& ac) { + {{"escrow specifies invalid amount"}}, [](Account const& A1, Account const&, ApplyContext& ac) { // mptissuance outstanding is less than locked auto const sle = ac.view().peek(keylet::account(A1.id())); if (!sle) return false; - MPTIssue const mpt{ - MPTIssue{makeMptID(1, AccountID(0x4985601))}}; - auto sleNew = - std::make_shared(keylet::mptIssuance(mpt.getMptID())); + MPTIssue const mpt{MPTIssue{makeMptID(1, AccountID(0x4985601))}}; + auto sleNew = std::make_shared(keylet::mptIssuance(mpt.getMptID())); sleNew->setFieldU64(sfOutstandingAmount, 1); sleNew->setFieldU64(sfLockedAmount, 10); ac.view().insert(sleNew); @@ -941,17 +894,14 @@ class Invariants_test : public beast::unit_test::suite // MPT MPTAmount < 0 doInvariantCheck( - {{"escrow specifies invalid amount"}}, - [](Account const& A1, Account const&, ApplyContext& ac) { + {{"escrow specifies invalid amount"}}, [](Account const& A1, Account const&, ApplyContext& ac) { // mptoken amount is negative auto const sle = ac.view().peek(keylet::account(A1.id())); if (!sle) return false; - MPTIssue const mpt{ - MPTIssue{makeMptID(1, AccountID(0x4985601))}}; - auto sleNew = - std::make_shared(keylet::mptoken(mpt.getMptID(), A1)); + MPTIssue const mpt{MPTIssue{makeMptID(1, AccountID(0x4985601))}}; + auto sleNew = std::make_shared(keylet::mptoken(mpt.getMptID(), A1)); sleNew->setFieldU64(sfMPTAmount, -1); ac.view().insert(sleNew); return true; @@ -959,17 +909,14 @@ class Invariants_test : public beast::unit_test::suite // MPT LockedAmount < 0 doInvariantCheck( - {{"escrow specifies invalid amount"}}, - [](Account const& A1, Account const&, ApplyContext& ac) { + {{"escrow specifies invalid amount"}}, [](Account const& A1, Account const&, ApplyContext& ac) { // mptoken locked amount is negative auto const sle = ac.view().peek(keylet::account(A1.id())); if (!sle) return false; - MPTIssue const mpt{ - MPTIssue{makeMptID(1, AccountID(0x4985601))}}; - auto sleNew = - std::make_shared(keylet::mptoken(mpt.getMptID(), A1)); + MPTIssue const mpt{MPTIssue{makeMptID(1, AccountID(0x4985601))}}; + auto sleNew = std::make_shared(keylet::mptoken(mpt.getMptID(), A1)); sleNew->setFieldU64(sfLockedAmount, -1); ac.view().insert(sleNew); return true; @@ -982,17 +929,15 @@ class Invariants_test : public beast::unit_test::suite using namespace test::jtx; testcase << "valid new account root"; - doInvariantCheck( - {{"account root created illegally"}}, - [](Account const&, Account const&, ApplyContext& ac) { - // Insert a new account root created by a non-payment into - // the view. - Account const A3{"A3"}; - Keylet const acctKeylet = keylet::account(A3); - auto const sleNew = std::make_shared(acctKeylet); - ac.view().insert(sleNew); - return true; - }); + doInvariantCheck({{"account root created illegally"}}, [](Account const&, Account const&, ApplyContext& ac) { + // Insert a new account root created by a non-payment into + // the view. + Account const A3{"A3"}; + Keylet const acctKeylet = keylet::account(A3); + auto const sleNew = std::make_shared(acctKeylet); + ac.view().insert(sleNew); + return true; + }); doInvariantCheck( {{"multiple accounts created in a single transaction"}}, @@ -1035,9 +980,7 @@ class Invariants_test : public beast::unit_test::suite auto const sleNew = std::make_shared(acctKeylet); sleNew->setFieldU32(sfSequence, 0); sleNew->setFieldH256(sfAMMID, uint256(1)); - sleNew->setFieldU32( - sfFlags, - lsfDisableMaster | lsfDefaultRipple | lsfDefaultRipple); + sleNew->setFieldU32(sfFlags, lsfDisableMaster | lsfDefaultRipple | lsfDefaultRipple); ac.view().insert(sleNew); return true; }, @@ -1052,9 +995,7 @@ class Invariants_test : public beast::unit_test::suite auto const sleNew = std::make_shared(acctKeylet); sleNew->setFieldU32(sfSequence, ac.view().seq()); sleNew->setFieldH256(sfAMMID, uint256(1)); - sleNew->setFieldU32( - sfFlags, - lsfDisableMaster | lsfDefaultRipple | lsfDepositAuth); + sleNew->setFieldU32(sfFlags, lsfDisableMaster | lsfDefaultRipple | lsfDepositAuth); ac.view().insert(sleNew); return true; }, @@ -1069,8 +1010,7 @@ class Invariants_test : public beast::unit_test::suite auto const sleNew = std::make_shared(acctKeylet); sleNew->setFieldU32(sfSequence, 0); sleNew->setFieldH256(sfAMMID, uint256(1)); - sleNew->setFieldU32( - sfFlags, lsfDisableMaster | lsfDefaultRipple); + sleNew->setFieldU32(sfFlags, lsfDisableMaster | lsfDefaultRipple); ac.view().insert(sleNew); return true; }, @@ -1085,10 +1025,7 @@ class Invariants_test : public beast::unit_test::suite auto const sleNew = std::make_shared(acctKeylet); sleNew->setFieldU32(sfSequence, 0); sleNew->setFieldH256(sfAMMID, uint256(1)); - sleNew->setFieldU32( - sfFlags, - lsfDisableMaster | lsfDefaultRipple | lsfDepositAuth | - lsfRequireDestTag); + sleNew->setFieldU32(sfFlags, lsfDisableMaster | lsfDefaultRipple | lsfDepositAuth | lsfRequireDestTag); ac.view().insert(sleNew); return true; }, @@ -1103,21 +1040,17 @@ class Invariants_test : public beast::unit_test::suite testcase << "NFTokenPage"; // lambda that returns an STArray of NFTokenIDs. - uint256 const firstNFTID( - "0000000000000000000000000000000000000001FFFFFFFFFFFFFFFF00000000"); + uint256 const firstNFTID("0000000000000000000000000000000000000001FFFFFFFFFFFFFFFF00000000"); auto makeNFTokenIDs = [&firstNFTID](unsigned int nftCount) { - SOTemplate const* nfTokenTemplate = - InnerObjectFormats::getInstance().findSOTemplateBySField( - sfNFToken); + SOTemplate const* nfTokenTemplate = InnerObjectFormats::getInstance().findSOTemplateBySField(sfNFToken); uint256 nftID(firstNFTID); STArray ret; for (int i = 0; i < nftCount; ++i) { - STObject newNFToken( - *nfTokenTemplate, sfNFToken, [&nftID](STObject& object) { - object.setFieldH256(sfNFTokenID, nftID); - }); + STObject newNFToken(*nfTokenTemplate, sfNFToken, [&nftID](STObject& object) { + object.setFieldH256(sfNFTokenID, nftID); + }); ret.push_back(std::move(newNFToken)); ++nftID; } @@ -1125,9 +1058,7 @@ class Invariants_test : public beast::unit_test::suite }; doInvariantCheck( - {{"NFT page has invalid size"}}, - [&makeNFTokenIDs]( - Account const& A1, Account const&, ApplyContext& ac) { + {{"NFT page has invalid size"}}, [&makeNFTokenIDs](Account const& A1, Account const&, ApplyContext& ac) { auto nftPage = std::make_shared(keylet::nftpage_max(A1)); nftPage->setFieldArray(sfNFTokens, makeNFTokenIDs(0)); @@ -1136,9 +1067,7 @@ class Invariants_test : public beast::unit_test::suite }); doInvariantCheck( - {{"NFT page has invalid size"}}, - [&makeNFTokenIDs]( - Account const& A1, Account const&, ApplyContext& ac) { + {{"NFT page has invalid size"}}, [&makeNFTokenIDs](Account const& A1, Account const&, ApplyContext& ac) { auto nftPage = std::make_shared(keylet::nftpage_max(A1)); nftPage->setFieldArray(sfNFTokens, makeNFTokenIDs(33)); @@ -1147,9 +1076,7 @@ class Invariants_test : public beast::unit_test::suite }); doInvariantCheck( - {{"NFTs on page are not sorted"}}, - [&makeNFTokenIDs]( - Account const& A1, Account const&, ApplyContext& ac) { + {{"NFTs on page are not sorted"}}, [&makeNFTokenIDs](Account const& A1, Account const&, ApplyContext& ac) { STArray nfTokens = makeNFTokenIDs(2); std::iter_swap(nfTokens.begin(), nfTokens.begin() + 1); @@ -1161,9 +1088,7 @@ class Invariants_test : public beast::unit_test::suite }); doInvariantCheck( - {{"NFT contains empty URI"}}, - [&makeNFTokenIDs]( - Account const& A1, Account const&, ApplyContext& ac) { + {{"NFT contains empty URI"}}, [&makeNFTokenIDs](Account const& A1, Account const&, ApplyContext& ac) { STArray nfTokens = makeNFTokenIDs(1); nfTokens[0].setFieldVL(sfURI, Blob{}); @@ -1176,12 +1101,10 @@ class Invariants_test : public beast::unit_test::suite doInvariantCheck( {{"NFT page is improperly linked"}}, - [&makeNFTokenIDs]( - Account const& A1, Account const&, ApplyContext& ac) { + [&makeNFTokenIDs](Account const& A1, Account const&, ApplyContext& ac) { auto nftPage = std::make_shared(keylet::nftpage_max(A1)); nftPage->setFieldArray(sfNFTokens, makeNFTokenIDs(1)); - nftPage->setFieldH256( - sfPreviousPageMin, keylet::nftpage_max(A1).key); + nftPage->setFieldH256(sfPreviousPageMin, keylet::nftpage_max(A1).key); ac.view().insert(nftPage); return true; @@ -1189,12 +1112,10 @@ class Invariants_test : public beast::unit_test::suite doInvariantCheck( {{"NFT page is improperly linked"}}, - [&makeNFTokenIDs]( - Account const& A1, Account const& A2, ApplyContext& ac) { + [&makeNFTokenIDs](Account const& A1, Account const& A2, ApplyContext& ac) { auto nftPage = std::make_shared(keylet::nftpage_max(A1)); nftPage->setFieldArray(sfNFTokens, makeNFTokenIDs(1)); - nftPage->setFieldH256( - sfPreviousPageMin, keylet::nftpage_min(A2).key); + nftPage->setFieldH256(sfPreviousPageMin, keylet::nftpage_min(A2).key); ac.view().insert(nftPage); return true; @@ -1202,8 +1123,7 @@ class Invariants_test : public beast::unit_test::suite doInvariantCheck( {{"NFT page is improperly linked"}}, - [&makeNFTokenIDs]( - Account const& A1, Account const&, ApplyContext& ac) { + [&makeNFTokenIDs](Account const& A1, Account const&, ApplyContext& ac) { auto nftPage = std::make_shared(keylet::nftpage_max(A1)); nftPage->setFieldArray(sfNFTokens, makeNFTokenIDs(1)); nftPage->setFieldH256(sfNextPageMin, nftPage->key()); @@ -1214,28 +1134,22 @@ class Invariants_test : public beast::unit_test::suite doInvariantCheck( {{"NFT page is improperly linked"}}, - [&makeNFTokenIDs]( - Account const& A1, Account const& A2, ApplyContext& ac) { + [&makeNFTokenIDs](Account const& A1, Account const& A2, ApplyContext& ac) { STArray nfTokens = makeNFTokenIDs(1); - auto nftPage = std::make_shared(keylet::nftpage( - keylet::nftpage_max(A1), - ++(nfTokens[0].getFieldH256(sfNFTokenID)))); + auto nftPage = std::make_shared( + keylet::nftpage(keylet::nftpage_max(A1), ++(nfTokens[0].getFieldH256(sfNFTokenID)))); nftPage->setFieldArray(sfNFTokens, std::move(nfTokens)); - nftPage->setFieldH256( - sfNextPageMin, keylet::nftpage_max(A2).key); + nftPage->setFieldH256(sfNextPageMin, keylet::nftpage_max(A2).key); ac.view().insert(nftPage); return true; }); doInvariantCheck( - {{"NFT found in incorrect page"}}, - [&makeNFTokenIDs]( - Account const& A1, Account const&, ApplyContext& ac) { + {{"NFT found in incorrect page"}}, [&makeNFTokenIDs](Account const& A1, Account const&, ApplyContext& ac) { STArray nfTokens = makeNFTokenIDs(2); - auto nftPage = std::make_shared(keylet::nftpage( - keylet::nftpage_max(A1), - (nfTokens[1].getFieldH256(sfNFTokenID)))); + auto nftPage = std::make_shared( + keylet::nftpage(keylet::nftpage_max(A1), (nfTokens[1].getFieldH256(sfNFTokenID)))); nftPage->setFieldArray(sfNFTokens, std::move(nfTokens)); ac.view().insert(nftPage); @@ -1243,120 +1157,104 @@ class Invariants_test : public beast::unit_test::suite }); } - void + static std::shared_ptr createPermissionedDomain( ApplyContext& ac, - std::shared_ptr& sle, test::jtx::Account const& A1, - test::jtx::Account const& A2) + test::jtx::Account const& A2, + std::uint32_t numCreds = 2, + std::uint32_t seq = 10) { - sle->setAccountID(sfOwner, A1); - sle->setFieldU32(sfSequence, 10); + Keylet const pdKeylet = keylet::permissionedDomain(A1.id(), seq); + auto sle = std::make_shared(pdKeylet); - STArray credentials(sfAcceptedCredentials, 2); - for (std::size_t n = 0; n < 2; ++n) + sle->setAccountID(sfOwner, A1); + sle->setFieldU32(sfSequence, seq); + + if (numCreds) { - auto cred = STObject::makeInnerObject(sfCredential); - cred.setAccountID(sfIssuer, A2); - auto credType = "cred_type" + std::to_string(n); - cred.setFieldVL( - sfCredentialType, Slice(credType.c_str(), credType.size())); - credentials.push_back(std::move(cred)); + // This array is sorted naturally, but if you willing to change this + // behavior don't forget to use credentials::makeSorted + STArray credentials(sfAcceptedCredentials, numCreds); + for (std::size_t n = 0; n < numCreds; ++n) + { + auto cred = STObject::makeInnerObject(sfCredential); + cred.setAccountID(sfIssuer, A2); + auto credType = "cred_type" + std::to_string(n); + cred.setFieldVL(sfCredentialType, Slice(credType.c_str(), credType.size())); + credentials.push_back(std::move(cred)); + } + sle->setFieldArray(sfAcceptedCredentials, credentials); } - sle->setFieldArray(sfAcceptedCredentials, credentials); + ac.view().insert(sle); + return sle; }; void - testPermissionedDomainInvariants() + testPermissionedDomainInvariants(FeatureBitset features) { using namespace test::jtx; - testcase << "PermissionedDomain"; - doInvariantCheck( - {{"permissioned domain with no rules."}}, - [](Account const& A1, Account const&, ApplyContext& ac) { - Keylet const pdKeylet = keylet::permissionedDomain(A1.id(), 10); - auto slePd = std::make_shared(pdKeylet); - slePd->setAccountID(sfOwner, A1); - slePd->setFieldU32(sfSequence, 10); + bool const fixPDEnabled = features[fixPermissionedDomainInvariant]; + std::initializer_list badTers = {tecINVARIANT_FAILED, tecINVARIANT_FAILED}; + std::initializer_list failTers = {tecINVARIANT_FAILED, tefINVARIANT_FAILED}; - ac.view().insert(slePd); - return true; + testcase << "PermissionedDomain" + std::string(fixPDEnabled ? " fix" : ""); + + doInvariantCheck( + Env(*this, features), + {{"permissioned domain with no rules."}}, + [](Account const& A1, Account const& A2, ApplyContext& ac) { + return createPermissionedDomain(ac, A1, A2, 0).get(); }, XRPAmount{}, - STTx{ttPERMISSIONED_DOMAIN_SET, [](STObject& tx) {}}, - {tecINVARIANT_FAILED, tecINVARIANT_FAILED}); + STTx{ttPERMISSIONED_DOMAIN_SET, [](STObject&) {}}, + fixPDEnabled ? failTers : badTers); testcase << "PermissionedDomain 2"; auto constexpr tooBig = maxPermissionedDomainCredentialsArraySize + 1; doInvariantCheck( - {{"permissioned domain bad credentials size " + - std::to_string(tooBig)}}, + Env(*this, features), + {{"permissioned domain bad credentials size " + std::to_string(tooBig)}}, [](Account const& A1, Account const& A2, ApplyContext& ac) { - Keylet const pdKeylet = keylet::permissionedDomain(A1.id(), 10); - auto slePd = std::make_shared(pdKeylet); - slePd->setAccountID(sfOwner, A1); - slePd->setFieldU32(sfSequence, 10); - - STArray credentials(sfAcceptedCredentials, tooBig); - for (std::size_t n = 0; n < tooBig; ++n) - { - auto cred = STObject::makeInnerObject(sfCredential); - cred.setAccountID(sfIssuer, A2); - auto credType = - std::string("cred_type") + std::to_string(n); - cred.setFieldVL( - sfCredentialType, - Slice(credType.c_str(), credType.size())); - credentials.push_back(std::move(cred)); - } - slePd->setFieldArray(sfAcceptedCredentials, credentials); - ac.view().insert(slePd); - return true; + return !!createPermissionedDomain(ac, A1, A2, tooBig); }, XRPAmount{}, STTx{ttPERMISSIONED_DOMAIN_SET, [](STObject&) {}}, - {tecINVARIANT_FAILED, tecINVARIANT_FAILED}); + fixPDEnabled ? failTers : badTers); testcase << "PermissionedDomain 3"; doInvariantCheck( + Env(*this, features), {{"permissioned domain credentials aren't sorted"}}, [](Account const& A1, Account const& A2, ApplyContext& ac) { - Keylet const pdKeylet = keylet::permissionedDomain(A1.id(), 10); - auto slePd = std::make_shared(pdKeylet); - slePd->setAccountID(sfOwner, A1); - slePd->setFieldU32(sfSequence, 10); + auto slePd = createPermissionedDomain(ac, A1, A2, 0); STArray credentials(sfAcceptedCredentials, 2); for (std::size_t n = 0; n < 2; ++n) { auto cred = STObject::makeInnerObject(sfCredential); cred.setAccountID(sfIssuer, A2); - auto credType = - std::string("cred_type") + std::to_string(9 - n); - cred.setFieldVL( - sfCredentialType, - Slice(credType.c_str(), credType.size())); + auto credType = std::string("cred_type") + std::to_string(9 - n); + cred.setFieldVL(sfCredentialType, Slice(credType.c_str(), credType.size())); credentials.push_back(std::move(cred)); } slePd->setFieldArray(sfAcceptedCredentials, credentials); - ac.view().insert(slePd); + ac.view().update(slePd); return true; }, XRPAmount{}, STTx{ttPERMISSIONED_DOMAIN_SET, [](STObject&) {}}, - {tecINVARIANT_FAILED, tecINVARIANT_FAILED}); + fixPDEnabled ? failTers : badTers); testcase << "PermissionedDomain 4"; doInvariantCheck( + Env(*this, features), {{"permissioned domain credentials aren't unique"}}, [](Account const& A1, Account const& A2, ApplyContext& ac) { - Keylet const pdKeylet = keylet::permissionedDomain(A1.id(), 10); - auto slePd = std::make_shared(pdKeylet); - slePd->setAccountID(sfOwner, A1); - slePd->setFieldU32(sfSequence, 10); + auto slePd = createPermissionedDomain(ac, A1, A2, 0); STArray credentials(sfAcceptedCredentials, 2); for (std::size_t n = 0; n < 2; ++n) @@ -1367,22 +1265,20 @@ class Invariants_test : public beast::unit_test::suite credentials.push_back(std::move(cred)); } slePd->setFieldArray(sfAcceptedCredentials, credentials); - ac.view().insert(slePd); + ac.view().update(slePd); return true; }, XRPAmount{}, - STTx{ttPERMISSIONED_DOMAIN_SET, [](STObject& tx) {}}, - {tecINVARIANT_FAILED, tecINVARIANT_FAILED}); + STTx{ttPERMISSIONED_DOMAIN_SET, [](STObject&) {}}, + fixPDEnabled ? failTers : badTers); testcase << "PermissionedDomain Set 1"; doInvariantCheck( + Env(*this, features), {{"permissioned domain with no rules."}}, [&](Account const& A1, Account const& A2, ApplyContext& ac) { - Keylet const pdKeylet = keylet::permissionedDomain(A1.id(), 10); - auto slePd = std::make_shared(pdKeylet); - // create PD - createPermissionedDomain(ac, slePd, A1, A2); + auto slePd = createPermissionedDomain(ac, A1, A2); // update PD with empty rules { @@ -1394,19 +1290,16 @@ class Invariants_test : public beast::unit_test::suite return true; }, XRPAmount{}, - STTx{ttPERMISSIONED_DOMAIN_SET, [](STObject& tx) {}}, - {tecINVARIANT_FAILED, tecINVARIANT_FAILED}); + STTx{ttPERMISSIONED_DOMAIN_SET, [](STObject&) {}}, + fixPDEnabled ? failTers : badTers); testcase << "PermissionedDomain Set 2"; doInvariantCheck( - {{"permissioned domain bad credentials size " + - std::to_string(tooBig)}}, + Env(*this, features), + {{"permissioned domain bad credentials size " + std::to_string(tooBig)}}, [&](Account const& A1, Account const& A2, ApplyContext& ac) { - Keylet const pdKeylet = keylet::permissionedDomain(A1.id(), 10); - auto slePd = std::make_shared(pdKeylet); - // create PD - createPermissionedDomain(ac, slePd, A1, A2); + auto slePd = createPermissionedDomain(ac, A1, A2); // update PD { @@ -1417,9 +1310,7 @@ class Invariants_test : public beast::unit_test::suite auto cred = STObject::makeInnerObject(sfCredential); cred.setAccountID(sfIssuer, A2); auto credType = "cred_type2" + std::to_string(n); - cred.setFieldVL( - sfCredentialType, - Slice(credType.c_str(), credType.size())); + cred.setFieldVL(sfCredentialType, Slice(credType.c_str(), credType.size())); credentials.push_back(std::move(cred)); } @@ -1430,18 +1321,16 @@ class Invariants_test : public beast::unit_test::suite return true; }, XRPAmount{}, - STTx{ttPERMISSIONED_DOMAIN_SET, [](STObject& tx) {}}, - {tecINVARIANT_FAILED, tecINVARIANT_FAILED}); + STTx{ttPERMISSIONED_DOMAIN_SET, [](STObject&) {}}, + fixPDEnabled ? failTers : badTers); testcase << "PermissionedDomain Set 3"; doInvariantCheck( + Env(*this, features), {{"permissioned domain credentials aren't sorted"}}, [&](Account const& A1, Account const& A2, ApplyContext& ac) { - Keylet const pdKeylet = keylet::permissionedDomain(A1.id(), 10); - auto slePd = std::make_shared(pdKeylet); - // create PD - createPermissionedDomain(ac, slePd, A1, A2); + auto slePd = createPermissionedDomain(ac, A1, A2); // update PD { @@ -1450,11 +1339,8 @@ class Invariants_test : public beast::unit_test::suite { auto cred = STObject::makeInnerObject(sfCredential); cred.setAccountID(sfIssuer, A2); - auto credType = - std::string("cred_type2") + std::to_string(9 - n); - cred.setFieldVL( - sfCredentialType, - Slice(credType.c_str(), credType.size())); + auto credType = std::string("cred_type2") + std::to_string(9 - n); + cred.setFieldVL(sfCredentialType, Slice(credType.c_str(), credType.size())); credentials.push_back(std::move(cred)); } @@ -1465,18 +1351,16 @@ class Invariants_test : public beast::unit_test::suite return true; }, XRPAmount{}, - STTx{ttPERMISSIONED_DOMAIN_SET, [](STObject& tx) {}}, - {tecINVARIANT_FAILED, tecINVARIANT_FAILED}); + STTx{ttPERMISSIONED_DOMAIN_SET, [](STObject&) {}}, + fixPDEnabled ? failTers : badTers); testcase << "PermissionedDomain Set 4"; doInvariantCheck( + Env(*this, features), {{"permissioned domain credentials aren't unique"}}, [&](Account const& A1, Account const& A2, ApplyContext& ac) { - Keylet const pdKeylet = keylet::permissionedDomain(A1.id(), 10); - auto slePd = std::make_shared(pdKeylet); - // create PD - createPermissionedDomain(ac, slePd, A1, A2); + auto slePd = createPermissionedDomain(ac, A1, A2); // update PD { @@ -1485,8 +1369,7 @@ class Invariants_test : public beast::unit_test::suite { auto cred = STObject::makeInnerObject(sfCredential); cred.setAccountID(sfIssuer, A2); - cred.setFieldVL( - sfCredentialType, Slice("cred_type", 9)); + cred.setFieldVL(sfCredentialType, Slice("cred_type", 9)); credentials.push_back(std::move(cred)); } slePd->setFieldArray(sfAcceptedCredentials, credentials); @@ -1496,8 +1379,155 @@ class Invariants_test : public beast::unit_test::suite return true; }, XRPAmount{}, - STTx{ttPERMISSIONED_DOMAIN_SET, [](STObject& tx) {}}, - {tecINVARIANT_FAILED, tecINVARIANT_FAILED}); + STTx{ttPERMISSIONED_DOMAIN_SET, [](STObject&) {}}, + fixPDEnabled ? failTers : badTers); + + std::initializer_list goodTers = {tesSUCCESS, tesSUCCESS}; + + std::vector badMoreThan1{{"transaction affected more than 1 permissioned domain entry."}}; + std::vector emptyV; + std::vector badNoDomains{{"no domain objects affected by"}}; + std::vector badNotDeleted{{"domain object modified, but not deleted by "}}; + std::vector badDeleted{{"domain object deleted by"}}; + std::vector badTx{{"domain object(s) affected by an unauthorized transaction."}}; + + { + testcase << "PermissionedDomain set 2 domains "; + doInvariantCheck( + Env(*this, features), + fixPDEnabled ? badMoreThan1 : emptyV, + [](Account const& A1, Account const& A2, ApplyContext& ac) { + createPermissionedDomain(ac, A1, A2); + createPermissionedDomain(ac, A1, A2, 2, 11); + return true; + }, + XRPAmount{}, + STTx{ttPERMISSIONED_DOMAIN_SET, [](STObject&) {}}, + fixPDEnabled ? failTers : goodTers); + } + + { + testcase << "PermissionedDomain del 2 domains"; + + Env env1(*this, features); + + Account const A1{"A1"}; + Account const A2{"A2"}; + env1.fund(XRP(1000), A1, A2); + env1.close(); + + [[maybe_unused]] auto [seq1, pd1] = createPermissionedDomainEnv(env1, A1, A2); + [[maybe_unused]] auto [seq2, pd2] = createPermissionedDomainEnv(env1, A1, A2); + env1.close(); + + doInvariantCheck( + std::move(env1), + A1, + A2, + fixPDEnabled ? badMoreThan1 : emptyV, + [&pd1, &pd2](Account const&, Account const&, ApplyContext& ac) { + auto sle1 = ac.view().peek({ltPERMISSIONED_DOMAIN, pd1}); + auto sle2 = ac.view().peek({ltPERMISSIONED_DOMAIN, pd2}); + ac.view().erase(sle1); + ac.view().erase(sle2); + return true; + }, + XRPAmount{}, + STTx{ttPERMISSIONED_DOMAIN_DELETE, [](STObject&) {}}, + fixPDEnabled ? failTers : goodTers); + } + + { + testcase << "PermissionedDomain set 0 domains "; + doInvariantCheck( + Env(*this, features), + fixPDEnabled ? badNoDomains : emptyV, + [](Account const&, Account const&, ApplyContext&) { return true; }, + XRPAmount{}, + STTx{ttPERMISSIONED_DOMAIN_SET, [](STObject&) {}}, + fixPDEnabled ? badTers : goodTers); + } + + { + testcase << "PermissionedDomain del 0 domains"; + + Env env1(*this, features); + + Account const A1{"A1"}; + Account const A2{"A2"}; + env1.fund(XRP(1000), A1, A2); + env1.close(); + + [[maybe_unused]] auto [seq1, pd1] = createPermissionedDomainEnv(env1, A1, A2); + [[maybe_unused]] auto [seq2, pd2] = createPermissionedDomainEnv(env1, A1, A2); + env1.close(); + + doInvariantCheck( + Env(*this, features), + A1, + A2, + fixPDEnabled ? badNoDomains : emptyV, + [](Account const&, Account const&, ApplyContext&) { return true; }, + XRPAmount{}, + STTx{ttPERMISSIONED_DOMAIN_DELETE, [](STObject&) {}}, + fixPDEnabled ? badTers : goodTers); + } + + { + testcase << "PermissionedDomain set, delete domain"; + + Env env1(*this, features); + + Account const A1{"A1"}; + Account const A2{"A2"}; + env1.fund(XRP(1000), A1, A2); + env1.close(); + + [[maybe_unused]] auto [seq1, pd1] = createPermissionedDomainEnv(env1, A1, A2); + env1.close(); + + doInvariantCheck( + std::move(env1), + A1, + A2, + fixPDEnabled ? badDeleted : emptyV, + [&pd1](Account const&, Account const&, ApplyContext& ac) { + auto sle1 = ac.view().peek({ltPERMISSIONED_DOMAIN, pd1}); + ac.view().erase(sle1); + return true; + }, + XRPAmount{}, + STTx{ttPERMISSIONED_DOMAIN_SET, [](STObject&) {}}, + fixPDEnabled ? failTers : goodTers); + } + + { + testcase << "PermissionedDomain del, create domain "; + doInvariantCheck( + Env(*this, features), + fixPDEnabled ? badNotDeleted : emptyV, + [](Account const& A1, Account const& A2, ApplyContext& ac) { + createPermissionedDomain(ac, A1, A2); + return true; + }, + XRPAmount{}, + STTx{ttPERMISSIONED_DOMAIN_DELETE, [](STObject&) {}}, + fixPDEnabled ? failTers : goodTers); + } + + { + testcase << "PermissionedDomain invalid tx"; + + doInvariantCheck( + fixPDEnabled ? badTx : emptyV, + [&](Account const& A1, Account const& A2, ApplyContext& ac) { + createPermissionedDomain(ac, A1, A2); + return true; + }, + XRPAmount{}, + STTx{ttPAYMENT, [](STObject&) {}}, + failTers); + } } void @@ -1508,23 +1538,21 @@ class Invariants_test : public beast::unit_test::suite using namespace jtx; AccountID pseudoAccountID; - Preclose createPseudo = - [&, this](Account const& a, Account const& b, Env& env) { - PrettyAsset const xrpAsset{xrpIssue(), 1'000'000}; + Preclose createPseudo = [&, this](Account const& a, Account const& b, Env& env) { + PrettyAsset const xrpAsset{xrpIssue(), 1'000'000}; - // Create vault - Vault vault{env}; - auto [tx, vKeylet] = - vault.create({.owner = a, .asset = xrpAsset}); - env(tx); - env.close(); - if (auto const vSle = env.le(vKeylet); BEAST_EXPECT(vSle)) - { - pseudoAccountID = vSle->at(sfAccount); - } + // Create vault + Vault vault{env}; + auto [tx, vKeylet] = vault.create({.owner = a, .asset = xrpAsset}); + env(tx); + env.close(); + if (auto const vSle = env.le(vKeylet); BEAST_EXPECT(vSle)) + { + pseudoAccountID = vSle->at(sfAccount); + } - return BEAST_EXPECT(env.le(keylet::account(pseudoAccountID))); - }; + return BEAST_EXPECT(env.le(keylet::account(pseudoAccountID))); + }; /* Cases to check "pseudo-account has 0 pseudo-account fields set" @@ -1556,9 +1584,7 @@ class Invariants_test : public beast::unit_test::suite }, { "pseudo-account has a regular key", - [](SLE::pointer& sle) { - sle->at(sfRegularKey) = Account("regular").id(); - }, + [](SLE::pointer& sle) { sle->at(sfRegularKey) = Account("regular").id(); }, }, }); @@ -1621,13 +1647,43 @@ class Invariants_test : public beast::unit_test::suite }); } - void - testPermissionedDEX() + static std::pair + createPermissionedDomainEnv( + test::jtx::Env& env, + test::jtx::Account const& A1, + test::jtx::Account const& A2, + std::uint32_t numCreds = 2) { using namespace test::jtx; - testcase << "PermissionedDEX"; + + pdomain::Credentials credentials; + + for (std::size_t n = 0; n < numCreds; ++n) + { + auto credType = "cred_type" + std::to_string(n); + credentials.push_back({A2, credType}); + } + + std::uint32_t const seq = env.seq(A1); + env(pdomain::setTx(A1, credentials)); + uint256 key = pdomain::getNewDomain(env.meta()); + + // std::cout << "PD, acc: " << A1.id() << ", seq: " << seq << ", k: " << + // key << std::endl; + return {seq, key}; + } + + void + testPermissionedDEX(FeatureBitset features) + { + using namespace test::jtx; + + bool const fixPDEnabled = features[fixPermissionedDomainInvariant]; + + testcase << "PermissionedDEX" + std::string(fixPDEnabled ? " fix" : ""); doInvariantCheck( + Env(*this, features), {{"domain doesn't exist"}}, [](Account const& A1, Account const&, ApplyContext& ac) { Keylet const offerKey = keylet::offer(A1.id(), 10); @@ -1644,9 +1700,8 @@ class Invariants_test : public beast::unit_test::suite [](STObject& tx) { tx.setFieldH256( sfDomainID, - uint256{ - "F10D0CC9A0F9A3CBF585B80BE09A186483668FDBDD39AA7E33" - "70F3649CE134E5"}); + uint256{"F10D0CC9A0F9A3CBF585B80BE09A186483668FDBDD39AA7E33" + "70F3649CE134E5"}); Account const A1{"A1"}; tx.setFieldAmount(sfTakerPays, A1["USD"](10)); tx.setFieldAmount(sfTakerGets, XRP(1)); @@ -1655,12 +1710,9 @@ class Invariants_test : public beast::unit_test::suite // missing domain ID in offer object doInvariantCheck( + Env(*this, features), {{"hybrid offer is malformed"}}, [&](Account const& A1, Account const& A2, ApplyContext& ac) { - Keylet const pdKeylet = keylet::permissionedDomain(A1.id(), 10); - auto slePd = std::make_shared(pdKeylet); - createPermissionedDomain(ac, slePd, A1, A2); - Keylet const offerKey = keylet::offer(A2.id(), 10); auto sleOffer = std::make_shared(offerKey); sleOffer->setAccountID(sfAccount, A2); @@ -1675,126 +1727,158 @@ class Invariants_test : public beast::unit_test::suite return true; }, XRPAmount{}, - STTx{ttOFFER_CREATE, [&](STObject& tx) {}}, + STTx{ttOFFER_CREATE, [&](STObject&) {}}, {tecINVARIANT_FAILED, tecINVARIANT_FAILED}); // more than one entry in sfAdditionalBooks - doInvariantCheck( - {{"hybrid offer is malformed"}}, - [&](Account const& A1, Account const& A2, ApplyContext& ac) { - Keylet const pdKeylet = keylet::permissionedDomain(A1.id(), 10); - auto slePd = std::make_shared(pdKeylet); - createPermissionedDomain(ac, slePd, A1, A2); + { + Env env1(*this, features); - Keylet const offerKey = keylet::offer(A2.id(), 10); - auto sleOffer = std::make_shared(offerKey); - sleOffer->setAccountID(sfAccount, A2); - sleOffer->setFieldAmount(sfTakerPays, A1["USD"](10)); - sleOffer->setFieldAmount(sfTakerGets, XRP(1)); - sleOffer->setFlag(lsfHybrid); - sleOffer->setFieldH256(sfDomainID, pdKeylet.key); + Account const A1{"A1"}; + Account const A2{"A2"}; + env1.fund(XRP(1000), A1, A2); + env1.close(); - STArray bookArr; - bookArr.push_back(STObject::makeInnerObject(sfBook)); - bookArr.push_back(STObject::makeInnerObject(sfBook)); - sleOffer->setFieldArray(sfAdditionalBooks, bookArr); - ac.view().insert(sleOffer); - return true; - }, - XRPAmount{}, - STTx{ttOFFER_CREATE, [&](STObject& tx) {}}, - {tecINVARIANT_FAILED, tecINVARIANT_FAILED}); + [[maybe_unused]] auto [seq1, pd1] = createPermissionedDomainEnv(env1, A1, A2); + env1.close(); + + doInvariantCheck( + std::move(env1), + A1, + A2, + {{"hybrid offer is malformed"}}, + [&pd1](Account const& A1, Account const& A2, ApplyContext& ac) { + Keylet const offerKey = keylet::offer(A2.id(), 10); + auto sleOffer = std::make_shared(offerKey); + sleOffer->setAccountID(sfAccount, A2); + sleOffer->setFieldAmount(sfTakerPays, A1["USD"](10)); + sleOffer->setFieldAmount(sfTakerGets, XRP(1)); + sleOffer->setFlag(lsfHybrid); + sleOffer->setFieldH256(sfDomainID, pd1); + + STArray bookArr; + bookArr.push_back(STObject::makeInnerObject(sfBook)); + bookArr.push_back(STObject::makeInnerObject(sfBook)); + sleOffer->setFieldArray(sfAdditionalBooks, bookArr); + ac.view().insert(sleOffer); + return true; + }, + XRPAmount{}, + STTx{ttOFFER_CREATE, [&](STObject&) {}}, + {tecINVARIANT_FAILED, tecINVARIANT_FAILED}); + } // hybrid offer missing sfAdditionalBooks - doInvariantCheck( - {{"hybrid offer is malformed"}}, - [&](Account const& A1, Account const& A2, ApplyContext& ac) { - Keylet const pdKeylet = keylet::permissionedDomain(A1.id(), 10); - auto slePd = std::make_shared(pdKeylet); - createPermissionedDomain(ac, slePd, A1, A2); + { + Env env1(*this, features); - Keylet const offerKey = keylet::offer(A2.id(), 10); - auto sleOffer = std::make_shared(offerKey); - sleOffer->setAccountID(sfAccount, A2); - sleOffer->setFieldAmount(sfTakerPays, A1["USD"](10)); - sleOffer->setFieldAmount(sfTakerGets, XRP(1)); - sleOffer->setFlag(lsfHybrid); - sleOffer->setFieldH256(sfDomainID, pdKeylet.key); - ac.view().insert(sleOffer); - return true; - }, - XRPAmount{}, - STTx{ttOFFER_CREATE, [&](STObject& tx) {}}, - {tecINVARIANT_FAILED, tecINVARIANT_FAILED}); + Account const A1{"A1"}; + Account const A2{"A2"}; + env1.fund(XRP(1000), A1, A2); + env1.close(); - doInvariantCheck( - {{"transaction consumed wrong domains"}}, - [&](Account const& A1, Account const& A2, ApplyContext& ac) { - Keylet const pdKeylet = keylet::permissionedDomain(A1.id(), 10); - auto slePd = std::make_shared(pdKeylet); - createPermissionedDomain(ac, slePd, A1, A2); + [[maybe_unused]] auto [seq1, pd1] = createPermissionedDomainEnv(env1, A1, A2); + env1.close(); - Keylet const badDomainKeylet = - keylet::permissionedDomain(A1.id(), 20); - auto sleBadPd = std::make_shared(badDomainKeylet); - createPermissionedDomain(ac, sleBadPd, A1, A2); + doInvariantCheck( + std::move(env1), + A1, + A2, + {{"hybrid offer is malformed"}}, + [&pd1](Account const& A1, Account const& A2, ApplyContext& ac) { + Keylet const offerKey = keylet::offer(A2.id(), 10); + auto sleOffer = std::make_shared(offerKey); + sleOffer->setAccountID(sfAccount, A2); + sleOffer->setFieldAmount(sfTakerPays, A1["USD"](10)); + sleOffer->setFieldAmount(sfTakerGets, XRP(1)); + sleOffer->setFlag(lsfHybrid); + sleOffer->setFieldH256(sfDomainID, pd1); + ac.view().insert(sleOffer); + return true; + }, + XRPAmount{}, + STTx{ttOFFER_CREATE, [&](STObject&) {}}, + {tecINVARIANT_FAILED, tecINVARIANT_FAILED}); + } - Keylet const offerKey = keylet::offer(A2.id(), 10); - auto sleOffer = std::make_shared(offerKey); - sleOffer->setAccountID(sfAccount, A2); - sleOffer->setFieldAmount(sfTakerPays, A1["USD"](10)); - sleOffer->setFieldAmount(sfTakerGets, XRP(1)); - sleOffer->setFieldH256(sfDomainID, pdKeylet.key); - ac.view().insert(sleOffer); - return true; - }, - XRPAmount{}, - STTx{ - ttOFFER_CREATE, - [&](STObject& tx) { - Account const A1{"A1"}; - Keylet const badDomainKey = - keylet::permissionedDomain(A1.id(), 20); - tx.setFieldH256(sfDomainID, badDomainKey.key); - tx.setFieldAmount(sfTakerPays, A1["USD"](10)); - tx.setFieldAmount(sfTakerGets, XRP(1)); - }}, - {tecINVARIANT_FAILED, tecINVARIANT_FAILED}); + { + Env env1(*this, features); - doInvariantCheck( - {{"domain transaction affected regular offers"}}, - [&](Account const& A1, Account const& A2, ApplyContext& ac) { - Keylet const pdKeylet = keylet::permissionedDomain(A1.id(), 10); - auto slePd = std::make_shared(pdKeylet); - createPermissionedDomain(ac, slePd, A1, A2); + Account const A1{"A1"}; + Account const A2{"A2"}; + env1.fund(XRP(1000), A1, A2); + env1.close(); - Keylet const offerKey = keylet::offer(A2.id(), 10); - auto sleOffer = std::make_shared(offerKey); - sleOffer->setAccountID(sfAccount, A2); - sleOffer->setFieldAmount(sfTakerPays, A1["USD"](10)); - sleOffer->setFieldAmount(sfTakerGets, XRP(1)); - ac.view().insert(sleOffer); - return true; - }, - XRPAmount{}, - STTx{ - ttOFFER_CREATE, - [&](STObject& tx) { - Account const A1{"A1"}; - Keylet const domainKey = - keylet::permissionedDomain(A1.id(), 10); - tx.setFieldH256(sfDomainID, domainKey.key); - tx.setFieldAmount(sfTakerPays, A1["USD"](10)); - tx.setFieldAmount(sfTakerGets, XRP(1)); - }}, - {tecINVARIANT_FAILED, tecINVARIANT_FAILED}); + [[maybe_unused]] auto [seq1, pd1] = createPermissionedDomainEnv(env1, A1, A2); + [[maybe_unused]] auto [seq2, pd2] = createPermissionedDomainEnv(env1, A1, A2); + env1.close(); + + doInvariantCheck( + std::move(env1), + A1, + A2, + {{"transaction consumed wrong domains"}}, + [&pd1](Account const& A1, Account const& A2, ApplyContext& ac) { + Keylet const offerKey = keylet::offer(A2.id(), 10); + auto sleOffer = std::make_shared(offerKey); + sleOffer->setAccountID(sfAccount, A2); + sleOffer->setFieldAmount(sfTakerPays, A1["USD"](10)); + sleOffer->setFieldAmount(sfTakerGets, XRP(1)); + sleOffer->setFieldH256(sfDomainID, pd1); + ac.view().insert(sleOffer); + return true; + }, + XRPAmount{}, + STTx{ + ttOFFER_CREATE, + [&pd2, &A1](STObject& tx) { + tx.setFieldH256(sfDomainID, pd2); + tx.setFieldAmount(sfTakerPays, A1["USD"](10)); + tx.setFieldAmount(sfTakerGets, XRP(1)); + }}, + {tecINVARIANT_FAILED, tecINVARIANT_FAILED}); + } + + { + Env env1(*this, features); + + Account const A1{"A1"}; + Account const A2{"A2"}; + env1.fund(XRP(1000), A1, A2); + env1.close(); + + [[maybe_unused]] auto [seq1, pd1] = createPermissionedDomainEnv(env1, A1, A2); + env1.close(); + + doInvariantCheck( + std::move(env1), + A1, + A2, + {{"domain transaction affected regular offers"}}, + [&](Account const& A1, Account const& A2, ApplyContext& ac) { + Keylet const offerKey = keylet::offer(A2.id(), 10); + auto sleOffer = std::make_shared(offerKey); + sleOffer->setAccountID(sfAccount, A2); + sleOffer->setFieldAmount(sfTakerPays, A1["USD"](10)); + sleOffer->setFieldAmount(sfTakerGets, XRP(1)); + ac.view().insert(sleOffer); + return true; + }, + XRPAmount{}, + STTx{ + ttOFFER_CREATE, + [&](STObject& tx) { + Account const A1{"A1"}; + tx.setFieldH256(sfDomainID, pd1); + tx.setFieldAmount(sfTakerPays, A1["USD"](10)); + tx.setFieldAmount(sfTakerGets, XRP(1)); + }}, + {tecINVARIANT_FAILED, tecINVARIANT_FAILED}); + } } Keylet - createLoanBroker( - jtx::Account const& a, - jtx::Env& env, - jtx::PrettyAsset const& asset) + createLoanBroker(jtx::Account const& a, jtx::Env& env, jtx::PrettyAsset const& asset) { using namespace jtx; @@ -1825,39 +1909,27 @@ class Invariants_test : public beast::unit_test::suite // Initialize with a placeholder value because there's no default ctor Keylet loanBrokerKeylet = keylet::amendments(); - Preclose createLoanBroker = - [&, this](Account const& a, Account const& b, Env& env) { - PrettyAsset const xrpAsset{xrpIssue(), 1'000'000}; + Preclose createLoanBroker = [&, this](Account const& a, Account const& b, Env& env) { + PrettyAsset const xrpAsset{xrpIssue(), 1'000'000}; - loanBrokerKeylet = this->createLoanBroker(a, env, xrpAsset); - return BEAST_EXPECT(env.le(loanBrokerKeylet)); - }; + loanBrokerKeylet = this->createLoanBroker(a, env, xrpAsset); + return BEAST_EXPECT(env.le(loanBrokerKeylet)); + }; { - auto const mods = - std::to_array>({ - [](SLE::pointer& sle) { sle->at(sfSequence) += 1; }, - [](SLE::pointer& sle) { sle->at(sfOwnerNode) += 1; }, - [](SLE::pointer& sle) { sle->at(sfVaultNode) += 1; }, - [](SLE::pointer& sle) { sle->at(sfVaultID) = uint256(1u); }, - [](SLE::pointer& sle) { - sle->at(sfAccount) = sle->at(sfOwner); - }, - [](SLE::pointer& sle) { - sle->at(sfOwner) = sle->at(sfAccount); - }, - [](SLE::pointer& sle) { - sle->at(sfManagementFeeRate) += 1; - }, - [](SLE::pointer& sle) { sle->at(sfCoverRateMinimum) += 1; }, - [](SLE::pointer& sle) { - sle->at(sfCoverRateLiquidation) += 1; - }, - [](SLE::pointer& sle) { sle->at(sfLedgerEntryType) += 1; }, - [](SLE::pointer& sle) { - sle->at(sfLedgerIndex) = sle->at(sfVaultID).value(); - }, - }); + auto const mods = std::to_array>({ + [](SLE::pointer& sle) { sle->at(sfSequence) += 1; }, + [](SLE::pointer& sle) { sle->at(sfOwnerNode) += 1; }, + [](SLE::pointer& sle) { sle->at(sfVaultNode) += 1; }, + [](SLE::pointer& sle) { sle->at(sfVaultID) = uint256(1u); }, + [](SLE::pointer& sle) { sle->at(sfAccount) = sle->at(sfOwner); }, + [](SLE::pointer& sle) { sle->at(sfOwner) = sle->at(sfAccount); }, + [](SLE::pointer& sle) { sle->at(sfManagementFeeRate) += 1; }, + [](SLE::pointer& sle) { sle->at(sfCoverRateMinimum) += 1; }, + [](SLE::pointer& sle) { sle->at(sfCoverRateLiquidation) += 1; }, + [](SLE::pointer& sle) { sle->at(sfLedgerEntryType) += 1; }, + [](SLE::pointer& sle) { sle->at(sfLedgerIndex) = sle->at(sfVaultID).value(); }, + }); for (auto const& mod : mods) { @@ -1881,19 +1953,15 @@ class Invariants_test : public beast::unit_test::suite // TODO: Loan Object { - auto const mods = - std::to_array>({ - [](SLE::pointer& sle) { sle->at(sfLedgerEntryType) += 1; }, - [](SLE::pointer& sle) { - sle->at(sfLedgerIndex) = uint256(1u); - }, - }); + auto const mods = std::to_array>({ + [](SLE::pointer& sle) { sle->at(sfLedgerEntryType) += 1; }, + [](SLE::pointer& sle) { sle->at(sfLedgerIndex) = uint256(1u); }, + }); for (auto const& mod : mods) { doInvariantCheck( - {{"changed an unchangeable field"}}, - [&](Account const& A1, Account const&, ApplyContext& ac) { + {{"changed an unchangeable field"}}, [&](Account const& A1, Account const&, ApplyContext& ac) { auto sle = ac.view().peek(keylet::account(A1.id())); if (!sle) return false; @@ -1913,18 +1981,14 @@ class Invariants_test : public beast::unit_test::suite using namespace jtx; enum class Asset { XRP, IOU, MPT }; - auto const assetTypes = - std::to_array({Asset::XRP, Asset::IOU, Asset::MPT}); + auto const assetTypes = std::to_array({Asset::XRP, Asset::IOU, Asset::MPT}); for (auto const assetType : assetTypes) { // Initialize with a placeholder value because there's no default // ctor Keylet loanBrokerKeylet = keylet::amendments(); - Preclose createLoanBroker = [&, this]( - Account const& alice, - Account const& issuer, - Env& env) { + Preclose createLoanBroker = [&, this](Account const& alice, Account const& issuer, Env& env) { PrettyAsset const asset = [&]() { switch (assetType) { @@ -1938,9 +2002,7 @@ class Invariants_test : public beast::unit_test::suite case Asset::MPT: { MPTTester mptt{env, issuer, mptInitNoFund}; - mptt.create( - {.flags = tfMPTCanClawback | tfMPTCanTransfer | - tfMPTCanLock}); + mptt.create({.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock}); PrettyAsset const mptAsset = mptt.issuanceID(); mptt.authorize({.account = alice}); env(pay(issuer, alice, mptAsset(1000))); @@ -1960,8 +2022,7 @@ class Invariants_test : public beast::unit_test::suite // Ensure the test scenarios are set up completely. The test cases // will need to recompute any of these values it needs for itself // rather than trying to return a bunch of items - auto setupTest = - [&, this](Account const& A1, Account const&, ApplyContext& ac) + auto setupTest = [&, this](Account const& A1, Account const&, ApplyContext& ac) -> std::optional> { if (loanBrokerKeylet.type != ltLOAN_BROKER) return {}; @@ -1976,8 +2037,7 @@ class Invariants_test : public beast::unit_test::suite // The pseudo-account holds the directory, so get it auto const pseudoAccountID = sleBroker->at(sfAccount); - auto const pseudoAccountKeylet = - keylet::account(pseudoAccountID); + auto const pseudoAccountKeylet = keylet::account(pseudoAccountID); // Strictly speaking, we don't need to load the // ACCOUNT_ROOT, but check anyway auto slePseudo = ac.view().peek(pseudoAccountKeylet); @@ -1991,11 +2051,7 @@ class Invariants_test : public beast::unit_test::suite { // Create the directory BEAST_EXPECT( - ::xrpl::directory::createRoot( - ac.view(), - dirKeylet, - loanBrokerKeylet.key, - describe) == 0); + ::xrpl::directory::createRoot(ac.view(), dirKeylet, loanBrokerKeylet.key, describe) == 0); sleDir = ac.view().peek(dirKeylet); } @@ -2006,16 +2062,14 @@ class Invariants_test : public beast::unit_test::suite doInvariantCheck( {{"Loan Broker with zero OwnerCount has multiple directory " "pages"}}, - [&setupTest, this]( - Account const& A1, Account const& A2, ApplyContext& ac) { + [&setupTest, this](Account const& A1, Account const& A2, ApplyContext& ac) { auto test = setupTest(A1, A2, ac); if (!test || !test->first || !test->second) return false; auto slePseudo = test->first; auto sleDir = test->second; - auto const describe = - describeOwnerDir(slePseudo->at(sfAccount)); + auto const describe = describeOwnerDir(slePseudo->at(sfAccount)); BEAST_EXPECT( ::xrpl::directory::insertPage( @@ -2038,8 +2092,7 @@ class Invariants_test : public beast::unit_test::suite doInvariantCheck( {{"Loan Broker with zero OwnerCount has multiple indexes in " "the Directory root"}}, - [&setupTest]( - Account const& A1, Account const& A2, ApplyContext& ac) { + [&setupTest](Account const& A1, Account const& A2, ApplyContext& ac) { auto test = setupTest(A1, A2, ac); if (!test || !test->first || !test->second) return false; @@ -2051,8 +2104,7 @@ class Invariants_test : public beast::unit_test::suite // Put some extra garbage into the directory for (auto const& key : {slePseudo->key(), sleDir->key()}) { - ::xrpl::directory::insertKey( - ac.view(), sleDir, 0, false, indexes, key); + ::xrpl::directory::insertKey(ac.view(), sleDir, 0, false, indexes, key); } return true; @@ -2064,26 +2116,22 @@ class Invariants_test : public beast::unit_test::suite doInvariantCheck( {{"Loan Broker directory corrupt"}}, - [&setupTest]( - Account const& A1, Account const& A2, ApplyContext& ac) { + [&setupTest](Account const& A1, Account const& A2, ApplyContext& ac) { auto test = setupTest(A1, A2, ac); if (!test || !test->first || !test->second) return false; auto slePseudo = test->first; auto sleDir = test->second; - auto const describe = - describeOwnerDir(slePseudo->at(sfAccount)); + auto const describe = describeOwnerDir(slePseudo->at(sfAccount)); // Empty vector will overwrite the existing entry for the // holding, if any, avoiding the "has multiple indexes" // failure. STVector256 indexes; // Put one meaningless key into the directory - auto const key = - keylet::account(Account("random").id()).key; - ::xrpl::directory::insertKey( - ac.view(), sleDir, 0, false, indexes, key); + auto const key = keylet::account(Account("random").id()).key; + ::xrpl::directory::insertKey(ac.view(), sleDir, 0, false, indexes, key); return true; }, @@ -2095,8 +2143,7 @@ class Invariants_test : public beast::unit_test::suite doInvariantCheck( {{"Loan Broker with zero OwnerCount has an unexpected entry in " "the directory"}}, - [&setupTest]( - Account const& A1, Account const& A2, ApplyContext& ac) { + [&setupTest](Account const& A1, Account const& A2, ApplyContext& ac) { auto test = setupTest(A1, A2, ac); if (!test || !test->first || !test->second) return false; @@ -2108,8 +2155,7 @@ class Invariants_test : public beast::unit_test::suite // failure. STVector256 indexes; - ::xrpl::directory::insertKey( - ac.view(), sleDir, 0, false, indexes, slePseudo->key()); + ::xrpl::directory::insertKey(ac.view(), sleDir, 0, false, indexes, slePseudo->key()); return true; }, @@ -2164,9 +2210,7 @@ class Invariants_test : public beast::unit_test::suite std::optional accountAssets = {}; std::optional accountShares = {}; }; - auto constexpr adjust = [&](ApplyView& ac, - xrpl::Keylet keylet, - Adjustments args) { + auto constexpr adjust = [&](ApplyView& ac, xrpl::Keylet keylet, Adjustments args) { auto sleVault = ac.peek(keylet); if (!sleVault) return false; @@ -2184,17 +2228,14 @@ class Invariants_test : public beast::unit_test::suite // Remaining fields are adjusted in terms of difference if (args.assetsTotal) - (*sleVault)[sfAssetsTotal] = - *(*sleVault)[sfAssetsTotal] + *args.assetsTotal; + (*sleVault)[sfAssetsTotal] = *(*sleVault)[sfAssetsTotal] + *args.assetsTotal; if (args.assetsAvailable) - (*sleVault)[sfAssetsAvailable] = - *(*sleVault)[sfAssetsAvailable] + *args.assetsAvailable; + (*sleVault)[sfAssetsAvailable] = *(*sleVault)[sfAssetsAvailable] + *args.assetsAvailable; ac.update(sleVault); if (args.sharesTotal) { - (*sleShares)[sfOutstandingAmount] = - *(*sleShares)[sfOutstandingAmount] + *args.sharesTotal; + (*sleShares)[sfOutstandingAmount] = *(*sleShares)[sfOutstandingAmount] + *args.sharesTotal; ac.update(sleShares); } @@ -2207,8 +2248,7 @@ class Invariants_test : public beast::unit_test::suite auto slePseudoAccount = ac.peek(keylet::account(pseudoId)); if (!slePseudoAccount) return false; - (*slePseudoAccount)[sfBalance] = - *(*slePseudoAccount)[sfBalance] + *args.vaultAssets; + (*slePseudoAccount)[sfBalance] = *(*slePseudoAccount)[sfBalance] + *args.vaultAssets; ac.update(slePseudoAccount); } else if (assets.holds()) @@ -2217,8 +2257,7 @@ class Invariants_test : public beast::unit_test::suite auto sleMPToken = ac.peek(keylet::mptoken(mptId, pseudoId)); if (!sleMPToken) return false; - (*sleMPToken)[sfMPTAmount] = - *(*sleMPToken)[sfMPTAmount] + *args.vaultAssets; + (*sleMPToken)[sfMPTAmount] = *(*sleMPToken)[sfMPTAmount] + *args.vaultAssets; ac.update(sleMPToken); } else @@ -2233,19 +2272,16 @@ class Invariants_test : public beast::unit_test::suite auto sleAccount = ac.peek(keylet::account(pair.account)); if (!sleAccount) return false; - (*sleAccount)[sfBalance] = - *(*sleAccount)[sfBalance] + pair.amount; + (*sleAccount)[sfBalance] = *(*sleAccount)[sfBalance] + pair.amount; ac.update(sleAccount); } else if (assets.holds()) { auto const mptID = assets.get().getMptID(); - auto sleMPToken = - ac.peek(keylet::mptoken(mptID, pair.account)); + auto sleMPToken = ac.peek(keylet::mptoken(mptID, pair.account)); if (!sleMPToken) return false; - (*sleMPToken)[sfMPTAmount] = - *(*sleMPToken)[sfMPTAmount] + pair.amount; + (*sleMPToken)[sfMPTAmount] = *(*sleMPToken)[sfMPTAmount] + pair.amount; ac.update(sleMPToken); } else @@ -2255,19 +2291,16 @@ class Invariants_test : public beast::unit_test::suite if (args.accountShares) { auto const& pair = *args.accountShares; - auto sleMPToken = - ac.peek(keylet::mptoken(mptIssuanceID, pair.account)); + auto sleMPToken = ac.peek(keylet::mptoken(mptIssuanceID, pair.account)); if (!sleMPToken) return false; - (*sleMPToken)[sfMPTAmount] = - *(*sleMPToken)[sfMPTAmount] + pair.amount; + (*sleMPToken)[sfMPTAmount] = *(*sleMPToken)[sfMPTAmount] + pair.amount; ac.update(sleMPToken); } return true; }; - constexpr auto args = - [](AccountID id, int adjustment, auto fn) -> Adjustments { + constexpr auto args = [](AccountID id, int adjustment, auto fn) -> Adjustments { Adjustments sample = { .assetsTotal = adjustment, .assetsAvailable = adjustment, @@ -2284,19 +2317,14 @@ class Invariants_test : public beast::unit_test::suite Account A3{"A3"}; Account A4{"A4"}; - auto const precloseXrp = - [&](Account const& A1, Account const& A2, Env& env) -> bool { + auto const precloseXrp = [&](Account const& A1, Account const& A2, Env& env) -> bool { env.fund(XRP(1000), A3, A4); Vault vault{env}; - auto [tx, keylet] = - vault.create({.owner = A1, .asset = xrpIssue()}); + auto [tx, keylet] = vault.create({.owner = A1, .asset = xrpIssue()}); env(tx); - env(vault.deposit( - {.depositor = A1, .id = keylet.key, .amount = XRP(10)})); - env(vault.deposit( - {.depositor = A2, .id = keylet.key, .amount = XRP(10)})); - env(vault.deposit( - {.depositor = A3, .id = keylet.key, .amount = XRP(10)})); + env(vault.deposit({.depositor = A1, .id = keylet.key, .amount = XRP(10)})); + env(vault.deposit({.depositor = A2, .id = keylet.key, .amount = XRP(10)})); + env(vault.deposit({.depositor = A3, .id = keylet.key, .amount = XRP(10)})); return true; }; @@ -2367,10 +2395,8 @@ class Invariants_test : public beast::unit_test::suite auto const sequence = ac.view().seq(); auto const vaultKeylet = keylet::vault(A1.id(), sequence); auto sleVault = std::make_shared(vaultKeylet); - auto const vaultPage = ac.view().dirInsert( - keylet::ownerDir(A1.id()), - sleVault->key(), - describeOwnerDir(A1.id())); + auto const vaultPage = + ac.view().dirInsert(keylet::ownerDir(A1.id()), sleVault->key(), describeOwnerDir(A1.id())); sleVault->setFieldU64(sfOwnerNode, *vaultPage); ac.view().insert(sleVault); return true; @@ -2424,13 +2450,11 @@ class Invariants_test : public beast::unit_test::suite [&](Account const& A1, Account const& A2, Env& env) { Vault vault{env}; { - auto [tx, _] = - vault.create({.owner = A1, .asset = xrpIssue()}); + auto [tx, _] = vault.create({.owner = A1, .asset = xrpIssue()}); env(tx); } { - auto [tx, _] = - vault.create({.owner = A2, .asset = xrpIssue()}); + auto [tx, _] = vault.create({.owner = A2, .asset = xrpIssue()}); env(tx); } return true; @@ -2443,10 +2467,8 @@ class Invariants_test : public beast::unit_test::suite auto const insertVault = [&](Account const A) { auto const vaultKeylet = keylet::vault(A.id(), sequence); auto sleVault = std::make_shared(vaultKeylet); - auto const vaultPage = ac.view().dirInsert( - keylet::ownerDir(A.id()), - sleVault->key(), - describeOwnerDir(A.id())); + auto const vaultPage = + ac.view().dirInsert(keylet::ownerDir(A.id()), sleVault->key(), describeOwnerDir(A.id())); sleVault->setFieldU64(sfOwnerNode, *vaultPage); ac.view().insert(sleVault); }; @@ -2487,8 +2509,7 @@ class Invariants_test : public beast::unit_test::suite auto sleVault = ac.view().peek(keylet); if (!sleVault) return false; - auto sleShares = ac.view().peek( - keylet::mptIssuance((*sleVault)[sfShareMPTID])); + auto sleShares = ac.view().peek(keylet::mptIssuance((*sleVault)[sfShareMPTID])); if (!sleShares) return false; ac.view().erase(sleVault); @@ -2500,11 +2521,9 @@ class Invariants_test : public beast::unit_test::suite {tecINVARIANT_FAILED, tefINVARIANT_FAILED}, [&](Account const& A1, Account const& A2, Env& env) { Vault vault{env}; - auto [tx, keylet] = - vault.create({.owner = A1, .asset = xrpIssue()}); + auto [tx, keylet] = vault.create({.owner = A1, .asset = xrpIssue()}); env(tx); - env(vault.deposit( - {.depositor = A1, .id = keylet.key, .amount = XRP(10)})); + env(vault.deposit({.depositor = A1, .id = keylet.key, .amount = XRP(10)})); return true; }); @@ -2515,8 +2534,7 @@ class Invariants_test : public beast::unit_test::suite auto sleVault = ac.view().peek(keylet); if (!sleVault) return false; - auto sleShares = ac.view().peek( - keylet::mptIssuance((*sleVault)[sfShareMPTID])); + auto sleShares = ac.view().peek(keylet::mptIssuance((*sleVault)[sfShareMPTID])); if (!sleShares) return false; // Note, such an "orphaned" update of MPT issuance attached to a @@ -2533,9 +2551,7 @@ class Invariants_test : public beast::unit_test::suite doInvariantCheck( {"vault operation succeeded without modifying a vault"}, - [&](Account const& A1, Account const& A2, ApplyContext& ac) { - return true; - }, + [&](Account const& A1, Account const& A2, ApplyContext& ac) { return true; }, XRPAmount{}, STTx{ttVAULT_CREATE, [](STObject&) {}}, {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, @@ -2548,9 +2564,7 @@ class Invariants_test : public beast::unit_test::suite doInvariantCheck( {"vault operation succeeded without modifying a vault"}, - [&](Account const& A1, Account const& A2, ApplyContext& ac) { - return true; - }, + [&](Account const& A1, Account const& A2, ApplyContext& ac) { return true; }, XRPAmount{}, STTx{ttVAULT_DEPOSIT, [](STObject&) {}}, {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, @@ -2563,9 +2577,7 @@ class Invariants_test : public beast::unit_test::suite doInvariantCheck( {"vault operation succeeded without modifying a vault"}, - [&](Account const& A1, Account const& A2, ApplyContext& ac) { - return true; - }, + [&](Account const& A1, Account const& A2, ApplyContext& ac) { return true; }, XRPAmount{}, STTx{ttVAULT_WITHDRAW, [](STObject&) {}}, {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, @@ -2578,9 +2590,7 @@ class Invariants_test : public beast::unit_test::suite doInvariantCheck( {"vault operation succeeded without modifying a vault"}, - [&](Account const& A1, Account const& A2, ApplyContext& ac) { - return true; - }, + [&](Account const& A1, Account const& A2, ApplyContext& ac) { return true; }, XRPAmount{}, STTx{ttVAULT_CLAWBACK, [](STObject&) {}}, {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, @@ -2593,9 +2603,7 @@ class Invariants_test : public beast::unit_test::suite doInvariantCheck( {"vault operation succeeded without modifying a vault"}, - [&](Account const& A1, Account const& A2, ApplyContext& ac) { - return true; - }, + [&](Account const& A1, Account const& A2, ApplyContext& ac) { return true; }, XRPAmount{}, STTx{ttVAULT_DELETE, [](STObject&) {}}, {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, @@ -2616,8 +2624,7 @@ class Invariants_test : public beast::unit_test::suite (*sleVault)[sfAssetsMaximum] = 200; ac.view().update(sleVault); - auto sleShares = ac.view().peek( - keylet::mptIssuance((*sleVault)[sfShareMPTID])); + auto sleShares = ac.view().peek(keylet::mptIssuance((*sleVault)[sfShareMPTID])); if (!sleShares) return false; ac.view().erase(sleShares); @@ -2650,11 +2657,9 @@ class Invariants_test : public beast::unit_test::suite {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, [&](Account const& A1, Account const& A2, Env& env) { Vault vault{env}; - auto [tx, keylet] = - vault.create({.owner = A1, .asset = xrpIssue()}); + auto [tx, keylet] = vault.create({.owner = A1, .asset = xrpIssue()}); env(tx); - env(vault.deposit( - {.depositor = A1, .id = keylet.key, .amount = XRP(10)})); + env(vault.deposit({.depositor = A1, .id = keylet.key, .amount = XRP(10)})); return true; }); @@ -2671,12 +2676,10 @@ class Invariants_test : public beast::unit_test::suite auto sleVault = ac.view().peek(keylet); if (!sleVault) return false; - auto slePseudoAccount = - ac.view().peek(keylet::account(*(*sleVault)[sfAccount])); + auto slePseudoAccount = ac.view().peek(keylet::account(*(*sleVault)[sfAccount])); if (!slePseudoAccount) return false; - (*slePseudoAccount)[sfBalance] = - *(*slePseudoAccount)[sfBalance] - 10; + (*slePseudoAccount)[sfBalance] = *(*slePseudoAccount)[sfBalance] - 10; ac.view().update(slePseudoAccount); // Move 10 drops to A4 to enforce total XRP balance @@ -2686,14 +2689,11 @@ class Invariants_test : public beast::unit_test::suite (*sleA4)[sfBalance] = *(*sleA4)[sfBalance] + 10; ac.view().update(sleA4); - return adjust( - ac.view(), - keylet, - args(A2.id(), 0, [&](Adjustments& sample) { - sample.assetsAvailable = (DROPS_PER_XRP * -100).value(); - sample.assetsTotal = (DROPS_PER_XRP * -200).value(); - sample.sharesTotal = -1; - })); + return adjust(ac.view(), keylet, args(A2.id(), 0, [&](Adjustments& sample) { + sample.assetsAvailable = (DROPS_PER_XRP * -100).value(); + sample.assetsTotal = (DROPS_PER_XRP * -200).value(); + sample.sharesTotal = -1; + })); }, XRPAmount{}, STTx{ttVAULT_SET, [](STObject& tx) {}}, @@ -2708,8 +2708,7 @@ class Invariants_test : public beast::unit_test::suite auto sleVault = ac.view().peek(keylet); if (!sleVault) return false; - sleVault->setFieldIssue( - sfAsset, STIssue{sfAsset, MPTIssue(MPTID(42))}); + sleVault->setFieldIssue(sfAsset, STIssue{sfAsset, MPTIssue(MPTID(42))}); ac.view().update(sleVault); return true; }, @@ -2751,17 +2750,13 @@ class Invariants_test : public beast::unit_test::suite precloseXrp); doInvariantCheck( - {"vault transaction must not change loss unrealized", - "set must not change assets outstanding"}, + {"vault transaction must not change loss unrealized", "set must not change assets outstanding"}, [&](Account const& A1, Account const& A2, ApplyContext& ac) { auto const keylet = keylet::vault(A1.id(), ac.view().seq()); - return adjust( - ac.view(), - keylet, - args(A2.id(), 0, [&](Adjustments& sample) { - sample.lossUnrealized = 13; - sample.assetsTotal = 20; - })); + return adjust(ac.view(), keylet, args(A2.id(), 0, [&](Adjustments& sample) { + sample.lossUnrealized = 13; + sample.assetsTotal = 20; + })); }, XRPAmount{}, STTx{ttVAULT_SET, [](STObject& tx) {}}, @@ -2776,18 +2771,10 @@ class Invariants_test : public beast::unit_test::suite [&](Account const& A1, Account const& A2, ApplyContext& ac) { auto const keylet = keylet::vault(A1.id(), ac.view().seq()); return adjust( - ac.view(), - keylet, - args(A2.id(), 100, [&](Adjustments& sample) { - sample.lossUnrealized = 13; - })); + ac.view(), keylet, args(A2.id(), 100, [&](Adjustments& sample) { sample.lossUnrealized = 13; })); }, XRPAmount{}, - STTx{ - ttVAULT_DEPOSIT, - [](STObject& tx) { - tx.setFieldAmount(sfAmount, XRPAmount(200)); - }}, + STTx{ttVAULT_DEPOSIT, [](STObject& tx) { tx.setFieldAmount(sfAmount, XRPAmount(200)); }}, {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, precloseXrp, TxAccount::A2); @@ -2797,11 +2784,7 @@ class Invariants_test : public beast::unit_test::suite [&](Account const& A1, Account const& A2, ApplyContext& ac) { auto const keylet = keylet::vault(A1.id(), ac.view().seq()); return adjust( - ac.view(), - keylet, - args(A2.id(), 0, [&](Adjustments& sample) { - sample.assetsMaximum = 1; - })); + ac.view(), keylet, args(A2.id(), 0, [&](Adjustments& sample) { sample.assetsMaximum = 1; })); }, XRPAmount{}, STTx{ttVAULT_SET, [](STObject& tx) {}}, @@ -2814,11 +2797,7 @@ class Invariants_test : public beast::unit_test::suite [&](Account const& A1, Account const& A2, ApplyContext& ac) { auto const keylet = keylet::vault(A1.id(), ac.view().seq()); return adjust( - ac.view(), - keylet, - args(A2.id(), 0, [&](Adjustments& sample) { - sample.assetsMaximum = -1; - })); + ac.view(), keylet, args(A2.id(), 0, [&](Adjustments& sample) { sample.assetsMaximum = -1; })); }, XRPAmount{}, STTx{ttVAULT_SET, [](STObject& tx) {}}, @@ -2836,8 +2815,7 @@ class Invariants_test : public beast::unit_test::suite if (!sleVault) return false; ac.view().update(sleVault); - auto sleShares = ac.view().peek( - keylet::mptIssuance((*sleVault)[sfShareMPTID])); + auto sleShares = ac.view().peek(keylet::mptIssuance((*sleVault)[sfShareMPTID])); if (!sleShares) return false; (*sleShares)[sfOutstandingAmount] = 0; @@ -2857,15 +2835,13 @@ class Invariants_test : public beast::unit_test::suite auto sleVault = ac.view().peek(keylet); if (!sleVault) return false; - auto sleShares = ac.view().peek( - keylet::mptIssuance((*sleVault)[sfShareMPTID])); + auto sleShares = ac.view().peek(keylet::mptIssuance((*sleVault)[sfShareMPTID])); if (!sleShares) return false; (*sleShares)[sfMaximumAmount] = 10; ac.view().update(sleShares); - return adjust( - ac.view(), keylet, args(A2.id(), 10, [](Adjustments&) {})); + return adjust(ac.view(), keylet, args(A2.id(), 10, [](Adjustments&) {})); }, XRPAmount{}, STTx{ttVAULT_DEPOSIT, [](STObject&) {}}, @@ -2877,14 +2853,12 @@ class Invariants_test : public beast::unit_test::suite {"updated shares must not exceed maximum"}, [&](Account const& A1, Account const& A2, ApplyContext& ac) { auto const keylet = keylet::vault(A1.id(), ac.view().seq()); - adjust( - ac.view(), keylet, args(A2.id(), 10, [](Adjustments&) {})); + adjust(ac.view(), keylet, args(A2.id(), 10, [](Adjustments&) {})); auto sleVault = ac.view().peek(keylet); if (!sleVault) return false; - auto sleShares = ac.view().peek( - keylet::mptIssuance((*sleVault)[sfShareMPTID])); + auto sleShares = ac.view().peek(keylet::mptIssuance((*sleVault)[sfShareMPTID])); if (!sleShares) return false; (*sleShares)[sfOutstandingAmount] = maxMPTokenAmount + 1; @@ -2918,8 +2892,7 @@ class Invariants_test : public beast::unit_test::suite {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, [&](Account const& A1, Account const& A2, Env& env) { Vault vault{env}; - auto [tx, keylet] = - vault.create({.owner = A1, .asset = xrpIssue()}); + auto [tx, keylet] = vault.create({.owner = A1, .asset = xrpIssue()}); env(tx); return true; }); @@ -2945,8 +2918,7 @@ class Invariants_test : public beast::unit_test::suite {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, [&](Account const& A1, Account const& A2, Env& env) { Vault vault{env}; - auto [tx, keylet] = - vault.create({.owner = A1, .asset = xrpIssue()}); + auto [tx, keylet] = vault.create({.owner = A1, .asset = xrpIssue()}); env(tx); return true; }); @@ -2973,8 +2945,7 @@ class Invariants_test : public beast::unit_test::suite {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, [&](Account const& A1, Account const& A2, Env& env) { Vault vault{env}; - auto [tx, keylet] = - vault.create({.owner = A1, .asset = xrpIssue()}); + auto [tx, keylet] = vault.create({.owner = A1, .asset = xrpIssue()}); env(tx); return true; }); @@ -2989,8 +2960,7 @@ class Invariants_test : public beast::unit_test::suite auto sleVault = ac.view().peek(keylet); if (!sleVault) return false; - auto sleShares = ac.view().peek( - keylet::mptIssuance((*sleVault)[sfShareMPTID])); + auto sleShares = ac.view().peek(keylet::mptIssuance((*sleVault)[sfShareMPTID])); if (!sleShares) return false; ac.view().update(sleVault); @@ -3003,8 +2973,7 @@ class Invariants_test : public beast::unit_test::suite {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, [&](Account const& A1, Account const& A2, Env& env) { Vault vault{env}; - auto [tx, keylet] = - vault.create({.owner = A1, .asset = xrpIssue()}); + auto [tx, keylet] = vault.create({.owner = A1, .asset = xrpIssue()}); env(tx); return true; }); @@ -3028,8 +2997,7 @@ class Invariants_test : public beast::unit_test::suite {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, [&](Account const& A1, Account const& A2, Env& env) { Vault vault{env}; - auto [tx, keylet] = - vault.create({.owner = A1, .asset = xrpIssue()}); + auto [tx, keylet] = vault.create({.owner = A1, .asset = xrpIssue()}); env(tx); return true; }); @@ -3044,8 +3012,7 @@ class Invariants_test : public beast::unit_test::suite auto sleVault = ac.view().peek(keylet); if (!sleVault) return false; - auto sleShares = ac.view().peek( - keylet::mptIssuance((*sleVault)[sfShareMPTID])); + auto sleShares = ac.view().peek(keylet::mptIssuance((*sleVault)[sfShareMPTID])); if (!sleShares) return false; ac.view().update(sleVault); @@ -3058,15 +3025,13 @@ class Invariants_test : public beast::unit_test::suite {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, [&](Account const& A1, Account const& A2, Env& env) { Vault vault{env}; - auto [tx, keylet] = - vault.create({.owner = A1, .asset = xrpIssue()}); + auto [tx, keylet] = vault.create({.owner = A1, .asset = xrpIssue()}); env(tx); return true; }); doInvariantCheck( - {"vault created by a wrong transaction type", - "account root created illegally"}, + {"vault created by a wrong transaction type", "account root created illegally"}, [&](Account const& A1, Account const& A2, ApplyContext& ac) { // The code below will create a valid vault with (almost) all // the invariants holding. Except one: it is created by the @@ -3074,17 +3039,13 @@ class Invariants_test : public beast::unit_test::suite auto const sequence = ac.view().seq(); auto const vaultKeylet = keylet::vault(A1.id(), sequence); auto sleVault = std::make_shared(vaultKeylet); - auto const vaultPage = ac.view().dirInsert( - keylet::ownerDir(A1.id()), - sleVault->key(), - describeOwnerDir(A1.id())); + auto const vaultPage = + ac.view().dirInsert(keylet::ownerDir(A1.id()), sleVault->key(), describeOwnerDir(A1.id())); sleVault->setFieldU64(sfOwnerNode, *vaultPage); - auto pseudoId = - pseudoAccountAddress(ac.view(), vaultKeylet.key); + auto pseudoId = pseudoAccountAddress(ac.view(), vaultKeylet.key); // Create pseudo-account. - auto sleAccount = - std::make_shared(keylet::account(pseudoId)); + auto sleAccount = std::make_shared(keylet::account(pseudoId)); sleAccount->setAccountID(sfAccount, pseudoId); sleAccount->setFieldAmount(sfBalance, STAmount{}); std::uint32_t const seqno = // @@ -3092,19 +3053,15 @@ class Invariants_test : public beast::unit_test::suite ? 0 // : sequence; sleAccount->setFieldU32(sfSequence, seqno); - sleAccount->setFieldU32( - sfFlags, - lsfDisableMaster | lsfDefaultRipple | lsfDepositAuth); + sleAccount->setFieldU32(sfFlags, lsfDisableMaster | lsfDefaultRipple | lsfDepositAuth); sleAccount->setFieldH256(sfVaultID, vaultKeylet.key); ac.view().insert(sleAccount); auto const sharesMptId = makeMptID(sequence, pseudoId); auto const sharesKeylet = keylet::mptIssuance(sharesMptId); auto sleShares = std::make_shared(sharesKeylet); - auto const sharesPage = ac.view().dirInsert( - keylet::ownerDir(pseudoId), - sharesKeylet, - describeOwnerDir(pseudoId)); + auto const sharesPage = + ac.view().dirInsert(keylet::ownerDir(pseudoId), sharesKeylet, describeOwnerDir(pseudoId)); sleShares->setFieldU64(sfOwnerNode, *sharesPage); sleShares->at(sfFlags) = 0; @@ -3120,8 +3077,7 @@ class Invariants_test : public beast::unit_test::suite sleVault->at(sfAssetsAvailable) = Number(0); sleVault->at(sfLossUnrealized) = Number(0); sleVault->at(sfShareMPTID) = sharesMptId; - sleVault->at(sfWithdrawalPolicy) = - vaultStrategyFirstComeFirstServe; + sleVault->at(sfWithdrawalPolicy) = vaultStrategyFirstComeFirstServe; ac.view().insert(sleVault); ac.view().insert(sleShares); @@ -3138,17 +3094,13 @@ class Invariants_test : public beast::unit_test::suite auto const sequence = ac.view().seq(); auto const vaultKeylet = keylet::vault(A1.id(), sequence); auto sleVault = std::make_shared(vaultKeylet); - auto const vaultPage = ac.view().dirInsert( - keylet::ownerDir(A1.id()), - sleVault->key(), - describeOwnerDir(A1.id())); + auto const vaultPage = + ac.view().dirInsert(keylet::ownerDir(A1.id()), sleVault->key(), describeOwnerDir(A1.id())); sleVault->setFieldU64(sfOwnerNode, *vaultPage); - auto pseudoId = - pseudoAccountAddress(ac.view(), vaultKeylet.key); + auto pseudoId = pseudoAccountAddress(ac.view(), vaultKeylet.key); // Create pseudo-account. - auto sleAccount = - std::make_shared(keylet::account(pseudoId)); + auto sleAccount = std::make_shared(keylet::account(pseudoId)); sleAccount->setAccountID(sfAccount, pseudoId); sleAccount->setFieldAmount(sfBalance, STAmount{}); std::uint32_t const seqno = // @@ -3156,9 +3108,7 @@ class Invariants_test : public beast::unit_test::suite ? 0 // : sequence; sleAccount->setFieldU32(sfSequence, seqno); - sleAccount->setFieldU32( - sfFlags, - lsfDisableMaster | lsfDefaultRipple | lsfDepositAuth); + sleAccount->setFieldU32(sfFlags, lsfDisableMaster | lsfDefaultRipple | lsfDepositAuth); // sleAccount->setFieldH256(sfVaultID, vaultKeylet.key); // Setting wrong vault key sleAccount->setFieldH256(sfVaultID, uint256(42)); @@ -3167,10 +3117,8 @@ class Invariants_test : public beast::unit_test::suite auto const sharesMptId = makeMptID(sequence, pseudoId); auto const sharesKeylet = keylet::mptIssuance(sharesMptId); auto sleShares = std::make_shared(sharesKeylet); - auto const sharesPage = ac.view().dirInsert( - keylet::ownerDir(pseudoId), - sharesKeylet, - describeOwnerDir(pseudoId)); + auto const sharesPage = + ac.view().dirInsert(keylet::ownerDir(pseudoId), sharesKeylet, describeOwnerDir(pseudoId)); sleShares->setFieldU64(sfOwnerNode, *sharesPage); sleShares->at(sfFlags) = 0; @@ -3188,8 +3136,7 @@ class Invariants_test : public beast::unit_test::suite sleVault->at(sfAssetsAvailable) = Number(0); sleVault->at(sfLossUnrealized) = Number(0); sleVault->at(sfShareMPTID) = sharesMptId; - sleVault->at(sfWithdrawalPolicy) = - vaultStrategyFirstComeFirstServe; + sleVault->at(sfWithdrawalPolicy) = vaultStrategyFirstComeFirstServe; ac.view().insert(sleVault); ac.view().insert(sleShares); @@ -3200,25 +3147,20 @@ class Invariants_test : public beast::unit_test::suite {tecINVARIANT_FAILED, tefINVARIANT_FAILED}); doInvariantCheck( - {"shares issuer and vault pseudo-account must be the same", - "shares issuer must exist"}, + {"shares issuer and vault pseudo-account must be the same", "shares issuer must exist"}, [&](Account const& A1, Account const& A2, ApplyContext& ac) { auto const sequence = ac.view().seq(); auto const vaultKeylet = keylet::vault(A1.id(), sequence); auto sleVault = std::make_shared(vaultKeylet); - auto const vaultPage = ac.view().dirInsert( - keylet::ownerDir(A1.id()), - sleVault->key(), - describeOwnerDir(A1.id())); + auto const vaultPage = + ac.view().dirInsert(keylet::ownerDir(A1.id()), sleVault->key(), describeOwnerDir(A1.id())); sleVault->setFieldU64(sfOwnerNode, *vaultPage); auto const sharesMptId = makeMptID(sequence, A2.id()); auto const sharesKeylet = keylet::mptIssuance(sharesMptId); auto sleShares = std::make_shared(sharesKeylet); - auto const sharesPage = ac.view().dirInsert( - keylet::ownerDir(A2.id()), - sharesKeylet, - describeOwnerDir(A2.id())); + auto const sharesPage = + ac.view().dirInsert(keylet::ownerDir(A2.id()), sharesKeylet, describeOwnerDir(A2.id())); sleShares->setFieldU64(sfOwnerNode, *sharesPage); sleShares->at(sfFlags) = 0; @@ -3235,8 +3177,7 @@ class Invariants_test : public beast::unit_test::suite sleVault->at(sfAssetsAvailable) = Number(0); sleVault->at(sfLossUnrealized) = Number(0); sleVault->at(sfShareMPTID) = sharesMptId; - sleVault->at(sfWithdrawalPolicy) = - vaultStrategyFirstComeFirstServe; + sleVault->at(sfWithdrawalPolicy) = vaultStrategyFirstComeFirstServe; ac.view().insert(sleVault); ac.view().insert(sleShares); @@ -3252,11 +3193,7 @@ class Invariants_test : public beast::unit_test::suite [&](Account const& A1, Account const& A2, ApplyContext& ac) { auto const keylet = keylet::vault(A1.id(), ac.view().seq()); return adjust( - ac.view(), - keylet, - args(A2.id(), 0, [](Adjustments& sample) { - sample.vaultAssets.reset(); - })); + ac.view(), keylet, args(A2.id(), 0, [](Adjustments& sample) { sample.vaultAssets.reset(); })); }, XRPAmount{}, STTx{ttVAULT_DEPOSIT, [](STObject&) {}}, @@ -3268,18 +3205,10 @@ class Invariants_test : public beast::unit_test::suite [&](Account const& A1, Account const& A2, ApplyContext& ac) { auto const keylet = keylet::vault(A1.id(), ac.view().seq()); return adjust( - ac.view(), - keylet, - args(A2.id(), 200, [&](Adjustments& sample) { - sample.assetsMaximum = 1; - })); + ac.view(), keylet, args(A2.id(), 200, [&](Adjustments& sample) { sample.assetsMaximum = 1; })); }, XRPAmount{}, - STTx{ - ttVAULT_DEPOSIT, - [](STObject& tx) { - tx.setFieldAmount(sfAmount, XRPAmount(200)); - }}, + STTx{ttVAULT_DEPOSIT, [](STObject& tx) { tx.setFieldAmount(sfAmount, XRPAmount(200)); }}, {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, precloseXrp, TxAccount::A2); @@ -3289,8 +3218,7 @@ class Invariants_test : public beast::unit_test::suite // The operation makes no sense, but the defensive check in // ValidVault::finalize is otherwise impossible to trigger. doInvariantCheck( - {"deposit must increase vault balance", - "deposit must change depositor balance"}, + {"deposit must increase vault balance", "deposit must change depositor balance"}, [&](Account const& A1, Account const& A2, ApplyContext& ac) { auto const keylet = keylet::vault(A1.id(), ac.view().seq()); @@ -3301,12 +3229,9 @@ class Invariants_test : public beast::unit_test::suite (*sleA4)[sfBalance] = *(*sleA4)[sfBalance] + 10; ac.view().update(sleA4); - return adjust( - ac.view(), - keylet, - args(A3.id(), -10, [&](Adjustments& sample) { - sample.accountAssets->amount = -100; - })); + return adjust(ac.view(), keylet, args(A3.id(), -10, [&](Adjustments& sample) { + sample.accountAssets->amount = -100; + })); }, XRPAmount{100}, STTx{ @@ -3334,18 +3259,13 @@ class Invariants_test : public beast::unit_test::suite (*sleA3)[sfBalance] = *(*sleA3)[sfBalance] + 10; ac.view().update(sleA3); - return adjust( - ac.view(), - keylet, - args(A2.id(), 10, [&](Adjustments& sample) { - sample.vaultAssets = -20; - sample.accountAssets->amount = 10; - })); + return adjust(ac.view(), keylet, args(A2.id(), 10, [&](Adjustments& sample) { + sample.vaultAssets = -20; + sample.accountAssets->amount = 10; + })); }, XRPAmount{}, - STTx{ - ttVAULT_DEPOSIT, - [](STObject& tx) { tx[sfAmount] = XRPAmount(10); }}, + STTx{ttVAULT_DEPOSIT, [](STObject& tx) { tx[sfAmount] = XRPAmount(10); }}, {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, precloseXrp, TxAccount::A2); @@ -3362,17 +3282,12 @@ class Invariants_test : public beast::unit_test::suite (*sleA3)[sfBalance] = *(*sleA3)[sfBalance] - 10; ac.view().update(sleA3); - return adjust( - ac.view(), - keylet, - args(A2.id(), 10, [&](Adjustments& sample) { - sample.accountAssets->amount = 0; - })); + return adjust(ac.view(), keylet, args(A2.id(), 10, [&](Adjustments& sample) { + sample.accountAssets->amount = 0; + })); }, XRPAmount{}, - STTx{ - ttVAULT_DEPOSIT, - [](STObject& tx) { tx[sfAmount] = XRPAmount(10); }}, + STTx{ttVAULT_DEPOSIT, [](STObject& tx) { tx[sfAmount] = XRPAmount(10); }}, {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, precloseXrp, TxAccount::A2); @@ -3382,16 +3297,10 @@ class Invariants_test : public beast::unit_test::suite [&](Account const& A1, Account const& A2, ApplyContext& ac) { auto const keylet = keylet::vault(A1.id(), ac.view().seq()); return adjust( - ac.view(), - keylet, - args(A2.id(), 10, [&](Adjustments& sample) { - sample.accountShares.reset(); - })); + ac.view(), keylet, args(A2.id(), 10, [&](Adjustments& sample) { sample.accountShares.reset(); })); }, XRPAmount{}, - STTx{ - ttVAULT_DEPOSIT, - [](STObject& tx) { tx[sfAmount] = XRPAmount(10); }}, + STTx{ttVAULT_DEPOSIT, [](STObject& tx) { tx[sfAmount] = XRPAmount(10); }}, {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, precloseXrp, TxAccount::A2); @@ -3402,16 +3311,10 @@ class Invariants_test : public beast::unit_test::suite auto const keylet = keylet::vault(A1.id(), ac.view().seq()); return adjust( - ac.view(), - keylet, - args(A2.id(), 10, [](Adjustments& sample) { - sample.sharesTotal = 0; - })); + ac.view(), keylet, args(A2.id(), 10, [](Adjustments& sample) { sample.sharesTotal = 0; })); }, XRPAmount{}, - STTx{ - ttVAULT_DEPOSIT, - [](STObject& tx) { tx[sfAmount] = XRPAmount(10); }}, + STTx{ttVAULT_DEPOSIT, [](STObject& tx) { tx[sfAmount] = XRPAmount(10); }}, {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, precloseXrp, TxAccount::A2); @@ -3423,18 +3326,13 @@ class Invariants_test : public beast::unit_test::suite "amount"}, [&](Account const& A1, Account const& A2, ApplyContext& ac) { auto const keylet = keylet::vault(A1.id(), ac.view().seq()); - return adjust( - ac.view(), - keylet, - args(A2.id(), 10, [&](Adjustments& sample) { - sample.accountShares->amount = -5; - sample.sharesTotal = -10; - })); + return adjust(ac.view(), keylet, args(A2.id(), 10, [&](Adjustments& sample) { + sample.accountShares->amount = -5; + sample.sharesTotal = -10; + })); }, XRPAmount{}, - STTx{ - ttVAULT_DEPOSIT, - [](STObject& tx) { tx[sfAmount] = XRPAmount(5); }}, + STTx{ttVAULT_DEPOSIT, [](STObject& tx) { tx[sfAmount] = XRPAmount(5); }}, {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, precloseXrp, TxAccount::A2); @@ -3448,11 +3346,7 @@ class Invariants_test : public beast::unit_test::suite auto const keylet = keylet::vault(A1.id(), ac.view().seq()); return adjust( - ac.view(), - keylet, - args(A2.id(), 10, [&](Adjustments& sample) { - sample.assetsTotal = 11; - })); + ac.view(), keylet, args(A2.id(), 10, [&](Adjustments& sample) { sample.assetsTotal = 11; })); }, XRPAmount{2000}, STTx{ @@ -3467,22 +3361,16 @@ class Invariants_test : public beast::unit_test::suite TxAccount::A2); doInvariantCheck( - {"deposit and assets outstanding must add up", - "deposit and assets available must add up"}, + {"deposit and assets outstanding must add up", "deposit and assets available must add up"}, [&](Account const& A1, Account const& A2, ApplyContext& ac) { auto const keylet = keylet::vault(A1.id(), ac.view().seq()); - return adjust( - ac.view(), - keylet, - args(A2.id(), 10, [&](Adjustments& sample) { - sample.assetsTotal = 7; - sample.assetsAvailable = 7; - })); + return adjust(ac.view(), keylet, args(A2.id(), 10, [&](Adjustments& sample) { + sample.assetsTotal = 7; + sample.assetsAvailable = 7; + })); }, XRPAmount{}, - STTx{ - ttVAULT_DEPOSIT, - [](STObject& tx) { tx[sfAmount] = XRPAmount(10); }}, + STTx{ttVAULT_DEPOSIT, [](STObject& tx) { tx[sfAmount] = XRPAmount(10); }}, {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, precloseXrp, TxAccount::A2); @@ -3493,11 +3381,7 @@ class Invariants_test : public beast::unit_test::suite [&](Account const& A1, Account const& A2, ApplyContext& ac) { auto const keylet = keylet::vault(A1.id(), ac.view().seq()); return adjust( - ac.view(), - keylet, - args(A2.id(), 0, [](Adjustments& sample) { - sample.vaultAssets.reset(); - })); + ac.view(), keylet, args(A2.id(), 0, [](Adjustments& sample) { sample.vaultAssets.reset(); })); }, XRPAmount{}, STTx{ttVAULT_WITHDRAW, [](STObject&) {}}, @@ -3520,12 +3404,9 @@ class Invariants_test : public beast::unit_test::suite (*sleA4)[sfBalance] = *(*sleA4)[sfBalance] + 10; ac.view().update(sleA4); - return adjust( - ac.view(), - keylet, - args(A3.id(), -10, [&](Adjustments& sample) { - sample.accountAssets->amount = -100; - })); + return adjust(ac.view(), keylet, args(A3.id(), -10, [&](Adjustments& sample) { + sample.accountAssets->amount = -100; + })); }, XRPAmount{100}, STTx{ @@ -3556,13 +3437,10 @@ class Invariants_test : public beast::unit_test::suite (*sleA3)[sfBalance] = *(*sleA3)[sfBalance] + 10; ac.view().update(sleA3); - return adjust( - ac.view(), - keylet, - args(A2.id(), -10, [&](Adjustments& sample) { - sample.vaultAssets = 10; - sample.accountAssets->amount = -20; - })); + return adjust(ac.view(), keylet, args(A2.id(), -10, [&](Adjustments& sample) { + sample.vaultAssets = 10; + sample.accountAssets->amount = -20; + })); }, XRPAmount{}, STTx{ttVAULT_WITHDRAW, [](STObject&) {}}, @@ -3575,11 +3453,7 @@ class Invariants_test : public beast::unit_test::suite [&](Account const& A1, Account const& A2, ApplyContext& ac) { auto const keylet = keylet::vault(A1.id(), ac.view().seq()); if (!adjust( - ac.view(), - keylet, - args(A2.id(), -10, [&](Adjustments& sample) { - *sample.vaultAssets -= 5; - }))) + ac.view(), keylet, args(A2.id(), -10, [&](Adjustments& sample) { *sample.vaultAssets -= 5; }))) return false; auto sleA3 = ac.view().peek(keylet::account(A3.id())); if (!sleA3) @@ -3589,9 +3463,7 @@ class Invariants_test : public beast::unit_test::suite return true; }, XRPAmount{}, - STTx{ - ttVAULT_WITHDRAW, - [&](STObject& tx) { tx.setAccountID(sfDestination, A3.id()); }}, + STTx{ttVAULT_WITHDRAW, [&](STObject& tx) { tx.setAccountID(sfDestination, A3.id()); }}, {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, precloseXrp, TxAccount::A2); @@ -3601,11 +3473,7 @@ class Invariants_test : public beast::unit_test::suite [&](Account const& A1, Account const& A2, ApplyContext& ac) { auto const keylet = keylet::vault(A1.id(), ac.view().seq()); return adjust( - ac.view(), - keylet, - args(A2.id(), -10, [&](Adjustments& sample) { - sample.accountShares.reset(); - })); + ac.view(), keylet, args(A2.id(), -10, [&](Adjustments& sample) { sample.accountShares.reset(); })); }, XRPAmount{}, STTx{ttVAULT_WITHDRAW, [](STObject&) {}}, @@ -3618,11 +3486,7 @@ class Invariants_test : public beast::unit_test::suite [&](Account const& A1, Account const& A2, ApplyContext& ac) { auto const keylet = keylet::vault(A1.id(), ac.view().seq()); return adjust( - ac.view(), - keylet, - args(A2.id(), -10, [](Adjustments& sample) { - sample.sharesTotal = 0; - })); + ac.view(), keylet, args(A2.id(), -10, [](Adjustments& sample) { sample.sharesTotal = 0; })); }, XRPAmount{}, STTx{ttVAULT_WITHDRAW, [](STObject&) {}}, @@ -3636,13 +3500,10 @@ class Invariants_test : public beast::unit_test::suite "amount"}, [&](Account const& A1, Account const& A2, ApplyContext& ac) { auto const keylet = keylet::vault(A1.id(), ac.view().seq()); - return adjust( - ac.view(), - keylet, - args(A2.id(), -10, [&](Adjustments& sample) { - sample.accountShares->amount = 5; - sample.sharesTotal = 10; - })); + return adjust(ac.view(), keylet, args(A2.id(), -10, [&](Adjustments& sample) { + sample.accountShares->amount = 5; + sample.sharesTotal = 10; + })); }, XRPAmount{}, STTx{ttVAULT_WITHDRAW, [](STObject&) {}}, @@ -3651,17 +3512,13 @@ class Invariants_test : public beast::unit_test::suite TxAccount::A2); doInvariantCheck( - {"withdrawal and assets outstanding must add up", - "withdrawal and assets available must add up"}, + {"withdrawal and assets outstanding must add up", "withdrawal and assets available must add up"}, [&](Account const& A1, Account const& A2, ApplyContext& ac) { auto const keylet = keylet::vault(A1.id(), ac.view().seq()); - return adjust( - ac.view(), - keylet, - args(A2.id(), -10, [&](Adjustments& sample) { - sample.assetsTotal = -15; - sample.assetsAvailable = -15; - })); + return adjust(ac.view(), keylet, args(A2.id(), -10, [&](Adjustments& sample) { + sample.assetsTotal = -15; + sample.assetsAvailable = -15; + })); }, XRPAmount{}, STTx{ttVAULT_WITHDRAW, [](STObject&) {}}, @@ -3678,11 +3535,7 @@ class Invariants_test : public beast::unit_test::suite auto const keylet = keylet::vault(A1.id(), ac.view().seq()); return adjust( - ac.view(), - keylet, - args(A2.id(), -10, [&](Adjustments& sample) { - sample.assetsTotal = -7; - })); + ac.view(), keylet, args(A2.id(), -10, [&](Adjustments& sample) { sample.assetsTotal = -7; })); }, XRPAmount{2000}, STTx{ @@ -3696,8 +3549,7 @@ class Invariants_test : public beast::unit_test::suite precloseXrp, TxAccount::A2); - auto const precloseMpt = - [&](Account const& A1, Account const& A2, Env& env) -> bool { + auto const precloseMpt = [&](Account const& A1, Account const& A2, Env& env) -> bool { env.fund(XRP(1000), A3, A4); // Create MPT asset @@ -3737,12 +3589,9 @@ class Invariants_test : public beast::unit_test::suite Vault vault{env}; auto [tx, keylet] = vault.create({.owner = A1, .asset = asset}); env(tx); - env(vault.deposit( - {.depositor = A1, .id = keylet.key, .amount = asset(10)})); - env(vault.deposit( - {.depositor = A2, .id = keylet.key, .amount = asset(10)})); - env(vault.deposit( - {.depositor = A4, .id = keylet.key, .amount = asset(10)})); + env(vault.deposit({.depositor = A1, .id = keylet.key, .amount = asset(10)})); + env(vault.deposit({.depositor = A2, .id = keylet.key, .amount = asset(10)})); + env(vault.deposit({.depositor = A4, .id = keylet.key, .amount = asset(10)})); return true; }; @@ -3752,17 +3601,12 @@ class Invariants_test : public beast::unit_test::suite "amount"}, [&](Account const& A1, Account const& A2, ApplyContext& ac) { auto const keylet = keylet::vault(A1.id(), ac.view().seq() - 2); - return adjust( - ac.view(), - keylet, - args(A2.id(), -10, [&](Adjustments& sample) { - sample.accountShares->amount = 5; - })); + return adjust(ac.view(), keylet, args(A2.id(), -10, [&](Adjustments& sample) { + sample.accountShares->amount = 5; + })); }, XRPAmount{}, - STTx{ - ttVAULT_WITHDRAW, - [&](STObject& tx) { tx[sfAccount] = A3.id(); }}, + STTx{ttVAULT_WITHDRAW, [&](STObject& tx) { tx[sfAccount] = A3.id(); }}, {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, precloseMpt, TxAccount::A2); @@ -3773,16 +3617,10 @@ class Invariants_test : public beast::unit_test::suite [&](Account const& A1, Account const& A2, ApplyContext& ac) { auto const keylet = keylet::vault(A1.id(), ac.view().seq() - 2); return adjust( - ac.view(), - keylet, - args(A2.id(), -1, [&](Adjustments& sample) { - sample.vaultAssets.reset(); - })); + ac.view(), keylet, args(A2.id(), -1, [&](Adjustments& sample) { sample.vaultAssets.reset(); })); }, XRPAmount{}, - STTx{ - ttVAULT_CLAWBACK, - [&](STObject& tx) { tx[sfAccount] = A3.id(); }}, + STTx{ttVAULT_CLAWBACK, [&](STObject& tx) { tx[sfAccount] = A3.id(); }}, {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, precloseMpt); @@ -3791,10 +3629,7 @@ class Invariants_test : public beast::unit_test::suite {"clawback may only be performed by the asset issuer"}, [&](Account const& A1, Account const& A2, ApplyContext& ac) { auto const keylet = keylet::vault(A1.id(), ac.view().seq()); - return adjust( - ac.view(), - keylet, - args(A2.id(), 0, [&](Adjustments& sample) {})); + return adjust(ac.view(), keylet, args(A2.id(), 0, [&](Adjustments& sample) {})); }, XRPAmount{}, STTx{ttVAULT_CLAWBACK, [](STObject&) {}}, @@ -3806,15 +3641,10 @@ class Invariants_test : public beast::unit_test::suite {"clawback may only be performed by the asset issuer"}, [&](Account const& A1, Account const& A2, ApplyContext& ac) { auto const keylet = keylet::vault(A1.id(), ac.view().seq() - 2); - return adjust( - ac.view(), - keylet, - args(A2.id(), 0, [&](Adjustments& sample) {})); + return adjust(ac.view(), keylet, args(A2.id(), 0, [&](Adjustments& sample) {})); }, XRPAmount{}, - STTx{ - ttVAULT_CLAWBACK, - [&](STObject& tx) { tx[sfAccount] = A4.id(); }}, + STTx{ttVAULT_CLAWBACK, [&](STObject& tx) { tx[sfAccount] = A4.id(); }}, {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, precloseMpt); @@ -3825,11 +3655,7 @@ class Invariants_test : public beast::unit_test::suite [&](Account const& A1, Account const& A2, ApplyContext& ac) { auto const keylet = keylet::vault(A1.id(), ac.view().seq() - 2); return adjust( - ac.view(), - keylet, - args(A4.id(), 10, [&](Adjustments& sample) { - sample.sharesTotal = 0; - })); + ac.view(), keylet, args(A4.id(), 10, [&](Adjustments& sample) { sample.sharesTotal = 0; })); }, XRPAmount{}, STTx{ @@ -3846,11 +3672,7 @@ class Invariants_test : public beast::unit_test::suite [&](Account const& A1, Account const& A2, ApplyContext& ac) { auto const keylet = keylet::vault(A1.id(), ac.view().seq() - 2); return adjust( - ac.view(), - keylet, - args(A4.id(), -10, [&](Adjustments& sample) { - sample.accountShares.reset(); - })); + ac.view(), keylet, args(A4.id(), -10, [&](Adjustments& sample) { sample.accountShares.reset(); })); }, XRPAmount{}, STTx{ @@ -3868,14 +3690,11 @@ class Invariants_test : public beast::unit_test::suite "clawback and assets available must add up"}, [&](Account const& A1, Account const& A2, ApplyContext& ac) { auto const keylet = keylet::vault(A1.id(), ac.view().seq() - 2); - return adjust( - ac.view(), - keylet, - args(A4.id(), -10, [&](Adjustments& sample) { - sample.accountShares->amount = -8; - sample.assetsTotal = -7; - sample.assetsAvailable = -7; - })); + return adjust(ac.view(), keylet, args(A4.id(), -10, [&](Adjustments& sample) { + sample.accountShares->amount = -8; + sample.assetsTotal = -7; + sample.assetsAvailable = -7; + })); }, XRPAmount{}, STTx{ @@ -3905,8 +3724,10 @@ public: testNoZeroEscrow(); testValidNewAccountRoot(); testNFTokenPageInvariants(); - testPermissionedDomainInvariants(); - testPermissionedDEX(); + testPermissionedDomainInvariants(defaultAmendments() | fixPermissionedDomainInvariant); + testPermissionedDomainInvariants(defaultAmendments() - fixPermissionedDomainInvariant); + testPermissionedDEX(defaultAmendments() | fixPermissionedDomainInvariant); + testPermissionedDEX(defaultAmendments() - fixPermissionedDomainInvariant); testNoModifiedUnmodifiableFields(); testValidPseudoAccounts(); testValidLoanBroker(); diff --git a/src/test/app/LPTokenTransfer_test.cpp b/src/test/app/LPTokenTransfer_test.cpp index b2a6f39ddf..055b72ebe6 100644 --- a/src/test/app/LPTokenTransfer_test.cpp +++ b/src/test/app/LPTokenTransfer_test.cpp @@ -18,18 +18,15 @@ class LPTokenTransfer_test : public jtx::AMMTest env.close(); AMM ammAlice(env, alice, USD(20'000), BTC(0.5)); - BEAST_EXPECT( - ammAlice.expectBalances(USD(20'000), BTC(0.5), IOUAmount{100, 0})); + BEAST_EXPECT(ammAlice.expectBalances(USD(20'000), BTC(0.5), IOUAmount{100, 0})); fund(env, gw, {carol}, {USD(4'000), BTC(1)}, Fund::Acct); ammAlice.deposit(carol, 10); - BEAST_EXPECT( - ammAlice.expectBalances(USD(22'000), BTC(0.55), IOUAmount{110, 0})); + BEAST_EXPECT(ammAlice.expectBalances(USD(22'000), BTC(0.55), IOUAmount{110, 0})); fund(env, gw, {bob}, {USD(4'000), BTC(1)}, Fund::Acct); ammAlice.deposit(bob, 10); - BEAST_EXPECT( - ammAlice.expectBalances(USD(24'000), BTC(0.60), IOUAmount{120, 0})); + BEAST_EXPECT(ammAlice.expectBalances(USD(24'000), BTC(0.60), IOUAmount{120, 0})); auto const lpIssue = ammAlice.lptIssue(); env.trust(STAmount{lpIssue, 500}, alice); @@ -49,8 +46,7 @@ class LPTokenTransfer_test : public jtx::AMMTest env.close(); // cannot transfer to an amm account - env(pay(carol, lpIssue.getIssuer(), STAmount{lpIssue, 5}), - ter(tecNO_PERMISSION)); + env(pay(carol, lpIssue.getIssuer(), STAmount{lpIssue, 5}), ter(tecNO_PERMISSION)); env.close(); if (features[fixFrozenLPTokenTransfer]) @@ -73,12 +69,7 @@ class LPTokenTransfer_test : public jtx::AMMTest using namespace jtx; Env env{*this, features}; - fund( - env, - gw, - {alice, bob, carol}, - {USD(10'000), EUR(10'000)}, - Fund::All); + fund(env, gw, {alice, bob, carol}, {USD(10'000), EUR(10'000)}, Fund::All); AMM ammAlice(env, alice, USD(10'000), EUR(10'000)); ammAlice.deposit(carol, 1'000); ammAlice.deposit(bob, 1'000); @@ -106,10 +97,7 @@ class LPTokenTransfer_test : public jtx::AMMTest { // with fixFrozenLPTokenTransfer, alice fails to consume carol's // offer since carol's USD is frozen - env(pay(alice, bob, STAmount{lpIssue, 10}), - txflags(tfPartialPayment), - sendmax(XRP(10)), - ter(tecPATH_DRY)); + env(pay(alice, bob, STAmount{lpIssue, 10}), txflags(tfPartialPayment), sendmax(XRP(10)), ter(tecPATH_DRY)); env.close(); BEAST_EXPECT(expectOffers(env, carol, 1)); @@ -118,9 +106,7 @@ class LPTokenTransfer_test : public jtx::AMMTest env.close(); // alice successfully consumes carol's offer - env(pay(alice, bob, STAmount{lpIssue, 10}), - txflags(tfPartialPayment), - sendmax(XRP(10))); + env(pay(alice, bob, STAmount{lpIssue, 10}), txflags(tfPartialPayment), sendmax(XRP(10))); env.close(); BEAST_EXPECT(expectOffers(env, carol, 0)); } @@ -128,9 +114,7 @@ class LPTokenTransfer_test : public jtx::AMMTest { // without fixFrozenLPTokenTransfer, alice can consume carol's offer // even when carol's USD is frozen - env(pay(alice, bob, STAmount{lpIssue, 10}), - txflags(tfPartialPayment), - sendmax(XRP(10))); + env(pay(alice, bob, STAmount{lpIssue, 10}), txflags(tfPartialPayment), sendmax(XRP(10))); env.close(); BEAST_EXPECT(expectOffers(env, carol, 0)); } @@ -143,8 +127,7 @@ class LPTokenTransfer_test : public jtx::AMMTest // even when carol's USD is frozen { // carol creates an offer to buy lptoken - env(offer(carol, STAmount{lpIssue, 10}, XRP(10)), - txflags(tfPassive)); + env(offer(carol, STAmount{lpIssue, 10}, XRP(10)), txflags(tfPassive)); env.close(); BEAST_EXPECT(expectOffers(env, carol, 1)); @@ -153,9 +136,7 @@ class LPTokenTransfer_test : public jtx::AMMTest env.close(); // alice successfully consumes carol's offer - env(pay(alice, bob, XRP(10)), - txflags(tfPartialPayment), - sendmax(STAmount{lpIssue, 10})); + env(pay(alice, bob, XRP(10)), txflags(tfPartialPayment), sendmax(STAmount{lpIssue, 10})); env.close(); BEAST_EXPECT(expectOffers(env, carol, 0)); } @@ -169,12 +150,7 @@ class LPTokenTransfer_test : public jtx::AMMTest using namespace jtx; Env env{*this, features}; - fund( - env, - gw, - {alice, bob, carol}, - {USD(10'000), EUR(10'000)}, - Fund::All); + fund(env, gw, {alice, bob, carol}, {USD(10'000), EUR(10'000)}, Fund::All); AMM ammAlice(env, alice, USD(10'000), EUR(10'000)); ammAlice.deposit(carol, 1'000); ammAlice.deposit(bob, 1'000); @@ -193,9 +169,7 @@ class LPTokenTransfer_test : public jtx::AMMTest // sell lptoken when one of the assets is frozen // carol can't create an offer to sell lptoken - env(offer(carol, XRP(10), STAmount{lpIssue, 10}), - txflags(tfPassive), - ter(tecUNFUNDED_OFFER)); + env(offer(carol, XRP(10), STAmount{lpIssue, 10}), txflags(tfPassive), ter(tecUNFUNDED_OFFER)); env.close(); BEAST_EXPECT(expectOffers(env, carol, 0)); @@ -204,16 +178,14 @@ class LPTokenTransfer_test : public jtx::AMMTest env.close(); // carol can create an offer to sell lptoken after USD is unfrozen - env(offer(carol, XRP(10), STAmount{lpIssue, 10}), - txflags(tfPassive)); + env(offer(carol, XRP(10), STAmount{lpIssue, 10}), txflags(tfPassive)); env.close(); BEAST_EXPECT(expectOffers(env, carol, 1)); } else { // without fixFrozenLPTokenTransfer, carol can create an offer - env(offer(carol, XRP(10), STAmount{lpIssue, 10}), - txflags(tfPassive)); + env(offer(carol, XRP(10), STAmount{lpIssue, 10}), txflags(tfPassive)); env.close(); BEAST_EXPECT(expectOffers(env, carol, 1)); } @@ -273,8 +245,7 @@ class LPTokenTransfer_test : public jtx::AMMTest BEAST_EXPECT( expectHolding(env, carol, STAmount{token2, 10'000'000}) && expectHolding(env, carol, STAmount{token1, 10'000'000})); - BEAST_EXPECT( - expectOffers(env, alice, 1) && expectOffers(env, carol, 0)); + BEAST_EXPECT(expectOffers(env, alice, 1) && expectOffers(env, carol, 0)); } else { @@ -286,8 +257,7 @@ class LPTokenTransfer_test : public jtx::AMMTest BEAST_EXPECT( expectHolding(env, carol, STAmount{token2, 10'000'100}) && expectHolding(env, carol, STAmount{token1, 9'999'900})); - BEAST_EXPECT( - expectOffers(env, alice, 0) && expectOffers(env, carol, 0)); + BEAST_EXPECT(expectOffers(env, alice, 0) && expectOffers(env, carol, 0)); } } @@ -299,12 +269,7 @@ class LPTokenTransfer_test : public jtx::AMMTest using namespace jtx; Env env{*this, features}; - fund( - env, - gw, - {alice, bob, carol}, - {USD(10'000), EUR(10'000)}, - Fund::All); + fund(env, gw, {alice, bob, carol}, {USD(10'000), EUR(10'000)}, Fund::All); AMM ammAlice(env, alice, USD(10'000), EUR(10'000)); ammAlice.deposit(carol, 1'000); ammAlice.deposit(bob, 1'000); @@ -323,8 +288,7 @@ class LPTokenTransfer_test : public jtx::AMMTest // with fixFrozenLPTokenTransfer enabled, bob fails to cash the check if (features[fixFrozenLPTokenTransfer]) - env(check::cash(bob, carolChkId, STAmount{lpIssue, 10}), - ter(tecPATH_PARTIAL)); + env(check::cash(bob, carolChkId, STAmount{lpIssue, 10}), ter(tecPATH_PARTIAL)); else env(check::cash(bob, carolChkId, STAmount{lpIssue, 10})); @@ -350,12 +314,7 @@ class LPTokenTransfer_test : public jtx::AMMTest Env env{*this, features}; // Setup AMM - fund( - env, - gw, - {alice, bob, carol}, - {USD(10'000), EUR(10'000)}, - Fund::All); + fund(env, gw, {alice, bob, carol}, {USD(10'000), EUR(10'000)}, Fund::All); AMM ammAlice(env, alice, USD(10'000), EUR(10'000)); ammAlice.deposit(carol, 1'000); ammAlice.deposit(bob, 1'000); @@ -369,8 +328,7 @@ class LPTokenTransfer_test : public jtx::AMMTest // bob creates a sell offer for lptoken uint256 const sellOfferIndex = keylet::nftoffer(bob, env.seq(bob)).key; - env(token::createOffer(bob, nftID, STAmount{lpIssue, 10}), - txflags(tfSellNFToken)); + env(token::createOffer(bob, nftID, STAmount{lpIssue, 10}), txflags(tfSellNFToken)); env.close(); // gateway freezes carol's USD @@ -386,8 +344,7 @@ class LPTokenTransfer_test : public jtx::AMMTest // carol fails to accept bob's offer with lptoken because carol's // USD is frozen - env(token::acceptSellOffer(carol, sellOfferIndex), - ter(tecINSUFFICIENT_FUNDS)); + env(token::acceptSellOffer(carol, sellOfferIndex), ter(tecINSUFFICIENT_FUNDS)); env.close(); // gateway unfreezes carol's USD @@ -398,15 +355,13 @@ class LPTokenTransfer_test : public jtx::AMMTest env(token::acceptSellOffer(carol, sellOfferIndex)); env.close(); - // gateway freezes bobs's USD + // gateway freezes bob's USD env(trust(gw, bob["USD"](0), tfSetFreeze)); env.close(); // bob fails to create a buy offer with lptoken for carol's nft // since bob's USD is frozen - env(token::createOffer(bob, nftID, STAmount{lpIssue, 10}), - token::owner(carol), - ter(tecUNFUNDED_OFFER)); + env(token::createOffer(bob, nftID, STAmount{lpIssue, 10}), token::owner(carol), ter(tecUNFUNDED_OFFER)); env.close(); // gateway unfreezes bob's USD @@ -414,8 +369,7 @@ class LPTokenTransfer_test : public jtx::AMMTest env.close(); // bob can now create a buy offer - env(token::createOffer(bob, nftID, STAmount{lpIssue, 10}), - token::owner(carol)); + env(token::createOffer(bob, nftID, STAmount{lpIssue, 10}), token::owner(carol)); env.close(); } else @@ -432,10 +386,8 @@ class LPTokenTransfer_test : public jtx::AMMTest env.close(); // bob creates a buy offer with lptoken despite bob's USD is frozen - uint256 const buyOfferIndex = - keylet::nftoffer(bob, env.seq(bob)).key; - env(token::createOffer(bob, nftID, STAmount{lpIssue, 10}), - token::owner(carol)); + uint256 const buyOfferIndex = keylet::nftoffer(bob, env.seq(bob)).key; + env(token::createOffer(bob, nftID, STAmount{lpIssue, 10}), token::owner(carol)); env.close(); // carol accepts bob's offer diff --git a/src/test/app/LedgerHistory_test.cpp b/src/test/app/LedgerHistory_test.cpp index b69203f1e0..eeca551f35 100644 --- a/src/test/app/LedgerHistory_test.cpp +++ b/src/test/app/LedgerHistory_test.cpp @@ -37,19 +37,14 @@ public: { assert(!stx); return std::make_shared( - create_genesis, - env.app().config(), - std::vector{}, - env.app().getNodeFamily()); + create_genesis, env.app().config(), std::vector{}, env.app().getNodeFamily()); } - auto res = std::make_shared( - *prev, prev->header().closeTime + closeOffset); + auto res = std::make_shared(*prev, prev->header().closeTime + closeOffset); if (stx) { OpenView accum(&*res); - applyTransaction( - env.app(), accum, *stx, false, tapNONE, env.journal); + applyTransaction(env.app(), accum, *stx, false, tapNONE, env.journal); accum.apply(*res); } res->updateSkipList(); @@ -61,10 +56,7 @@ public: res->unshare(); // Accept ledger - res->setAccepted( - res->header().closeTime, - res->header().closeTimeResolution, - true /* close time correct*/); + res->setAccepted(res->header().closeTime, res->header().closeTimeResolution, true /* close time correct*/); lh.insert(res, false); return res; } @@ -79,10 +71,7 @@ public: // No mismatch { bool found = false; - Env env{ - *this, - envconfig(), - std::make_unique("MISMATCH ", &found)}; + Env env{*this, envconfig(), std::make_unique("MISMATCH ", &found)}; LedgerHistory lh{beast::insight::NullCollector::New(), env.app()}; auto const genesis = makeLedger({}, env, lh, 0s); uint256 const dummyTxHash{1}; @@ -95,11 +84,7 @@ public: // Close time mismatch { bool found = false; - Env env{ - *this, - envconfig(), - std::make_unique( - "MISMATCH on close time", &found)}; + Env env{*this, envconfig(), std::make_unique("MISMATCH on close time", &found)}; LedgerHistory lh{beast::insight::NullCollector::New(), env.app()}; auto const genesis = makeLedger({}, env, lh, 0s); auto const ledgerA = makeLedger(genesis, env, lh, 4s); @@ -115,11 +100,7 @@ public: // Prior ledger mismatch { bool found = false; - Env env{ - *this, - envconfig(), - std::make_unique( - "MISMATCH on prior ledger", &found)}; + Env env{*this, envconfig(), std::make_unique("MISMATCH on prior ledger", &found)}; LedgerHistory lh{beast::insight::NullCollector::New(), env.app()}; auto const genesis = makeLedger({}, env, lh, 0s); auto const ledgerA = makeLedger(genesis, env, lh, 4s); @@ -138,14 +119,10 @@ public: // somehow generate different ledgers for (bool const txBug : {true, false}) { - std::string const msg = txBug - ? "MISMATCH with same consensus transaction set" - : "MISMATCH on consensus transaction set"; + std::string const msg = + txBug ? "MISMATCH with same consensus transaction set" : "MISMATCH on consensus transaction set"; bool found = false; - Env env{ - *this, - envconfig(), - std::make_unique(msg, &found)}; + Env env{*this, envconfig(), std::make_unique(msg, &found)}; LedgerHistory lh{beast::insight::NullCollector::New(), env.app()}; Account alice{"A1"}; @@ -153,12 +130,10 @@ public: env.fund(XRP(1000), alice, bob); env.close(); - auto const ledgerBase = - env.app().getLedgerMaster().getClosedLedger(); + auto const ledgerBase = env.app().getLedgerMaster().getClosedLedger(); JTx txAlice = env.jt(noop(alice)); - auto const ledgerA = - makeLedger(ledgerBase, env, lh, 4s, txAlice.stx); + auto const ledgerA = makeLedger(ledgerBase, env, lh, 4s, txAlice.stx); JTx txBob = env.jt(noop(bob)); auto const ledgerB = makeLedger(ledgerBase, env, lh, 4s, txBob.stx); @@ -166,10 +141,7 @@ public: lh.builtLedger(ledgerA, txAlice.stx->getTransactionID(), {}); // Simulate the bug by claiming ledgerB had the same consensus hash // as ledgerA, but somehow generated different ledgers - lh.validatedLedger( - ledgerB, - txBug ? txAlice.stx->getTransactionID() - : txBob.stx->getTransactionID()); + lh.validatedLedger(ledgerB, txBug ? txAlice.stx->getTransactionID() : txBob.stx->getTransactionID()); BEAST_EXPECT(found); } diff --git a/src/test/app/LedgerLoad_test.cpp b/src/test/app/LedgerLoad_test.cpp index d5c37d0404..b4e84a3123 100644 --- a/src/test/app/LedgerLoad_test.cpp +++ b/src/test/app/LedgerLoad_test.cpp @@ -21,7 +21,7 @@ class LedgerLoad_test : public beast::unit_test::suite std::unique_ptr cfg, std::string const& dbPath, std::string const& ledger, - Config::StartUpType type, + StartUpType type, std::optional trapTxHash) { cfg->START_LEDGER = ledger; @@ -69,8 +69,7 @@ class LedgerLoad_test : public beast::unit_test::suite } retval.ledger = env.rpc("ledger", "current", "full")[jss::result]; - BEAST_EXPECT( - retval.ledger[jss::ledger][jss::accountState].size() == 102); + BEAST_EXPECT(retval.ledger[jss::ledger][jss::accountState].size() == 102); retval.hashes = [&] { for (auto const& it : retval.ledger[jss::ledger][jss::accountState]) @@ -83,10 +82,7 @@ class LedgerLoad_test : public beast::unit_test::suite BEAST_EXPECT(retval.hashes.size() == 41); retval.trapTxHash = [&]() { - auto const txs = env.rpc( - "ledger", - std::to_string(41), - "tx")[jss::result][jss::ledger][jss::transactions]; + auto const txs = env.rpc("ledger", std::to_string(41), "tx")[jss::result][jss::ledger][jss::transactions]; BEAST_EXPECT(txs.isArray() && txs.size() > 0); uint256 tmp; BEAST_EXPECT(tmp.parseHex(txs[0u][jss::hash].asString())); @@ -109,18 +105,11 @@ class LedgerLoad_test : public beast::unit_test::suite // create a new env with the ledger file specified for startup Env env( *this, - envconfig( - ledgerConfig, - sd.dbPath, - sd.ledgerFile, - Config::LOAD_FILE, - std::nullopt), + envconfig(ledgerConfig, sd.dbPath, sd.ledgerFile, StartUpType::LOAD_FILE, std::nullopt), nullptr, beast::severities::kDisabled); auto jrb = env.rpc("ledger", "current", "full")[jss::result]; - BEAST_EXPECT( - sd.ledger[jss::ledger][jss::accountState].size() == - jrb[jss::ledger][jss::accountState].size()); + BEAST_EXPECT(sd.ledger[jss::ledger][jss::accountState].size() == jrb[jss::ledger][jss::accountState].size()); } void @@ -134,12 +123,7 @@ class LedgerLoad_test : public beast::unit_test::suite except([&] { Env env( *this, - envconfig( - ledgerConfig, - sd.dbPath, - "", - Config::LOAD_FILE, - std::nullopt), + envconfig(ledgerConfig, sd.dbPath, "", StartUpType::LOAD_FILE, std::nullopt), nullptr, beast::severities::kDisabled); }); @@ -148,25 +132,15 @@ class LedgerLoad_test : public beast::unit_test::suite except([&] { Env env( *this, - envconfig( - ledgerConfig, - sd.dbPath, - "badfile.json", - Config::LOAD_FILE, - std::nullopt), + envconfig(ledgerConfig, sd.dbPath, "badfile.json", StartUpType::LOAD_FILE, std::nullopt), nullptr, beast::severities::kDisabled); }); // make a corrupted version of the ledger file (last 10 bytes removed). boost::system::error_code ec; - auto ledgerFileCorrupt = - boost::filesystem::path{sd.dbPath} / "ledgerdata_bad.json"; - copy_file( - sd.ledgerFile, - ledgerFileCorrupt, - copy_options::overwrite_existing, - ec); + auto ledgerFileCorrupt = boost::filesystem::path{sd.dbPath} / "ledgerdata_bad.json"; + copy_file(sd.ledgerFile, ledgerFileCorrupt, copy_options::overwrite_existing, ec); if (!BEAST_EXPECTS(!ec, ec.message())) return; auto filesize = file_size(ledgerFileCorrupt, ec); @@ -179,12 +153,7 @@ class LedgerLoad_test : public beast::unit_test::suite except([&] { Env env( *this, - envconfig( - ledgerConfig, - sd.dbPath, - ledgerFileCorrupt.string(), - Config::LOAD_FILE, - std::nullopt), + envconfig(ledgerConfig, sd.dbPath, ledgerFileCorrupt.string(), StartUpType::LOAD_FILE, std::nullopt), nullptr, beast::severities::kDisabled); }); @@ -201,19 +170,12 @@ class LedgerLoad_test : public beast::unit_test::suite boost::erase_all(ledgerHash, "\""); Env env( *this, - envconfig( - ledgerConfig, - sd.dbPath, - ledgerHash, - Config::LOAD, - std::nullopt), + envconfig(ledgerConfig, sd.dbPath, ledgerHash, StartUpType::LOAD, std::nullopt), nullptr, beast::severities::kDisabled); auto jrb = env.rpc("ledger", "current", "full")[jss::result]; BEAST_EXPECT(jrb[jss::ledger][jss::accountState].size() == 98); - BEAST_EXPECT( - jrb[jss::ledger][jss::accountState].size() <= - sd.ledger[jss::ledger][jss::accountState].size()); + BEAST_EXPECT(jrb[jss::ledger][jss::accountState].size() <= sd.ledger[jss::ledger][jss::accountState].size()); } void @@ -227,12 +189,7 @@ class LedgerLoad_test : public beast::unit_test::suite boost::erase_all(ledgerHash, "\""); Env env( *this, - envconfig( - ledgerConfig, - sd.dbPath, - ledgerHash, - Config::REPLAY, - std::nullopt), + envconfig(ledgerConfig, sd.dbPath, ledgerHash, StartUpType::REPLAY, std::nullopt), nullptr, beast::severities::kDisabled); auto const jrb = env.rpc("ledger", "current", "full")[jss::result]; @@ -242,9 +199,7 @@ class LedgerLoad_test : public beast::unit_test::suite env.close(); auto const closed = env.rpc("ledger", "current", "full")[jss::result]; BEAST_EXPECT(closed[jss::ledger][jss::accountState].size() == 98); - BEAST_EXPECT( - closed[jss::ledger][jss::accountState].size() <= - sd.ledger[jss::ledger][jss::accountState].size()); + BEAST_EXPECT(closed[jss::ledger][jss::accountState].size() <= sd.ledger[jss::ledger][jss::accountState].size()); } void @@ -258,12 +213,7 @@ class LedgerLoad_test : public beast::unit_test::suite boost::erase_all(ledgerHash, "\""); Env env( *this, - envconfig( - ledgerConfig, - sd.dbPath, - ledgerHash, - Config::REPLAY, - sd.trapTxHash), + envconfig(ledgerConfig, sd.dbPath, ledgerHash, StartUpType::REPLAY, sd.trapTxHash), nullptr, beast::severities::kDisabled); auto const jrb = env.rpc("ledger", "current", "full")[jss::result]; @@ -273,9 +223,7 @@ class LedgerLoad_test : public beast::unit_test::suite env.close(); auto const closed = env.rpc("ledger", "current", "full")[jss::result]; BEAST_EXPECT(closed[jss::ledger][jss::accountState].size() == 98); - BEAST_EXPECT( - closed[jss::ledger][jss::accountState].size() <= - sd.ledger[jss::ledger][jss::accountState].size()); + BEAST_EXPECT(closed[jss::ledger][jss::accountState].size() <= sd.ledger[jss::ledger][jss::accountState].size()); } void @@ -293,12 +241,7 @@ class LedgerLoad_test : public beast::unit_test::suite // replay when trapTxHash is set to an invalid transaction Env env( *this, - envconfig( - ledgerConfig, - sd.dbPath, - ledgerHash, - Config::REPLAY, - ~sd.trapTxHash), + envconfig(ledgerConfig, sd.dbPath, ledgerHash, StartUpType::REPLAY, ~sd.trapTxHash), nullptr, beast::severities::kDisabled); BEAST_EXPECT(false); @@ -322,14 +265,11 @@ class LedgerLoad_test : public beast::unit_test::suite // create a new env with the ledger "latest" specified for startup Env env( *this, - envconfig( - ledgerConfig, sd.dbPath, "latest", Config::LOAD, std::nullopt), + envconfig(ledgerConfig, sd.dbPath, "latest", StartUpType::LOAD, std::nullopt), nullptr, beast::severities::kDisabled); auto jrb = env.rpc("ledger", "current", "full")[jss::result]; - BEAST_EXPECT( - sd.ledger[jss::ledger][jss::accountState].size() == - jrb[jss::ledger][jss::accountState].size()); + BEAST_EXPECT(sd.ledger[jss::ledger][jss::accountState].size() == jrb[jss::ledger][jss::accountState].size()); } void @@ -341,14 +281,11 @@ class LedgerLoad_test : public beast::unit_test::suite // create a new env with specific ledger index at startup Env env( *this, - envconfig( - ledgerConfig, sd.dbPath, "43", Config::LOAD, std::nullopt), + envconfig(ledgerConfig, sd.dbPath, "43", StartUpType::LOAD, std::nullopt), nullptr, beast::severities::kDisabled); auto jrb = env.rpc("ledger", "current", "full")[jss::result]; - BEAST_EXPECT( - sd.ledger[jss::ledger][jss::accountState].size() == - jrb[jss::ledger][jss::accountState].size()); + BEAST_EXPECT(sd.ledger[jss::ledger][jss::accountState].size() == jrb[jss::ledger][jss::accountState].size()); } public: diff --git a/src/test/app/LedgerMaster_test.cpp b/src/test/app/LedgerMaster_test.cpp index 59e02cbabb..eb346288c2 100644 --- a/src/test/app/LedgerMaster_test.cpp +++ b/src/test/app/LedgerMaster_test.cpp @@ -43,8 +43,7 @@ class LedgerMaster_test : public beast::unit_test::suite env(noop(alice)); txns.emplace_back(env.tx()); env.close(); - metas.emplace_back( - env.closed()->txRead(env.tx()->getTransactionID()).second); + metas.emplace_back(env.closed()->txRead(env.tx()->getTransactionID()).second); } // add last (empty) ledger env.close(); @@ -54,35 +53,30 @@ class LedgerMaster_test : public beast::unit_test::suite { std::uint32_t ledgerSeq = -1; std::uint32_t txnIndex = 0; - auto result = - env.app().getLedgerMaster().txnIdFromIndex(ledgerSeq, txnIndex); + auto result = env.app().getLedgerMaster().txnIdFromIndex(ledgerSeq, txnIndex); BEAST_EXPECT(!result); } // test not in ledger { uint32_t txnIndex = metas[0]->getFieldU32(sfTransactionIndex); - auto result = - env.app().getLedgerMaster().txnIdFromIndex(0, txnIndex); + auto result = env.app().getLedgerMaster().txnIdFromIndex(0, txnIndex); BEAST_EXPECT(!result); } // test empty ledger { - auto result = - env.app().getLedgerMaster().txnIdFromIndex(endLegSeq, 0); + auto result = env.app().getLedgerMaster().txnIdFromIndex(endLegSeq, 0); BEAST_EXPECT(!result); } // ended without result { uint32_t txnIndex = metas[0]->getFieldU32(sfTransactionIndex); - auto result = env.app().getLedgerMaster().txnIdFromIndex( - endLegSeq + 1, txnIndex); + auto result = env.app().getLedgerMaster().txnIdFromIndex(endLegSeq + 1, txnIndex); BEAST_EXPECT(!result); } // success (first tx) { uint32_t txnIndex = metas[0]->getFieldU32(sfTransactionIndex); - auto result = env.app().getLedgerMaster().txnIdFromIndex( - startLegSeq, txnIndex); + auto result = env.app().getLedgerMaster().txnIdFromIndex(startLegSeq, txnIndex); BEAST_EXPECT( *result == uint256("277F4FD89C20B92457FEF05FF63F6405563AD0563C73D967A29727" @@ -91,8 +85,7 @@ class LedgerMaster_test : public beast::unit_test::suite // success (second tx) { uint32_t txnIndex = metas[1]->getFieldU32(sfTransactionIndex); - auto result = env.app().getLedgerMaster().txnIdFromIndex( - startLegSeq + 1, txnIndex); + auto result = env.app().getLedgerMaster().txnIdFromIndex(startLegSeq + 1, txnIndex); BEAST_EXPECT( *result == uint256("293DF7335EBBAF4420D52E70ABF470EB4C5792CAEA2F91F76193C2" diff --git a/src/test/app/LedgerReplay_test.cpp b/src/test/app/LedgerReplay_test.cpp index beb27817a1..229cad21c9 100644 --- a/src/test/app/LedgerReplay_test.cpp +++ b/src/test/app/LedgerReplay_test.cpp @@ -39,14 +39,9 @@ struct LedgerReplay_test : public beast::unit_test::suite LedgerMaster& ledgerMaster = env.app().getLedgerMaster(); auto const lastClosed = ledgerMaster.getClosedLedger(); - auto const lastClosedParent = - ledgerMaster.getLedgerByHash(lastClosed->header().parentHash); + auto const lastClosedParent = ledgerMaster.getLedgerByHash(lastClosed->header().parentHash); - auto const replayed = buildLedger( - LedgerReplay(lastClosedParent, lastClosed), - tapNONE, - env.app(), - env.journal); + auto const replayed = buildLedger(LedgerReplay(lastClosedParent, lastClosed), tapNONE, env.app(), env.journal); BEAST_EXPECT(replayed->header().hash == lastClosed->header().hash); } @@ -65,18 +60,14 @@ enum class InboundLedgersBehavior { class MagicInboundLedgers : public InboundLedgers { public: - MagicInboundLedgers( - LedgerMaster& ledgerSource, - LedgerMaster& ledgerSink, - InboundLedgersBehavior bhvr) + MagicInboundLedgers(LedgerMaster& ledgerSource, LedgerMaster& ledgerSink, InboundLedgersBehavior bhvr) : ledgerSource(ledgerSource), ledgerSink(ledgerSink), bhvr(bhvr) { } virtual ~MagicInboundLedgers() = default; virtual std::shared_ptr - acquire(uint256 const& hash, std::uint32_t seq, InboundLedger::Reason) - override + acquire(uint256 const& hash, std::uint32_t seq, InboundLedger::Reason) override { if (bhvr == InboundLedgersBehavior::DropAll) return {}; @@ -90,10 +81,7 @@ public: } virtual void - acquireAsync( - uint256 const& hash, - std::uint32_t seq, - InboundLedger::Reason reason) override + acquireAsync(uint256 const& hash, std::uint32_t seq, InboundLedger::Reason reason) override { } @@ -104,10 +92,7 @@ public: } virtual bool - gotLedgerData( - LedgerHash const& ledgerHash, - std::shared_ptr, - std::shared_ptr) override + gotLedgerData(LedgerHash const& ledgerHash, std::shared_ptr, std::shared_ptr) override { return false; } @@ -189,8 +174,7 @@ class TestPeer : public Peer { public: TestPeer(bool enableLedgerReplay) - : ledgerReplayEnabled_(enableLedgerReplay) - , nodePublicKey_(derivePublicKey(KeyType::ed25519, randomSecretKey())) + : ledgerReplayEnabled_(enableLedgerReplay), nodePublicKey_(derivePublicKey(KeyType::ed25519, randomSecretKey())) { } @@ -204,8 +188,7 @@ public: return {}; } void - charge(Resource::Charge const& fee, std::string const& context = {}) - override + charge(Resource::Charge const& fee, std::string const& context = {}) override { } id_t @@ -339,10 +322,7 @@ struct TestPeerSet : public PeerSet LedgerReplayMsgHandler& other, PeerSetBehavior bhvr, bool enableLedgerReplay) - : local(me) - , remote(other) - , dummyPeer(std::make_shared(enableLedgerReplay)) - , behavior(bhvr) + : local(me), remote(other), dummyPeer(std::make_shared(enableLedgerReplay)), behavior(bhvr) { } @@ -357,10 +337,8 @@ struct TestPeerSet : public PeerSet } void - sendRequest( - ::google::protobuf::Message const& msg, - protocol::MessageType type, - std::shared_ptr const& peer) override + sendRequest(::google::protobuf::Message const& msg, protocol::MessageType type, std::shared_ptr const& peer) + override { int dropRate = 0; if (behavior == PeerSetBehavior::Drop50) @@ -378,8 +356,7 @@ struct TestPeerSet : public PeerSet return; auto request = std::make_shared( dynamic_cast(msg)); - auto reply = std::make_shared( - remote.processProofPathRequest(request)); + auto reply = std::make_shared(remote.processProofPathRequest(request)); local.processProofPathResponse(reply); if (behavior == PeerSetBehavior::Repeat) local.processProofPathResponse(reply); @@ -390,8 +367,8 @@ struct TestPeerSet : public PeerSet return; auto request = std::make_shared( dynamic_cast(msg)); - auto reply = std::make_shared( - remote.processReplayDeltaRequest(request)); + auto reply = + std::make_shared(remote.processReplayDeltaRequest(request)); local.processReplayDeltaResponse(reply); if (behavior == PeerSetBehavior::Repeat) local.processReplayDeltaResponse(reply); @@ -426,18 +403,14 @@ public: LedgerReplayMsgHandler& other, PeerSetBehavior bhvr, PeerFeature peerFeature) - : local(me) - , remote(other) - , behavior(bhvr) - , enableLedgerReplay(peerFeature == PeerFeature::LedgerReplayEnabled) + : local(me), remote(other), behavior(bhvr), enableLedgerReplay(peerFeature == PeerFeature::LedgerReplayEnabled) { } std::unique_ptr build() override { - return std::make_unique( - local, remote, behavior, enableLedgerReplay); + return std::make_unique(local, remote, behavior, enableLedgerReplay); } private: @@ -484,8 +457,7 @@ struct LedgerServer auto fundedAccounts = accounts.size(); for (int i = 0; i < newAccounts; ++i) { - accounts.emplace_back( - "alice_" + std::to_string(fundedAccounts + i)); + accounts.emplace_back("alice_" + std::to_string(fundedAccounts + i)); env.fund(jtx::XRP(param.initAmount), accounts.back()); } env.close(); @@ -519,11 +491,9 @@ struct LedgerServer for (int i = 0; i < newTxes; ++i) { updateIdx(); - env.apply( - pay(accounts[fromIdx], + env(pay(accounts[fromIdx], accounts[toIdx], - jtx::drops(ledgerMaster.getClosedLedger()->fees().base) + - jtx::XRP(param.txAmount)), + jtx::drops(ledgerMaster.getClosedLedger()->fees().base) + jtx::XRP(param.txAmount)), jtx::seq(jtx::autofill), jtx::fee(jtx::autofill), jtx::sig(jtx::autofill)); @@ -577,20 +547,13 @@ public: : env(suite, jtx::envconfig(), nullptr, beast::severities::kDisabled) , app(env.app()) , ledgerMaster(env.app().getLedgerMaster()) - , inboundLedgers( - server.app.getLedgerMaster(), - ledgerMaster, - inboundBhvr) + , inboundLedgers(server.app.getLedgerMaster(), ledgerMaster, inboundBhvr) , serverMsgHandler(server.app, server.app.getLedgerReplayer()) , clientMsgHandler(env.app(), replayer) , replayer( env.app(), inboundLedgers, - std::make_unique( - clientMsgHandler, - serverMsgHandler, - behavior, - peerFeature)) + std::make_unique(clientMsgHandler, serverMsgHandler, behavior, peerFeature)) { } @@ -666,11 +629,9 @@ public: findTask(uint256 const& hash, int totalReplay) { std::unique_lock lock(replayer.mtx_); - auto i = std::find_if( - replayer.tasks_.begin(), replayer.tasks_.end(), [&](auto const& t) { - return t->parameter_.finishHash_ == hash && - t->parameter_.totalLedgers_ == totalReplay; - }); + auto i = std::find_if(replayer.tasks_.begin(), replayer.tasks_.end(), [&](auto const& t) { + return t->parameter_.finishHash_ == hash && t->parameter_.totalLedgers_ == totalReplay; + }); if (i == replayer.tasks_.end()) return {}; return *i; @@ -691,14 +652,10 @@ public: } bool - countsAsExpected( - std::size_t tasks, - std::size_t skipLists, - std::size_t deltas) + countsAsExpected(std::size_t tasks, std::size_t skipLists, std::size_t deltas) { std::unique_lock lock(replayer.mtx_); - return replayer.tasks_.size() == tasks && - replayer.skipLists_.size() == skipLists && + return replayer.tasks_.size() == tasks && replayer.skipLists_.size() == skipLists && replayer.deltas_.size() == deltas; } @@ -807,8 +764,7 @@ public: if (!waitForDone()) return false; - return checkStatus( - hash, totalReplay, taskExpect, skiplistExpect, deltaExpects); + return checkStatus(hash, totalReplay, taskExpect, skiplistExpect, deltaExpects); } jtx::Env env; @@ -822,10 +778,7 @@ public: using namespace beast::severities; void -logAll( - LedgerServer& server, - LedgerReplayClient& client, - beast::severities::Severity level = Severity::kTrace) +logAll(LedgerServer& server, LedgerReplayClient& client, beast::severities::Severity level = Severity::kTrace) { server.app.logs().threshold(level); client.app.logs().threshold(level); @@ -843,8 +796,7 @@ struct NetworkOfTwo PeerSetBehavior behavior = PeerSetBehavior::Good, InboundLedgersBehavior inboundBhvr = InboundLedgersBehavior::Good, PeerFeature peerFeature = PeerFeature::LedgerReplayEnabled) - : server(suite, param) - , client(suite, server, behavior, inboundBhvr, peerFeature) + : server(suite, param), client(suite, server, behavior, inboundBhvr, peerFeature) { // logAll(server, client); } @@ -889,11 +841,10 @@ struct LedgerReplayer_test : public beast::unit_test::suite { // request, missing key auto request = std::make_shared(); - request->set_ledgerhash( - l->header().hash.data(), l->header().hash.size()); + request->set_ledgerhash(l->header().hash.data(), l->header().hash.size()); request->set_type(protocol::TMLedgerMapType::lmACCOUNT_STATE); - auto reply = std::make_shared( - server.msgHandler.processProofPathRequest(request)); + auto reply = + std::make_shared(server.msgHandler.processProofPathRequest(request)); BEAST_EXPECT(reply->has_error()); BEAST_EXPECT(!server.msgHandler.processProofPathResponse(reply)); } @@ -901,26 +852,23 @@ struct LedgerReplayer_test : public beast::unit_test::suite // request, wrong hash auto request = std::make_shared(); request->set_type(protocol::TMLedgerMapType::lmACCOUNT_STATE); - request->set_key( - keylet::skip().key.data(), keylet::skip().key.size()); + request->set_key(keylet::skip().key.data(), keylet::skip().key.size()); uint256 hash(1234567); request->set_ledgerhash(hash.data(), hash.size()); - auto reply = std::make_shared( - server.msgHandler.processProofPathRequest(request)); + auto reply = + std::make_shared(server.msgHandler.processProofPathRequest(request)); BEAST_EXPECT(reply->has_error()); } { // good request auto request = std::make_shared(); - request->set_ledgerhash( - l->header().hash.data(), l->header().hash.size()); + request->set_ledgerhash(l->header().hash.data(), l->header().hash.size()); request->set_type(protocol::TMLedgerMapType::lmACCOUNT_STATE); - request->set_key( - keylet::skip().key.data(), keylet::skip().key.size()); + request->set_key(keylet::skip().key.data(), keylet::skip().key.size()); // generate response - auto reply = std::make_shared( - server.msgHandler.processProofPathRequest(request)); + auto reply = + std::make_shared(server.msgHandler.processProofPathRequest(request)); BEAST_EXPECT(!reply->has_error()); BEAST_EXPECT(server.msgHandler.processProofPathResponse(reply)); @@ -930,15 +878,13 @@ struct LedgerReplayer_test : public beast::unit_test::suite std::string r(reply->ledgerheader()); r.back()--; reply->set_ledgerheader(r); - BEAST_EXPECT( - !server.msgHandler.processProofPathResponse(reply)); + BEAST_EXPECT(!server.msgHandler.processProofPathResponse(reply)); r.back()++; reply->set_ledgerheader(r); BEAST_EXPECT(server.msgHandler.processProofPathResponse(reply)); // bad proof path reply->mutable_path()->RemoveLast(); - BEAST_EXPECT( - !server.msgHandler.processProofPathResponse(reply)); + BEAST_EXPECT(!server.msgHandler.processProofPathResponse(reply)); } } } @@ -953,15 +899,15 @@ struct LedgerReplayer_test : public beast::unit_test::suite { // request, missing hash auto request = std::make_shared(); - auto reply = std::make_shared( - server.msgHandler.processReplayDeltaRequest(request)); + auto reply = + std::make_shared(server.msgHandler.processReplayDeltaRequest(request)); BEAST_EXPECT(reply->has_error()); BEAST_EXPECT(!server.msgHandler.processReplayDeltaResponse(reply)); // request, wrong hash uint256 hash(1234567); request->set_ledgerhash(hash.data(), hash.size()); - reply = std::make_shared( - server.msgHandler.processReplayDeltaRequest(request)); + reply = + std::make_shared(server.msgHandler.processReplayDeltaRequest(request)); BEAST_EXPECT(reply->has_error()); BEAST_EXPECT(!server.msgHandler.processReplayDeltaResponse(reply)); } @@ -969,10 +915,9 @@ struct LedgerReplayer_test : public beast::unit_test::suite { // good request auto request = std::make_shared(); - request->set_ledgerhash( - l->header().hash.data(), l->header().hash.size()); - auto reply = std::make_shared( - server.msgHandler.processReplayDeltaRequest(request)); + request->set_ledgerhash(l->header().hash.data(), l->header().hash.size()); + auto reply = + std::make_shared(server.msgHandler.processReplayDeltaRequest(request)); BEAST_EXPECT(!reply->has_error()); BEAST_EXPECT(server.msgHandler.processReplayDeltaResponse(reply)); @@ -982,16 +927,13 @@ struct LedgerReplayer_test : public beast::unit_test::suite std::string r(reply->ledgerheader()); r.back()--; reply->set_ledgerheader(r); - BEAST_EXPECT( - !server.msgHandler.processReplayDeltaResponse(reply)); + BEAST_EXPECT(!server.msgHandler.processReplayDeltaResponse(reply)); r.back()++; reply->set_ledgerheader(r); - BEAST_EXPECT( - server.msgHandler.processReplayDeltaResponse(reply)); + BEAST_EXPECT(server.msgHandler.processReplayDeltaResponse(reply)); // bad txns reply->mutable_transaction()->RemoveLast(); - BEAST_EXPECT( - !server.msgHandler.processReplayDeltaResponse(reply)); + BEAST_EXPECT(!server.msgHandler.processReplayDeltaResponse(reply)); } } } @@ -1008,8 +950,7 @@ struct LedgerReplayer_test : public beast::unit_test::suite return sList; }; - LedgerReplayTask::TaskParameter tp10( - InboundLedger::Reason::GENERIC, uint256(10), 10); + LedgerReplayTask::TaskParameter tp10(InboundLedger::Reason::GENERIC, uint256(10), 10); BEAST_EXPECT(!tp10.update(uint256(777), 5, makeSkipList(10))); BEAST_EXPECT(!tp10.update(uint256(10), 5, makeSkipList(8))); BEAST_EXPECT(tp10.update(uint256(10), 10, makeSkipList(10))); @@ -1018,8 +959,7 @@ struct LedgerReplayer_test : public beast::unit_test::suite BEAST_EXPECT(tp10.canMergeInto(tp10)); // smaller task - LedgerReplayTask::TaskParameter tp9( - InboundLedger::Reason::GENERIC, uint256(9), 9); + LedgerReplayTask::TaskParameter tp9(InboundLedger::Reason::GENERIC, uint256(9), 9); BEAST_EXPECT(tp9.canMergeInto(tp10)); BEAST_EXPECT(!tp10.canMergeInto(tp9)); @@ -1040,8 +980,7 @@ struct LedgerReplayer_test : public beast::unit_test::suite BEAST_EXPECT(tp9.canMergeInto(tp10)); // larger task - LedgerReplayTask::TaskParameter tp20( - InboundLedger::Reason::GENERIC, uint256(20), 20); + LedgerReplayTask::TaskParameter tp20(InboundLedger::Reason::GENERIC, uint256(20), 20); BEAST_EXPECT(tp20.update(uint256(20), 20, makeSkipList(20))); BEAST_EXPECT(tp10.canMergeInto(tp20)); BEAST_EXPECT(tp9.canMergeInto(tp20)); @@ -1088,26 +1027,15 @@ struct LedgerReplayer_test : public beast::unit_test::suite http_request_type http_request; http_request.version(request.version()); http_request.base() = request.base(); - bool serverResult = - peerFeatureEnabled(http_request, FEATURE_LEDGER_REPLAY, server); + bool serverResult = peerFeatureEnabled(http_request, FEATURE_LEDGER_REPLAY, server); if (serverResult != expecting) return false; - beast::IP::Address addr = - boost::asio::ip::make_address("172.1.1.100"); + beast::IP::Address addr = boost::asio::ip::make_address("172.1.1.100"); jtx::Env serverEnv(*this); serverEnv.app().config().LEDGER_REPLAY = server; - auto http_resp = xrpl::makeResponse( - true, - http_request, - addr, - addr, - uint256{1}, - 1, - {1, 0}, - serverEnv.app()); - auto const clientResult = - peerFeatureEnabled(http_resp, FEATURE_LEDGER_REPLAY, client); + auto http_resp = xrpl::makeResponse(true, http_request, addr, addr, uint256{1}, 1, {1, 0}, serverEnv.app()); + auto const clientResult = peerFeatureEnabled(http_resp, FEATURE_LEDGER_REPLAY, client); if (clientResult != expecting) return false; @@ -1138,24 +1066,17 @@ struct LedgerReplayer_test : public beast::unit_test::suite if (l) { net.client.ledgerMaster.storeLedger(l); - l = net.server.ledgerMaster.getLedgerByHash( - l->header().parentHash); + l = net.server.ledgerMaster.getLedgerByHash(l->header().parentHash); } else break; } - net.client.replayer.replay( - InboundLedger::Reason::GENERIC, finalHash, totalReplay); + net.client.replayer.replay(InboundLedger::Reason::GENERIC, finalHash, totalReplay); - std::vector deltaStatuses( - totalReplay - 1, TaskStatus::Completed); + std::vector deltaStatuses(totalReplay - 1, TaskStatus::Completed); BEAST_EXPECT(net.client.waitAndCheckStatus( - finalHash, - totalReplay, - TaskStatus::Completed, - TaskStatus::Completed, - deltaStatuses)); + finalHash, totalReplay, TaskStatus::Completed, TaskStatus::Completed, deltaStatuses)); // sweep net.client.replayer.sweep(); @@ -1167,25 +1088,15 @@ struct LedgerReplayer_test : public beast::unit_test::suite { testcase("all the ledgers from InboundLedgers"); NetworkOfTwo net( - *this, - {totalReplay + 1}, - PeerSetBehavior::DropAll, - InboundLedgersBehavior::Good, - PeerFeature::None); + *this, {totalReplay + 1}, PeerSetBehavior::DropAll, InboundLedgersBehavior::Good, PeerFeature::None); auto l = net.server.ledgerMaster.getClosedLedger(); uint256 finalHash = l->header().hash; - net.client.replayer.replay( - InboundLedger::Reason::GENERIC, finalHash, totalReplay); + net.client.replayer.replay(InboundLedger::Reason::GENERIC, finalHash, totalReplay); - std::vector deltaStatuses( - totalReplay - 1, TaskStatus::Completed); + std::vector deltaStatuses(totalReplay - 1, TaskStatus::Completed); BEAST_EXPECT(net.client.waitAndCheckStatus( - finalHash, - totalReplay, - TaskStatus::Completed, - TaskStatus::Completed, - deltaStatuses)); + finalHash, totalReplay, TaskStatus::Completed, TaskStatus::Completed, deltaStatuses)); // sweep net.client.replayer.sweep(); @@ -1226,17 +1137,11 @@ struct LedgerReplayer_test : public beast::unit_test::suite } net.client.ledgerMaster.storeLedger(l); - net.client.replayer.replay( - InboundLedger::Reason::GENERIC, finalHash, totalReplay); + net.client.replayer.replay(InboundLedger::Reason::GENERIC, finalHash, totalReplay); - std::vector deltaStatuses( - totalReplay - 1, TaskStatus::Completed); + std::vector deltaStatuses(totalReplay - 1, TaskStatus::Completed); BEAST_EXPECT(net.client.waitAndCheckStatus( - finalHash, - totalReplay, - TaskStatus::Completed, - TaskStatus::Completed, - deltaStatuses)); + finalHash, totalReplay, TaskStatus::Completed, TaskStatus::Completed, deltaStatuses)); BEAST_EXPECT(net.client.waitForLedgers(finalHash, totalReplay)); // sweep @@ -1258,16 +1163,11 @@ struct LedgerReplayer_test : public beast::unit_test::suite auto l = net.server.ledgerMaster.getClosedLedger(); uint256 finalHash = l->header().hash; - net.client.replayer.replay( - InboundLedger::Reason::GENERIC, finalHash, totalReplay); + net.client.replayer.replay(InboundLedger::Reason::GENERIC, finalHash, totalReplay); std::vector deltaStatuses; - BEAST_EXPECT(net.client.checkStatus( - finalHash, - totalReplay, - TaskStatus::NotDone, - TaskStatus::NotDone, - deltaStatuses)); + BEAST_EXPECT( + net.client.checkStatus(finalHash, totalReplay, TaskStatus::NotDone, TaskStatus::NotDone, deltaStatuses)); BEAST_EXPECT(net.client.countsAsExpected(1, 1, 0)); net.client.replayer.stop(); @@ -1288,34 +1188,22 @@ struct LedgerReplayer_test : public beast::unit_test::suite auto l = net.server.ledgerMaster.getClosedLedger(); uint256 finalHash = l->header().hash; - net.client.replayer.replay( - InboundLedger::Reason::GENERIC, finalHash, totalReplay); + net.client.replayer.replay(InboundLedger::Reason::GENERIC, finalHash, totalReplay); auto skipList = net.client.findSkipListAcquire(finalHash); - std::uint8_t payload[55] = { - 0x6A, 0x09, 0xE6, 0x67, 0xF3, 0xBC, 0xC9, 0x08, 0xB2}; - auto item = - make_shamapitem(uint256(12345), Slice(payload, sizeof(payload))); + std::uint8_t payload[55] = {0x6A, 0x09, 0xE6, 0x67, 0xF3, 0xBC, 0xC9, 0x08, 0xB2}; + auto item = make_shamapitem(uint256(12345), Slice(payload, sizeof(payload))); skipList->processData(l->seq(), item); std::vector deltaStatuses; BEAST_EXPECT(net.client.waitAndCheckStatus( - finalHash, - totalReplay, - TaskStatus::Failed, - TaskStatus::Failed, - deltaStatuses)); + finalHash, totalReplay, TaskStatus::Failed, TaskStatus::Failed, deltaStatuses)); // add another task - net.client.replayer.replay( - InboundLedger::Reason::GENERIC, finalHash, totalReplay + 1); + net.client.replayer.replay(InboundLedger::Reason::GENERIC, finalHash, totalReplay + 1); BEAST_EXPECT(net.client.waitAndCheckStatus( - finalHash, - totalReplay, - TaskStatus::Failed, - TaskStatus::Failed, - deltaStatuses)); + finalHash, totalReplay, TaskStatus::Failed, TaskStatus::Failed, deltaStatuses)); BEAST_EXPECT(net.client.countsAsExpected(2, 1, 0)); } @@ -1334,24 +1222,18 @@ struct LedgerReplayer_test : public beast::unit_test::suite auto l = net.server.ledgerMaster.getClosedLedger(); uint256 finalHash = l->header().hash; net.client.ledgerMaster.storeLedger(l); - net.client.replayer.replay( - InboundLedger::Reason::GENERIC, finalHash, totalReplay); + net.client.replayer.replay(InboundLedger::Reason::GENERIC, finalHash, totalReplay); auto delta = net.client.findLedgerDeltaAcquire(l->header().parentHash); delta->processData( l->header(), // wrong ledger info std::map>()); BEAST_EXPECT(net.client.taskStatus(delta) == TaskStatus::Failed); - BEAST_EXPECT( - net.client.taskStatus(net.client.findTask( - finalHash, totalReplay)) == TaskStatus::Failed); + BEAST_EXPECT(net.client.taskStatus(net.client.findTask(finalHash, totalReplay)) == TaskStatus::Failed); // add another task - net.client.replayer.replay( - InboundLedger::Reason::GENERIC, finalHash, totalReplay + 1); - BEAST_EXPECT( - net.client.taskStatus(net.client.findTask( - finalHash, totalReplay + 1)) == TaskStatus::Failed); + net.client.replayer.replay(InboundLedger::Reason::GENERIC, finalHash, totalReplay + 1); + BEAST_EXPECT(net.client.taskStatus(net.client.findTask(finalHash, totalReplay + 1)) == TaskStatus::Failed); } void @@ -1367,25 +1249,17 @@ struct LedgerReplayer_test : public beast::unit_test::suite PeerFeature::LedgerReplayEnabled); auto l = net.server.ledgerMaster.getClosedLedger(); uint256 finalHash = l->header().hash; - net.client.replayer.replay( - InboundLedger::Reason::GENERIC, finalHash, totalReplay); - std::vector deltaStatuses( - totalReplay - 1, TaskStatus::Completed); + net.client.replayer.replay(InboundLedger::Reason::GENERIC, finalHash, totalReplay); + std::vector deltaStatuses(totalReplay - 1, TaskStatus::Completed); BEAST_EXPECT(net.client.waitAndCheckStatus( - finalHash, - totalReplay, - TaskStatus::Completed, - TaskStatus::Completed, - deltaStatuses)); + finalHash, totalReplay, TaskStatus::Completed, TaskStatus::Completed, deltaStatuses)); BEAST_EXPECT(net.client.waitForLedgers(finalHash, totalReplay)); // same range, same reason - net.client.replayer.replay( - InboundLedger::Reason::GENERIC, finalHash, totalReplay); + net.client.replayer.replay(InboundLedger::Reason::GENERIC, finalHash, totalReplay); BEAST_EXPECT(net.client.countsAsExpected(1, 1, totalReplay - 1)); // same range, different reason - net.client.replayer.replay( - InboundLedger::Reason::CONSENSUS, finalHash, totalReplay); + net.client.replayer.replay(InboundLedger::Reason::CONSENSUS, finalHash, totalReplay); BEAST_EXPECT(net.client.countsAsExpected(2, 1, totalReplay - 1)); // no overlap @@ -1394,8 +1268,7 @@ struct LedgerReplayer_test : public beast::unit_test::suite l = net.server.ledgerMaster.getLedgerByHash(l->header().parentHash); } auto finalHash_early = l->header().hash; - net.client.replayer.replay( - InboundLedger::Reason::GENERIC, finalHash_early, totalReplay); + net.client.replayer.replay(InboundLedger::Reason::GENERIC, finalHash_early, totalReplay); BEAST_EXPECT(net.client.waitAndCheckStatus( finalHash_early, totalReplay, @@ -1408,24 +1281,19 @@ struct LedgerReplayer_test : public beast::unit_test::suite // partial overlap l = net.server.ledgerMaster.getLedgerByHash(l->header().parentHash); auto finalHash_moreEarly = l->header().parentHash; - net.client.replayer.replay( - InboundLedger::Reason::GENERIC, finalHash_moreEarly, totalReplay); + net.client.replayer.replay(InboundLedger::Reason::GENERIC, finalHash_moreEarly, totalReplay); BEAST_EXPECT(net.client.waitAndCheckStatus( finalHash_moreEarly, totalReplay, TaskStatus::Completed, TaskStatus::Completed, deltaStatuses)); // deltaStatuses no change - BEAST_EXPECT( - net.client.waitForLedgers(finalHash_moreEarly, totalReplay)); - BEAST_EXPECT( - net.client.countsAsExpected(4, 3, 2 * (totalReplay - 1) + 2)); + BEAST_EXPECT(net.client.waitForLedgers(finalHash_moreEarly, totalReplay)); + BEAST_EXPECT(net.client.countsAsExpected(4, 3, 2 * (totalReplay - 1) + 2)); // cover - net.client.replayer.replay( - InboundLedger::Reason::GENERIC, finalHash, totalReplay * 3); - deltaStatuses = - std::vector(totalReplay * 3 - 1, TaskStatus::Completed); + net.client.replayer.replay(InboundLedger::Reason::GENERIC, finalHash, totalReplay * 3); + deltaStatuses = std::vector(totalReplay * 3 - 1, TaskStatus::Completed); BEAST_EXPECT(net.client.waitAndCheckStatus( finalHash, totalReplay * 3, @@ -1479,16 +1347,11 @@ struct LedgerReplayerTimeout_test : public beast::unit_test::suite auto l = net.server.ledgerMaster.getClosedLedger(); uint256 finalHash = l->header().hash; - net.client.replayer.replay( - InboundLedger::Reason::GENERIC, finalHash, totalReplay); + net.client.replayer.replay(InboundLedger::Reason::GENERIC, finalHash, totalReplay); std::vector deltaStatuses; BEAST_EXPECT(net.client.waitAndCheckStatus( - finalHash, - totalReplay, - TaskStatus::Failed, - TaskStatus::Failed, - deltaStatuses)); + finalHash, totalReplay, TaskStatus::Failed, TaskStatus::Failed, deltaStatuses)); // sweep BEAST_EXPECT(net.client.countsAsExpected(1, 1, 0)); @@ -1511,18 +1374,12 @@ struct LedgerReplayerTimeout_test : public beast::unit_test::suite auto l = net.server.ledgerMaster.getClosedLedger(); uint256 finalHash = l->header().hash; net.client.ledgerMaster.storeLedger(l); - net.client.replayer.replay( - InboundLedger::Reason::GENERIC, finalHash, totalReplay); + net.client.replayer.replay(InboundLedger::Reason::GENERIC, finalHash, totalReplay); - std::vector deltaStatuses( - totalReplay - 1, TaskStatus::Failed); + std::vector deltaStatuses(totalReplay - 1, TaskStatus::Failed); deltaStatuses.back() = TaskStatus::Completed; // in client ledgerMaster BEAST_EXPECT(net.client.waitAndCheckStatus( - finalHash, - totalReplay, - TaskStatus::Failed, - TaskStatus::Completed, - deltaStatuses)); + finalHash, totalReplay, TaskStatus::Failed, TaskStatus::Completed, deltaStatuses)); // sweep BEAST_EXPECT(net.client.countsAsExpected(1, 1, totalReplay - 1)); @@ -1560,34 +1417,25 @@ struct LedgerReplayerLong_test : public beast::unit_test::suite finishHashes.push_back(l->header().hash); for (int j = 0; j < totalReplay; ++j) { - l = net.server.ledgerMaster.getLedgerByHash( - l->header().parentHash); + l = net.server.ledgerMaster.getLedgerByHash(l->header().parentHash); } } BEAST_EXPECT(finishHashes.size() == rounds); for (int i = 0; i < rounds; ++i) { - net.client.replayer.replay( - InboundLedger::Reason::GENERIC, finishHashes[i], totalReplay); + net.client.replayer.replay(InboundLedger::Reason::GENERIC, finishHashes[i], totalReplay); } - std::vector deltaStatuses( - totalReplay - 1, TaskStatus::Completed); + std::vector deltaStatuses(totalReplay - 1, TaskStatus::Completed); for (int i = 0; i < rounds; ++i) { BEAST_EXPECT(net.client.waitAndCheckStatus( - finishHashes[i], - totalReplay, - TaskStatus::Completed, - TaskStatus::Completed, - deltaStatuses)); + finishHashes[i], totalReplay, TaskStatus::Completed, TaskStatus::Completed, deltaStatuses)); } - BEAST_EXPECT( - net.client.waitForLedgers(finishHashes[0], totalReplay * rounds)); - BEAST_EXPECT(net.client.countsAsExpected( - rounds, rounds, rounds * (totalReplay - 1))); + BEAST_EXPECT(net.client.waitForLedgers(finishHashes[0], totalReplay * rounds)); + BEAST_EXPECT(net.client.countsAsExpected(rounds, rounds, rounds * (totalReplay - 1))); // sweep net.client.replayer.sweep(); diff --git a/src/test/app/LendingHelpers_test.cpp b/src/test/app/LendingHelpers_test.cpp index 55fffad6b0..58e4c5aaa4 100644 --- a/src/test/app/LendingHelpers_test.cpp +++ b/src/test/app/LendingHelpers_test.cpp @@ -64,12 +64,10 @@ class LendingHelpers_test : public beast::unit_test::suite { testcase("computeRaisedRate: " + tc.name); - auto const computedRaisedRate = - computeRaisedRate(tc.periodicRate, tc.paymentsRemaining); + auto const computedRaisedRate = computeRaisedRate(tc.periodicRate, tc.paymentsRemaining); BEAST_EXPECTS( computedRaisedRate == tc.expectedRaisedRate, - "Raised rate mismatch: expected " + - to_string(tc.expectedRaisedRate) + ", got " + + "Raised rate mismatch: expected " + to_string(tc.expectedRaisedRate) + ", got " + to_string(computedRaisedRate)); } } @@ -118,12 +116,10 @@ class LendingHelpers_test : public beast::unit_test::suite { testcase("computePaymentFactor: " + tc.name); - auto const computedPaymentFactor = - computePaymentFactor(tc.periodicRate, tc.paymentsRemaining); + auto const computedPaymentFactor = computePaymentFactor(tc.periodicRate, tc.paymentsRemaining); BEAST_EXPECTS( computedPaymentFactor == tc.expectedPaymentFactor, - "Payment factor mismatch: expected " + - to_string(tc.expectedPaymentFactor) + ", got " + + "Payment factor mismatch: expected " + to_string(tc.expectedPaymentFactor) + ", got " + to_string(computedPaymentFactor)); } } @@ -168,11 +164,9 @@ class LendingHelpers_test : public beast::unit_test::suite { .name = "Standard case", .principalOutstanding = Number{1'000}, - .periodicRate = - loanPeriodicRate(TenthBips32(100'000), 30 * 24 * 60 * 60), + .periodicRate = loanPeriodicRate(TenthBips32(100'000), 30 * 24 * 60 * 60), .paymentsRemaining = 3, - .expectedPeriodicPayment = - Number{389569066396123265, -15}, // from calc + .expectedPeriodicPayment = Number{389569066396123265, -15}, // from calc }, }; @@ -180,12 +174,11 @@ class LendingHelpers_test : public beast::unit_test::suite { testcase("loanPeriodicPayment: " + tc.name); - auto const computedPeriodicPayment = loanPeriodicPayment( - tc.principalOutstanding, tc.periodicRate, tc.paymentsRemaining); + auto const computedPeriodicPayment = + loanPeriodicPayment(tc.principalOutstanding, tc.periodicRate, tc.paymentsRemaining); BEAST_EXPECTS( computedPeriodicPayment == tc.expectedPeriodicPayment, - "Periodic payment mismatch: expected " + - to_string(tc.expectedPeriodicPayment) + ", got " + + "Periodic payment mismatch: expected " + to_string(tc.expectedPeriodicPayment) + ", got " + to_string(computedPeriodicPayment)); } } @@ -229,10 +222,8 @@ class LendingHelpers_test : public beast::unit_test::suite }, { .name = "Standard case", - .periodicPayment = - Number{389569066396123265, -15}, // from calc - .periodicRate = - loanPeriodicRate(TenthBips32(100'000), 30 * 24 * 60 * 60), + .periodicPayment = Number{389569066396123265, -15}, // from calc + .periodicRate = loanPeriodicRate(TenthBips32(100'000), 30 * 24 * 60 * 60), .paymentsRemaining = 3, .expectedPrincipalOutstanding = Number{1'000}, }, @@ -243,12 +234,10 @@ class LendingHelpers_test : public beast::unit_test::suite testcase("loanPrincipalFromPeriodicPayment: " + tc.name); auto const computedPrincipalOutstanding = - loanPrincipalFromPeriodicPayment( - tc.periodicPayment, tc.periodicRate, tc.paymentsRemaining); + loanPrincipalFromPeriodicPayment(tc.periodicPayment, tc.periodicRate, tc.paymentsRemaining); BEAST_EXPECTS( computedPrincipalOutstanding == tc.expectedPrincipalOutstanding, - "Principal outstanding mismatch: expected " + - to_string(tc.expectedPrincipalOutstanding) + ", got " + + "Principal outstanding mismatch: expected " + to_string(tc.expectedPrincipalOutstanding) + ", got " + to_string(computedPrincipalOutstanding)); } } @@ -268,45 +257,28 @@ class LendingHelpers_test : public beast::unit_test::suite auto const overpaymentFeeRate = TenthBips32{50'000}; // 50% auto const managementFeeRate = TenthBips16{10'000}; // 10% - auto const expectedOverpaymentFee = Number{500}; // 50% of 1,000 - auto const expectedOverpaymentInterestGross = - Number{100}; // 10% of 1,000 - auto const expectedOverpaymentInterestNet = - Number{90}; // 100 - 10% of 100 - auto const expectedOverpaymentManagementFee = Number{10}; // 10% of 100 - auto const expectedPrincipalPortion = Number{400}; // 1,000 - 100 - 500 + auto const expectedOverpaymentFee = Number{500}; // 50% of 1,000 + auto const expectedOverpaymentInterestGross = Number{100}; // 10% of 1,000 + auto const expectedOverpaymentInterestNet = Number{90}; // 100 - 10% of 100 + auto const expectedOverpaymentManagementFee = Number{10}; // 10% of 100 + auto const expectedPrincipalPortion = Number{400}; // 1,000 - 100 - 500 auto const components = detail::computeOverpaymentComponents( - IOU, - loanScale, - overpayment, - overpaymentInterestRate, - overpaymentFeeRate, - managementFeeRate); + IOU, loanScale, overpayment, overpaymentInterestRate, overpaymentFeeRate, managementFeeRate); + + BEAST_EXPECT(components.untrackedManagementFee == expectedOverpaymentFee); + + BEAST_EXPECT(components.untrackedInterest == expectedOverpaymentInterestNet); + + BEAST_EXPECT(components.trackedInterestPart() == expectedOverpaymentInterestNet); + + BEAST_EXPECT(components.trackedManagementFeeDelta == expectedOverpaymentManagementFee); + BEAST_EXPECT(components.trackedPrincipalDelta == expectedPrincipalPortion); + BEAST_EXPECT( + components.trackedManagementFeeDelta + components.untrackedInterest == expectedOverpaymentInterestGross); BEAST_EXPECT( - components.untrackedManagementFee == expectedOverpaymentFee); - - BEAST_EXPECT( - components.untrackedInterest == expectedOverpaymentInterestNet); - - BEAST_EXPECT( - components.trackedInterestPart() == expectedOverpaymentInterestNet); - - BEAST_EXPECT( - components.trackedManagementFeeDelta == - expectedOverpaymentManagementFee); - BEAST_EXPECT( - components.trackedPrincipalDelta == expectedPrincipalPortion); - BEAST_EXPECT( - components.trackedManagementFeeDelta + - components.untrackedInterest == - expectedOverpaymentInterestGross); - - BEAST_EXPECT( - components.trackedManagementFeeDelta + - components.untrackedInterest + - components.trackedPrincipalDelta + + components.trackedManagementFeeDelta + components.untrackedInterest + components.trackedPrincipalDelta + components.untrackedManagementFee == overpayment); } @@ -353,17 +325,14 @@ class LendingHelpers_test : public beast::unit_test::suite testcase("computeInterestAndFeeParts: " + tc.name); auto const [computedInterestPart, computedFeePart] = - computeInterestAndFeeParts( - IOU, tc.interest, tc.managementFeeRate, loanScale); + computeInterestAndFeeParts(IOU, tc.interest, tc.managementFeeRate, loanScale); BEAST_EXPECTS( computedInterestPart == tc.expectedInterestPart, - "Interest part mismatch: expected " + - to_string(tc.expectedInterestPart) + ", got " + + "Interest part mismatch: expected " + to_string(tc.expectedInterestPart) + ", got " + to_string(computedInterestPart)); BEAST_EXPECTS( computedFeePart == tc.expectedFeePart, - "Fee part mismatch: expected " + to_string(tc.expectedFeePart) + - ", got " + to_string(computedFeePart)); + "Fee part mismatch: expected " + to_string(tc.expectedFeePart) + ", got " + to_string(computedFeePart)); } } @@ -387,8 +356,7 @@ class LendingHelpers_test : public beast::unit_test::suite .name = "On-time payment", .principalOutstanding = Number{1'000}, .lateInterestRate = TenthBips32{10'000}, // 10% - .parentCloseTime = - NetClock::time_point{NetClock::duration{3'000}}, + .parentCloseTime = NetClock::time_point{NetClock::duration{3'000}}, .nextPaymentDueDate = 3'000, .expectedLateInterest = Number{0}, }, @@ -396,8 +364,7 @@ class LendingHelpers_test : public beast::unit_test::suite .name = "Early payment", .principalOutstanding = Number{1'000}, .lateInterestRate = TenthBips32{10'000}, // 10% - .parentCloseTime = - NetClock::time_point{NetClock::duration{3'000}}, + .parentCloseTime = NetClock::time_point{NetClock::duration{3'000}}, .nextPaymentDueDate = 4'000, .expectedLateInterest = Number{0}, }, @@ -405,8 +372,7 @@ class LendingHelpers_test : public beast::unit_test::suite .name = "No principal outstanding", .principalOutstanding = Number{0}, .lateInterestRate = TenthBips32{10'000}, // 10% - .parentCloseTime = - NetClock::time_point{NetClock::duration{3'000}}, + .parentCloseTime = NetClock::time_point{NetClock::duration{3'000}}, .nextPaymentDueDate = 2'000, .expectedLateInterest = Number{0}, }, @@ -414,8 +380,7 @@ class LendingHelpers_test : public beast::unit_test::suite .name = "No late interest rate", .principalOutstanding = Number{1'000}, .lateInterestRate = TenthBips32{0}, // 0% - .parentCloseTime = - NetClock::time_point{NetClock::duration{3'000}}, + .parentCloseTime = NetClock::time_point{NetClock::duration{3'000}}, .nextPaymentDueDate = 2'000, .expectedLateInterest = Number{0}, }, @@ -423,11 +388,9 @@ class LendingHelpers_test : public beast::unit_test::suite .name = "Late payment", .principalOutstanding = Number{1'000}, .lateInterestRate = TenthBips32{100'000}, // 100% - .parentCloseTime = - NetClock::time_point{NetClock::duration{3'000}}, + .parentCloseTime = NetClock::time_point{NetClock::duration{3'000}}, .nextPaymentDueDate = 2'000, - .expectedLateInterest = - Number{317097919837645865, -19}, // from calc + .expectedLateInterest = Number{317097919837645865, -19}, // from calc }, }; @@ -436,14 +399,10 @@ class LendingHelpers_test : public beast::unit_test::suite testcase("loanLatePaymentInterest: " + tc.name); auto const computedLateInterest = loanLatePaymentInterest( - tc.principalOutstanding, - tc.lateInterestRate, - tc.parentCloseTime, - tc.nextPaymentDueDate); + tc.principalOutstanding, tc.lateInterestRate, tc.parentCloseTime, tc.nextPaymentDueDate); BEAST_EXPECTS( computedLateInterest == tc.expectedLateInterest, - "Late interest mismatch: expected " + - to_string(tc.expectedLateInterest) + ", got " + + "Late interest mismatch: expected " + to_string(tc.expectedLateInterest) + ", got " + to_string(computedLateInterest)); } } @@ -470,8 +429,7 @@ class LendingHelpers_test : public beast::unit_test::suite .name = "Zero principal outstanding", .principalOutstanding = Number{0}, .periodicRate = Number{5, -2}, - .parentCloseTime = - NetClock::time_point{NetClock::duration{3'000}}, + .parentCloseTime = NetClock::time_point{NetClock::duration{3'000}}, .startDate = 2'000, .prevPaymentDate = 2'500, .paymentInterval = 30 * 24 * 60 * 60, @@ -481,8 +439,7 @@ class LendingHelpers_test : public beast::unit_test::suite .name = "Before start date", .principalOutstanding = Number{1'000}, .periodicRate = Number{5, -2}, - .parentCloseTime = - NetClock::time_point{NetClock::duration{1'000}}, + .parentCloseTime = NetClock::time_point{NetClock::duration{1'000}}, .startDate = 2'000, .prevPaymentDate = 1'500, .paymentInterval = 30 * 24 * 60 * 60, @@ -492,8 +449,7 @@ class LendingHelpers_test : public beast::unit_test::suite .name = "Zero periodic rate", .principalOutstanding = Number{1'000}, .periodicRate = Number{0}, - .parentCloseTime = - NetClock::time_point{NetClock::duration{3'000}}, + .parentCloseTime = NetClock::time_point{NetClock::duration{3'000}}, .startDate = 2'000, .prevPaymentDate = 2'500, .paymentInterval = 30 * 24 * 60 * 60, @@ -503,8 +459,7 @@ class LendingHelpers_test : public beast::unit_test::suite .name = "Zero payment interval", .principalOutstanding = Number{1'000}, .periodicRate = Number{5, -2}, - .parentCloseTime = - NetClock::time_point{NetClock::duration{3'000}}, + .parentCloseTime = NetClock::time_point{NetClock::duration{3'000}}, .startDate = 2'000, .prevPaymentDate = 2'500, .paymentInterval = 0, @@ -514,13 +469,11 @@ class LendingHelpers_test : public beast::unit_test::suite .name = "Standard case", .principalOutstanding = Number{1'000}, .periodicRate = Number{5, -2}, - .parentCloseTime = - NetClock::time_point{NetClock::duration{3'000}}, + .parentCloseTime = NetClock::time_point{NetClock::duration{3'000}}, .startDate = 1'000, .prevPaymentDate = 2'000, .paymentInterval = 30 * 24 * 60 * 60, - .expectedAccruedInterest = - Number{1929012345679012346, -20}, // from calc + .expectedAccruedInterest = Number{1929012345679012346, -20}, // from calc }, }; @@ -537,8 +490,7 @@ class LendingHelpers_test : public beast::unit_test::suite tc.paymentInterval); BEAST_EXPECTS( computedAccruedInterest == tc.expectedAccruedInterest, - "Accrued interest mismatch: expected " + - to_string(tc.expectedAccruedInterest) + ", got " + + "Accrued interest mismatch: expected " + to_string(tc.expectedAccruedInterest) + ", got " + to_string(computedAccruedInterest)); } } @@ -569,8 +521,7 @@ class LendingHelpers_test : public beast::unit_test::suite .name = "Zero principal outstanding", .rawPrincipalOutstanding = Number{0}, .periodicRate = Number{5, -2}, - .parentCloseTime = - NetClock::time_point{NetClock::duration{3'000}}, + .parentCloseTime = NetClock::time_point{NetClock::duration{3'000}}, .paymentInterval = 30 * 24 * 60 * 60, .prevPaymentDate = 2'000, .startDate = 1'000, @@ -581,27 +532,23 @@ class LendingHelpers_test : public beast::unit_test::suite .name = "Zero close interest rate", .rawPrincipalOutstanding = Number{1'000}, .periodicRate = Number{5, -2}, - .parentCloseTime = - NetClock::time_point{NetClock::duration{3'000}}, + .parentCloseTime = NetClock::time_point{NetClock::duration{3'000}}, .paymentInterval = 30 * 24 * 60 * 60, .prevPaymentDate = 2'000, .startDate = 1'000, .closeInterestRate = TenthBips32{0}, - .expectedFullPaymentInterest = - Number{1929012345679012346, -20}, // from calc + .expectedFullPaymentInterest = Number{1929012345679012346, -20}, // from calc }, { .name = "Standard case", .rawPrincipalOutstanding = Number{1'000}, .periodicRate = Number{5, -2}, - .parentCloseTime = - NetClock::time_point{NetClock::duration{3'000}}, + .parentCloseTime = NetClock::time_point{NetClock::duration{3'000}}, .paymentInterval = 30 * 24 * 60 * 60, .prevPaymentDate = 2'000, .startDate = 1'000, .closeInterestRate = TenthBips32{10'000}, - .expectedFullPaymentInterest = - Number{1000192901234567901, -16}, // from calc + .expectedFullPaymentInterest = Number{1000192901234567901, -16}, // from calc }, }; @@ -619,8 +566,7 @@ class LendingHelpers_test : public beast::unit_test::suite tc.closeInterestRate); BEAST_EXPECTS( computedFullPaymentInterest == tc.expectedFullPaymentInterest, - "Full payment interest mismatch: expected " + - to_string(tc.expectedFullPaymentInterest) + ", got " + + "Full payment interest mismatch: expected " + to_string(tc.expectedFullPaymentInterest) + ", got " + to_string(computedFullPaymentInterest)); } } @@ -643,36 +589,21 @@ class LendingHelpers_test : public beast::unit_test::suite Number const loanPrincipal{1'000}; std::uint32_t const paymentInterval = 30 * 24 * 60 * 60; std::uint32_t const paymentsRemaining = 10; - auto const periodicRate = - loanPeriodicRate(loanInterestRate, paymentInterval); + auto const periodicRate = loanPeriodicRate(loanInterestRate, paymentInterval); Number const overpaymentAmount{50}; - ExtendedPaymentComponents const overpaymentComponents = - computeOverpaymentComponents( - asset, - loanScale, - overpaymentAmount, - TenthBips32(0), - TenthBips32(0), - managementFeeRate); + auto const overpaymentComponents = computeOverpaymentComponents( + asset, loanScale, overpaymentAmount, TenthBips32(0), TenthBips32(0), managementFeeRate); - auto const loanProperites = computeLoanProperties( - asset, - loanPrincipal, - loanInterestRate, - paymentInterval, - paymentsRemaining, - managementFeeRate, - loanScale); - - Number const periodicPayment = loanProperites.periodicPayment; + auto const loanProperties = computeLoanProperties( + asset, loanPrincipal, loanInterestRate, paymentInterval, paymentsRemaining, managementFeeRate, loanScale); auto const ret = tryOverpayment( asset, loanScale, overpaymentComponents, - loanProperites.loanState, - periodicPayment, + loanProperties.loanState, + loanProperties.periodicPayment, periodicRate, paymentsRemaining, managementFeeRate, @@ -686,51 +617,38 @@ class LendingHelpers_test : public beast::unit_test::suite // =========== VALIDATE PAYMENT PARTS =========== BEAST_EXPECTS( actualPaymentParts.valueChange == 0, - " valueChange mismatch: expected 0, got " + - to_string(actualPaymentParts.valueChange)); + " valueChange mismatch: expected 0, got " + to_string(actualPaymentParts.valueChange)); BEAST_EXPECTS( actualPaymentParts.feePaid == 0, - " feePaid mismatch: expected 0, got " + - to_string(actualPaymentParts.feePaid)); + " feePaid mismatch: expected 0, got " + to_string(actualPaymentParts.feePaid)); BEAST_EXPECTS( actualPaymentParts.interestPaid == 0, - " interestPaid mismatch: expected 0, got " + - to_string(actualPaymentParts.interestPaid)); + " interestPaid mismatch: expected 0, got " + to_string(actualPaymentParts.interestPaid)); BEAST_EXPECTS( actualPaymentParts.principalPaid == overpaymentAmount, - " principalPaid mismatch: expected " + - to_string(overpaymentAmount) + ", got " + + " principalPaid mismatch: expected " + to_string(overpaymentAmount) + ", got " + to_string(actualPaymentParts.principalPaid)); // =========== VALIDATE STATE CHANGES =========== BEAST_EXPECTS( - loanProperites.loanState.interestDue - newState.interestDue == 0, + loanProperties.loanState.interestDue - newState.interestDue == 0, " interest change mismatch: expected 0, got " + - to_string( - loanProperites.loanState.interestDue - - newState.interestDue)); + to_string(loanProperties.loanState.interestDue - newState.interestDue)); BEAST_EXPECTS( - loanProperites.loanState.managementFeeDue - - newState.managementFeeDue == - 0, + loanProperties.loanState.managementFeeDue - newState.managementFeeDue == 0, " management fee change mismatch: expected 0, got " + - to_string( - loanProperites.loanState.managementFeeDue - - newState.managementFeeDue)); + to_string(loanProperties.loanState.managementFeeDue - newState.managementFeeDue)); BEAST_EXPECTS( actualPaymentParts.principalPaid == - loanProperites.loanState.principalOutstanding - - newState.principalOutstanding, + loanProperties.loanState.principalOutstanding - newState.principalOutstanding, " principalPaid mismatch: expected " + - to_string( - loanProperites.loanState.principalOutstanding - - newState.principalOutstanding) + - ", got " + to_string(actualPaymentParts.principalPaid)); + to_string(loanProperties.loanState.principalOutstanding - newState.principalOutstanding) + ", got " + + to_string(actualPaymentParts.principalPaid)); } void @@ -750,35 +668,25 @@ class LendingHelpers_test : public beast::unit_test::suite Number const loanPrincipal{1'000}; std::uint32_t const paymentInterval = 30 * 24 * 60 * 60; std::uint32_t const paymentsRemaining = 10; - auto const periodicRate = - loanPeriodicRate(loanInterestRate, paymentInterval); + auto const periodicRate = loanPeriodicRate(loanInterestRate, paymentInterval); - ExtendedPaymentComponents const overpaymentComponents = - computeOverpaymentComponents( - asset, - loanScale, - Number{50, 0}, - TenthBips32(0), - TenthBips32(10'000), // 10% overpayment fee - managementFeeRate); - - auto const loanProperites = computeLoanProperties( + auto const overpaymentComponents = computeOverpaymentComponents( asset, - loanPrincipal, - loanInterestRate, - paymentInterval, - paymentsRemaining, - managementFeeRate, - loanScale); + loanScale, + Number{50, 0}, + TenthBips32(0), + TenthBips32(10'000), // 10% overpayment fee + managementFeeRate); - Number const periodicPayment = loanProperites.periodicPayment; + auto const loanProperties = computeLoanProperties( + asset, loanPrincipal, loanInterestRate, paymentInterval, paymentsRemaining, managementFeeRate, loanScale); auto const ret = tryOverpayment( asset, loanScale, overpaymentComponents, - loanProperites.loanState, - periodicPayment, + loanProperties.loanState, + loanProperties.periodicPayment, periodicRate, paymentsRemaining, managementFeeRate, @@ -792,52 +700,39 @@ class LendingHelpers_test : public beast::unit_test::suite // =========== VALIDATE PAYMENT PARTS =========== BEAST_EXPECTS( actualPaymentParts.valueChange == 0, - " valueChange mismatch: expected 0, got " + - to_string(actualPaymentParts.valueChange)); + " valueChange mismatch: expected 0, got " + to_string(actualPaymentParts.valueChange)); BEAST_EXPECTS( actualPaymentParts.feePaid == 5, - " feePaid mismatch: expected 5, got " + - to_string(actualPaymentParts.feePaid)); + " feePaid mismatch: expected 5, got " + to_string(actualPaymentParts.feePaid)); BEAST_EXPECTS( actualPaymentParts.principalPaid == 45, - " principalPaid mismatch: expected 45, got `" + - to_string(actualPaymentParts.principalPaid)); + " principalPaid mismatch: expected 45, got `" + to_string(actualPaymentParts.principalPaid)); BEAST_EXPECTS( actualPaymentParts.interestPaid == 0, - " interestPaid mismatch: expected 0, got " + - to_string(actualPaymentParts.interestPaid)); + " interestPaid mismatch: expected 0, got " + to_string(actualPaymentParts.interestPaid)); // =========== VALIDATE STATE CHANGES =========== // With no Loan interest, interest outstanding should not change BEAST_EXPECTS( - loanProperites.loanState.interestDue - newState.interestDue == 0, + loanProperties.loanState.interestDue - newState.interestDue == 0, " interest change mismatch: expected 0, got " + - to_string( - loanProperites.loanState.interestDue - - newState.interestDue)); + to_string(loanProperties.loanState.interestDue - newState.interestDue)); // With no Loan management fee, management fee due should not change BEAST_EXPECTS( - loanProperites.loanState.managementFeeDue - - newState.managementFeeDue == - 0, + loanProperties.loanState.managementFeeDue - newState.managementFeeDue == 0, " management fee change mismatch: expected 0, got " + - to_string( - loanProperites.loanState.managementFeeDue - - newState.managementFeeDue)); + to_string(loanProperties.loanState.managementFeeDue - newState.managementFeeDue)); BEAST_EXPECTS( actualPaymentParts.principalPaid == - loanProperites.loanState.principalOutstanding - - newState.principalOutstanding, + loanProperties.loanState.principalOutstanding - newState.principalOutstanding, " principalPaid mismatch: expected " + - to_string( - loanProperites.loanState.principalOutstanding - - newState.principalOutstanding) + - ", got " + to_string(actualPaymentParts.principalPaid)); + to_string(loanProperties.loanState.principalOutstanding - newState.principalOutstanding) + ", got " + + to_string(actualPaymentParts.principalPaid)); } void @@ -857,35 +752,25 @@ class LendingHelpers_test : public beast::unit_test::suite Number const loanPrincipal{1'000}; std::uint32_t const paymentInterval = 30 * 24 * 60 * 60; std::uint32_t const paymentsRemaining = 10; - auto const periodicRate = - loanPeriodicRate(loanInterestRate, paymentInterval); + auto const periodicRate = loanPeriodicRate(loanInterestRate, paymentInterval); - ExtendedPaymentComponents const overpaymentComponents = - computeOverpaymentComponents( - asset, - loanScale, - Number{50, 0}, - TenthBips32(0), // no overpayment interest - TenthBips32(0), // 0% overpayment fee - managementFeeRate); - - auto const loanProperites = computeLoanProperties( + auto const overpaymentComponents = computeOverpaymentComponents( asset, - loanPrincipal, - loanInterestRate, - paymentInterval, - paymentsRemaining, - managementFeeRate, - loanScale); + loanScale, + Number{50, 0}, + TenthBips32(0), // no overpayment interest + TenthBips32(0), // 0% overpayment fee + managementFeeRate); - Number const periodicPayment = loanProperites.periodicPayment; + auto const loanProperties = computeLoanProperties( + asset, loanPrincipal, loanInterestRate, paymentInterval, paymentsRemaining, managementFeeRate, loanScale); auto const ret = tryOverpayment( asset, loanScale, overpaymentComponents, - loanProperites.loanState, - periodicPayment, + loanProperties.loanState, + loanProperties.periodicPayment, periodicRate, paymentsRemaining, managementFeeRate, @@ -901,63 +786,48 @@ class LendingHelpers_test : public beast::unit_test::suite // interest decrease BEAST_EXPECTS( (actualPaymentParts.valueChange == Number{-228802, -5}), - " valueChange mismatch: expected " + - to_string(Number{-228802, -5}) + ", got " + + " valueChange mismatch: expected " + to_string(Number{-228802, -5}) + ", got " + to_string(actualPaymentParts.valueChange)); // with no fee portion, fee paid should be zero BEAST_EXPECTS( actualPaymentParts.feePaid == 0, - " feePaid mismatch: expected 0, got " + - to_string(actualPaymentParts.feePaid)); + " feePaid mismatch: expected 0, got " + to_string(actualPaymentParts.feePaid)); BEAST_EXPECTS( actualPaymentParts.principalPaid == 50, - " principalPaid mismatch: expected 50, got `" + - to_string(actualPaymentParts.principalPaid)); + " principalPaid mismatch: expected 50, got `" + to_string(actualPaymentParts.principalPaid)); // with no interest portion, interest paid should be zero BEAST_EXPECTS( actualPaymentParts.interestPaid == 0, - " interestPaid mismatch: expected 0, got " + - to_string(actualPaymentParts.interestPaid)); + " interestPaid mismatch: expected 0, got " + to_string(actualPaymentParts.interestPaid)); // =========== VALIDATE STATE CHANGES =========== BEAST_EXPECTS( actualPaymentParts.principalPaid == - loanProperites.loanState.principalOutstanding - - newState.principalOutstanding, + loanProperties.loanState.principalOutstanding - newState.principalOutstanding, " principalPaid mismatch: expected " + - to_string( - loanProperites.loanState.principalOutstanding - - newState.principalOutstanding) + - ", got " + to_string(actualPaymentParts.principalPaid)); + to_string(loanProperties.loanState.principalOutstanding - newState.principalOutstanding) + ", got " + + to_string(actualPaymentParts.principalPaid)); BEAST_EXPECTS( - actualPaymentParts.valueChange == - newState.interestDue - loanProperites.loanState.interestDue, + actualPaymentParts.valueChange == newState.interestDue - loanProperties.loanState.interestDue, " valueChange mismatch: expected " + - to_string( - newState.interestDue - - loanProperites.loanState.interestDue) + - ", got " + to_string(actualPaymentParts.valueChange)); + to_string(newState.interestDue - loanProperties.loanState.interestDue) + ", got " + + to_string(actualPaymentParts.valueChange)); // With no Loan management fee, management fee due should not change BEAST_EXPECTS( - loanProperites.loanState.managementFeeDue - - newState.managementFeeDue == - 0, + loanProperties.loanState.managementFeeDue - newState.managementFeeDue == 0, " management fee change mismatch: expected 0, got " + - to_string( - loanProperites.loanState.managementFeeDue - - newState.managementFeeDue)); + to_string(loanProperties.loanState.managementFeeDue - newState.managementFeeDue)); } void testTryOverpaymentLoanInterestOverpaymentInterest() { - testcase( - "tryOverpayment - Loan Interest, Overpayment Interest, No Fee"); + testcase("tryOverpayment - Loan Interest, Overpayment Interest, No Fee"); using namespace jtx; using namespace xrpl::detail; @@ -971,35 +841,25 @@ class LendingHelpers_test : public beast::unit_test::suite Number const loanPrincipal{1'000}; std::uint32_t const paymentInterval = 30 * 24 * 60 * 60; std::uint32_t const paymentsRemaining = 10; - auto const periodicRate = - loanPeriodicRate(loanInterestRate, paymentInterval); + auto const periodicRate = loanPeriodicRate(loanInterestRate, paymentInterval); - ExtendedPaymentComponents const overpaymentComponents = - computeOverpaymentComponents( - asset, - loanScale, - Number{50, 0}, - TenthBips32(10'000), // 10% overpayment interest - TenthBips32(0), // 0% overpayment fee - managementFeeRate); - - auto const loanProperites = computeLoanProperties( + auto const overpaymentComponents = computeOverpaymentComponents( asset, - loanPrincipal, - loanInterestRate, - paymentInterval, - paymentsRemaining, - managementFeeRate, - loanScale); + loanScale, + Number{50, 0}, + TenthBips32(10'000), // 10% overpayment interest + TenthBips32(0), // 0% overpayment fee + managementFeeRate); - Number const periodicPayment = loanProperites.periodicPayment; + auto const loanProperties = computeLoanProperties( + asset, loanPrincipal, loanInterestRate, paymentInterval, paymentsRemaining, managementFeeRate, loanScale); auto const ret = tryOverpayment( asset, loanScale, overpaymentComponents, - loanProperites.loanState, - periodicPayment, + loanProperties.loanState, + loanProperties.periodicPayment, periodicRate, paymentsRemaining, managementFeeRate, @@ -1014,63 +874,48 @@ class LendingHelpers_test : public beast::unit_test::suite // with overpayment interest portion, interest paid should be 5 BEAST_EXPECTS( actualPaymentParts.interestPaid == 5, - " interestPaid mismatch: expected 5, got " + - to_string(actualPaymentParts.interestPaid)); + " interestPaid mismatch: expected 5, got " + to_string(actualPaymentParts.interestPaid)); // With overpayment interest portion, value change should equal the // interest decrease plus overpayment interest portion BEAST_EXPECTS( - (actualPaymentParts.valueChange == - Number{-205922, -5} + actualPaymentParts.interestPaid), + (actualPaymentParts.valueChange == Number{-205922, -5} + actualPaymentParts.interestPaid), " valueChange mismatch: expected " + - to_string( - actualPaymentParts.valueChange - - actualPaymentParts.interestPaid) + - ", got " + to_string(actualPaymentParts.valueChange)); + to_string(actualPaymentParts.valueChange - actualPaymentParts.interestPaid) + ", got " + + to_string(actualPaymentParts.valueChange)); // with no fee portion, fee paid should be zero BEAST_EXPECTS( actualPaymentParts.feePaid == 0, - " feePaid mismatch: expected 0, got " + - to_string(actualPaymentParts.feePaid)); + " feePaid mismatch: expected 0, got " + to_string(actualPaymentParts.feePaid)); BEAST_EXPECTS( actualPaymentParts.principalPaid == 45, - " principalPaid mismatch: expected 45, got `" + - to_string(actualPaymentParts.principalPaid)); + " principalPaid mismatch: expected 45, got `" + to_string(actualPaymentParts.principalPaid)); // =========== VALIDATE STATE CHANGES =========== BEAST_EXPECTS( actualPaymentParts.principalPaid == - loanProperites.loanState.principalOutstanding - - newState.principalOutstanding, + loanProperties.loanState.principalOutstanding - newState.principalOutstanding, " principalPaid mismatch: expected " + - to_string( - loanProperites.loanState.principalOutstanding - - newState.principalOutstanding) + - ", got " + to_string(actualPaymentParts.principalPaid)); + to_string(loanProperties.loanState.principalOutstanding - newState.principalOutstanding) + ", got " + + to_string(actualPaymentParts.principalPaid)); // The change in interest is equal to the value change sans the // overpayment interest BEAST_EXPECTS( actualPaymentParts.valueChange - actualPaymentParts.interestPaid == - newState.interestDue - loanProperites.loanState.interestDue, + newState.interestDue - loanProperties.loanState.interestDue, " valueChange mismatch: expected " + to_string( - newState.interestDue - - loanProperites.loanState.interestDue + - actualPaymentParts.interestPaid) + + newState.interestDue - loanProperties.loanState.interestDue + actualPaymentParts.interestPaid) + ", got " + to_string(actualPaymentParts.valueChange)); // With no Loan management fee, management fee due should not change BEAST_EXPECTS( - loanProperites.loanState.managementFeeDue - - newState.managementFeeDue == - 0, + loanProperties.loanState.managementFeeDue - newState.managementFeeDue == 0, " management fee change mismatch: expected 0, got " + - to_string( - loanProperites.loanState.managementFeeDue - - newState.managementFeeDue)); + to_string(loanProperties.loanState.managementFeeDue - newState.managementFeeDue)); } void @@ -1092,35 +937,25 @@ class LendingHelpers_test : public beast::unit_test::suite Number const loanPrincipal{1'000}; std::uint32_t const paymentInterval = 30 * 24 * 60 * 60; std::uint32_t const paymentsRemaining = 10; - auto const periodicRate = - loanPeriodicRate(loanInterestRate, paymentInterval); + auto const periodicRate = loanPeriodicRate(loanInterestRate, paymentInterval); - ExtendedPaymentComponents const overpaymentComponents = - computeOverpaymentComponents( - asset, - loanScale, - Number{50, 0}, - TenthBips32(10'000), // 10% overpayment interest - TenthBips32(0), // 0% overpayment fee - managementFeeRate); - - auto const loanProperites = computeLoanProperties( + auto const overpaymentComponents = computeOverpaymentComponents( asset, - loanPrincipal, - loanInterestRate, - paymentInterval, - paymentsRemaining, - managementFeeRate, - loanScale); + loanScale, + Number{50, 0}, + TenthBips32(10'000), // 10% overpayment interest + TenthBips32(0), // 0% overpayment fee + managementFeeRate); - Number const periodicPayment = loanProperites.periodicPayment; + auto const loanProperties = computeLoanProperties( + asset, loanPrincipal, loanInterestRate, paymentInterval, paymentsRemaining, managementFeeRate, loanScale); auto const ret = tryOverpayment( asset, loanScale, overpaymentComponents, - loanProperites.loanState, - periodicPayment, + loanProperties.loanState, + loanProperties.periodicPayment, periodicRate, paymentsRemaining, managementFeeRate, @@ -1137,72 +972,52 @@ class LendingHelpers_test : public beast::unit_test::suite // overpayment interest portion first, so interest paid remains 4.5 BEAST_EXPECTS( (actualPaymentParts.interestPaid == Number{45, -1}), - " interestPaid mismatch: expected 4.5, got " + - to_string(actualPaymentParts.interestPaid)); + " interestPaid mismatch: expected 4.5, got " + to_string(actualPaymentParts.interestPaid)); // With overpayment interest portion, value change should equal the // interest decrease plus overpayment interest portion BEAST_EXPECTS( - (actualPaymentParts.valueChange == - Number{-18533, -4} + actualPaymentParts.interestPaid), - " valueChange mismatch: expected " + - to_string( - Number{-18533, -4} + actualPaymentParts.interestPaid) + + (actualPaymentParts.valueChange == Number{-18533, -4} + actualPaymentParts.interestPaid), + " valueChange mismatch: expected " + to_string(Number{-18533, -4} + actualPaymentParts.interestPaid) + ", got " + to_string(actualPaymentParts.valueChange)); // While there is no overpayment fee, fee paid should equal the // management fee charged against the overpayment interest portion BEAST_EXPECTS( (actualPaymentParts.feePaid == Number{5, -1}), - " feePaid mismatch: expected 0.5, got " + - to_string(actualPaymentParts.feePaid)); + " feePaid mismatch: expected 0.5, got " + to_string(actualPaymentParts.feePaid)); BEAST_EXPECTS( actualPaymentParts.principalPaid == 45, - " principalPaid mismatch: expected 45, got `" + - to_string(actualPaymentParts.principalPaid)); + " principalPaid mismatch: expected 45, got `" + to_string(actualPaymentParts.principalPaid)); // =========== VALIDATE STATE CHANGES =========== BEAST_EXPECTS( actualPaymentParts.principalPaid == - loanProperites.loanState.principalOutstanding - - newState.principalOutstanding, + loanProperties.loanState.principalOutstanding - newState.principalOutstanding, " principalPaid mismatch: expected " + - to_string( - loanProperites.loanState.principalOutstanding - - newState.principalOutstanding) + - ", got " + to_string(actualPaymentParts.principalPaid)); + to_string(loanProperties.loanState.principalOutstanding - newState.principalOutstanding) + ", got " + + to_string(actualPaymentParts.principalPaid)); // Note that the management fee value change is not captured, as this // value is not needed to correctly update the Vault state. BEAST_EXPECTS( - (newState.managementFeeDue - - loanProperites.loanState.managementFeeDue == - Number{-20592, -5}), - " management fee change mismatch: expected " + - to_string(Number{-20592, -5}) + ", got " + - to_string( - newState.managementFeeDue - - loanProperites.loanState.managementFeeDue)); + (newState.managementFeeDue - loanProperties.loanState.managementFeeDue == Number{-20592, -5}), + " management fee change mismatch: expected " + to_string(Number{-20592, -5}) + ", got " + + to_string(newState.managementFeeDue - loanProperties.loanState.managementFeeDue)); BEAST_EXPECTS( actualPaymentParts.valueChange - actualPaymentParts.interestPaid == - newState.interestDue - loanProperites.loanState.interestDue, + newState.interestDue - loanProperties.loanState.interestDue, " valueChange mismatch: expected " + - to_string( - newState.interestDue - - loanProperites.loanState.interestDue) + - ", got " + - to_string( - actualPaymentParts.valueChange - - actualPaymentParts.interestPaid)); + to_string(newState.interestDue - loanProperties.loanState.interestDue) + ", got " + + to_string(actualPaymentParts.valueChange - actualPaymentParts.interestPaid)); } void testTryOverpaymentLoanInterestFeeOverpaymentInterestFee() { - testcase( - "tryOverpayment - Loan Interest, Fee, Overpayment Interest, Fee"); + testcase("tryOverpayment - Loan Interest, Fee, Overpayment Interest, Fee"); using namespace jtx; using namespace xrpl::detail; @@ -1216,35 +1031,25 @@ class LendingHelpers_test : public beast::unit_test::suite Number const loanPrincipal{1'000}; std::uint32_t const paymentInterval = 30 * 24 * 60 * 60; std::uint32_t const paymentsRemaining = 10; - auto const periodicRate = - loanPeriodicRate(loanInterestRate, paymentInterval); + auto const periodicRate = loanPeriodicRate(loanInterestRate, paymentInterval); - ExtendedPaymentComponents const overpaymentComponents = - computeOverpaymentComponents( - asset, - loanScale, - Number{50, 0}, - TenthBips32(10'000), // 10% overpayment interest - TenthBips32(10'000), // 10% overpayment fee - managementFeeRate); - - auto const loanProperites = computeLoanProperties( + auto const overpaymentComponents = computeOverpaymentComponents( asset, - loanPrincipal, - loanInterestRate, - paymentInterval, - paymentsRemaining, - managementFeeRate, - loanScale); + loanScale, + Number{50, 0}, + TenthBips32(10'000), // 10% overpayment interest + TenthBips32(10'000), // 10% overpayment fee + managementFeeRate); - Number const periodicPayment = loanProperites.periodicPayment; + auto const loanProperties = computeLoanProperties( + asset, loanPrincipal, loanInterestRate, paymentInterval, paymentsRemaining, managementFeeRate, loanScale); auto const ret = tryOverpayment( asset, loanScale, overpaymentComponents, - loanProperites.loanState, - periodicPayment, + loanProperties.loanState, + loanProperties.periodicPayment, periodicRate, paymentsRemaining, managementFeeRate, @@ -1261,66 +1066,47 @@ class LendingHelpers_test : public beast::unit_test::suite // overpayment interest portion first, so interest paid remains 4.5 BEAST_EXPECTS( (actualPaymentParts.interestPaid == Number{45, -1}), - " interestPaid mismatch: expected 4.5, got " + - to_string(actualPaymentParts.interestPaid)); + " interestPaid mismatch: expected 4.5, got " + to_string(actualPaymentParts.interestPaid)); // With overpayment interest portion, value change should equal the // interest decrease plus overpayment interest portion BEAST_EXPECTS( - (actualPaymentParts.valueChange == - Number{-164737, -5} + actualPaymentParts.interestPaid), - " valueChange mismatch: expected " + - to_string( - Number{-164737, -5} + actualPaymentParts.interestPaid) + + (actualPaymentParts.valueChange == Number{-164737, -5} + actualPaymentParts.interestPaid), + " valueChange mismatch: expected " + to_string(Number{-164737, -5} + actualPaymentParts.interestPaid) + ", got " + to_string(actualPaymentParts.valueChange)); // While there is no overpayment fee, fee paid should equal the // management fee charged against the overpayment interest portion BEAST_EXPECTS( (actualPaymentParts.feePaid == Number{55, -1}), - " feePaid mismatch: expected 5.5, got " + - to_string(actualPaymentParts.feePaid)); + " feePaid mismatch: expected 5.5, got " + to_string(actualPaymentParts.feePaid)); BEAST_EXPECTS( actualPaymentParts.principalPaid == 40, - " principalPaid mismatch: expected 40, got `" + - to_string(actualPaymentParts.principalPaid)); + " principalPaid mismatch: expected 40, got `" + to_string(actualPaymentParts.principalPaid)); // =========== VALIDATE STATE CHANGES =========== BEAST_EXPECTS( actualPaymentParts.principalPaid == - loanProperites.loanState.principalOutstanding - - newState.principalOutstanding, + loanProperties.loanState.principalOutstanding - newState.principalOutstanding, " principalPaid mismatch: expected " + - to_string( - loanProperites.loanState.principalOutstanding - - newState.principalOutstanding) + - ", got " + to_string(actualPaymentParts.principalPaid)); + to_string(loanProperties.loanState.principalOutstanding - newState.principalOutstanding) + ", got " + + to_string(actualPaymentParts.principalPaid)); // Note that the management fee value change is not captured, as this // value is not needed to correctly update the Vault state. BEAST_EXPECTS( - (newState.managementFeeDue - - loanProperites.loanState.managementFeeDue == - Number{-18304, -5}), - " management fee change mismatch: expected " + - to_string(Number{-18304, -5}) + ", got " + - to_string( - newState.managementFeeDue - - loanProperites.loanState.managementFeeDue)); + (newState.managementFeeDue - loanProperties.loanState.managementFeeDue == Number{-18304, -5}), + " management fee change mismatch: expected " + to_string(Number{-18304, -5}) + ", got " + + to_string(newState.managementFeeDue - loanProperties.loanState.managementFeeDue)); BEAST_EXPECTS( actualPaymentParts.valueChange - actualPaymentParts.interestPaid == - newState.interestDue - loanProperites.loanState.interestDue, + newState.interestDue - loanProperties.loanState.interestDue, " valueChange mismatch: expected " + - to_string( - newState.interestDue - - loanProperites.loanState.interestDue) + - ", got " + - to_string( - actualPaymentParts.valueChange - - actualPaymentParts.interestPaid)); + to_string(newState.interestDue - loanProperties.loanState.interestDue) + ", got " + + to_string(actualPaymentParts.valueChange - actualPaymentParts.interestPaid)); } public: diff --git a/src/test/app/LoadFeeTrack_test.cpp b/src/test/app/LoadFeeTrack_test.cpp index e0638b64bc..61174fc9e9 100644 --- a/src/test/app/LoadFeeTrack_test.cpp +++ b/src/test/app/LoadFeeTrack_test.cpp @@ -23,13 +23,9 @@ public: return f; }(); - BEAST_EXPECT( - scaleFeeLoad(XRPAmount{0}, l, fees, false) == XRPAmount{0}); - BEAST_EXPECT( - scaleFeeLoad(XRPAmount{10000}, l, fees, false) == - XRPAmount{10000}); - BEAST_EXPECT( - scaleFeeLoad(XRPAmount{1}, l, fees, false) == XRPAmount{1}); + BEAST_EXPECT(scaleFeeLoad(XRPAmount{0}, l, fees, false) == XRPAmount{0}); + BEAST_EXPECT(scaleFeeLoad(XRPAmount{10000}, l, fees, false) == XRPAmount{10000}); + BEAST_EXPECT(scaleFeeLoad(XRPAmount{1}, l, fees, false) == XRPAmount{1}); } { Fees const fees = [&]() { @@ -40,13 +36,9 @@ public: return f; }(); - BEAST_EXPECT( - scaleFeeLoad(XRPAmount{0}, l, fees, false) == XRPAmount{0}); - BEAST_EXPECT( - scaleFeeLoad(XRPAmount{10000}, l, fees, false) == - XRPAmount{10000}); - BEAST_EXPECT( - scaleFeeLoad(XRPAmount{1}, l, fees, false) == XRPAmount{1}); + BEAST_EXPECT(scaleFeeLoad(XRPAmount{0}, l, fees, false) == XRPAmount{0}); + BEAST_EXPECT(scaleFeeLoad(XRPAmount{10000}, l, fees, false) == XRPAmount{10000}); + BEAST_EXPECT(scaleFeeLoad(XRPAmount{1}, l, fees, false) == XRPAmount{1}); } { Fees const fees = [&]() { @@ -57,13 +49,9 @@ public: return f; }(); - BEAST_EXPECT( - scaleFeeLoad(XRPAmount{0}, l, fees, false) == XRPAmount{0}); - BEAST_EXPECT( - scaleFeeLoad(XRPAmount{10000}, l, fees, false) == - XRPAmount{10000}); - BEAST_EXPECT( - scaleFeeLoad(XRPAmount{1}, l, fees, false) == XRPAmount{1}); + BEAST_EXPECT(scaleFeeLoad(XRPAmount{0}, l, fees, false) == XRPAmount{0}); + BEAST_EXPECT(scaleFeeLoad(XRPAmount{10000}, l, fees, false) == XRPAmount{10000}); + BEAST_EXPECT(scaleFeeLoad(XRPAmount{1}, l, fees, false) == XRPAmount{1}); } } }; diff --git a/src/test/app/LoanBroker_test.cpp b/src/test/app/LoanBroker_test.cpp index 769ed40321..58052e3fb1 100644 --- a/src/test/app/LoanBroker_test.cpp +++ b/src/test/app/LoanBroker_test.cpp @@ -12,8 +12,7 @@ class LoanBroker_test : public beast::unit_test::suite // Ensure that all the features needed for Lending Protocol are included, // even if they are set to unsupported. FeatureBitset const all{ - jtx::testable_amendments() | featureMPTokensV1 | - featureSingleAssetVault | featureLendingProtocol}; + jtx::testable_amendments() | featureMPTokensV1 | featureSingleAssetVault | featureLendingProtocol}; void testDisabled() @@ -33,8 +32,7 @@ class LoanBroker_test : public beast::unit_test::suite // Try to create a vault PrettyAsset const asset{xrpIssue(), 1'000'000}; Vault vault{env}; - auto const [tx, keylet] = - vault.create({.owner = alice, .asset = asset}); + auto const [tx, keylet] = vault.create({.owner = alice, .asset = asset}); env(tx, ter(goodVault ? ter(tesSUCCESS) : ter(temDISABLED))); env.close(); BEAST_EXPECT(static_cast(env.le(keylet)) == goodVault); @@ -42,25 +40,17 @@ class LoanBroker_test : public beast::unit_test::suite using namespace loanBroker; // Can't create a loan broker regardless of whether the vault exists env(set(alice, keylet.key), ter(temDISABLED)); - auto const brokerKeylet = - keylet::loanbroker(alice.id(), env.seq(alice)); + auto const brokerKeylet = keylet::loanbroker(alice.id(), env.seq(alice)); // Other LoanBroker transactions are disabled, too. // 1. LoanBrokerCoverDeposit - env(coverDeposit(alice, brokerKeylet.key, asset(1000)), - ter(temDISABLED)); + env(coverDeposit(alice, brokerKeylet.key, asset(1000)), ter(temDISABLED)); // 2. LoanBrokerCoverWithdraw - env(coverWithdraw(alice, brokerKeylet.key, asset(1000)), - ter(temDISABLED)); + env(coverWithdraw(alice, brokerKeylet.key, asset(1000)), ter(temDISABLED)); // 3. LoanBrokerCoverClawback env(coverClawback(alice), ter(temDISABLED)); - env(coverClawback(alice), - loanBrokerID(brokerKeylet.key), - ter(temDISABLED)); + env(coverClawback(alice), loanBrokerID(brokerKeylet.key), ter(temDISABLED)); env(coverClawback(alice), amount(asset(0)), ter(temDISABLED)); - env(coverClawback(alice), - loanBrokerID(brokerKeylet.key), - amount(asset(1000)), - ter(temDISABLED)); + env(coverClawback(alice), loanBrokerID(brokerKeylet.key), amount(asset(1000)), ter(temDISABLED)); // 4. LoanBrokerDelete env(del(alice, brokerKeylet.key), ter(temDISABLED)); }; @@ -75,10 +65,7 @@ class LoanBroker_test : public beast::unit_test::suite jtx::PrettyAsset asset; uint256 vaultID; jtx::Account pseudoAccount; - VaultInfo( - jtx::PrettyAsset const& asset_, - uint256 const& vaultID_, - AccountID const& pseudo) + VaultInfo(jtx::PrettyAsset const& asset_, uint256 const& vaultID_, AccountID const& pseudo) : asset(asset_), vaultID(vaultID_), pseudoAccount("vault", pseudo) { } @@ -115,8 +102,7 @@ class LoanBroker_test : public beast::unit_test::suite // Bogus assets to use in test cases static PrettyAsset const badMptAsset = [&]() { MPTTester badMptt{env, evan, mptInitNoFund}; - badMptt.create( - {.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock}); + badMptt.create({.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock}); env.close(); return badMptt["BAD"]; }(); @@ -172,8 +158,7 @@ class LoanBroker_test : public beast::unit_test::suite // std::endl; // } // Load the pseudo-account - Account const pseudoAccount{ - "Broker pseudo-account", broker->at(sfAccount)}; + Account const pseudoAccount{"Broker pseudo-account", broker->at(sfAccount)}; auto const pseudoKeylet = keylet::account(pseudoAccount); if (auto const pseudo = env.le(pseudoKeylet); BEAST_EXPECT(pseudo)) @@ -181,14 +166,10 @@ class LoanBroker_test : public beast::unit_test::suite // log << "Pseudo-account after create: " // << to_string(pseudo->getJson()) << std::endl // << std::endl; - BEAST_EXPECT( - pseudo->at(sfFlags) == - (lsfDisableMaster | lsfDefaultRipple | lsfDepositAuth)); + BEAST_EXPECT(pseudo->at(sfFlags) == (lsfDisableMaster | lsfDefaultRipple | lsfDepositAuth)); BEAST_EXPECT(pseudo->at(sfSequence) == 0); BEAST_EXPECT(pseudo->at(sfBalance) == beast::zero); - BEAST_EXPECT( - pseudo->at(sfOwnerCount) == - (vault.asset.raw().native() ? 0 : 1)); + BEAST_EXPECT(pseudo->at(sfOwnerCount) == (vault.asset.raw().native() ? 0 : 1)); BEAST_EXPECT(!pseudo->isFieldPresent(sfAccountTxnID)); BEAST_EXPECT(!pseudo->isFieldPresent(sfRegularKey)); BEAST_EXPECT(!pseudo->isFieldPresent(sfEmailHash)); @@ -214,17 +195,13 @@ class LoanBroker_test : public beast::unit_test::suite auto const accountInfo = env.rpc("account_info", pseudoStr); if (BEAST_EXPECT(accountInfo.isObject())) { - auto const& accountData = - accountInfo[jss::result][jss::account_data]; + auto const& accountData = accountInfo[jss::result][jss::account_data]; if (BEAST_EXPECT(accountData.isObject())) { BEAST_EXPECT(accountData[jss::Account] == pseudoStr); - BEAST_EXPECT( - accountData[sfLoanBrokerID] == - to_string(keylet.key)); + BEAST_EXPECT(accountData[sfLoanBrokerID] == to_string(keylet.key)); } - auto const& pseudoInfo = - accountInfo[jss::result][jss::pseudo_account]; + auto const& pseudoInfo = accountInfo[jss::result][jss::pseudo_account]; if (BEAST_EXPECT(pseudoInfo.isObject())) { BEAST_EXPECT(pseudoInfo[jss::type] == "LoanBroker"); @@ -232,58 +209,41 @@ class LoanBroker_test : public beast::unit_test::suite } } - auto verifyCoverAmount = - [&env, &vault, &pseudoAccount, &broker, &keylet, this](auto n) { - using namespace jtx; + auto verifyCoverAmount = [&env, &vault, &pseudoAccount, &broker, &keylet, this](auto n) { + using namespace jtx; - if (BEAST_EXPECT(broker = env.le(keylet))) - { - auto const amount = vault.asset(n); - BEAST_EXPECT( - broker->at(sfCoverAvailable) == amount.number()); - env.require(balance(pseudoAccount, amount)); - } - }; + if (BEAST_EXPECT(broker = env.le(keylet))) + { + auto const amount = vault.asset(n); + BEAST_EXPECT(broker->at(sfCoverAvailable) == amount.number()); + env.require(balance(pseudoAccount, amount)); + } + }; // Test Cover funding before allowing alterations - env(coverDeposit(alice, uint256(0), vault.asset(10)), - ter(temINVALID)); - env(coverDeposit(evan, keylet.key, vault.asset(10)), - ter(tecNO_PERMISSION)); - env(coverDeposit(evan, keylet.key, vault.asset(0)), - ter(temBAD_AMOUNT)); - env(coverDeposit(evan, keylet.key, vault.asset(-10)), - ter(temBAD_AMOUNT)); - env(coverDeposit(alice, vault.vaultID, vault.asset(10)), - ter(tecNO_ENTRY)); + env(coverDeposit(alice, uint256(0), vault.asset(10)), ter(temINVALID)); + env(coverDeposit(evan, keylet.key, vault.asset(10)), ter(tecNO_PERMISSION)); + env(coverDeposit(evan, keylet.key, vault.asset(0)), ter(temBAD_AMOUNT)); + env(coverDeposit(evan, keylet.key, vault.asset(-10)), ter(temBAD_AMOUNT)); + env(coverDeposit(alice, vault.vaultID, vault.asset(10)), ter(tecNO_ENTRY)); verifyCoverAmount(0); // Test cover clawback failure cases BEFORE depositing any cover // Need one of brokerID or amount env(coverClawback(alice), ter(temINVALID)); - env(coverClawback(alice), - loanBrokerID(uint256(0)), - ter(temINVALID)); + env(coverClawback(alice), loanBrokerID(uint256(0)), ter(temINVALID)); env(coverClawback(alice), amount(XRP(1000)), ter(temBAD_AMOUNT)); - env(coverClawback(alice), - amount(vault.asset(-10)), - ter(temBAD_AMOUNT)); + env(coverClawback(alice), amount(vault.asset(-10)), ter(temBAD_AMOUNT)); // Clawbacks with an MPT need to specify the broker ID env(coverClawback(alice), amount(badMptAsset(1)), ter(temINVALID)); - env(coverClawback(evan), - loanBrokerID(vault.vaultID), - ter(tecNO_ENTRY)); + env(coverClawback(evan), loanBrokerID(vault.vaultID), ter(tecNO_ENTRY)); // Only the issuer can clawback - env(coverClawback(alice), - loanBrokerID(keylet.key), - ter(tecNO_PERMISSION)); + env(coverClawback(alice), loanBrokerID(keylet.key), ter(tecNO_PERMISSION)); if (vault.asset.raw().native()) { // Can not clawback XRP under any circumstances - env(coverClawback(issuer), - loanBrokerID(keylet.key), - ter(tecNO_PERMISSION)); + env(coverClawback(issuer), loanBrokerID(keylet.key), ter(tecNO_PERMISSION)); } else { @@ -291,24 +251,17 @@ class LoanBroker_test : public beast::unit_test::suite { // Clawbacks without a loanBrokerID need to specify an IOU // with the broker's pseudo-account as the issuer - env(coverClawback(alice), - amount(ghostIouAsset(1)), - ter(tecNO_ENTRY)); - env(coverClawback(alice), - amount(badIouAsset(1)), - ter(tecOBJECT_NOT_FOUND)); + env(coverClawback(alice), amount(ghostIouAsset(1)), ter(tecNO_ENTRY)); + env(coverClawback(alice), amount(badIouAsset(1)), ter(tecOBJECT_NOT_FOUND)); // Pseudo-account is not for a broker - env(coverClawback(alice), - amount(vaultPseudoIouAsset(1)), - ter(tecOBJECT_NOT_FOUND)); + env(coverClawback(alice), amount(vaultPseudoIouAsset(1)), ter(tecOBJECT_NOT_FOUND)); // If we specify a pseudo-account as the IOU amount, it // needs to match the loan broker env(coverClawback(issuer), loanBrokerID(keylet.key), amount(badBrokerPseudoIouAsset(10)), ter(tecWRONG_ASSET)); - PrettyAsset const brokerWrongCurrencyAsset = - pseudoAccount["WAT"]; + PrettyAsset const brokerWrongCurrencyAsset = pseudoAccount["WAT"]; env(coverClawback(issuer), loanBrokerID(keylet.key), amount(brokerWrongCurrencyAsset(10)), @@ -319,9 +272,7 @@ class LoanBroker_test : public beast::unit_test::suite // Clawbacks with an MPT need to specify the broker ID, even // if the asset is valid BEAST_EXPECT(vault.asset.raw().holds()); - env(coverClawback(alice), - amount(vault.asset(10)), - ter(temINVALID)); + env(coverClawback(alice), amount(vault.asset(10)), ter(temINVALID)); } // Since no cover has been deposited, there's nothing to claw // back @@ -338,34 +289,22 @@ class LoanBroker_test : public beast::unit_test::suite verifyCoverAmount(10); // Test withdrawal failure cases - env(coverWithdraw(alice, uint256(0), vault.asset(10)), - ter(temINVALID)); - env(coverWithdraw(evan, keylet.key, vault.asset(10)), - ter(tecNO_PERMISSION)); - env(coverWithdraw(evan, keylet.key, vault.asset(0)), - ter(temBAD_AMOUNT)); - env(coverWithdraw(evan, keylet.key, vault.asset(-10)), - ter(temBAD_AMOUNT)); - env(coverWithdraw(alice, vault.vaultID, vault.asset(10)), - ter(tecNO_ENTRY)); - env(coverWithdraw(alice, keylet.key, vault.asset(900)), - ter(tecINSUFFICIENT_FUNDS)); + env(coverWithdraw(alice, uint256(0), vault.asset(10)), ter(temINVALID)); + env(coverWithdraw(evan, keylet.key, vault.asset(10)), ter(tecNO_PERMISSION)); + env(coverWithdraw(evan, keylet.key, vault.asset(0)), ter(temBAD_AMOUNT)); + env(coverWithdraw(evan, keylet.key, vault.asset(-10)), ter(temBAD_AMOUNT)); + env(coverWithdraw(alice, vault.vaultID, vault.asset(10)), ter(tecNO_ENTRY)); + env(coverWithdraw(alice, keylet.key, vault.asset(900)), ter(tecINSUFFICIENT_FUNDS)); // Skip this test for XRP, because that can always be sent if (!vault.asset.raw().native()) { - TER const expected = vault.asset.raw().holds() - ? tecNO_AUTH - : tecNO_LINE; - env(coverWithdraw(alice, keylet.key, vault.asset(1)), - destination(bystander), - ter(expected)); + TER const expected = vault.asset.raw().holds() ? tecNO_AUTH : tecNO_LINE; + env(coverWithdraw(alice, keylet.key, vault.asset(1)), destination(bystander), ter(expected)); } // Can not withdraw to the zero address - env(coverWithdraw(alice, keylet.key, vault.asset(1)), - destination(AccountID{}), - ter(temMALFORMED)); + env(coverWithdraw(alice, keylet.key, vault.asset(1)), destination(AccountID{}), ter(temMALFORMED)); // Withdraw some of the cover amount env(coverWithdraw(alice, keylet.key, vault.asset(7))); @@ -379,25 +318,20 @@ class LoanBroker_test : public beast::unit_test::suite // Withdraw some more. Send it to Evan. Very generous, considering // how much trouble he's been. - env(coverWithdraw(alice, keylet.key, vault.asset(1)), - destination(evan)); + env(coverWithdraw(alice, keylet.key, vault.asset(1)), destination(evan)); env.close(); verifyCoverAmount(7); // Withdraw some more. Send it to Evan. Very generous, considering // how much trouble he's been. - env(coverWithdraw(alice, keylet.key, vault.asset(1)), - destination(evan), - dtag(3)); + env(coverWithdraw(alice, keylet.key, vault.asset(1)), destination(evan), dtag(3)); env.close(); verifyCoverAmount(6); if (!vault.asset.raw().native()) { // Issuer claws back some of the cover - env(coverClawback(issuer), - loanBrokerID(keylet.key), - amount(vault.asset(2))); + env(coverClawback(issuer), loanBrokerID(keylet.key), amount(vault.asset(2))); env.close(); verifyCoverAmount(4); @@ -409,12 +343,7 @@ class LoanBroker_test : public beast::unit_test::suite // Issuer claws it all back in various different ways for (auto const& tx : { // defer autofills until submission time - env.json( - coverClawback(issuer), - loanBrokerID(keylet.key), - fee(none), - seq(none), - sig(none)), + env.json(coverClawback(issuer), loanBrokerID(keylet.key), fee(none), seq(none), sig(none)), env.json( coverClawback(issuer), loanBrokerID(keylet.key), @@ -468,10 +397,7 @@ class LoanBroker_test : public beast::unit_test::suite // Verify that fields get removed when set to default values // Debt maximum: explicit 0 // Data: explicit empty - env(set(alice, vault.vaultID), - loanBrokerID(broker->key()), - debtMaximum(Number(0)), - data("")); + env(set(alice, vault.vaultID), loanBrokerID(broker->key()), debtMaximum(Number(0)), data("")); env.close(); // Check the updated fields @@ -519,9 +445,7 @@ class LoanBroker_test : public beast::unit_test::suite BEAST_EXPECT(!pseudo); } auto const expectedBalance = aliceBalance + coverFunds - - (aliceBalance.value().native() - ? STAmount(env.current()->fees().base.value()) - : vault.asset(0)); + (aliceBalance.value().native() ? STAmount(env.current()->fees().base.value()) : vault.asset(0)); env.require(balance(alice, expectedBalance)); env.require(balance(pseudoAccount, vault.asset(none))); } @@ -566,8 +490,7 @@ class LoanBroker_test : public beast::unit_test::suite env.close(); MPTTester mptt{env, issuer, mptInitNoFund}; - mptt.create( - {.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock}); + mptt.create({.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock}); env.close(); PrettyAsset const mptAsset = mptt["MPT"]; mptt.authorize({.account = alice}); @@ -591,13 +514,11 @@ class LoanBroker_test : public beast::unit_test::suite vaults.emplace_back(asset, keylet.key, le->at(sfAccount)); } - env(vault.deposit( - {.depositor = alice, .id = keylet.key, .amount = asset(50)})); + env(vault.deposit({.depositor = alice, .id = keylet.key, .amount = asset(50)})); env.close(); } VaultInfo const badVault = [&]() -> VaultInfo { - auto [tx, keylet] = - vault.create({.owner = alice, .asset = iouAsset}); + auto [tx, keylet] = vault.create({.owner = alice, .asset = iouAsset}); env(tx); env.close(); if (auto const le = env.le(keylet); BEAST_EXPECT(env.le(keylet))) @@ -615,21 +536,17 @@ class LoanBroker_test : public beast::unit_test::suite { { // Get the AccountInfo RPC result for the vault pseudo-account - std::string const pseudoStr = - to_string(vault.pseudoAccount.id()); + std::string const pseudoStr = to_string(vault.pseudoAccount.id()); auto const accountInfo = env.rpc("account_info", pseudoStr); if (BEAST_EXPECT(accountInfo.isObject())) { - auto const& accountData = - accountInfo[jss::result][jss::account_data]; + auto const& accountData = accountInfo[jss::result][jss::account_data]; if (BEAST_EXPECT(accountData.isObject())) { BEAST_EXPECT(accountData[jss::Account] == pseudoStr); - BEAST_EXPECT( - accountData[sfVaultID] == to_string(vault.vaultID)); + BEAST_EXPECT(accountData[sfVaultID] == to_string(vault.vaultID)); } - auto const& pseudoInfo = - accountInfo[jss::result][jss::pseudo_account]; + auto const& pseudoInfo = accountInfo[jss::result][jss::pseudo_account]; if (BEAST_EXPECT(pseudoInfo.isObject())) { BEAST_EXPECT(pseudoInfo[jss::type] == "Vault"); @@ -652,21 +569,13 @@ class LoanBroker_test : public beast::unit_test::suite env(set(evan, vault.vaultID, ~tfUniversal), ter(temINVALID_FLAG)); // field length validation // sfData: good length, bad account - env(set(evan, vault.vaultID), - data(std::string(maxDataPayloadLength, 'X')), - ter(tecNO_PERMISSION)); + env(set(evan, vault.vaultID), data(std::string(maxDataPayloadLength, 'X')), ter(tecNO_PERMISSION)); // sfData: too long - env(set(evan, vault.vaultID), - data(std::string(maxDataPayloadLength + 1, 'Y')), - ter(temINVALID)); + env(set(evan, vault.vaultID), data(std::string(maxDataPayloadLength + 1, 'Y')), ter(temINVALID)); // sfManagementFeeRate: good value, bad account - env(set(evan, vault.vaultID), - managementFeeRate(maxManagementFeeRate), - ter(tecNO_PERMISSION)); + env(set(evan, vault.vaultID), managementFeeRate(maxManagementFeeRate), ter(tecNO_PERMISSION)); // sfManagementFeeRate: too big - env(set(evan, vault.vaultID), - managementFeeRate(maxManagementFeeRate + TenthBips16(10)), - ter(temINVALID)); + env(set(evan, vault.vaultID), managementFeeRate(maxManagementFeeRate + TenthBips16(10)), ter(temINVALID)); // sfCoverRateMinimum and sfCoverRateLiquidation are linked // Cover: good value, bad account env(set(evan, vault.vaultID), @@ -685,34 +594,24 @@ class LoanBroker_test : public beast::unit_test::suite ter(temINVALID)); // Cover: zero min, non-zero liquidation - implicit and // explicit zero values. - env(set(evan, vault.vaultID), - coverRateLiquidation(maxCoverRate), - ter(temINVALID)); + env(set(evan, vault.vaultID), coverRateLiquidation(maxCoverRate), ter(temINVALID)); env(set(evan, vault.vaultID), coverRateMinimum(tenthBipsZero), coverRateLiquidation(maxCoverRate), ter(temINVALID)); // Cover: non-zero min, zero liquidation - implicit and // explicit zero values. - env(set(evan, vault.vaultID), - coverRateMinimum(maxCoverRate), - ter(temINVALID)); + env(set(evan, vault.vaultID), coverRateMinimum(maxCoverRate), ter(temINVALID)); env(set(evan, vault.vaultID), coverRateMinimum(maxCoverRate), coverRateLiquidation(tenthBipsZero), ter(temINVALID)); // sfDebtMaximum: good value, bad account - env(set(evan, vault.vaultID), - debtMaximum(Number(0)), - ter(tecNO_PERMISSION)); + env(set(evan, vault.vaultID), debtMaximum(Number(0)), ter(tecNO_PERMISSION)); // sfDebtMaximum: overflow - env(set(evan, vault.vaultID), - debtMaximum(Number(1, 100)), - ter(temINVALID)); + env(set(evan, vault.vaultID), debtMaximum(Number(1, 100)), ter(temINVALID)); // sfDebtMaximum: negative - env(set(evan, vault.vaultID), - debtMaximum(Number(-1)), - ter(temINVALID)); + env(set(evan, vault.vaultID), debtMaximum(Number(-1)), ter(temINVALID)); std::string testData; lifecycle( @@ -730,40 +629,28 @@ class LoanBroker_test : public beast::unit_test::suite // Extra checks BEAST_EXPECT(!broker->isFieldPresent(sfManagementFeeRate)); BEAST_EXPECT(!broker->isFieldPresent(sfCoverRateMinimum)); - BEAST_EXPECT( - !broker->isFieldPresent(sfCoverRateLiquidation)); + BEAST_EXPECT(!broker->isFieldPresent(sfCoverRateLiquidation)); BEAST_EXPECT(!broker->isFieldPresent(sfData)); BEAST_EXPECT(!broker->isFieldPresent(sfDebtMaximum)); BEAST_EXPECT(broker->at(sfDebtMaximum) == 0); BEAST_EXPECT(broker->at(sfCoverRateMinimum) == 0); BEAST_EXPECT(broker->at(sfCoverRateLiquidation) == 0); - BEAST_EXPECT( - env.ownerCount(alice) == aliceOriginalCount + 4); + BEAST_EXPECT(env.ownerCount(alice) == aliceOriginalCount + 4); }, [&](SLE::const_ref broker) { // Modifications // Update the fields - auto const nextKeylet = - keylet::loanbroker(alice.id(), env.seq(alice)); + auto const nextKeylet = keylet::loanbroker(alice.id(), env.seq(alice)); // fields that can't be changed // LoanBrokerID - env(set(alice, vault.vaultID), - loanBrokerID(nextKeylet.key), - ter(tecNO_ENTRY), - THISLINE); + env(set(alice, vault.vaultID), loanBrokerID(nextKeylet.key), ter(tecNO_ENTRY), THISLINE); // VaultID - env(set(alice, nextKeylet.key), - loanBrokerID(broker->key()), - ter(tecNO_ENTRY), - THISLINE); + env(set(alice, nextKeylet.key), loanBrokerID(broker->key()), ter(tecNO_ENTRY), THISLINE); // Owner - env(set(evan, vault.vaultID), - loanBrokerID(broker->key()), - ter(tecNO_PERMISSION), - THISLINE); + env(set(evan, vault.vaultID), loanBrokerID(broker->key()), ter(tecNO_PERMISSION), THISLINE); // ManagementFeeRate env(set(alice, vault.vaultID), loanBrokerID(broker->key()), @@ -819,13 +706,10 @@ class LoanBroker_test : public beast::unit_test::suite [&](SLE::const_ref broker) { // Check the updated fields BEAST_EXPECT(checkVL(broker->at(sfData), testData)); - Number const expected = - STAmount{vault.asset, Number(175, -1)}; + Number const expected = STAmount{vault.asset, Number(175, -1)}; auto const actual = broker->at(sfDebtMaximum); BEAST_EXPECTS( - actual == expected, - "Expected: " + to_string(expected) + - ", Actual: " + to_string(actual)); + actual == expected, "Expected: " + to_string(expected) + ", Actual: " + to_string(actual)); }); lifecycle( @@ -859,10 +743,7 @@ class LoanBroker_test : public beast::unit_test::suite }, [&](SLE::const_ref broker) { // Reset Data & Debt maximum to default values - env(set(alice, vault.vaultID), - loanBrokerID(broker->key()), - data(""), - debtMaximum(Number(0))); + env(set(alice, vault.vaultID), loanBrokerID(broker->key()), data(""), debtMaximum(Number(0))); }, [&](SLE::const_ref broker) { // Check the updated fields @@ -874,20 +755,11 @@ class LoanBroker_test : public beast::unit_test::suite BEAST_EXPECT(env.ownerCount(alice) == aliceOriginalCount); } - enum LoanBrokerTest { - CoverClawback, - CoverDeposit, - CoverWithdraw, - Delete, - Set - }; + enum LoanBrokerTest { CoverClawback, CoverDeposit, CoverWithdraw, Delete, Set }; void testLoanBroker( - std::function getAsset, + std::function getAsset, LoanBrokerTest brokerTest) { using namespace jtx; @@ -923,15 +795,10 @@ class LoanBroker_test : public beast::unit_test::suite if (vaultInfo.vaultID == uint256{}) return; - env(vault.deposit( - {.depositor = alice, - .id = vaultKeylet.key, - .amount = asset(50)}), - THISLINE); + env(vault.deposit({.depositor = alice, .id = vaultKeylet.key, .amount = asset(50)}), THISLINE); env.close(); - auto const brokerKeylet = - keylet::loanbroker(alice.id(), env.seq(alice)); + auto const brokerKeylet = keylet::loanbroker(alice.id(), env.seq(alice)); env(set(alice, vaultInfo.vaultID), THISLINE); env.close(); @@ -965,91 +832,62 @@ class LoanBroker_test : public beast::unit_test::suite if (brokerTest == CoverDeposit) { // preflight: temINVALID (empty/zero broker id) - testZeroBrokerID([&]() { - return coverDeposit(alice, brokerKeylet.key, asset(10)); - }); + testZeroBrokerID([&]() { return coverDeposit(alice, brokerKeylet.key, asset(10)); }); // preclaim: tecWRONG_ASSET - env(coverDeposit(alice, brokerKeylet.key, issuer["BAD"](10)), - ter(tecWRONG_ASSET), - THISLINE); + env(coverDeposit(alice, brokerKeylet.key, issuer["BAD"](10)), ter(tecWRONG_ASSET), THISLINE); // preclaim: tecINSUFFICIENT_FUNDS env(pay(alice, issuer, asset(100'000 - 50)), THISLINE); env.close(); - env(coverDeposit(alice, brokerKeylet.key, vaultInfo.asset(10)), - ter(tecINSUFFICIENT_FUNDS)); + env(coverDeposit(alice, brokerKeylet.key, vaultInfo.asset(10)), ter(tecINSUFFICIENT_FUNDS)); // preclaim: tecFROZEN env(fset(issuer, asfGlobalFreeze), THISLINE); env.close(); - env(coverDeposit(alice, brokerKeylet.key, vaultInfo.asset(10)), - ter(tecFROZEN), - THISLINE); + env(coverDeposit(alice, brokerKeylet.key, vaultInfo.asset(10)), ter(tecFROZEN), THISLINE); } else // Fund the cover deposit - env(coverDeposit(alice, brokerKeylet.key, vaultInfo.asset(10)), - THISLINE); + env(coverDeposit(alice, brokerKeylet.key, vaultInfo.asset(10)), THISLINE); env.close(); if (brokerTest == CoverWithdraw) { // preflight: temINVALID (empty/zero broker id) - testZeroBrokerID([&]() { - return coverWithdraw(alice, brokerKeylet.key, asset(10)); - }); + testZeroBrokerID([&]() { return coverWithdraw(alice, brokerKeylet.key, asset(10)); }); // preclaim: tecWRONG_ASSET - env(coverWithdraw(alice, brokerKeylet.key, issuer["BAD"](10)), - ter(tecWRONG_ASSET), - THISLINE); + env(coverWithdraw(alice, brokerKeylet.key, issuer["BAD"](10)), ter(tecWRONG_ASSET), THISLINE); // preclaim: tecNO_DST Account const bogus{"bogus"}; - env(coverWithdraw(alice, brokerKeylet.key, asset(10)), - destination(bogus), - ter(tecNO_DST), - THISLINE); + env(coverWithdraw(alice, brokerKeylet.key, asset(10)), destination(bogus), ter(tecNO_DST), THISLINE); // preclaim: tecDST_TAG_NEEDED Account const dest{"dest"}; env.fund(XRP(1'000), dest); env(fset(dest, asfRequireDest), THISLINE); env.close(); - env(coverWithdraw(alice, brokerKeylet.key, asset(10)), - destination(dest), - ter(tecDST_TAG_NEEDED), - THISLINE); + env(coverWithdraw(alice, brokerKeylet.key, asset(10)), destination(dest), ter(tecDST_TAG_NEEDED), THISLINE); // preclaim: tecNO_PERMISSION env(fclear(dest, asfRequireDest), THISLINE); env(fset(dest, asfDepositAuth), THISLINE); env.close(); - env(coverWithdraw(alice, brokerKeylet.key, asset(10)), - destination(dest), - ter(tecNO_PERMISSION), - THISLINE); + env(coverWithdraw(alice, brokerKeylet.key, asset(10)), destination(dest), ter(tecNO_PERMISSION), THISLINE); // preclaim: tecFROZEN env(trust(dest, asset(1'000)), THISLINE); env(fclear(dest, asfDepositAuth), THISLINE); env(fset(issuer, asfGlobalFreeze), THISLINE); env.close(); - env(coverWithdraw(alice, brokerKeylet.key, asset(10)), - destination(dest), - ter(tecFROZEN), - THISLINE); + env(coverWithdraw(alice, brokerKeylet.key, asset(10)), destination(dest), ter(tecFROZEN), THISLINE); // preclaim:: tecFROZEN (deep frozen) env(fclear(issuer, asfGlobalFreeze), THISLINE); - env(trust( - issuer, asset(1'000), dest, tfSetFreeze | tfSetDeepFreeze), - THISLINE); - env(coverWithdraw(alice, brokerKeylet.key, asset(10)), - destination(dest), - ter(tecFROZEN), - THISLINE); + env(trust(issuer, asset(1'000), dest, tfSetFreeze | tfSetDeepFreeze), THISLINE); + env(coverWithdraw(alice, brokerKeylet.key, asset(10)), destination(dest), ter(tecFROZEN), THISLINE); // preclaim: tecPSEUDO_ACCOUNT env(coverWithdraw(alice, brokerKeylet.key, asset(10)), @@ -1062,15 +900,12 @@ class LoanBroker_test : public beast::unit_test::suite { // preflight: temINVALID (empty/zero broker id) testZeroBrokerID([&]() { - return env.json( - coverClawback(alice), - loanBrokerID(brokerKeylet.key), - amount(vaultInfo.asset(2))); + return env.json(coverClawback(alice), loanBrokerID(brokerKeylet.key), amount(vaultInfo.asset(2))); }); if (asset.holds()) { - // preclaim: AllowTrustLineClaback is not set + // preclaim: AllowTrustLineClawback is not set env(coverClawback(issuer), loanBrokerID(brokerKeylet.key), amount(vaultInfo.asset(2)), @@ -1078,8 +913,7 @@ class LoanBroker_test : public beast::unit_test::suite THISLINE); // preclaim: NoFreeze is set - env(fset(issuer, asfAllowTrustLineClawback | asfNoFreeze), - THISLINE); + env(fset(issuer, asfAllowTrustLineClawback | asfNoFreeze), THISLINE); env.close(); env(coverClawback(issuer), loanBrokerID(brokerKeylet.key), @@ -1112,23 +946,17 @@ class LoanBroker_test : public beast::unit_test::suite testZeroBrokerID([&]() { return del(alice, brokerKeylet.key); }); // preclaim: tecHAS_OBLIGATIONS - env(del(alice, brokerKeylet.key), - ter(tecHAS_OBLIGATIONS), - THISLINE); + env(del(alice, brokerKeylet.key), ter(tecHAS_OBLIGATIONS), THISLINE); // Repay and delete the loan auto const loanKeylet = keylet::loan(brokerKeylet.key, 1); - env(loan::pay(borrower, loanKeylet.key, asset(50).value()), - THISLINE); + env(loan::pay(borrower, loanKeylet.key, asset(50).value()), THISLINE); env(loan::del(alice, loanKeylet.key), THISLINE); - env(trust(issuer, asset(0), alice, tfSetFreeze | tfSetDeepFreeze), - THISLINE); + env(trust(issuer, asset(0), alice, tfSetFreeze | tfSetDeepFreeze), THISLINE); // preclaim: tecFROZEN (deep frozen) env(del(alice, brokerKeylet.key), ter(tecFROZEN), THISLINE); - env(trust( - issuer, asset(0), alice, tfClearFreeze | tfClearDeepFreeze), - THISLINE); + env(trust(issuer, asset(0), alice, tfClearFreeze | tfClearDeepFreeze), THISLINE); // successful delete the loan broker object env(del(alice, brokerKeylet.key), ter(tesSUCCESS), THISLINE); @@ -1139,17 +967,9 @@ class LoanBroker_test : public beast::unit_test::suite if (brokerTest == Set) { // preflight: temINVALID (empty/zero broker id) - testZeroBrokerID([&]() { - return env.json( - set(alice, vaultInfo.vaultID), - loanBrokerID(brokerKeylet.key)); - }); + testZeroBrokerID([&]() { return env.json(set(alice, vaultInfo.vaultID), loanBrokerID(brokerKeylet.key)); }); // preflight: temINVALID (empty/zero vault id) - testZeroVaultID([&]() { - return env.json( - set(alice, vaultInfo.vaultID), - loanBrokerID(brokerKeylet.key)); - }); + testZeroVaultID([&]() { return env.json(set(alice, vaultInfo.vaultID), loanBrokerID(brokerKeylet.key)); }); if (asset.holds()) { @@ -1162,14 +982,11 @@ class LoanBroker_test : public beast::unit_test::suite env.close(); } - auto const amt = env.balance(alice) - - env.current()->fees().accountReserve(env.ownerCount(alice)); + auto const amt = env.balance(alice) - env.current()->fees().accountReserve(env.ownerCount(alice)); env(pay(alice, issuer, amt), THISLINE); // preclaim:: tecINSUFFICIENT_RESERVE - env(set(alice, vaultInfo.vaultID), - ter(tecINSUFFICIENT_RESERVE), - THISLINE); + env(set(alice, vaultInfo.vaultID), ter(tecINSUFFICIENT_RESERVE), THISLINE); } } @@ -1216,8 +1033,7 @@ class LoanBroker_test : public beast::unit_test::suite // MPTCanClawback is not set testLoanBroker( [&](Env& env, Account const& issuer, Account const& alice) -> MPT { - MPTTester mpt( - {.env = env, .issuer = issuer, .holders = {alice}}); + MPTTester mpt({.env = env, .issuer = issuer, .holders = {alice}}); return mpt; }, CoverClawback); @@ -1298,14 +1114,12 @@ class LoanBroker_test : public beast::unit_test::suite // Create a Vault owned by alice with an XRP asset PrettyAsset const asset{xrpIssue(), 1}; Vault vault{env}; - auto const [createTx, vaultKeylet] = - vault.create({.owner = alice, .asset = asset}); + auto const [createTx, vaultKeylet] = vault.create({.owner = alice, .asset = asset}); env(createTx); env.close(); // Predict LoanBroker key using alice's current sequence BEFORE submit - auto const brokerKeylet = - keylet::loanbroker(alice.id(), env.seq(alice)); + auto const brokerKeylet = keylet::loanbroker(alice.id(), env.seq(alice)); // Create LoanBroker pointing to the vault env(loanBroker::set(alice, vaultKeylet.key)); @@ -1322,17 +1136,9 @@ class LoanBroker_test : public beast::unit_test::suite OpenView ov{*env.current()}; test::StreamSink sink{beast::severities::kWarning}; beast::Journal jlog{sink}; - ApplyContext ac{ - env.app(), - ov, - tx, - tesSUCCESS, - env.current()->fees().base, - tapNONE, - jlog}; + ApplyContext ac{env.app(), ov, tx, tesSUCCESS, env.current()->fees().base, tapNONE, jlog}; - if (auto sleBroker = - ac.view().peek(keylet::loanbroker(brokerKeylet.key))) + if (auto sleBroker = ac.view().peek(keylet::loanbroker(brokerKeylet.key))) { auto const vaultID = (*sleBroker)[sfVaultID]; if (auto sleVault = ac.view().peek(keylet::vault(vaultID))) @@ -1343,8 +1149,7 @@ class LoanBroker_test : public beast::unit_test::suite // Invoke preclaim against the mutated (ApplyView) view; triggers // nullptr deref - PreclaimContext pctx{ - env.app(), ac.view(), tesSUCCESS, tx, tapNONE, jlog}; + PreclaimContext pctx{env.app(), ac.view(), tesSUCCESS, tx, tapNONE, jlog}; (void)LoanBrokerCoverDeposit::preclaim(pctx); } @@ -1367,8 +1172,7 @@ class LoanBroker_test : public beast::unit_test::suite .env = env, .issuer = issuer, .holders = {alice}, - .flags = MPTDEXFlags | tfMPTRequireAuth | tfMPTCanClawback | - tfMPTCanLock, + .flags = MPTDEXFlags | tfMPTRequireAuth | tfMPTCanClawback | tfMPTCanLock, .authHolder = true, }); @@ -1376,8 +1180,7 @@ class LoanBroker_test : public beast::unit_test::suite env.close(); // Alice is not authorized, can still create the vault - asset.authorize( - {.account = issuer, .holder = alice, .flags = tfMPTUnauthorize}); + asset.authorize({.account = issuer, .holder = alice, .flags = tfMPTUnauthorize}); auto [tx, vaultKeylet] = vault.create({.owner = alice, .asset = asset}); env(tx); env.close(); @@ -1393,16 +1196,12 @@ class LoanBroker_test : public beast::unit_test::suite // Can't unauthorize Vault pseudo-account asset.authorize( - {.account = issuer, - .holder = vaultInfo.pseudoAccount, - .flags = tfMPTUnauthorize, - .err = tecNO_PERMISSION}); + {.account = issuer, .holder = vaultInfo.pseudoAccount, .flags = tfMPTUnauthorize, .err = tecNO_PERMISSION}); auto forUnauthAuth = [&](auto&& doTx) { for (auto const flag : {tfMPTUnauthorize, 0u}) { - asset.authorize( - {.account = issuer, .holder = alice, .flags = flag}); + asset.authorize({.account = issuer, .holder = alice, .flags = flag}); env.close(); doTx(flag == 0); env.close(); @@ -1412,25 +1211,16 @@ class LoanBroker_test : public beast::unit_test::suite // Can't deposit into Vault if the vault owner is not authorized forUnauthAuth([&](bool authorized) { auto const err = !authorized ? ter(tecNO_AUTH) : ter(tesSUCCESS); - env(vault.deposit( - {.depositor = alice, - .id = vaultKeylet.key, - .amount = asset(51)}), - err); + env(vault.deposit({.depositor = alice, .id = vaultKeylet.key, .amount = asset(51)}), err); }); // Can't withdraw from Vault if the vault owner is not authorized forUnauthAuth([&](bool authorized) { auto const err = !authorized ? ter(tecNO_AUTH) : ter(tesSUCCESS); - env(vault.withdraw( - {.depositor = alice, - .id = vaultKeylet.key, - .amount = asset(1)}), - err); + env(vault.withdraw({.depositor = alice, .id = vaultKeylet.key, .amount = asset(1)}), err); }); - auto const brokerKeylet = - keylet::loanbroker(alice.id(), env.seq(alice)); + auto const brokerKeylet = keylet::loanbroker(alice.id(), env.seq(alice)); // Can create LoanBroker if the vault owner is not authorized forUnauthAuth([&](auto) { env(set(alice, vaultInfo.vaultID)); }); @@ -1441,31 +1231,23 @@ class LoanBroker_test : public beast::unit_test::suite // Can't unauthorize LoanBroker pseudo-account asset.authorize( - {.account = issuer, - .holder = brokerPseudo, - .flags = tfMPTUnauthorize, - .err = tecNO_PERMISSION}); + {.account = issuer, .holder = brokerPseudo, .flags = tfMPTUnauthorize, .err = tecNO_PERMISSION}); // Can't cover deposit into Vault if the vault owner is not authorized forUnauthAuth([&](bool authorized) { auto const err = !authorized ? ter(tecNO_AUTH) : ter(tesSUCCESS); - env(coverDeposit(alice, brokerKeylet.key, vaultInfo.asset(10)), - err); + env(coverDeposit(alice, brokerKeylet.key, vaultInfo.asset(10)), err); }); // Can't cover withdraw from Vault if the vault owner is not authorized forUnauthAuth([&](bool authorized) { auto const err = !authorized ? ter(tecNO_AUTH) : ter(tesSUCCESS); - env(coverWithdraw(alice, brokerKeylet.key, vaultInfo.asset(5)), - err); + env(coverWithdraw(alice, brokerKeylet.key, vaultInfo.asset(5)), err); }); // Issuer can always cover clawback. The holder authorization is n/a. - forUnauthAuth([&](bool) { - env(coverClawback(issuer), - loanBrokerID(brokerKeylet.key), - amount(vaultInfo.asset(1))); - }); + forUnauthAuth( + [&](bool) { env(coverClawback(issuer), loanBrokerID(brokerKeylet.key), amount(vaultInfo.asset(1))); }); } void @@ -1484,8 +1266,7 @@ class LoanBroker_test : public beast::unit_test::suite PrettyAsset const asset = [&]() { MPTTester mptt{env, issuer, mptInitNoFund}; - mptt.create( - {.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock}); + mptt.create({.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock}); env.close(); PrettyAsset const mptAsset = mptt["MPT"]; mptt.authorize({.account = alice}); @@ -1508,15 +1289,10 @@ class LoanBroker_test : public beast::unit_test::suite if (vaultInfo.vaultID == uint256{}) return; - env(vault.deposit( - {.depositor = alice, - .id = vaultKeylet.key, - .amount = asset(50)}), - THISLINE); + env(vault.deposit({.depositor = alice, .id = vaultKeylet.key, .amount = asset(50)}), THISLINE); env.close(); - auto const brokerKeylet = - keylet::loanbroker(alice.id(), env.seq(alice)); + auto const brokerKeylet = keylet::loanbroker(alice.id(), env.seq(alice)); env(set(alice, vaultInfo.vaultID), THISLINE); env.close(); @@ -1597,24 +1373,19 @@ class LoanBroker_test : public beast::unit_test::suite auto const [token, deposit, err] = getToken(env); Vault vault(env); - auto const [tx, keylet] = - vault.create({.owner = broker, .asset = token.asset()}); + auto const [tx, keylet] = vault.create({.owner = broker, .asset = token.asset()}); env(tx); env.close(); - env(vault.deposit( - {.depositor = broker, .id = keylet.key, .amount = deposit}), - ter(err)); + env(vault.deposit({.depositor = broker, .id = keylet.key, .amount = deposit}), ter(err)); env.close(); - auto const brokerKeylet = - keylet::loanbroker(broker, env.seq(broker)); + auto const brokerKeylet = keylet::loanbroker(broker, env.seq(broker)); env(loanBroker::set(broker, keylet.key)); env.close(); - env(loanBroker::coverDeposit(broker, brokerKeylet.key, deposit), - ter(err)); + env(loanBroker::coverDeposit(broker, brokerKeylet.key, deposit), ter(err)); env.close(); }; @@ -1672,8 +1443,7 @@ class LoanBroker_test : public beast::unit_test::suite auto const IOU = issuer["IOU"]; Vault vault{env}; - auto [tx, vaultKeylet] = - vault.create({.owner = lender, .asset = IOU.asset()}); + auto [tx, vaultKeylet] = vault.create({.owner = lender, .asset = IOU.asset()}); env(tx); env.close(); @@ -1706,8 +1476,7 @@ class LoanBroker_test : public beast::unit_test::suite auto test = [&](TrustState trustState) { Env env(*this); - testcase << "RIPD-4274 IOU with state: " - << static_cast(trustState); + testcase << "RIPD-4274 IOU with state: " << static_cast(trustState); auto setTrustLine = [&](Account const& acct, TrustState state) { switch (state) @@ -1762,41 +1531,29 @@ class LoanBroker_test : public beast::unit_test::suite env.close(); Vault vault(env); - auto const [tx, keylet] = - vault.create({.owner = broker, .asset = token.asset()}); + auto const [tx, keylet] = vault.create({.owner = broker, .asset = token.asset()}); env(tx); env.close(); // Test Vault withdraw - env(vault.deposit( - {.depositor = broker, - .id = keylet.key, - .amount = token(1'000)})); + env(vault.deposit({.depositor = broker, .id = keylet.key, .amount = token(1'000)})); env.close(); - env(vault.withdraw( - {.depositor = broker, - .id = keylet.key, - .amount = token(1'000)}), + env(vault.withdraw({.depositor = broker, .id = keylet.key, .amount = token(1'000)}), loanBroker::destination(dest), ter(std::ignore)); BEAST_EXPECT(env.ter() == tecNO_LINE); env.close(); - env(vault.withdraw( - {.depositor = broker, - .id = keylet.key, - .amount = token(1'000)})); + env(vault.withdraw({.depositor = broker, .id = keylet.key, .amount = token(1'000)})); // Test LoanBroker withdraw - auto const brokerKeylet = - keylet::loanbroker(broker, env.seq(broker)); + auto const brokerKeylet = keylet::loanbroker(broker, env.seq(broker)); env(loanBroker::set(broker, keylet.key)); env.close(); - env(loanBroker::coverDeposit( - broker, brokerKeylet.key, token(1'000))); + env(loanBroker::coverDeposit(broker, brokerKeylet.key, token(1'000))); env.close(); env(loanBroker::coverWithdraw(broker, brokerKeylet.key, token(100)), @@ -1811,8 +1568,7 @@ class LoanBroker_test : public beast::unit_test::suite env(fclear(issuer, asfRequireAuth)); env.close(); - env(loanBroker::coverWithdraw( - broker, brokerKeylet.key, token(100)), + env(loanBroker::coverWithdraw(broker, brokerKeylet.key, token(100)), loanBroker::destination(dest), ter(std::ignore)); BEAST_EXPECT(env.ter() == tecNO_LINE); @@ -1844,8 +1600,7 @@ class LoanBroker_test : public beast::unit_test::suite auto test = [&](MPTState MPTState) { Env env(*this); - testcase << "RIPD-4274 MPT with state: " - << static_cast(MPTState); + testcase << "RIPD-4274 MPT with state: " << static_cast(MPTState); env.fund(XRP(1'000), issuer, broker, dest); env.close(); @@ -1863,10 +1618,7 @@ class LoanBroker_test : public beast::unit_test::suite .authHolder = true, .maxAmt = 5'000}); // unauthorize dest - tester.authorize( - {.account = issuer, - .holder = dest, - .flags = tfMPTUnauthorize}); + tester.authorize({.account = issuer, .holder = dest, .flags = tfMPTUnauthorize}); return tester; } case ReachedMAX: { @@ -1877,8 +1629,7 @@ class LoanBroker_test : public beast::unit_test::suite .pay = 2'000, .flags = MPTDEXFlags, .maxAmt = 4'000}); - BEAST_EXPECT( - env.balance(issuer, tester) == tester(-4'000)); + BEAST_EXPECT(env.balance(issuer, tester) == tester(-4'000)); return tester; } case NoMPT: { @@ -1900,48 +1651,35 @@ class LoanBroker_test : public beast::unit_test::suite auto const& token = *maybeToken; Vault vault(env); - auto const [tx, keylet] = - vault.create({.owner = broker, .asset = token.asset()}); + auto const [tx, keylet] = vault.create({.owner = broker, .asset = token.asset()}); env(tx); env.close(); // Test Vault withdraw - env(vault.deposit( - {.depositor = broker, - .id = keylet.key, - .amount = token(1'000)})); + env(vault.deposit({.depositor = broker, .id = keylet.key, .amount = token(1'000)})); env.close(); - env(vault.withdraw( - {.depositor = broker, - .id = keylet.key, - .amount = token(1'000)}), + env(vault.withdraw({.depositor = broker, .id = keylet.key, .amount = token(1'000)}), loanBroker::destination(dest), ter(std::ignore)); // Shouldn't fail if at MaximumAmount since no new tokens are issued - TER const err = - MPTState == ReachedMAX ? TER(tesSUCCESS) : tecNO_AUTH; + TER const err = MPTState == ReachedMAX ? TER(tesSUCCESS) : tecNO_AUTH; BEAST_EXPECT(env.ter() == err); env.close(); if (err != tesSUCCESS) { - env(vault.withdraw( - {.depositor = broker, - .id = keylet.key, - .amount = token(1'000)})); + env(vault.withdraw({.depositor = broker, .id = keylet.key, .amount = token(1'000)})); } // Test LoanBroker withdraw - auto const brokerKeylet = - keylet::loanbroker(broker, env.seq(broker)); + auto const brokerKeylet = keylet::loanbroker(broker, env.seq(broker)); env(loanBroker::set(broker, keylet.key)); env.close(); - env(loanBroker::coverDeposit( - broker, brokerKeylet.key, token(1'000))); + env(loanBroker::coverDeposit(broker, brokerKeylet.key, token(1'000))); env.close(); env(loanBroker::coverWithdraw(broker, brokerKeylet.key, token(100)), diff --git a/src/test/app/Loan_test.cpp b/src/test/app/Loan_test.cpp index e9780211de..5deb1f179c 100644 --- a/src/test/app/Loan_test.cpp +++ b/src/test/app/Loan_test.cpp @@ -10,6 +10,7 @@ #include #include +// cspell: words LOANTODO #include @@ -22,8 +23,7 @@ protected: // Ensure that all the features needed for Lending Protocol are included, // even if they are set to unsupported. FeatureBitset const all{ - jtx::testable_amendments() | featureMPTokensV1 | - featureSingleAssetVault | featureLendingProtocol}; + jtx::testable_amendments() | featureMPTokensV1 | featureSingleAssetVault | featureLendingProtocol}; std::string const iouCurrency{"IOU"}; @@ -50,14 +50,12 @@ protected: // counter party signature is optional on LoanSet. Confirm that by // sending transaction without one. - auto setTx = - env.jt(set(alice, keylet.key, Number(10000)), ter(temDISABLED)); + auto setTx = env.jt(set(alice, keylet.key, Number(10000)), ter(temDISABLED)); env(setTx); // All loan transactions are disabled. // 1. LoanSet - setTx = env.jt( - setTx, sig(sfCounterpartySignature, bob), ter(temDISABLED)); + setTx = env.jt(setTx, sig(sfCounterpartySignature, bob), ter(temDISABLED)); env(setTx); // Actual sequence will be based off the loan broker, but we // obviously don't have one of those if the amendment is disabled @@ -91,8 +89,7 @@ protected: maxCoveredLoanValue(Number const& currentDebt) const { NumberRoundModeGuard mg(Number::downward); - auto debtLimit = - coverDeposit * tenthBipsPerUnity.value() / coverRateMin.value(); + auto debtLimit = coverDeposit * tenthBipsPerUnity.value() / coverRateMin.value(); return debtLimit - currentDebt; } @@ -119,10 +116,7 @@ protected: Keylet const& brokerKeylet_, Keylet const& vaultKeylet_, BrokerParameters const& p) - : asset(asset_) - , brokerID(brokerKeylet_.key) - , vaultID(vaultKeylet_.key) - , params(p) + : asset(asset_), brokerID(brokerKeylet_.key), vaultID(vaultKeylet_.key), params(p) { } @@ -174,17 +168,12 @@ protected: template jtx::JTx - operator()(jtx::Env& env, BrokerInfo const& broker, FN const&... fN) - const + operator()(jtx::Env& env, BrokerInfo const& broker, FN const&... fN) const { using namespace jtx; using namespace jtx::loan; - JTx jt{loan::set( - account, - broker.brokerID, - broker.asset(principalRequest).number(), - flags.value_or(0))}; + JTx jt{loan::set(account, broker.brokerID, broker.asset(principalRequest).number(), flags.value_or(0))}; sig(sfCounterpartySignature, counter)(env, jt); @@ -193,8 +182,7 @@ protected: if (counterpartyExplicit) counterparty(counter)(env, jt); if (originationFee) - loanOriginationFee(broker.asset(*originationFee).number())( - env, jt); + loanOriginationFee(broker.asset(*originationFee).number())(env, jt); if (serviceFee) loanServiceFee(broker.asset(*serviceFee).number())(env, jt); if (lateFee) @@ -270,10 +258,7 @@ protected: BrokerInfo const& broker_, jtx::Account const& pseudo_, Keylet const& keylet_) - : env(env_) - , broker(broker_) - , pseudoAccount(pseudo_) - , loanKeylet(keylet_) + : env(env_), broker(broker_), pseudoAccount(pseudo_), loanKeylet(keylet_) { } @@ -289,29 +274,21 @@ protected: std::uint32_t ownerCount) const { using namespace jtx; - if (auto brokerSle = env.le(keylet::loanbroker(broker.brokerID)); - env.test.BEAST_EXPECT(brokerSle)) + if (auto brokerSle = env.le(keylet::loanbroker(broker.brokerID)); env.test.BEAST_EXPECT(brokerSle)) { - TenthBips16 const managementFeeRate{ - brokerSle->at(sfManagementFeeRate)}; + TenthBips16 const managementFeeRate{brokerSle->at(sfManagementFeeRate)}; auto const brokerDebt = brokerSle->at(sfDebtTotal); auto const expectedDebt = principalOutstanding + interestOwed; env.test.BEAST_EXPECT(brokerDebt == expectedDebt); env.test.BEAST_EXPECT( - env.balance(pseudoAccount, broker.asset).number() == - brokerSle->at(sfCoverAvailable)); - env.test.BEAST_EXPECT( - brokerSle->at(sfOwnerCount) == ownerCount); + env.balance(pseudoAccount, broker.asset).number() == brokerSle->at(sfCoverAvailable)); + env.test.BEAST_EXPECT(brokerSle->at(sfOwnerCount) == ownerCount); - if (auto vaultSle = - env.le(keylet::vault(brokerSle->at(sfVaultID))); - env.test.BEAST_EXPECT(vaultSle)) + if (auto vaultSle = env.le(keylet::vault(brokerSle->at(sfVaultID))); env.test.BEAST_EXPECT(vaultSle)) { - Account const vaultPseudo{ - "vaultPseudoAccount", vaultSle->at(sfAccount)}; + Account const vaultPseudo{"vaultPseudoAccount", vaultSle->at(sfAccount)}; env.test.BEAST_EXPECT( - vaultSle->at(sfAssetsAvailable) == - env.balance(vaultPseudo, broker.asset).number()); + vaultSle->at(sfAssetsAvailable) == env.balance(vaultPseudo, broker.asset).number()); if (ownerCount == 0) { // Allow some slop for rounding IOUs @@ -323,10 +300,8 @@ protected: env.test.BEAST_EXPECT( total == available || (!broker.asset.integral() && available != 0 && - ((total - available) / available < - Number(1, -6)))); - env.test.BEAST_EXPECT( - vaultSle->at(sfLossUnrealized) == 0); + ((total - available) / available < Number(1, -6)))); + env.test.BEAST_EXPECT(vaultSle->at(sfLossUnrealized) == 0); } } } @@ -340,24 +315,18 @@ protected: STAmount const& expectedPayment, jtx::PrettyAmount const& adjustment) const { - auto const borrowerScale = - std::max(loanScale, balanceBefore.number().exponent()); + auto const borrowerScale = std::max(loanScale, balanceBefore.number().exponent()); STAmount const balanceChangeAmount{ - broker.asset, - roundToAsset( - broker.asset, expectedPayment + adjustment, borrowerScale)}; + broker.asset, roundToAsset(broker.asset, expectedPayment + adjustment, borrowerScale)}; { auto const difference = roundToScale( - env.balance(account, broker.asset) - - (balanceBefore - balanceChangeAmount), - borrowerScale); + env.balance(account, broker.asset) - (balanceBefore - balanceChangeAmount), borrowerScale); env.test.expect( roundToScale(difference, loanScale) >= beast::zero, "Balance before: " + to_string(balanceBefore.value()) + ", expected change: " + to_string(balanceChangeAmount) + - ", difference (balance after - expected): " + - to_string(difference), + ", difference (balance after - expected): " + to_string(difference), __FILE__, __LINE__); } @@ -379,55 +348,35 @@ protected: using namespace jtx; if (auto loan = env.le(loanKeylet); env.test.BEAST_EXPECT(loan)) { - env.test.BEAST_EXPECT( - loan->at(sfPreviousPaymentDueDate) == previousPaymentDate); - env.test.BEAST_EXPECT( - loan->at(sfPaymentRemaining) == paymentRemaining); - env.test.BEAST_EXPECT( - loan->at(sfNextPaymentDueDate) == nextPaymentDate); + env.test.BEAST_EXPECT(loan->at(sfPreviousPaymentDueDate) == previousPaymentDate); + env.test.BEAST_EXPECT(loan->at(sfPaymentRemaining) == paymentRemaining); + env.test.BEAST_EXPECT(loan->at(sfNextPaymentDueDate) == nextPaymentDate); env.test.BEAST_EXPECT(loan->at(sfLoanScale) == loanScale); - env.test.BEAST_EXPECT( - loan->at(sfTotalValueOutstanding) == totalValue); - env.test.BEAST_EXPECT( - loan->at(sfPrincipalOutstanding) == principalOutstanding); - env.test.BEAST_EXPECT( - loan->at(sfManagementFeeOutstanding) == - managementFeeOutstanding); - env.test.BEAST_EXPECT( - loan->at(sfPeriodicPayment) == periodicPayment); + env.test.BEAST_EXPECT(loan->at(sfTotalValueOutstanding) == totalValue); + env.test.BEAST_EXPECT(loan->at(sfPrincipalOutstanding) == principalOutstanding); + env.test.BEAST_EXPECT(loan->at(sfManagementFeeOutstanding) == managementFeeOutstanding); + env.test.BEAST_EXPECT(loan->at(sfPeriodicPayment) == periodicPayment); env.test.BEAST_EXPECT(loan->at(sfFlags) == flags); auto const ls = constructRoundedLoanState(loan); auto const interestRate = TenthBips32{loan->at(sfInterestRate)}; auto const paymentInterval = loan->at(sfPaymentInterval); - checkBroker( - principalOutstanding, - ls.interestDue, - interestRate, - paymentInterval, - paymentRemaining, - 1); + checkBroker(principalOutstanding, ls.interestDue, interestRate, paymentInterval, paymentRemaining, 1); - if (auto brokerSle = - env.le(keylet::loanbroker(broker.brokerID)); - env.test.BEAST_EXPECT(brokerSle)) + if (auto brokerSle = env.le(keylet::loanbroker(broker.brokerID)); env.test.BEAST_EXPECT(brokerSle)) { - if (auto vaultSle = - env.le(keylet::vault(brokerSle->at(sfVaultID))); + if (auto vaultSle = env.le(keylet::vault(brokerSle->at(sfVaultID))); env.test.BEAST_EXPECT(vaultSle)) { - if ((flags & lsfLoanImpaired) && - !(flags & lsfLoanDefault)) + if ((flags & lsfLoanImpaired) && !(flags & lsfLoanDefault)) { env.test.BEAST_EXPECT( - vaultSle->at(sfLossUnrealized) == - totalValue - managementFeeOutstanding); + vaultSle->at(sfLossUnrealized) == totalValue - managementFeeOutstanding); } else { - env.test.BEAST_EXPECT( - vaultSle->at(sfLossUnrealized) == 0); + env.test.BEAST_EXPECT(vaultSle->at(sfLossUnrealized) == 0); } } } @@ -468,17 +417,14 @@ protected: auto const coverRateMinValue = params.coverRateMin; - auto [tx, vaultKeylet] = - vault.create({.owner = lender, .asset = asset}); + auto [tx, vaultKeylet] = vault.create({.owner = lender, .asset = asset}); env(tx); env.close(); BEAST_EXPECT(env.le(vaultKeylet)); - env(vault.deposit( - {.depositor = lender, .id = vaultKeylet.key, .amount = deposit})); + env(vault.deposit({.depositor = lender, .id = vaultKeylet.key, .amount = deposit})); env.close(); - if (auto const vault = env.le(keylet::vault(vaultKeylet.key)); - BEAST_EXPECT(vault)) + if (auto const vault = env.le(keylet::vault(vaultKeylet.key)); BEAST_EXPECT(vault)) { BEAST_EXPECT(vault->at(sfAssetsAvailable) == deposit.value()); } @@ -503,10 +449,7 @@ protected: /// Get the state without checking anything LoanState - getCurrentState( - jtx::Env const& env, - BrokerInfo const& broker, - Keylet const& loanKeylet) + getCurrentState(jtx::Env const& env, BrokerInfo const& broker, Keylet const& loanKeylet) { using d = NetClock::duration; using tp = NetClock::time_point; @@ -522,8 +465,7 @@ protected: .loanScale = loan->at(sfLoanScale), .totalValue = loan->at(sfTotalValueOutstanding), .principalOutstanding = loan->at(sfPrincipalOutstanding), - .managementFeeOutstanding = - loan->at(sfManagementFeeOutstanding), + .managementFeeOutstanding = loan->at(sfManagementFeeOutstanding), .periodicPayment = loan->at(sfPeriodicPayment), .flags = loan->at(sfFlags), .paymentInterval = loan->at(sfPaymentInterval), @@ -553,20 +495,13 @@ protected: BEAST_EXPECT(state.principalOutstanding == broker.asset(1000).value()); BEAST_EXPECT( state.loanScale >= - (broker.asset.integral() - ? 0 - : std::max( - broker.vaultScale(env), - state.principalOutstanding.exponent()))); + (broker.asset.integral() ? 0 : std::max(broker.vaultScale(env), state.principalOutstanding.exponent()))); BEAST_EXPECT(state.paymentInterval == 600); { NumberRoundModeGuard mg(Number::upward); BEAST_EXPECT( state.totalValue == - roundToAsset( - broker.asset, - state.periodicPayment * state.paymentRemaining, - state.loanScale)); + roundToAsset(broker.asset, state.periodicPayment * state.paymentRemaining, state.loanScale)); } BEAST_EXPECT( state.managementFeeOutstanding == @@ -582,23 +517,16 @@ protected: } bool - canImpairLoan( - jtx::Env const& env, - BrokerInfo const& broker, - LoanState const& state) + canImpairLoan(jtx::Env const& env, BrokerInfo const& broker, LoanState const& state) { - if (auto const brokerSle = env.le(keylet::loanbroker(broker.brokerID)); - BEAST_EXPECT(brokerSle)) + if (auto const brokerSle = env.le(keylet::loanbroker(broker.brokerID)); BEAST_EXPECT(brokerSle)) { - if (auto const vaultSle = - env.le(keylet::vault(brokerSle->at(sfVaultID))); - BEAST_EXPECT(vaultSle)) + if (auto const vaultSle = env.le(keylet::vault(brokerSle->at(sfVaultID))); BEAST_EXPECT(vaultSle)) { // log << vaultSle->getJson() << std::endl; - auto const assetsUnavailable = vaultSle->at(sfAssetsTotal) - - vaultSle->at(sfAssetsAvailable); - auto const unrealizedLoss = vaultSle->at(sfLossUnrealized) + - state.totalValue - state.managementFeeOutstanding; + auto const assetsUnavailable = vaultSle->at(sfAssetsTotal) - vaultSle->at(sfAssetsAvailable); + auto const unrealizedLoss = + vaultSle->at(sfLossUnrealized) + state.totalValue - state.managementFeeOutstanding; if (!BEAST_EXPECT(unrealizedLoss <= assetsUnavailable)) { @@ -632,9 +560,7 @@ protected: case AssetType::IOU: { PrettyAsset const asset{issuer[iouCurrency]}; - auto const limit = asset( - 100 * - (brokerParams.vaultDeposit + brokerParams.coverDeposit)); + auto const limit = asset(100 * (brokerParams.vaultDeposit + brokerParams.coverDeposit)); if (lender != issuer) env(trust(lender, limit)); if (borrower != issuer) @@ -646,21 +572,14 @@ protected: case AssetType::MPT: { // Enough to cover initial fees if (!env.le(keylet::account(issuer))) - env.fund( - env.current()->fees().accountReserve(10) * 10, issuer); + env.fund(env.current()->fees().accountReserve(10) * 10, issuer); if (!env.le(keylet::account(lender))) - env.fund( - env.current()->fees().accountReserve(10) * 10, - noripple(lender)); + env.fund(env.current()->fees().accountReserve(10) * 10, noripple(lender)); if (!env.le(keylet::account(borrower))) - env.fund( - env.current()->fees().accountReserve(10) * 10, - noripple(borrower)); + env.fund(env.current()->fees().accountReserve(10) * 10, noripple(borrower)); MPTTester mptt{env, issuer, mptInitNoFund}; - mptt.create( - {.flags = - tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock}); + mptt.create({.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock}); // Scale the MPT asset so interest is interesting PrettyAsset const asset{mptt.issuanceID(), 10'000}; // Need to do the authorization here because mptt isn't @@ -692,23 +611,14 @@ protected: { using namespace jtx; - auto const asset = - createAsset(env, assetType, brokerParams, issuer, lender, borrower); + auto const asset = createAsset(env, assetType, brokerParams, issuer, lender, borrower); auto const principal = asset(loanParams.principalRequest).number(); auto const interest = loanParams.interest.value_or(TenthBips32{}); - auto const interval = - loanParams.payInterval.value_or(LoanSet::defaultPaymentInterval); - auto const total = - loanParams.payTotal.value_or(LoanSet::defaultPaymentTotal); + auto const interval = loanParams.payInterval.value_or(LoanSet::defaultPaymentInterval); + auto const total = loanParams.payTotal.value_or(LoanSet::defaultPaymentTotal); auto const feeRate = brokerParams.managementFeeRate; auto const props = computeLoanProperties( - asset, - principal, - interest, - interval, - total, - feeRate, - asset(brokerParams.vaultDeposit).number().exponent()); + asset, principal, interest, interval, total, feeRate, asset(brokerParams.vaultDeposit).number().exponent()); log << "Loan properties:\n" << "\tPrincipal: " << principal << std::endl << "\tInterest rate: " << interest << std::endl @@ -716,13 +626,10 @@ protected: << "\tManagement Fee Rate: " << feeRate << std::endl << "\tTotal Payments: " << total << std::endl << "\tPeriodic Payment: " << props.periodicPayment << std::endl - << "\tTotal Value: " << props.loanState.valueOutstanding - << std::endl - << "\tManagement Fee: " << props.loanState.managementFeeDue - << std::endl + << "\tTotal Value: " << props.loanState.valueOutstanding << std::endl + << "\tManagement Fee: " << props.loanState.managementFeeDue << std::endl << "\tLoan Scale: " << props.loanScale << std::endl - << "\tFirst payment principal: " << props.firstPaymentPrincipal - << std::endl; + << "\tFirst payment principal: " << props.firstPaymentPrincipal << std::endl; // checkGuards returns a TER, so success is 0 BEAST_EXPECT(!checkLoanGuards( @@ -749,32 +656,25 @@ protected: // Enough to cover initial fees env.fund(env.current()->fees().accountReserve(10) * 10, issuer); if (lender != issuer) - env.fund( - env.current()->fees().accountReserve(10) * 10, - noripple(lender)); + env.fund(env.current()->fees().accountReserve(10) * 10, noripple(lender)); if (borrower != issuer && borrower != lender) - env.fund( - env.current()->fees().accountReserve(10) * 10, - noripple(borrower)); + env.fund(env.current()->fees().accountReserve(10) * 10, noripple(borrower)); - describeLoan( - env, brokerParams, loanParams, assetType, issuer, lender, borrower); + describeLoan(env, brokerParams, loanParams, assetType, issuer, lender, borrower); // Make the asset - auto const asset = - createAsset(env, assetType, brokerParams, issuer, lender, borrower); + auto const asset = createAsset(env, assetType, brokerParams, issuer, lender, borrower); env.close(); if (asset.native() || lender != issuer) - env(pay( - (asset.native() ? env.master : issuer), - lender, - asset(brokerParams.vaultDeposit + brokerParams.coverDeposit))); + env( + pay((asset.native() ? env.master : issuer), + lender, + asset(brokerParams.vaultDeposit + brokerParams.coverDeposit))); // Fund the borrower later once we know the total loan // size - BrokerInfo const broker = - createVaultAndBroker(env, asset, lender, brokerParams); + BrokerInfo const broker = createVaultAndBroker(env, asset, lender, brokerParams); auto const pseudoAcctOpt = [&]() -> std::optional { auto const brokerSle = env.le(keylet::loanbroker(broker.brokerID)); @@ -832,22 +732,16 @@ protected: // Add extra for transaction fees and reserves, if appropriate, or a // tiny amount for the extra paid in each transaction - auto const totalNeeded = state.totalValue + - (serviceFee * state.paymentRemaining) + + auto const totalNeeded = state.totalValue + (serviceFee * state.paymentRemaining) + (broker.asset.native() ? Number( baseFee * state.paymentRemaining + - env.current()->fees().accountReserve( - env.ownerCount(borrower))) + env.current()->fees().accountReserve(env.ownerCount(borrower))) : broker.asset(15).number()); auto const shortage = totalNeeded - borrowerBalance.number(); - if (shortage > beast::zero && - (broker.asset.native() || issuer != borrower)) - env( - pay((broker.asset.native() ? env.master : issuer), - borrower, - STAmount{broker.asset, shortage})); + if (shortage > beast::zero && (broker.asset.native() || issuer != borrower)) + env(pay((broker.asset.native() ? env.master : issuer), borrower, STAmount{broker.asset, shortage})); } void @@ -879,11 +773,9 @@ protected: verifyLoanStatus(state); - STAmount const serviceFee = - broker.asset(loanParams.serviceFee.value_or(0)); + STAmount const serviceFee = broker.asset(loanParams.serviceFee.value_or(0)); - topUpBorrower( - env, broker, issuer, borrower, state, loanParams.serviceFee); + topUpBorrower(env, broker, issuer, borrower, state, loanParams.serviceFee); // Periodic payment amount will consist of // 1. principal outstanding (1000) @@ -893,12 +785,9 @@ protected: // Calculate these values without the helper functions // to verify they're working correctly The numbers in // the below BEAST_EXPECTs may not hold across assets. - auto const periodicRate = - loanPeriodicRate(state.interestRate, state.paymentInterval); + auto const periodicRate = loanPeriodicRate(state.interestRate, state.paymentInterval); STAmount const roundedPeriodicPayment{ - broker.asset, - roundPeriodicPayment( - broker.asset, state.periodicPayment, state.loanScale)}; + broker.asset, roundPeriodicPayment(broker.asset, state.periodicPayment, state.loanScale)}; if (!showStepBalances) log << currencyLabel << " Payment components: " @@ -910,43 +799,29 @@ protected: << std::endl; // Include the service fee - STAmount const totalDue = roundToScale( - roundedPeriodicPayment + serviceFee, - state.loanScale, - Number::upward); + STAmount const totalDue = roundToScale(roundedPeriodicPayment + serviceFee, state.loanScale, Number::upward); - auto currentRoundedState = constructLoanState( - state.totalValue, - state.principalOutstanding, - state.managementFeeOutstanding); + auto currentRoundedState = + constructLoanState(state.totalValue, state.principalOutstanding, state.managementFeeOutstanding); { auto const raw = computeTheoreticalLoanState( - state.periodicPayment, - periodicRate, - state.paymentRemaining, - broker.params.managementFeeRate); + state.periodicPayment, periodicRate, state.paymentRemaining, broker.params.managementFeeRate); if (showStepBalances) { log << currencyLabel << " Starting loan balances: " - << "\n\tTotal value: " - << currentRoundedState.valueOutstanding << "\n\tPrincipal: " - << currentRoundedState.principalOutstanding + << "\n\tTotal value: " << currentRoundedState.valueOutstanding + << "\n\tPrincipal: " << currentRoundedState.principalOutstanding << "\n\tInterest: " << currentRoundedState.interestDue - << "\n\tMgmt fee: " << currentRoundedState.managementFeeDue - << "\n\tPayments remaining " << state.paymentRemaining - << std::endl; + << "\n\tMgmt fee: " << currentRoundedState.managementFeeDue << "\n\tPayments remaining " + << state.paymentRemaining << std::endl; } else { - log << currencyLabel - << " Loan starting state: " << state.paymentRemaining - << ", " << raw.interestDue << ", " - << raw.principalOutstanding << ", " << raw.managementFeeDue - << ", " << currentRoundedState.valueOutstanding << ", " - << currentRoundedState.principalOutstanding << ", " - << currentRoundedState.interestDue << ", " - << currentRoundedState.managementFeeDue << std::endl; + log << currencyLabel << " Loan starting state: " << state.paymentRemaining << ", " << raw.interestDue + << ", " << raw.principalOutstanding << ", " << raw.managementFeeDue << ", " + << currentRoundedState.valueOutstanding << ", " << currentRoundedState.principalOutstanding << ", " + << currentRoundedState.interestDue << ", " << currentRoundedState.managementFeeDue << std::endl; } } @@ -954,47 +829,33 @@ protected: // taken auto const extraAmount = paymentParams.overpaymentExtra ? broker.asset(*paymentParams.overpaymentExtra).value() - : std::min( - broker.asset(10).value(), - STAmount{broker.asset, totalDue / 20}); + : std::min(broker.asset(10).value(), STAmount{broker.asset, totalDue / 20}); STAmount const transactionAmount = - STAmount{broker.asset, totalDue * paymentParams.overpaymentFactor} + - extraAmount; + STAmount{broker.asset, totalDue * paymentParams.overpaymentFactor} + extraAmount; - auto const borrowerInitialBalance = - env.balance(borrower, broker.asset).number(); + auto const borrowerInitialBalance = env.balance(borrower, broker.asset).number(); auto const initialState = state; detail::PaymentComponents totalPaid{ - .trackedValueDelta = 0, - .trackedPrincipalDelta = 0, - .trackedManagementFeeDelta = 0}; + .trackedValueDelta = 0, .trackedPrincipalDelta = 0, .trackedManagementFeeDelta = 0}; Number totalInterestPaid = 0; Number totalFeesPaid = 0; std::size_t totalPaymentsMade = 0; xrpl::LoanState currentTrueState = computeTheoreticalLoanState( - state.periodicPayment, - periodicRate, - state.paymentRemaining, - broker.params.managementFeeRate); + state.periodicPayment, periodicRate, state.paymentRemaining, broker.params.managementFeeRate); auto validateBorrowerBalance = [&]() { if (borrower == issuer || !paymentParams.validateBalances) return; auto const totalSpent = (totalPaid.trackedValueDelta + totalFeesPaid + - (broker.asset.native() ? Number(baseFee) * totalPaymentsMade - : numZero)); - BEAST_EXPECT( - env.balance(borrower, broker.asset).number() == - borrowerInitialBalance - totalSpent); + (broker.asset.native() ? Number(baseFee) * totalPaymentsMade : numZero)); + BEAST_EXPECT(env.balance(borrower, broker.asset).number() == borrowerInitialBalance - totalSpent); }; auto const defaultRound = broker.asset.integral() ? 3 : 0; - auto truncate = [defaultRound]( - Number const& n, - std::optional places = std::nullopt) { + auto truncate = [defaultRound](Number const& n, std::optional places = std::nullopt) { auto const p = places.value_or(defaultRound); if (p == 0) return n; @@ -1018,54 +879,35 @@ protected: BEAST_EXPECT( paymentComponents.trackedValueDelta <= roundedPeriodicPayment || - (paymentComponents.specialCase == - detail::PaymentSpecialCase::final && - paymentComponents.trackedValueDelta >= - roundedPeriodicPayment)); + (paymentComponents.specialCase == detail::PaymentSpecialCase::final && + paymentComponents.trackedValueDelta >= roundedPeriodicPayment)); BEAST_EXPECT( paymentComponents.trackedValueDelta == - paymentComponents.trackedPrincipalDelta + - paymentComponents.trackedInterestPart() + + paymentComponents.trackedPrincipalDelta + paymentComponents.trackedInterestPart() + paymentComponents.trackedManagementFeeDelta); xrpl::LoanState const nextTrueState = computeTheoreticalLoanState( - state.periodicPayment, - periodicRate, - state.paymentRemaining - 1, - broker.params.managementFeeRate); - detail::LoanStateDeltas const deltas = - currentTrueState - nextTrueState; + state.periodicPayment, periodicRate, state.paymentRemaining - 1, broker.params.managementFeeRate); + detail::LoanStateDeltas const deltas = currentTrueState - nextTrueState; + BEAST_EXPECT(deltas.total() == deltas.principal + deltas.interest + deltas.managementFee); BEAST_EXPECT( - deltas.total() == - deltas.principal + deltas.interest + deltas.managementFee); - BEAST_EXPECT( - paymentComponents.specialCase == - detail::PaymentSpecialCase::final || + paymentComponents.specialCase == detail::PaymentSpecialCase::final || deltas.total() == state.periodicPayment || - (state.loanScale - - (deltas.total() - state.periodicPayment).exponent()) > 14); + (state.loanScale - (deltas.total() - state.periodicPayment).exponent()) > 14); if (!showStepBalances) - log << currencyLabel - << " Payment components: " << state.paymentRemaining << ", " + log << currencyLabel << " Payment components: " << state.paymentRemaining << ", " - << deltas.interest << ", " << deltas.principal << ", " - << deltas.managementFee << ", " - << paymentComponents.trackedValueDelta << ", " - << paymentComponents.trackedPrincipalDelta << ", " - << paymentComponents.trackedInterestPart() << ", " - << paymentComponents.trackedManagementFeeDelta << ", " - << (paymentComponents.specialCase == - detail::PaymentSpecialCase::final - ? "final" - : paymentComponents.specialCase == - detail::PaymentSpecialCase::extra - ? "extra" - : "none") + << deltas.interest << ", " << deltas.principal << ", " << deltas.managementFee << ", " + << paymentComponents.trackedValueDelta << ", " << paymentComponents.trackedPrincipalDelta << ", " + << paymentComponents.trackedInterestPart() << ", " << paymentComponents.trackedManagementFeeDelta + << ", " + << (paymentComponents.specialCase == detail::PaymentSpecialCase::final ? "final" + : paymentComponents.specialCase == detail::PaymentSpecialCase::extra ? "extra" + : "none") << std::endl; - auto const totalDueAmount = STAmount{ - broker.asset, paymentComponents.trackedValueDelta + serviceFee}; + auto const totalDueAmount = STAmount{broker.asset, paymentComponents.trackedValueDelta + serviceFee}; if (paymentParams.validateBalances) { @@ -1077,34 +919,23 @@ protected: // IOUs, the difference should be dust. Number const diff = totalDue - totalDueAmount; BEAST_EXPECT( - paymentComponents.specialCase == - detail::PaymentSpecialCase::final || - diff == beast::zero || + paymentComponents.specialCase == detail::PaymentSpecialCase::final || diff == beast::zero || (diff > beast::zero && - ((broker.asset.integral() && - (static_cast(diff) < 3)) || + ((broker.asset.integral() && (static_cast(diff) < 3)) || (state.loanScale - diff.exponent() > 13)))); BEAST_EXPECT( paymentComponents.trackedPrincipalDelta >= beast::zero && - paymentComponents.trackedPrincipalDelta <= - state.principalOutstanding); + paymentComponents.trackedPrincipalDelta <= state.principalOutstanding); BEAST_EXPECT( - paymentComponents.specialCase != - detail::PaymentSpecialCase::final || - paymentComponents.trackedPrincipalDelta == - state.principalOutstanding); + paymentComponents.specialCase != detail::PaymentSpecialCase::final || + paymentComponents.trackedPrincipalDelta == state.principalOutstanding); } - auto const borrowerBalanceBeforePayment = - env.balance(borrower, broker.asset); + auto const borrowerBalanceBeforePayment = env.balance(borrower, broker.asset); // Make the payment - env( - pay(borrower, - loanKeylet.key, - transactionAmount, - paymentParams.flags)); + env(pay(borrower, loanKeylet.key, transactionAmount, paymentParams.flags)); env.close(d{state.paymentInterval / 2}); @@ -1119,11 +950,7 @@ protected: // Check the result verifyLoanStatus.checkPayment( - state.loanScale, - borrower, - borrowerBalanceBeforePayment, - totalDueAmount, - adjustment); + state.loanScale, borrower, borrowerBalanceBeforePayment, totalDueAmount, adjustment); } if (showStepBalances) @@ -1135,22 +962,16 @@ protected: auto const current = constructRoundedLoanState(loanSle); auto const errors = nextTrueState - current; log << currencyLabel << " Loan balances: " - << "\n\tAmount taken: " - << paymentComponents.trackedValueDelta + << "\n\tAmount taken: " << paymentComponents.trackedValueDelta << "\n\tTotal value: " << current.valueOutstanding - << " (true: " << truncate(nextTrueState.valueOutstanding) - << ", error: " << truncate(errors.total()) + << " (true: " << truncate(nextTrueState.valueOutstanding) << ", error: " << truncate(errors.total()) << ")\n\tPrincipal: " << current.principalOutstanding - << " (true: " - << truncate(nextTrueState.principalOutstanding) - << ", error: " << truncate(errors.principal) - << ")\n\tInterest: " << current.interestDue - << " (true: " << truncate(nextTrueState.interestDue) - << ", error: " << truncate(errors.interest) + << " (true: " << truncate(nextTrueState.principalOutstanding) + << ", error: " << truncate(errors.principal) << ")\n\tInterest: " << current.interestDue + << " (true: " << truncate(nextTrueState.interestDue) << ", error: " << truncate(errors.interest) << ")\n\tMgmt fee: " << current.managementFeeDue << " (true: " << truncate(nextTrueState.managementFeeDue) - << ", error: " << truncate(errors.managementFee) - << ")\n\tPayments remaining " + << ", error: " << truncate(errors.managementFee) << ")\n\tPayments remaining " << loanSle->at(sfPaymentRemaining) << std::endl; currentRoundedState = current; @@ -1158,8 +979,7 @@ protected: --state.paymentRemaining; state.previousPaymentDate = state.nextPaymentDate; - if (paymentComponents.specialCase == - detail::PaymentSpecialCase::final) + if (paymentComponents.specialCase == detail::PaymentSpecialCase::final) { state.paymentRemaining = 0; state.nextPaymentDate = 0; @@ -1168,20 +988,16 @@ protected: { state.nextPaymentDate += state.paymentInterval; } - state.principalOutstanding -= - paymentComponents.trackedPrincipalDelta; - state.managementFeeOutstanding -= - paymentComponents.trackedManagementFeeDelta; + state.principalOutstanding -= paymentComponents.trackedPrincipalDelta; + state.managementFeeOutstanding -= paymentComponents.trackedManagementFeeDelta; state.totalValue -= paymentComponents.trackedValueDelta; if (paymentParams.validateBalances) verifyLoanStatus(state); totalPaid.trackedValueDelta += paymentComponents.trackedValueDelta; - totalPaid.trackedPrincipalDelta += - paymentComponents.trackedPrincipalDelta; - totalPaid.trackedManagementFeeDelta += - paymentComponents.trackedManagementFeeDelta; + totalPaid.trackedPrincipalDelta += paymentComponents.trackedPrincipalDelta; + totalPaid.trackedManagementFeeDelta += paymentComponents.trackedManagementFeeDelta; totalInterestPaid += paymentComponents.trackedInterestPart(); totalFeesPaid += serviceFee; ++totalPaymentsMade; @@ -1194,20 +1010,14 @@ protected: BEAST_EXPECT(state.paymentRemaining == 0); BEAST_EXPECT(state.principalOutstanding == 0); - auto const initialInterestDue = initialState.totalValue - - (initialState.principalOutstanding + - initialState.managementFeeOutstanding); + auto const initialInterestDue = + initialState.totalValue - (initialState.principalOutstanding + initialState.managementFeeOutstanding); if (paymentParams.validateBalances) { // Make sure all the payments add up - BEAST_EXPECT( - totalPaid.trackedValueDelta == initialState.totalValue); - BEAST_EXPECT( - totalPaid.trackedPrincipalDelta == - initialState.principalOutstanding); - BEAST_EXPECT( - totalPaid.trackedManagementFeeDelta == - initialState.managementFeeOutstanding); + BEAST_EXPECT(totalPaid.trackedValueDelta == initialState.totalValue); + BEAST_EXPECT(totalPaid.trackedPrincipalDelta == initialState.principalOutstanding); + BEAST_EXPECT(totalPaid.trackedManagementFeeDelta == initialState.managementFeeOutstanding); // This is almost a tautology given the previous checks, but // check it anyway for completeness. BEAST_EXPECT(totalInterestPaid == initialInterestDue); @@ -1223,35 +1033,21 @@ protected: log << currencyLabel << " Total amounts paid: " << "\n\tTotal value: " << totalPaid.trackedValueDelta << " (initial: " << truncate(initialState.totalValue) - << ", error: " - << truncate( - initialState.totalValue - totalPaid.trackedValueDelta) + << ", error: " << truncate(initialState.totalValue - totalPaid.trackedValueDelta) << ")\n\tPrincipal: " << totalPaid.trackedPrincipalDelta << " (initial: " << truncate(initialState.principalOutstanding) - << ", error: " - << truncate( - initialState.principalOutstanding - - totalPaid.trackedPrincipalDelta) - << ")\n\tInterest: " << totalInterestPaid - << " (initial: " << truncate(initialInterestDue) << ", error: " - << truncate(initialInterestDue - totalInterestPaid) + << ", error: " << truncate(initialState.principalOutstanding - totalPaid.trackedPrincipalDelta) + << ")\n\tInterest: " << totalInterestPaid << " (initial: " << truncate(initialInterestDue) + << ", error: " << truncate(initialInterestDue - totalInterestPaid) << ")\n\tMgmt fee: " << totalPaid.trackedManagementFeeDelta - << " (initial: " - << truncate(initialState.managementFeeOutstanding) - << ", error: " - << truncate( - initialState.managementFeeOutstanding - - totalPaid.trackedManagementFeeDelta) - << ")\n\tTotal payments made: " << totalPaymentsMade - << std::endl; + << " (initial: " << truncate(initialState.managementFeeOutstanding) + << ", error: " << truncate(initialState.managementFeeOutstanding - totalPaid.trackedManagementFeeDelta) + << ")\n\tTotal payments made: " << totalPaymentsMade << std::endl; } } void - runLoan( - AssetType assetType, - BrokerParameters const& brokerParams, - LoanParameters const& loanParams) + runLoan(AssetType assetType, BrokerParameters const& brokerParams, LoanParameters const& loanParams) { using namespace jtx; @@ -1261,8 +1057,7 @@ protected: Env env(*this, all); - auto loanResult = createLoan( - env, assetType, brokerParams, loanParams, issuer, lender, borrower); + auto loanResult = createLoan(env, assetType, brokerParams, loanParams, issuer, lender, borrower); if (!BEAST_EXPECT(loanResult)) return; @@ -1309,16 +1104,13 @@ protected: std::uint32_t flags, // The end of life callback is expected to take the loan to 0 payments // remaining, one way or another - std::function toEndOfLife) + std::function toEndOfLife) { auto const [keylet, loanSequence] = [&]() { auto const brokerSle = env.le(keylet::loanbroker(broker.brokerID)); if (!BEAST_EXPECT(brokerSle)) // will be invalid - return std::make_pair( - keylet::loan(broker.brokerID), std::uint32_t(0)); + return std::make_pair(keylet::loan(broker.brokerID), std::uint32_t(0)); // Broker has no loans BEAST_EXPECT(brokerSle->at(sfOwnerCount) == 0); @@ -1326,12 +1118,10 @@ protected: // The loan keylet is based on the LoanSequence of the _LOAN_BROKER_ // object. auto const loanSequence = brokerSle->at(sfLoanSequence); - return std::make_pair( - keylet::loan(broker.brokerID, loanSequence), loanSequence); + return std::make_pair(keylet::loan(broker.brokerID, loanSequence), loanSequence); }(); - VerifyLoanStatus const verifyLoanStatus( - env, broker, pseudoAcct, keylet); + VerifyLoanStatus const verifyLoanStatus(env, broker, pseudoAcct, keylet); // No loans yet verifyLoanStatus.checkBroker(0, 0, TenthBips32{0}, 1, 0, 0); @@ -1345,8 +1135,7 @@ protected: using namespace loan; using namespace std::chrono_literals; - auto applyExponent = [interestExponent, - this](TenthBips32 value) mutable { + auto applyExponent = [interestExponent, this](TenthBips32 value) mutable { BEAST_EXPECT(value > TenthBips32(0)); while (interestExponent > 0) { @@ -1383,19 +1172,15 @@ protected: // 2.4% .lateInterest = applyExponent(percentageToTenthBips(24) / 10), .closeInterest = applyExponent(percentageToTenthBips(36) / 10), - .overpaymentInterest = - applyExponent(percentageToTenthBips(48) / 10), + .overpaymentInterest = applyExponent(percentageToTenthBips(48) / 10), .payTotal = 12, .payInterval = 600, .gracePd = 60, .flags = flags, }; - Number const principalRequestAmount = - broker.asset(loanParams.principalRequest).value(); - auto const originationFeeAmount = - broker.asset(*loanParams.originationFee).value(); - auto const serviceFeeAmount = - broker.asset(*loanParams.serviceFee).value(); + Number const principalRequestAmount = broker.asset(loanParams.principalRequest).value(); + auto const originationFeeAmount = broker.asset(*loanParams.originationFee).value(); + auto const serviceFeeAmount = broker.asset(*loanParams.serviceFee).value(); auto const lateFeeAmount = broker.asset(*loanParams.lateFee).value(); auto const closeFeeAmount = broker.asset(*loanParams.closeFee).value(); @@ -1407,11 +1192,9 @@ protected: env.close(); - auto const startDate = - env.current()->header().parentCloseTime.time_since_epoch().count(); + auto const startDate = env.current()->header().parentCloseTime.time_since_epoch().count(); - if (auto const brokerSle = env.le(keylet::loanbroker(broker.brokerID)); - BEAST_EXPECT(brokerSle)) + if (auto const brokerSle = env.le(keylet::loanbroker(broker.brokerID)); BEAST_EXPECT(brokerSle)) { BEAST_EXPECT(brokerSle->at(sfOwnerCount) == 1); } @@ -1426,56 +1209,38 @@ protected: BEAST_EXPECT( env.balance(borrower, broker.asset).value() == - borrowerStartbalance.value() + principalRequestAmount - - originationFeeAmount - adjustment.value()); + borrowerStartbalance.value() + principalRequestAmount - originationFeeAmount - adjustment.value()); } - auto const loanFlags = createJtx.stx->isFlag(tfLoanOverpayment) - ? lsfLoanOverpayment - : LedgerSpecificFlags(0); + auto const loanFlags = createJtx.stx->isFlag(tfLoanOverpayment) ? lsfLoanOverpayment : LedgerSpecificFlags(0); if (auto loan = env.le(keylet); BEAST_EXPECT(loan)) { // log << "loan after create: " << to_string(loan->getJson()) // << std::endl; - BEAST_EXPECT( - loan->isFlag(lsfLoanOverpayment) == - createJtx.stx->isFlag(tfLoanOverpayment)); + BEAST_EXPECT(loan->isFlag(lsfLoanOverpayment) == createJtx.stx->isFlag(tfLoanOverpayment)); BEAST_EXPECT(loan->at(sfLoanSequence) == loanSequence); BEAST_EXPECT(loan->at(sfBorrower) == borrower.id()); BEAST_EXPECT(loan->at(sfLoanBrokerID) == broker.brokerID); - BEAST_EXPECT( - loan->at(sfLoanOriginationFee) == originationFeeAmount); + BEAST_EXPECT(loan->at(sfLoanOriginationFee) == originationFeeAmount); BEAST_EXPECT(loan->at(sfLoanServiceFee) == serviceFeeAmount); BEAST_EXPECT(loan->at(sfLatePaymentFee) == lateFeeAmount); BEAST_EXPECT(loan->at(sfClosePaymentFee) == closeFeeAmount); BEAST_EXPECT(loan->at(sfOverpaymentFee) == *loanParams.overFee); BEAST_EXPECT(loan->at(sfInterestRate) == *loanParams.interest); - BEAST_EXPECT( - loan->at(sfLateInterestRate) == *loanParams.lateInterest); - BEAST_EXPECT( - loan->at(sfCloseInterestRate) == *loanParams.closeInterest); - BEAST_EXPECT( - loan->at(sfOverpaymentInterestRate) == - *loanParams.overpaymentInterest); + BEAST_EXPECT(loan->at(sfLateInterestRate) == *loanParams.lateInterest); + BEAST_EXPECT(loan->at(sfCloseInterestRate) == *loanParams.closeInterest); + BEAST_EXPECT(loan->at(sfOverpaymentInterestRate) == *loanParams.overpaymentInterest); BEAST_EXPECT(loan->at(sfStartDate) == startDate); - BEAST_EXPECT( - loan->at(sfPaymentInterval) == *loanParams.payInterval); + BEAST_EXPECT(loan->at(sfPaymentInterval) == *loanParams.payInterval); BEAST_EXPECT(loan->at(sfGracePeriod) == *loanParams.gracePd); BEAST_EXPECT(loan->at(sfPreviousPaymentDueDate) == 0); - BEAST_EXPECT( - loan->at(sfNextPaymentDueDate) == - startDate + *loanParams.payInterval); + BEAST_EXPECT(loan->at(sfNextPaymentDueDate) == startDate + *loanParams.payInterval); BEAST_EXPECT(loan->at(sfPaymentRemaining) == *loanParams.payTotal); BEAST_EXPECT( loan->at(sfLoanScale) >= - (broker.asset.integral() - ? 0 - : std::max( - broker.vaultScale(env), - principalRequestAmount.exponent()))); - BEAST_EXPECT( - loan->at(sfPrincipalOutstanding) == principalRequestAmount); + (broker.asset.integral() ? 0 : std::max(broker.vaultScale(env), principalRequestAmount.exponent()))); + BEAST_EXPECT(loan->at(sfPrincipalOutstanding) == principalRequestAmount); } auto state = getCurrentState(env, broker, keylet, verifyLoanStatus); @@ -1514,17 +1279,10 @@ protected: // unknown flags env(manage(lender, keylet.key, tfLoanManageMask), ter(temINVALID_FLAG)); // combinations of flags are not allowed - env(manage(lender, keylet.key, tfLoanUnimpair | tfLoanImpair), - ter(temINVALID_FLAG)); - env(manage(lender, keylet.key, tfLoanImpair | tfLoanDefault), - ter(temINVALID_FLAG)); - env(manage(lender, keylet.key, tfLoanUnimpair | tfLoanDefault), - ter(temINVALID_FLAG)); - env(manage( - lender, - keylet.key, - tfLoanUnimpair | tfLoanImpair | tfLoanDefault), - ter(temINVALID_FLAG)); + env(manage(lender, keylet.key, tfLoanUnimpair | tfLoanImpair), ter(temINVALID_FLAG)); + env(manage(lender, keylet.key, tfLoanImpair | tfLoanDefault), ter(temINVALID_FLAG)); + env(manage(lender, keylet.key, tfLoanUnimpair | tfLoanDefault), ter(temINVALID_FLAG)); + env(manage(lender, keylet.key, tfLoanUnimpair | tfLoanImpair | tfLoanDefault), ter(temINVALID_FLAG)); // invalid loan ID env(manage(lender, broker.brokerID, tfLoanImpair), ter(tecNO_ENTRY)); // Loan is unimpaired, can't unimpair it again @@ -1536,11 +1294,9 @@ protected: // Check the vault bool const canImpair = canImpairLoan(env, broker, state); // Impair the loan, if possible - env(manage(lender, keylet.key, tfLoanImpair), - canImpair ? ter(tesSUCCESS) : ter(tecLIMIT_EXCEEDED)); + env(manage(lender, keylet.key, tfLoanImpair), canImpair ? ter(tesSUCCESS) : ter(tecLIMIT_EXCEEDED)); // Unimpair the loan - env(manage(lender, keylet.key, tfLoanUnimpair), - canImpair ? ter(tesSUCCESS) : ter(tecNO_PERMISSION)); + env(manage(lender, keylet.key, tfLoanUnimpair), canImpair ? ter(tesSUCCESS) : ter(tecNO_PERMISSION)); auto const nextDueDate = startDate + *loanParams.payInterval; @@ -1570,8 +1326,7 @@ protected: BEAST_EXPECT(loan->at(sfPaymentRemaining) == 0); BEAST_EXPECT(loan->at(sfPrincipalOutstanding) == 0); } - auto const borrowerStartingBalance = - env.balance(borrower, broker.asset); + auto const borrowerStartingBalance = env.balance(borrower, broker.asset); // Try to delete the loan broker with an active loan env(loanBroker::del(lender, broker.brokerID), ter(tecHAS_OBLIGATIONS)); @@ -1605,13 +1360,10 @@ protected: // No loans left verifyLoanStatus.checkBroker(0, 0, *loanParams.interest, 1, 0, 0); - BEAST_EXPECT( - env.balance(borrower, broker.asset).value() == - borrowerStartingBalance.value() - adjustment); + BEAST_EXPECT(env.balance(borrower, broker.asset).value() == borrowerStartingBalance.value() - adjustment); BEAST_EXPECT(env.ownerCount(borrower) == borrowerOwnerCount); - if (auto const brokerSle = env.le(keylet::loanbroker(broker.brokerID)); - BEAST_EXPECT(brokerSle)) + if (auto const brokerSle = env.le(keylet::loanbroker(broker.brokerID)); BEAST_EXPECT(brokerSle)) { BEAST_EXPECT(brokerSle->at(sfOwnerCount) == 0); } @@ -1620,11 +1372,7 @@ protected: std::string getCurrencyLabel(Asset const& asset) { - return ( - asset.native() ? "XRP" - : asset.holds() ? "IOU" - : asset.holds() ? "MPT" - : "Unknown"); + return (asset.native() ? "XRP" : asset.holds() ? "IOU" : asset.holds() ? "MPT" : "Unknown"); } /** Wrapper to run a series of lifecycle tests for a given asset and loan @@ -1652,8 +1400,8 @@ protected: auto const currencyLabel = getCurrencyLabel(asset); auto const caseLabel = [&]() { std::stringstream ss; - ss << "Lifecycle: " << loanAmount << " " << currencyLabel - << " Scale interest to: " << interestExponent << " "; + ss << "Lifecycle: " << loanAmount << " " << currencyLabel << " Scale interest to: " << interestExponent + << " "; return ss.str(); }(); testcase << caseLabel; @@ -1677,12 +1425,9 @@ protected: Number const principalRequest = broker.asset(loanAmount).value(); Number const maxCoveredLoanValue = broker.params.maxCoveredLoanValue(0); BEAST_EXPECT(maxCoveredLoanValue == 1000 * 100 / 10); - Number const maxCoveredLoanRequest = - broker.asset(maxCoveredLoanValue).value(); - Number const totalVaultRequest = - broker.asset(broker.params.vaultDeposit).value(); - Number const debtMaximumRequest = - broker.asset(broker.params.debtMax).value(); + Number const maxCoveredLoanRequest = broker.asset(maxCoveredLoanValue).value(); + Number const totalVaultRequest = broker.asset(broker.params.vaultDeposit).value(); + Number const debtMaximumRequest = broker.asset(broker.params.debtMax).value(); auto const loanSetFee = fee(env.current()->fees().base * 2); @@ -1955,13 +1700,11 @@ protected: return; auto const vaultPseudo = [&]() { - auto const vaultSle = - env.le(keylet::vault(brokerSle->at(sfVaultID))); + auto const vaultSle = env.le(keylet::vault(brokerSle->at(sfVaultID))); if (!BEAST_EXPECT(vaultSle)) // This will be wrong, but the test has failed anyway. return lender; - auto const vaultPseudo = - Account("Vault pseudo-account", vaultSle->at(sfAccount)); + auto const vaultPseudo = Account("Vault pseudo-account", vaultSle->at(sfAccount)); return vaultPseudo; }(); @@ -1984,33 +1727,20 @@ protected: env(trust(issuer, holder[iouCurrency](0), tfSetFreeze)); }; auto deepfreeze = [&](Account const& holder) { - env(trust( - issuer, - holder[iouCurrency](0), - tfSetFreeze | tfSetDeepFreeze)); + env(trust(issuer, holder[iouCurrency](0), tfSetFreeze | tfSetDeepFreeze)); }; auto unfreeze = [&](Account const& holder) { - env(trust( - issuer, - holder[iouCurrency](0), - tfClearFreeze | tfClearDeepFreeze)); + env(trust(issuer, holder[iouCurrency](0), tfClearFreeze | tfClearDeepFreeze)); }; - return std::make_tuple( - freeze, deepfreeze, unfreeze, tecFROZEN); + return std::make_tuple(freeze, deepfreeze, unfreeze, tecFROZEN); } else { auto freeze = [&](Account const& holder) { - mptt.set( - {.account = issuer, - .holder = holder, - .flags = tfMPTLock}); + mptt.set({.account = issuer, .holder = holder, .flags = tfMPTLock}); }; auto unfreeze = [&](Account const& holder) { - mptt.set( - {.account = issuer, - .holder = holder, - .flags = tfMPTUnlock}); + mptt.set({.account = issuer, .holder = holder, .flags = tfMPTUnlock}); }; return std::make_tuple(freeze, empty, unfreeze, tecLOCKED); } @@ -2054,13 +1784,12 @@ protected: // automatically.) env(trust(evan, issuer[iouCurrency](100'000))); - for (auto const& account : - {// these accounts can't be frozen, which deep freeze - // implies - vaultPseudo, - evan, - // these accounts can't be deep frozen - lender}) + for (auto const& account : {// these accounts can't be frozen, which deep freeze + // implies + vaultPseudo, + evan, + // these accounts can't be deep frozen + lender}) { // Freeze evan deepfreeze(account); @@ -2089,39 +1818,28 @@ protected: // Finally! Create a loan std::string testData; - auto coverAvailable = - [&env, this](uint256 const& brokerID, Number const& expected) { - if (auto const brokerSle = env.le(keylet::loanbroker(brokerID)); - BEAST_EXPECT(brokerSle)) - { - auto const available = brokerSle->at(sfCoverAvailable); - BEAST_EXPECT(available == expected); - return available; - } - return Number{}; - }; - auto getDefaultInfo = [&env, this]( - LoanState const& state, - BrokerInfo const& broker) { - if (auto const brokerSle = - env.le(keylet::loanbroker(broker.brokerID)); - BEAST_EXPECT(brokerSle)) + auto coverAvailable = [&env, this](uint256 const& brokerID, Number const& expected) { + if (auto const brokerSle = env.le(keylet::loanbroker(brokerID)); BEAST_EXPECT(brokerSle)) + { + auto const available = brokerSle->at(sfCoverAvailable); + BEAST_EXPECT(available == expected); + return available; + } + return Number{}; + }; + auto getDefaultInfo = [&env, this](LoanState const& state, BrokerInfo const& broker) { + if (auto const brokerSle = env.le(keylet::loanbroker(broker.brokerID)); BEAST_EXPECT(brokerSle)) { BEAST_EXPECT( - state.loanScale >= - (broker.asset.integral() - ? 0 - : std::max( - broker.vaultScale(env), - state.principalOutstanding.exponent()))); + state.loanScale >= (broker.asset.integral() + ? 0 + : std::max(broker.vaultScale(env), state.principalOutstanding.exponent()))); NumberRoundModeGuard mg(Number::upward); auto const defaultAmount = roundToAsset( broker.asset, std::min( tenthBipsOfValue( - tenthBipsOfValue( - brokerSle->at(sfDebtTotal), - broker.params.coverRateMin), + tenthBipsOfValue(brokerSle->at(sfDebtTotal), broker.params.coverRateMin), broker.params.coverRateLiquidation), state.totalValue - state.managementFeeOutstanding), state.loanScale); @@ -2134,34 +1852,25 @@ protected: AccountID const& brokerAcct, Number const& startingCoverAvailable, Number const& amountToBeCovered) { - coverAvailable( - broker.brokerID, startingCoverAvailable - amountToBeCovered); - env(loanBroker::coverDeposit( - brokerAcct, - broker.brokerID, - STAmount{broker.asset, amountToBeCovered})); + coverAvailable(broker.brokerID, startingCoverAvailable - amountToBeCovered); + env(loanBroker::coverDeposit(brokerAcct, broker.brokerID, STAmount{broker.asset, amountToBeCovered})); coverAvailable(broker.brokerID, startingCoverAvailable); env.close(); }; - auto defaultImmediately = [&](std::uint32_t baseFlag, - bool impair = true) { - return [&, impair, baseFlag]( - Keylet const& loanKeylet, - VerifyLoanStatus const& verifyLoanStatus) { + auto defaultImmediately = [&](std::uint32_t baseFlag, bool impair = true) { + return [&, impair, baseFlag](Keylet const& loanKeylet, VerifyLoanStatus const& verifyLoanStatus) { // toEndOfLife // // Default the loan // Initialize values with the current state - auto state = - getCurrentState(env, broker, loanKeylet, verifyLoanStatus); + auto state = getCurrentState(env, broker, loanKeylet, verifyLoanStatus); BEAST_EXPECT(state.flags == baseFlag); auto const& broker = verifyLoanStatus.broker; - auto const startingCoverAvailable = coverAvailable( - broker.brokerID, - broker.asset(broker.params.coverDeposit).number()); + auto const startingCoverAvailable = + coverAvailable(broker.brokerID, broker.asset(broker.params.coverDeposit).number()); if (impair) { @@ -2174,12 +1883,10 @@ protected: if (canImpair) { state.flags |= tfLoanImpair; - state.nextPaymentDate = - env.now().time_since_epoch().count(); + state.nextPaymentDate = env.now().time_since_epoch().count(); // Once the loan is impaired, it can't be impaired again - env(manage(lender, loanKeylet.key, tfLoanImpair), - ter(tecNO_PERMISSION)); + env(manage(lender, loanKeylet.key, tfLoanImpair), ter(tecNO_PERMISSION)); } verifyLoanStatus(state); } @@ -2188,15 +1895,13 @@ protected: // Can't default the loan yet. The grace period hasn't // expired - env(manage(lender, loanKeylet.key, tfLoanDefault), - ter(tecTOO_SOON)); + env(manage(lender, loanKeylet.key, tfLoanDefault), ter(tecTOO_SOON)); // Let some time pass so that the loan can be // defaulted env.close(nextDueDate + 60s); - auto const [amountToBeCovered, brokerAcct] = - getDefaultInfo(state, broker); + auto const [amountToBeCovered, brokerAcct] = getDefaultInfo(state, broker); // Default the loan env(manage(lender, loanKeylet.key, tfLoanDefault)); @@ -2204,11 +1909,7 @@ protected: // The LoanBroker just lost some of it's first-loss capital. // Replenish it. - replenishCover( - broker, - brokerAcct, - startingCoverAvailable, - amountToBeCovered); + replenishCover(broker, brokerAcct, startingCoverAvailable, amountToBeCovered); state.flags |= tfLoanDefault; state.paymentRemaining = 0; @@ -2219,13 +1920,10 @@ protected: verifyLoanStatus(state); // Once a loan is defaulted, it can't be managed - env(manage(lender, loanKeylet.key, tfLoanUnimpair), - ter(tecNO_PERMISSION)); - env(manage(lender, loanKeylet.key, tfLoanImpair), - ter(tecNO_PERMISSION)); + env(manage(lender, loanKeylet.key, tfLoanUnimpair), ter(tecNO_PERMISSION)); + env(manage(lender, loanKeylet.key, tfLoanImpair), ter(tecNO_PERMISSION)); // Can't make a payment on it either - env(pay(borrower, loanKeylet.key, broker.asset(300)), - ter(tecKILLED)); + env(pay(borrower, loanKeylet.key, broker.asset(300)), ter(tecKILLED)); }; }; @@ -2241,19 +1939,12 @@ protected: verifyLoanStatus(state); // Send some bogus pay transactions - env(pay(borrower, - keylet::loan(uint256(0)).key, - broker.asset(10), - txFlags), - ter(temINVALID)); + env(pay(borrower, keylet::loan(uint256(0)).key, broker.asset(10), txFlags), ter(temINVALID)); // broker.asset(80) is less than a single payment, but all these // checks fail before that matters - env(pay(borrower, loanKeylet.key, broker.asset(-80), txFlags), - ter(temBAD_AMOUNT)); - env(pay(borrower, broker.brokerID, broker.asset(80), txFlags), - ter(tecNO_ENTRY)); - env(pay(evan, loanKeylet.key, broker.asset(80), txFlags), - ter(tecNO_PERMISSION)); + env(pay(borrower, loanKeylet.key, broker.asset(-80), txFlags), ter(temBAD_AMOUNT)); + env(pay(borrower, broker.brokerID, broker.asset(80), txFlags), ter(tecNO_ENTRY)); + env(pay(evan, loanKeylet.key, broker.asset(80), txFlags), ter(tecNO_PERMISSION)); // TODO: Write a general "isFlag" function? See STObject::isFlag. // Maybe add a static overloaded member? @@ -2264,13 +1955,9 @@ protected: // don't end up duplicating the next test transaction. env(pay(borrower, loanKeylet.key, - STAmount{ - broker.asset, - state.periodicPayment * Number{15, -1}}, + STAmount{broker.asset, state.periodicPayment * Number{15, -1}}, tfLoanOverpayment), - fee(XRPAmount{ - baseFee * - (Number{15, -1} / loanPaymentsPerFeeIncrement + 1)}), + fee(XRPAmount{baseFee * (Number{15, -1} / loanPaymentsPerFeeIncrement + 1)}), ter(temINVALID_FLAG)); } // Try to send a payment marked as multiple mutually exclusive @@ -2298,24 +1985,16 @@ protected: ter(temINVALID_FLAG)); { - auto const otherAsset = broker.asset.raw() == assets[0].raw() - ? assets[1] - : assets[0]; - env(pay(borrower, loanKeylet.key, otherAsset(100), txFlags), - ter(tecWRONG_ASSET)); + auto const otherAsset = broker.asset.raw() == assets[0].raw() ? assets[1] : assets[0]; + env(pay(borrower, loanKeylet.key, otherAsset(100), txFlags), ter(tecWRONG_ASSET)); } // Amount doesn't cover a single payment - env(pay(borrower, - loanKeylet.key, - STAmount{broker.asset, 1}, - txFlags), - ter(tecINSUFFICIENT_PAYMENT)); + env(pay(borrower, loanKeylet.key, STAmount{broker.asset, 1}, txFlags), ter(tecINSUFFICIENT_PAYMENT)); // Get the balance after these failed transactions take // fees - auto const borrowerBalanceBeforePayment = - env.balance(borrower, broker.asset); + auto const borrowerBalanceBeforePayment = env.balance(borrower, broker.asset); BEAST_EXPECT(payoffAmount > state.principalOutstanding); // Try to pay a little extra to show that it's _not_ @@ -2326,22 +2005,16 @@ protected: // balance XRPAmount const badFee{ baseFee * - (borrowerBalanceBeforePayment.number() * 2 / - state.periodicPayment / loanPaymentsPerFeeIncrement + - 1)}; + (borrowerBalanceBeforePayment.number() * 2 / state.periodicPayment / loanPaymentsPerFeeIncrement + 1)}; env(pay(borrower, loanKeylet.key, - STAmount{ - broker.asset, - borrowerBalanceBeforePayment.number() * 2}, + STAmount{broker.asset, borrowerBalanceBeforePayment.number() * 2}, txFlags), fee(badFee), ter(tecINSUFFICIENT_FUNDS)); - XRPAmount const goodFee{ - baseFee * (numPayments / loanPaymentsPerFeeIncrement + 1)}; - env(pay(borrower, loanKeylet.key, transactionAmount, txFlags), - fee(goodFee)); + XRPAmount const goodFee{baseFee * (numPayments / loanPaymentsPerFeeIncrement + 1)}; + env(pay(borrower, loanKeylet.key, transactionAmount, txFlags), fee(goodFee)); env.close(); @@ -2358,33 +2031,23 @@ protected: state.principalOutstanding = 0; state.totalValue = 0; state.managementFeeOutstanding = 0; - state.previousPaymentDate = state.nextPaymentDate + - state.paymentInterval * (numPayments - 1); + state.previousPaymentDate = state.nextPaymentDate + state.paymentInterval * (numPayments - 1); state.nextPaymentDate = 0; verifyLoanStatus(state); verifyLoanStatus.checkPayment( - state.loanScale, - borrower, - borrowerBalanceBeforePayment, - payoffAmount, - adjustment); + state.loanScale, borrower, borrowerBalanceBeforePayment, payoffAmount, adjustment); // Can't impair or default a paid off loan - env(manage(lender, loanKeylet.key, tfLoanImpair), - ter(tecNO_PERMISSION)); - env(manage(lender, loanKeylet.key, tfLoanDefault), - ter(tecNO_PERMISSION)); + env(manage(lender, loanKeylet.key, tfLoanImpair), ter(tecNO_PERMISSION)); + env(manage(lender, loanKeylet.key, tfLoanDefault), ter(tecNO_PERMISSION)); }; auto fullPayment = [&](std::uint32_t baseFlag) { - return [&, baseFlag]( - Keylet const& loanKeylet, - VerifyLoanStatus const& verifyLoanStatus) { + return [&, baseFlag](Keylet const& loanKeylet, VerifyLoanStatus const& verifyLoanStatus) { // toEndOfLife // - auto state = - getCurrentState(env, broker, loanKeylet, verifyLoanStatus); + auto state = getCurrentState(env, broker, loanKeylet, verifyLoanStatus); env.close(state.startDate + 20s); auto const loanAge = (env.now() - state.startDate).count(); BEAST_EXPECT(loanAge == 30); @@ -2398,79 +2061,48 @@ protected: // to verify they're working correctly The numbers in // the below BEAST_EXPECTs may not hold across assets. Number const interval = state.paymentInterval; - auto const periodicRate = - interval * Number(12, -2) / secondsInYear; - BEAST_EXPECT( - periodicRate == - Number(2283105022831050228ULL, -24, Number::normalized{})); - STAmount const principalOutstanding{ - broker.asset, state.principalOutstanding}; + auto const periodicRate = interval * Number(12, -2) / secondsInYear; + BEAST_EXPECT(periodicRate == Number(2283105022831050228ULL, -24, Number::normalized{})); + STAmount const principalOutstanding{broker.asset, state.principalOutstanding}; STAmount const accruedInterest{ - broker.asset, - state.principalOutstanding * periodicRate * loanAge / - interval}; - BEAST_EXPECT( - accruedInterest == - broker.asset(Number(1141552511415525, -19))); - STAmount const prepaymentPenalty{ - broker.asset, state.principalOutstanding * Number(36, -3)}; + broker.asset, state.principalOutstanding * periodicRate * loanAge / interval}; + BEAST_EXPECT(accruedInterest == broker.asset(Number(1141552511415525, -19))); + STAmount const prepaymentPenalty{broker.asset, state.principalOutstanding * Number(36, -3)}; BEAST_EXPECT(prepaymentPenalty == broker.asset(36)); STAmount const closePaymentFee = broker.asset(4); auto const payoffAmount = roundToScale( - principalOutstanding + accruedInterest + prepaymentPenalty + - closePaymentFee, - state.loanScale); + principalOutstanding + accruedInterest + prepaymentPenalty + closePaymentFee, state.loanScale); BEAST_EXPECT( payoffAmount == - roundToAsset( - broker.asset, - broker.asset(Number(1040000114155251, -12)).number(), - state.loanScale)); + roundToAsset(broker.asset, broker.asset(Number(1040000114155251, -12)).number(), state.loanScale)); // The terms of this loan actually make the early payoff // more expensive than just making payments - BEAST_EXPECT( - payoffAmount > state.paymentRemaining * - (state.periodicPayment + broker.asset(2).value())); + BEAST_EXPECT(payoffAmount > state.paymentRemaining * (state.periodicPayment + broker.asset(2).value())); - singlePayment( - loanKeylet, - verifyLoanStatus, - state, - payoffAmount, - 1, - baseFlag, - tfLoanFullPayment); + singlePayment(loanKeylet, verifyLoanStatus, state, payoffAmount, 1, baseFlag, tfLoanFullPayment); }; }; auto combineAllPayments = [&](std::uint32_t baseFlag) { - return [&, baseFlag]( - Keylet const& loanKeylet, - VerifyLoanStatus const& verifyLoanStatus) { + return [&, baseFlag](Keylet const& loanKeylet, VerifyLoanStatus const& verifyLoanStatus) { // toEndOfLife // - auto state = - getCurrentState(env, broker, loanKeylet, verifyLoanStatus); + auto state = getCurrentState(env, broker, loanKeylet, verifyLoanStatus); env.close(); BEAST_EXPECT( - STAmount(broker.asset, state.periodicPayment) == - broker.asset(Number(8333457002039338267, -17))); + STAmount(broker.asset, state.periodicPayment) == broker.asset(Number(8333457002039338267, -17))); // Make all the payments in one transaction // service fee is 2 auto const startingPayments = state.paymentRemaining; STAmount const payoffAmount = [&]() { NumberRoundModeGuard mg(Number::upward); - auto const rawPayoff = startingPayments * - (state.periodicPayment + broker.asset(2).value()); + auto const rawPayoff = startingPayments * (state.periodicPayment + broker.asset(2).value()); STAmount payoffAmount{broker.asset, rawPayoff}; - BEAST_EXPECTS( - payoffAmount == - broker.asset(Number(1024014840244721, -12)), - to_string(payoffAmount)); + BEAST_EXPECTS(payoffAmount == broker.asset(Number(1024014840244721, -12)), to_string(payoffAmount)); BEAST_EXPECT(payoffAmount > state.principalOutstanding); payoffAmount = roundToScale(payoffAmount, state.loanScale); @@ -2478,24 +2110,14 @@ protected: return payoffAmount; }(); - auto const totalPayoffValue = state.totalValue + - startingPayments * broker.asset(2).value(); - STAmount const totalPayoffAmount{ - broker.asset, totalPayoffValue}; + auto const totalPayoffValue = state.totalValue + startingPayments * broker.asset(2).value(); + STAmount const totalPayoffAmount{broker.asset, totalPayoffValue}; BEAST_EXPECTS( totalPayoffAmount == payoffAmount, - "Payoff amount: " + to_string(payoffAmount) + - ". Total Value: " + to_string(totalPayoffAmount)); + "Payoff amount: " + to_string(payoffAmount) + ". Total Value: " + to_string(totalPayoffAmount)); - singlePayment( - loanKeylet, - verifyLoanStatus, - state, - payoffAmount, - state.paymentRemaining, - baseFlag, - 0); + singlePayment(loanKeylet, verifyLoanStatus, state, payoffAmount, state.paymentRemaining, baseFlag, 0); }; }; @@ -2627,13 +2249,11 @@ protected: broker, pseudoAcct, 0, - [&](Keylet const& loanKeylet, - VerifyLoanStatus const& verifyLoanStatus) { + [&](Keylet const& loanKeylet, VerifyLoanStatus const& verifyLoanStatus) { // toEndOfLife // // Draw and make multiple payments - auto state = - getCurrentState(env, broker, loanKeylet, verifyLoanStatus); + auto state = getCurrentState(env, broker, loanKeylet, verifyLoanStatus); BEAST_EXPECT(state.flags == 0); env.close(); @@ -2652,152 +2272,105 @@ protected: // to verify they're working correctly The numbers in // the below BEAST_EXPECTs may not hold across assets. Number const interval = state.paymentInterval; - auto const periodicRate = - interval * Number(12, -2) / secondsInYear; - BEAST_EXPECT( - periodicRate == - Number(2283105022831050228, -24, Number::normalized{})); + auto const periodicRate = interval * Number(12, -2) / secondsInYear; + BEAST_EXPECT(periodicRate == Number(2283105022831050228, -24, Number::normalized{})); STAmount const roundedPeriodicPayment{ - broker.asset, - roundPeriodicPayment( - broker.asset, state.periodicPayment, state.loanScale)}; + broker.asset, roundPeriodicPayment(broker.asset, state.periodicPayment, state.loanScale)}; - testcase - << currencyLabel << " Payment components: " - << "Payments remaining, rawInterest, rawPrincipal, " - "rawMFee, trackedValueDelta, trackedPrincipalDelta, " - "trackedInterestDelta, trackedMgmtFeeDelta, special"; + testcase << currencyLabel << " Payment components: " + << "Payments remaining, rawInterest, rawPrincipal, " + "rawMFee, trackedValueDelta, trackedPrincipalDelta, " + "trackedInterestDelta, trackedMgmtFeeDelta, special"; auto const serviceFee = broker.asset(2); BEAST_EXPECT( roundedPeriodicPayment == roundToScale( - broker.asset( - Number(8333457002039338267, -17), Number::upward), + broker.asset(Number(8333457002039338267, -17), Number::upward), state.loanScale, Number::upward)); // 83334570.01162141 // Include the service fee - STAmount const totalDue = roundToScale( - roundedPeriodicPayment + serviceFee, - state.loanScale, - Number::upward); + STAmount const totalDue = + roundToScale(roundedPeriodicPayment + serviceFee, state.loanScale, Number::upward); // Only check the first payment since the rounding // may drift as payments are made BEAST_EXPECT( totalDue == roundToScale( - broker.asset( - Number(8533457002039338267, -17), Number::upward), + broker.asset(Number(8533457002039338267, -17), Number::upward), state.loanScale, Number::upward)); { auto const raw = computeTheoreticalLoanState( - state.periodicPayment, - periodicRate, - state.paymentRemaining, - broker.params.managementFeeRate); + state.periodicPayment, periodicRate, state.paymentRemaining, broker.params.managementFeeRate); auto const rounded = constructLoanState( - state.totalValue, - state.principalOutstanding, - state.managementFeeOutstanding); - testcase - << currencyLabel - << " Loan starting state: " << state.paymentRemaining - << ", " << raw.interestDue << ", " - << raw.principalOutstanding << ", " - << raw.managementFeeDue << ", " - << rounded.valueOutstanding << ", " - << rounded.principalOutstanding << ", " - << rounded.interestDue << ", " - << rounded.managementFeeDue; + state.totalValue, state.principalOutstanding, state.managementFeeOutstanding); + testcase << currencyLabel << " Loan starting state: " << state.paymentRemaining << ", " + << raw.interestDue << ", " << raw.principalOutstanding << ", " << raw.managementFeeDue + << ", " << rounded.valueOutstanding << ", " << rounded.principalOutstanding << ", " + << rounded.interestDue << ", " << rounded.managementFeeDue; } // Try to pay a little extra to show that it's _not_ // taken - STAmount const transactionAmount = - STAmount{broker.asset, totalDue} + broker.asset(10); + STAmount const transactionAmount = STAmount{broker.asset, totalDue} + broker.asset(10); // Only check the first payment since the rounding // may drift as payments are made BEAST_EXPECT( transactionAmount == roundToScale( - broker.asset( - Number(9533457002039400, -14), Number::upward), - state.loanScale, - Number::upward)); + broker.asset(Number(9533457002039400, -14), Number::upward), state.loanScale, Number::upward)); auto const initialState = state; detail::PaymentComponents totalPaid{ - .trackedValueDelta = 0, - .trackedPrincipalDelta = 0, - .trackedManagementFeeDelta = 0}; + .trackedValueDelta = 0, .trackedPrincipalDelta = 0, .trackedManagementFeeDelta = 0}; Number totalInterestPaid = 0; std::size_t totalPaymentsMade = 0; xrpl::LoanState currentTrueState = computeTheoreticalLoanState( - state.periodicPayment, - periodicRate, - state.paymentRemaining, - broker.params.managementFeeRate); + state.periodicPayment, periodicRate, state.paymentRemaining, broker.params.managementFeeRate); while (state.paymentRemaining > 0) { // Compute the expected principal amount - auto const paymentComponents = - detail::computePaymentComponents( - broker.asset.raw(), - state.loanScale, - state.totalValue, - state.principalOutstanding, - state.managementFeeOutstanding, - state.periodicPayment, - periodicRate, - state.paymentRemaining, - broker.params.managementFeeRate); + auto const paymentComponents = detail::computePaymentComponents( + broker.asset.raw(), + state.loanScale, + state.totalValue, + state.principalOutstanding, + state.managementFeeOutstanding, + state.periodicPayment, + periodicRate, + state.paymentRemaining, + broker.params.managementFeeRate); BEAST_EXPECTS( - paymentComponents.specialCase == - detail::PaymentSpecialCase::final || - paymentComponents.trackedValueDelta <= - roundedPeriodicPayment, - "Delta: " + - to_string(paymentComponents.trackedValueDelta) + - ", periodic payment: " + - to_string(roundedPeriodicPayment)); + paymentComponents.specialCase == detail::PaymentSpecialCase::final || + paymentComponents.trackedValueDelta <= roundedPeriodicPayment, + "Delta: " + to_string(paymentComponents.trackedValueDelta) + + ", periodic payment: " + to_string(roundedPeriodicPayment)); - xrpl::LoanState const nextTrueState = - computeTheoreticalLoanState( - state.periodicPayment, - periodicRate, - state.paymentRemaining - 1, - broker.params.managementFeeRate); - detail::LoanStateDeltas const deltas = - currentTrueState - nextTrueState; + xrpl::LoanState const nextTrueState = computeTheoreticalLoanState( + state.periodicPayment, + periodicRate, + state.paymentRemaining - 1, + broker.params.managementFeeRate); + detail::LoanStateDeltas const deltas = currentTrueState - nextTrueState; - testcase - << currencyLabel - << " Payment components: " << state.paymentRemaining - << ", " << deltas.interest << ", " << deltas.principal - << ", " << deltas.managementFee << ", " - << paymentComponents.trackedValueDelta << ", " - << paymentComponents.trackedPrincipalDelta << ", " - << paymentComponents.trackedInterestPart() << ", " - << paymentComponents.trackedManagementFeeDelta << ", " - << (paymentComponents.specialCase == - detail::PaymentSpecialCase::final - ? "final" - : paymentComponents.specialCase == - detail::PaymentSpecialCase::extra - ? "extra" - : "none"); + testcase << currencyLabel << " Payment components: " << state.paymentRemaining << ", " + << deltas.interest << ", " << deltas.principal << ", " << deltas.managementFee << ", " + << paymentComponents.trackedValueDelta << ", " << paymentComponents.trackedPrincipalDelta + << ", " << paymentComponents.trackedInterestPart() << ", " + << paymentComponents.trackedManagementFeeDelta << ", " + << (paymentComponents.specialCase == detail::PaymentSpecialCase::final ? "final" + : paymentComponents.specialCase == detail::PaymentSpecialCase::extra ? "extra" + : "none"); - auto const totalDueAmount = STAmount{ - broker.asset, - paymentComponents.trackedValueDelta + - serviceFee.number()}; + auto const totalDueAmount = + STAmount{broker.asset, paymentComponents.trackedValueDelta + serviceFee.number()}; // Due to the rounding algorithms to keep the interest and // principal in sync with "true" values, the computed amount @@ -2807,58 +2380,39 @@ protected: // IOUs, the difference should be after the 8th digit. Number const diff = totalDue - totalDueAmount; BEAST_EXPECT( - paymentComponents.specialCase == - detail::PaymentSpecialCase::final || - diff == beast::zero || + paymentComponents.specialCase == detail::PaymentSpecialCase::final || diff == beast::zero || (diff > beast::zero && - ((broker.asset.integral() && - (static_cast(diff) < 3)) || + ((broker.asset.integral() && (static_cast(diff) < 3)) || (state.loanScale - diff.exponent() > 13)))); BEAST_EXPECT( paymentComponents.trackedValueDelta == - paymentComponents.trackedPrincipalDelta + - paymentComponents.trackedInterestPart() + + paymentComponents.trackedPrincipalDelta + paymentComponents.trackedInterestPart() + paymentComponents.trackedManagementFeeDelta); BEAST_EXPECT( - paymentComponents.specialCase == - detail::PaymentSpecialCase::final || - paymentComponents.trackedValueDelta <= - roundedPeriodicPayment); + paymentComponents.specialCase == detail::PaymentSpecialCase::final || + paymentComponents.trackedValueDelta <= roundedPeriodicPayment); BEAST_EXPECT( state.paymentRemaining < 12 || - roundToAsset( - broker.asset, - deltas.principal, - state.loanScale, - Number::upward) == + roundToAsset(broker.asset, deltas.principal, state.loanScale, Number::upward) == roundToScale( - broker.asset( - Number(8333228691531218890, -17), - Number::upward), + broker.asset(Number(8333228691531218890, -17), Number::upward), state.loanScale, Number::upward)); BEAST_EXPECT( - paymentComponents.trackedPrincipalDelta >= - beast::zero && - paymentComponents.trackedPrincipalDelta <= - state.principalOutstanding); + paymentComponents.trackedPrincipalDelta >= beast::zero && + paymentComponents.trackedPrincipalDelta <= state.principalOutstanding); BEAST_EXPECT( - paymentComponents.specialCase != - detail::PaymentSpecialCase::final || - paymentComponents.trackedPrincipalDelta == - state.principalOutstanding); + paymentComponents.specialCase != detail::PaymentSpecialCase::final || + paymentComponents.trackedPrincipalDelta == state.principalOutstanding); BEAST_EXPECT( - paymentComponents.specialCase == - detail::PaymentSpecialCase::final || + paymentComponents.specialCase == detail::PaymentSpecialCase::final || (state.periodicPayment.exponent() - - (deltas.principal + deltas.interest + - deltas.managementFee - state.periodicPayment) + (deltas.principal + deltas.interest + deltas.managementFee - state.periodicPayment) .exponent()) > 14); - auto const borrowerBalanceBeforePayment = - env.balance(borrower, broker.asset); + auto const borrowerBalanceBeforePayment = env.balance(borrower, broker.asset); if (canImpairLoan(env, broker, state)) // Making a payment will unimpair the loan @@ -2880,16 +2434,11 @@ protected: // Check the result verifyLoanStatus.checkPayment( - state.loanScale, - borrower, - borrowerBalanceBeforePayment, - totalDueAmount, - adjustment); + state.loanScale, borrower, borrowerBalanceBeforePayment, totalDueAmount, adjustment); --state.paymentRemaining; state.previousPaymentDate = state.nextPaymentDate; - if (paymentComponents.specialCase == - detail::PaymentSpecialCase::final) + if (paymentComponents.specialCase == detail::PaymentSpecialCase::final) { state.paymentRemaining = 0; state.nextPaymentDate = 0; @@ -2898,22 +2447,16 @@ protected: { state.nextPaymentDate += state.paymentInterval; } - state.principalOutstanding -= - paymentComponents.trackedPrincipalDelta; - state.managementFeeOutstanding -= - paymentComponents.trackedManagementFeeDelta; + state.principalOutstanding -= paymentComponents.trackedPrincipalDelta; + state.managementFeeOutstanding -= paymentComponents.trackedManagementFeeDelta; state.totalValue -= paymentComponents.trackedValueDelta; verifyLoanStatus(state); - totalPaid.trackedValueDelta += - paymentComponents.trackedValueDelta; - totalPaid.trackedPrincipalDelta += - paymentComponents.trackedPrincipalDelta; - totalPaid.trackedManagementFeeDelta += - paymentComponents.trackedManagementFeeDelta; - totalInterestPaid += - paymentComponents.trackedInterestPart(); + totalPaid.trackedValueDelta += paymentComponents.trackedValueDelta; + totalPaid.trackedPrincipalDelta += paymentComponents.trackedPrincipalDelta; + totalPaid.trackedManagementFeeDelta += paymentComponents.trackedManagementFeeDelta; + totalInterestPaid += paymentComponents.trackedInterestPart(); ++totalPaymentsMade; currentTrueState = nextTrueState; @@ -2924,29 +2467,20 @@ protected: BEAST_EXPECT(state.principalOutstanding == 0); // Make sure all the payments add up - BEAST_EXPECT( - totalPaid.trackedValueDelta == initialState.totalValue); - BEAST_EXPECT( - totalPaid.trackedPrincipalDelta == - initialState.principalOutstanding); - BEAST_EXPECT( - totalPaid.trackedManagementFeeDelta == - initialState.managementFeeOutstanding); + BEAST_EXPECT(totalPaid.trackedValueDelta == initialState.totalValue); + BEAST_EXPECT(totalPaid.trackedPrincipalDelta == initialState.principalOutstanding); + BEAST_EXPECT(totalPaid.trackedManagementFeeDelta == initialState.managementFeeOutstanding); // This is almost a tautology given the previous checks, but // check it anyway for completeness. BEAST_EXPECT( totalInterestPaid == initialState.totalValue - - (initialState.principalOutstanding + - initialState.managementFeeOutstanding)); - BEAST_EXPECT( - totalPaymentsMade == initialState.paymentRemaining); + (initialState.principalOutstanding + initialState.managementFeeOutstanding)); + BEAST_EXPECT(totalPaymentsMade == initialState.paymentRemaining); // Can't impair or default a paid off loan - env(manage(lender, loanKeylet.key, tfLoanImpair), - ter(tecNO_PERMISSION)); - env(manage(lender, loanKeylet.key, tfLoanDefault), - ter(tecNO_PERMISSION)); + env(manage(lender, loanKeylet.key, tfLoanImpair), ter(tecNO_PERMISSION)); + env(manage(lender, loanKeylet.key, tfLoanDefault), ter(tecNO_PERMISSION)); }); #if LOANTODO @@ -2969,8 +2503,7 @@ protected: auto const start = clock_type::now(); timed(); - auto const duration = std::chrono::duration_cast( - clock_type::now() - start); + auto const duration = std::chrono::duration_cast(clock_type::now() - start); log << label << " took " << duration.count() << "ms" << std::endl; @@ -2989,45 +2522,32 @@ protected: broker, pseudoAcct, tfLoanOverpayment, - [&](Keylet const& loanKeylet, - VerifyLoanStatus const& verifyLoanStatus) { + [&](Keylet const& loanKeylet, VerifyLoanStatus const& verifyLoanStatus) { // Estimate optimal values for loanPaymentsPerFeeIncrement and // loanMaximumPaymentsPerTransaction. using namespace loan; - auto const state = - getCurrentState(env, broker, verifyLoanStatus.keylet); + auto const state = getCurrentState(env, broker, verifyLoanStatus.keylet); auto const serviceFee = broker.asset(2).value(); STAmount const totalDue{ broker.asset, - roundPeriodicPayment( - broker.asset, - state.periodicPayment + serviceFee, - state.loanScale)}; + roundPeriodicPayment(broker.asset, state.periodicPayment + serviceFee, state.loanScale)}; // Make a single payment - time("single payment", [&]() { - env(pay(borrower, loanKeylet.key, totalDue)); - }); + time("single payment", [&]() { env(pay(borrower, loanKeylet.key, totalDue)); }); env.close(); // Make all but the final payment auto const numPayments = (state.paymentRemaining - 2); STAmount const bigPayment{broker.asset, totalDue * numPayments}; - XRPAmount const bigFee{ - baseFee * (numPayments / loanPaymentsPerFeeIncrement + 1)}; - time("ten payments", [&]() { - env(pay(borrower, loanKeylet.key, bigPayment), fee(bigFee)); - }); + XRPAmount const bigFee{baseFee * (numPayments / loanPaymentsPerFeeIncrement + 1)}; + time("ten payments", [&]() { env(pay(borrower, loanKeylet.key, bigPayment), fee(bigFee)); }); env.close(); time("final payment", [&]() { // Make the final payment - env( - pay(borrower, - loanKeylet.key, - totalDue + STAmount{broker.asset, 1})); + env(pay(borrower, loanKeylet.key, totalDue + STAmount{broker.asset, 1})); }); env.close(); }); @@ -3044,8 +2564,7 @@ protected: broker, pseudoAcct, tfLoanOverpayment, - [&](Keylet const& loanKeylet, - VerifyLoanStatus const& verifyLoanStatus) { throw 0; }); + [&](Keylet const& loanKeylet, VerifyLoanStatus const& verifyLoanStatus) { throw 0; }); lifecycle( caseLabel, @@ -3059,8 +2578,7 @@ protected: broker, pseudoAcct, tfLoanOverpayment, - [&](Keylet const& loanKeylet, - VerifyLoanStatus const& verifyLoanStatus) { throw 0; }); + [&](Keylet const& loanKeylet, VerifyLoanStatus const& verifyLoanStatus) { throw 0; }); lifecycle( caseLabel, @@ -3074,8 +2592,7 @@ protected: broker, pseudoAcct, tfLoanOverpayment, - [&](Keylet const& loanKeylet, - VerifyLoanStatus const& verifyLoanStatus) { throw 0; }); + [&](Keylet const& loanKeylet, VerifyLoanStatus const& verifyLoanStatus) { throw 0; }); lifecycle( caseLabel, @@ -3089,8 +2606,7 @@ protected: broker, pseudoAcct, tfLoanOverpayment, - [&](Keylet const& loanKeylet, - VerifyLoanStatus const& verifyLoanStatus) { throw 0; }); + [&](Keylet const& loanKeylet, VerifyLoanStatus const& verifyLoanStatus) { throw 0; }); #endif } @@ -3111,81 +2627,76 @@ protected: int initialXRP = 1'000'000; }; - auto const testCase = - [&, this]( - std::function - mptTest, - std::function iouTest, - CaseArgs args = {}) { - Env env(*this, all); - env.fund(XRP(args.initialXRP), issuer, lender, borrower); + auto const testCase = [&, this]( + std::function mptTest, + std::function iouTest, + CaseArgs args = {}) { + Env env(*this, all); + env.fund(XRP(args.initialXRP), issuer, lender, borrower); + env.close(); + if (args.requireAuth) + { + env(fset(issuer, asfRequireAuth)); env.close(); - if (args.requireAuth) - { - env(fset(issuer, asfRequireAuth)); - env.close(); - } + } - // We need two different asset types, MPT and IOU. Prepare MPT - // first - MPTTester mptt{env, issuer, mptInitNoFund}; + // We need two different asset types, MPT and IOU. Prepare MPT + // first + MPTTester mptt{env, issuer, mptInitNoFund}; - auto const none = LedgerSpecificFlags(0); - mptt.create( - {.flags = tfMPTCanTransfer | tfMPTCanLock | - (args.requireAuth ? tfMPTRequireAuth : none)}); + auto const none = LedgerSpecificFlags(0); + mptt.create({.flags = tfMPTCanTransfer | tfMPTCanLock | (args.requireAuth ? tfMPTRequireAuth : none)}); + env.close(); + PrettyAsset mptAsset = mptt.issuanceID(); + mptt.authorize({.account = lender}); + mptt.authorize({.account = borrower}); + env.close(); + if (args.requireAuth) + { + mptt.authorize({.account = issuer, .holder = lender}); + if (args.authorizeBorrower) + mptt.authorize({.account = issuer, .holder = borrower}); env.close(); - PrettyAsset mptAsset = mptt.issuanceID(); - mptt.authorize({.account = lender}); - mptt.authorize({.account = borrower}); - env.close(); - if (args.requireAuth) - { - mptt.authorize({.account = issuer, .holder = lender}); - if (args.authorizeBorrower) - mptt.authorize({.account = issuer, .holder = borrower}); - env.close(); - } + } - env(pay(issuer, lender, mptAsset(10'000'000))); - env.close(); + env(pay(issuer, lender, mptAsset(10'000'000))); + env.close(); - // Prepare IOU - PrettyAsset const iouAsset = issuer[iouCurrency]; - env(trust(lender, iouAsset(10'000'000))); - env(trust(borrower, iouAsset(10'000'000))); - env.close(); - if (args.requireAuth) + // Prepare IOU + PrettyAsset const iouAsset = issuer[iouCurrency]; + env(trust(lender, iouAsset(10'000'000))); + env(trust(borrower, iouAsset(10'000'000))); + env.close(); + if (args.requireAuth) + { + env(trust(issuer, iouAsset(0), lender, tfSetfAuth)); + env(pay(issuer, lender, iouAsset(10'000'000))); + if (args.authorizeBorrower) { - env(trust(issuer, iouAsset(0), lender, tfSetfAuth)); - env(pay(issuer, lender, iouAsset(10'000'000))); - if (args.authorizeBorrower) - { - env(trust(issuer, iouAsset(0), borrower, tfSetfAuth)); - env(pay(issuer, borrower, iouAsset(10'000))); - } - } - else - { - env(pay(issuer, lender, iouAsset(10'000'000))); + env(trust(issuer, iouAsset(0), borrower, tfSetfAuth)); env(pay(issuer, borrower, iouAsset(10'000))); } - env.close(); + } + else + { + env(pay(issuer, lender, iouAsset(10'000'000))); + env(pay(issuer, borrower, iouAsset(10'000))); + } + env.close(); - // Create vaults and loan brokers - std::array const assets{mptAsset, iouAsset}; - std::vector brokers; - for (auto const& asset : assets) - { - brokers.emplace_back( - createVaultAndBroker(env, asset, lender)); - } + // Create vaults and loan brokers + std::array const assets{mptAsset, iouAsset}; + std::vector brokers; + for (auto const& asset : assets) + { + brokers.emplace_back(createVaultAndBroker(env, asset, lender)); + } - if (mptTest) - (mptTest)(env, brokers[0], mptt); - if (iouTest) - (iouTest)(env, brokers[1]); - }; + if (mptTest) + (mptTest)(env, brokers[0], mptt); + if (iouTest) + (iouTest)(env, brokers[1]); + }; testCase( [&, this](Env& env, BrokerInfo const& broker, auto&) { @@ -3264,10 +2775,8 @@ protected: auto const [acctReserve, incReserve] = [this]() -> std::pair { Env env{*this, testable_amendments()}; return { - env.current()->fees().accountReserve(0).drops() / - DROPS_PER_XRP.drops(), - env.current()->fees().increment.drops() / - DROPS_PER_XRP.drops()}; + env.current()->fees().accountReserve(0).drops() / DROPS_PER_XRP.drops(), + env.current()->fees().increment.drops() / DROPS_PER_XRP.drops()}; }(); testCase( @@ -3278,12 +2787,10 @@ protected: testcase( "MPT authorized borrower, borrower submits, borrower has " "no reserve"); - mptt.authorize( - {.account = borrower, .flags = tfMPTUnauthorize}); + mptt.authorize({.account = borrower, .flags = tfMPTUnauthorize}); env.close(); - auto const mptoken = - keylet::mptoken(mptt.issuanceID(), borrower); + auto const mptoken = keylet::mptoken(mptt.issuanceID(), borrower); auto const sleMPT1 = env.le(mptoken); BEAST_EXPECT(sleMPT1 == nullptr); @@ -3329,8 +2836,7 @@ protected: env(pay(borrower, issuer, broker.asset(10'000))); env.close(); - auto const trustline = - keylet::line(borrower, broker.asset.raw().get()); + auto const trustline = keylet::line(borrower, broker.asset.raw().get()); auto const sleLine1 = env.le(trustline); BEAST_EXPECT(sleLine1 == nullptr); @@ -3372,8 +2878,7 @@ protected: auto const sleMPT1 = env.le(mptoken); BEAST_EXPECT(sleMPT1 != nullptr); - env(pay( - lender, issuer, broker.asset(sleMPT1->at(sfMPTAmount)))); + env(pay(lender, issuer, broker.asset(sleMPT1->at(sfMPTAmount)))); env.close(); mptt.authorize({.account = lender, .flags = tfMPTUnauthorize}); @@ -3424,15 +2929,11 @@ protected: env.trust(broker.asset(0), lender); env.close(); - auto const trustline = - keylet::line(lender, broker.asset.raw().get()); + auto const trustline = keylet::line(lender, broker.asset.raw().get()); auto const sleLine1 = env.le(trustline); BEAST_EXPECT(sleLine1 != nullptr); - env( - pay(lender, - issuer, - broker.asset(abs(sleLine1->at(sfBalance).value())))); + env(pay(lender, issuer, broker.asset(abs(sleLine1->at(sfBalance).value())))); env.close(); auto const sleLine2 = env.le(trustline); BEAST_EXPECT(sleLine2 == nullptr); @@ -3475,8 +2976,7 @@ protected: auto const sleMPT1 = env.le(mptoken); BEAST_EXPECT(sleMPT1 != nullptr); - env(pay( - lender, issuer, broker.asset(sleMPT1->at(sfMPTAmount)))); + env(pay(lender, issuer, broker.asset(sleMPT1->at(sfMPTAmount)))); env.close(); mptt.authorize({.account = lender, .flags = tfMPTUnauthorize}); @@ -3648,9 +3148,7 @@ protected: Number const principalRequest = broker.asset(1'000).value(); Vault vault{env}; auto tx = vault.set({.owner = lender, .id = broker.vaultID}); - tx[sfAssetsMaximum] = - BrokerParameters::defaults().vaultDeposit + - broker.asset(1).number(); + tx[sfAssetsMaximum] = BrokerParameters::defaults().vaultDeposit + broker.asset(1).number(); env(tx); env.close(); @@ -3707,8 +3205,7 @@ protected: env.close(); MPTTester mptt{env, issuer, mptInitNoFund}; - mptt.create( - {.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock}); + mptt.create({.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock}); // Scale the MPT asset a little bit so we can get some interest PrettyAsset const mptAsset{mptt.issuanceID(), 100}; mptt.authorize({.account = lender}); @@ -3726,11 +3223,8 @@ protected: std::vector brokers; for (auto const& asset : assets) { - brokers.emplace_back(createVaultAndBroker( - env, - asset, - lender, - BrokerParameters{.data = "spam spam spam spam"})); + brokers.emplace_back( + createVaultAndBroker(env, asset, lender, BrokerParameters{.data = "spam spam spam spam"})); } // Create and update Loans @@ -3739,30 +3233,19 @@ protected: for (int amountExponent = 3; amountExponent >= 3; --amountExponent) { Number const loanAmount{1, amountExponent}; - for (int interestExponent = 0; interestExponent >= 0; - --interestExponent) + for (int interestExponent = 0; interestExponent >= 0; --interestExponent) { - testCaseWrapper( - env, - mptt, - assets, - broker, - loanAmount, - interestExponent); + testCaseWrapper(env, mptt, assets, broker, loanAmount, interestExponent); } } - if (auto brokerSle = env.le(keylet::loanbroker(broker.brokerID)); - BEAST_EXPECT(brokerSle)) + if (auto brokerSle = env.le(keylet::loanbroker(broker.brokerID)); BEAST_EXPECT(brokerSle)) { BEAST_EXPECT(brokerSle->at(sfOwnerCount) == 0); BEAST_EXPECT(brokerSle->at(sfDebtTotal) == 0); auto const coverAvailable = brokerSle->at(sfCoverAvailable); - env(loanBroker::coverWithdraw( - lender, - broker.brokerID, - STAmount(broker.asset, coverAvailable))); + env(loanBroker::coverWithdraw(lender, broker.brokerID, STAmount(broker.asset, coverAvailable))); env.close(); brokerSle = env.le(keylet::loanbroker(broker.brokerID)); @@ -3808,17 +3291,13 @@ protected: // The LoanSet json can be created without a counterparty signature, // but it will not pass preflight - auto createJson = env.json( - set(lender, - broker.brokerID, - broker.asset(principalRequest).value()), - fee(loanSetFee)); + auto createJson = + env.json(set(lender, broker.brokerID, broker.asset(principalRequest).value()), fee(loanSetFee)); env(createJson, ter(temBAD_SIGNER)); // Adding an empty counterparty signature object also fails, but // at the RPC level. - createJson = env.json( - createJson, json(sfCounterpartySignature, Json::objectValue)); + createJson = env.json(createJson, json(sfCounterpartySignature, Json::objectValue)); env(createJson, ter(telENV_RPC_FAILED)); if (auto const jt = env.jt(createJson); BEAST_EXPECT(jt.stx)) @@ -3830,9 +3309,7 @@ protected: BEAST_EXPECT(jr.isMember(jss::result)); auto const jResult = jr[jss::result]; BEAST_EXPECT(jResult[jss::error] == "invalidTransaction"); - BEAST_EXPECT( - jResult[jss::error_exception] == - "fails local checks: Transaction has bad signature."); + BEAST_EXPECT(jResult[jss::error_exception] == "fails local checks: Transaction has bad signature."); } // Copy the transaction signature into the counterparty signature. @@ -3843,8 +3320,7 @@ protected: counterpartyJson[sfSigners] = createJson[sfSigners]; // The duplicated signature works - createJson = env.json( - createJson, json(sfCounterpartySignature, counterpartyJson)); + createJson = env.json(createJson, json(sfCounterpartySignature, counterpartyJson)); env(createJson); env.close(); @@ -3863,8 +3339,7 @@ protected: ++types[object[sfLedgerEntryType].asString()]; } BEAST_EXPECT(types.size() == 4); - for (std::string const type : - {"MPToken", "Vault", "LoanBroker", "Loan"}) + for (std::string const type : {"MPToken", "Vault", "LoanBroker", "Loan"}) { BEAST_EXPECT(types[type] == 1); } @@ -3873,8 +3348,7 @@ protected: Json::Value params(Json::objectValue); params[jss::account] = lender.human(); params[jss::type] = "Loan"; - auto const res = - env.rpc("json", "account_objects", to_string(params)); + auto const res = env.rpc("json", "account_objects", to_string(params)); auto const objects = res[jss::result][jss::account_objects]; BEAST_EXPECT(objects.size() == 1); @@ -3894,8 +3368,7 @@ protected: BEAST_EXPECT(!loan.isMember(sfLoanOriginationFee)); BEAST_EXPECT(loan[sfLoanSequence] == 1); BEAST_EXPECT(!loan.isMember(sfLoanServiceFee)); - BEAST_EXPECT( - loan[sfNextPaymentDueDate] == loan[sfStartDate].asUInt() + 60); + BEAST_EXPECT(loan[sfNextPaymentDueDate] == loan[sfStartDate].asUInt() + 60); BEAST_EXPECT(!loan.isMember(sfOverpaymentFee)); BEAST_EXPECT(!loan.isMember(sfOverpaymentInterestRate)); BEAST_EXPECT(loan[sfPaymentInterval] == 60); @@ -3905,9 +3378,7 @@ protected: BEAST_EXPECT(loan[sfPrincipalOutstanding] == "1000000000"); BEAST_EXPECT(loan[sfTotalValueOutstanding] == "1000000000"); BEAST_EXPECT(!loan.isMember(sfLoanScale)); - BEAST_EXPECT( - loan[sfStartDate].asUInt() == - startDate.time_since_epoch().count()); + BEAST_EXPECT(loan[sfStartDate].asUInt() == startDate.time_since_epoch().count()); return loan["index"].asString(); }(); @@ -3925,10 +3396,10 @@ protected: // From FIND-001 testcase << "Batch Bypass Counterparty"; - bool const lendingBatchEnabled = !std::any_of( - Batch::disabledTxTypes.begin(), - Batch::disabledTxTypes.end(), - [](auto const& disabled) { return disabled == ttLOAN_BROKER_SET; }); + bool const lendingBatchEnabled = + !std::any_of(Batch::disabledTxTypes.begin(), Batch::disabledTxTypes.end(), [](auto const& disabled) { + return disabled == ttLOAN_BROKER_SET; + }); using namespace jtx; using namespace std::chrono_literals; @@ -3943,16 +3414,14 @@ protected: PrettyAsset const xrpAsset{xrpIssue(), 1'000'000}; - BrokerInfo broker{ - createVaultAndBroker(env, xrpAsset, lender, brokerParams)}; + BrokerInfo broker{createVaultAndBroker(env, xrpAsset, lender, brokerParams)}; using namespace loan; auto const loanSetFee = fee(env.current()->fees().base * 2); Number const principalRequest{1, 3}; - auto forgedLoanSet = - set(borrower, broker.brokerID, principalRequest, 0); + auto forgedLoanSet = set(borrower, broker.brokerID, principalRequest, 0); Json::Value randomData{Json::objectValue}; randomData[jss::SigningPubKey] = Json::StaticString{"2600"}; @@ -3975,8 +3444,7 @@ protected: env(batch::outer(borrower, seq, batchFee, tfAllOrNothing), batch::inner(forgedLoanSet, seq + 1), batch::inner(pay(borrower, lender, XRP(1)), seq + 2), - ter(lendingBatchEnabled ? temBAD_SIGNATURE - : temINVALID_INNER_BATCH)); + ter(lendingBatchEnabled ? temBAD_SIGNATURE : temINVALID_INNER_BATCH)); env.close(); // ? Check that the loan was NOT created @@ -3984,8 +3452,7 @@ protected: Json::Value params(Json::objectValue); params[jss::account] = borrower.human(); params[jss::type] = "Loan"; - auto const res = - env.rpc("json", "account_objects", to_string(params)); + auto const res = env.rpc("json", "account_objects", to_string(params)); auto const objects = res[jss::result][jss::account_objects]; BEAST_EXPECT(objects.size() == 0); } @@ -4005,17 +3472,14 @@ protected: Account const lender{"lender"}; BrokerParameters brokerParams{.debtMax = 0}; - env.fund( - XRP(brokerParams.vaultDeposit * 100), issuer, noripple(lender)); + env.fund(XRP(brokerParams.vaultDeposit * 100), issuer, noripple(lender)); env.close(); PrettyAsset const xrpAsset{xrpIssue(), 1'000'000}; - BrokerInfo broker{ - createVaultAndBroker(env, xrpAsset, lender, brokerParams)}; + BrokerInfo broker{createVaultAndBroker(env, xrpAsset, lender, brokerParams)}; - if (auto const brokerSle = env.le(keylet::loanbroker(broker.brokerID)); - BEAST_EXPECT(brokerSle)) + if (auto const brokerSle = env.le(keylet::loanbroker(broker.brokerID)); BEAST_EXPECT(brokerSle)) { BEAST_EXPECT(brokerSle->at(sfDebtMaximum) == 0); } @@ -4025,8 +3489,7 @@ protected: auto const loanSetFee = fee(env.current()->fees().base * 2); Number const principalRequest{1, 3}; - auto createJson = env.json( - set(lender, broker.brokerID, principalRequest), fee(loanSetFee)); + auto createJson = env.json(set(lender, broker.brokerID, principalRequest), fee(loanSetFee)); Json::Value counterpartyJson{Json::objectValue}; counterpartyJson[sfTxnSignature] = createJson[sfTxnSignature]; @@ -4034,8 +3497,7 @@ protected: if (!BEAST_EXPECT(!createJson.isMember(jss::Signers))) counterpartyJson[sfSigners] = createJson[sfSigners]; - createJson = env.json( - createJson, json(sfCounterpartySignature, counterpartyJson)); + createJson = env.json(createJson, json(sfCounterpartySignature, counterpartyJson)); env(createJson); env.close(); @@ -4057,13 +3519,11 @@ protected: Account const borrower{"borrower"}; BrokerParameters brokerParams; - env.fund( - XRP(brokerParams.vaultDeposit * 100), issuer, lender, borrower); + env.fund(XRP(brokerParams.vaultDeposit * 100), issuer, lender, borrower); env.close(); PrettyAsset const xrpAsset{xrpIssue(), 1'000'000}; - BrokerInfo broker{ - createVaultAndBroker(env, xrpAsset, lender, brokerParams)}; + BrokerInfo broker{createVaultAndBroker(env, xrpAsset, lender, brokerParams)}; using namespace loan; @@ -4088,8 +3548,7 @@ protected: createJson["OverpaymentInterestRate"] = 1360; createJson["PaymentInterval"] = 727; - auto const brokerStateBefore = - env.le(keylet::loanbroker(broker.brokerID)); + auto const brokerStateBefore = env.le(keylet::loanbroker(broker.brokerID)); auto const loanSequence = brokerStateBefore->at(sfLoanSequence); auto const keylet = keylet::loan(broker.brokerID, loanSequence); @@ -4162,9 +3621,7 @@ protected: return signParams; }(); auto const jSign = env.rpc("json", "sign", to_string(signParams)); - BEAST_EXPECT( - jSign.isMember(jss::result) && - jSign[jss::result].isMember(jss::tx_json)); + BEAST_EXPECT(jSign.isMember(jss::result) && jSign[jss::result].isMember(jss::tx_json)); auto txSignResult = jSign[jss::result][jss::tx_json]; auto txSignBlob = jSign[jss::result][jss::tx_blob].asString(); txSignResult.removeMember(jss::hash); @@ -4175,10 +3632,8 @@ protected: lowerFee(); auto const jSubmit = env.rpc("submit", txSignBlob); BEAST_EXPECT( - jSubmit.isMember(jss::result) && - jSubmit[jss::result].isMember(jss::engine_result) && - jSubmit[jss::result][jss::engine_result].asString() == - "tesSUCCESS"); + jSubmit.isMember(jss::result) && jSubmit[jss::result].isMember(jss::engine_result) && + jSubmit[jss::result][jss::engine_result].asString() == "tesSUCCESS"); lowerFee(); env(jtx.jv, sig(none), seq(none), fee(none), ter(tefPAST_SEQ)); @@ -4199,15 +3654,12 @@ protected: params[jss::tx_json] = txJson; return params; }(); - auto const jSignBorrower = - env.rpc("json", "sign", to_string(borrowerSignParams)); + auto const jSignBorrower = env.rpc("json", "sign", to_string(borrowerSignParams)); BEAST_EXPECT( - jSignBorrower.isMember(jss::result) && - jSignBorrower[jss::result].isMember(jss::error) && + jSignBorrower.isMember(jss::result) && jSignBorrower[jss::result].isMember(jss::error) && jSignBorrower[jss::result][jss::error] == "invalidParams" && jSignBorrower[jss::result].isMember(jss::error_message) && - jSignBorrower[jss::result][jss::error_message] == - "Destination"); + jSignBorrower[jss::result][jss::error_message] == "Destination"); } { testcase("RPC LoanSet - sign and submit borrower initiated"); @@ -4235,16 +3687,12 @@ protected: params[jss::tx_json] = txJson; return params; }(); - auto const jSignBorrower = - env.rpc("json", "sign", to_string(borrowerSignParams)); + auto const jSignBorrower = env.rpc("json", "sign", to_string(borrowerSignParams)); BEAST_EXPECTS( - jSignBorrower.isMember(jss::result) && - jSignBorrower[jss::result].isMember(jss::tx_json), + jSignBorrower.isMember(jss::result) && jSignBorrower[jss::result].isMember(jss::tx_json), to_string(jSignBorrower)); - auto const txBorrowerSignResult = - jSignBorrower[jss::result][jss::tx_json]; - auto const txBorrowerSignBlob = - jSignBorrower[jss::result][jss::tx_blob].asString(); + auto const txBorrowerSignResult = jSignBorrower[jss::result][jss::tx_json]; + auto const txBorrowerSignBlob = jSignBorrower[jss::result][jss::tx_blob].asString(); // 2a. Borrower attempts to submit the transaction. It doesn't // work @@ -4258,8 +3706,7 @@ protected: // missing BEAST_EXPECT( jSubmitBlobResult.isMember(jss::engine_result) && - jSubmitBlobResult[jss::engine_result].asString() == - "temBAD_SIGNER"); + jSubmitBlobResult[jss::engine_result].asString() == "temBAD_SIGNER"); } // 3. Borrower sends the signed transaction to the lender @@ -4272,15 +3719,10 @@ protected: params[jss::tx_json] = txBorrowerSignResult; return params; }(); - auto const jSignLender = - env.rpc("json", "sign", to_string(lenderSignParams)); - BEAST_EXPECT( - jSignLender.isMember(jss::result) && - jSignLender[jss::result].isMember(jss::tx_json)); - auto const txLenderSignResult = - jSignLender[jss::result][jss::tx_json]; - auto const txLenderSignBlob = - jSignLender[jss::result][jss::tx_blob].asString(); + auto const jSignLender = env.rpc("json", "sign", to_string(lenderSignParams)); + BEAST_EXPECT(jSignLender.isMember(jss::result) && jSignLender[jss::result].isMember(jss::tx_json)); + auto const txLenderSignResult = jSignLender[jss::result][jss::tx_json]; + auto const txLenderSignBlob = jSignLender[jss::result][jss::tx_blob].asString(); // 5. Lender submits the signed transaction blob lowerFee(); @@ -4294,21 +3736,17 @@ protected: // succeed because no Vault or Broker were created. BEAST_EXPECTS( jSubmitBlobResult.isMember(jss::engine_result) && - jSubmitBlobResult[jss::engine_result].asString() == - "tecNO_ENTRY", + jSubmitBlobResult[jss::engine_result].asString() == "tecNO_ENTRY", to_string(jSubmitBlobResult)); - BEAST_EXPECT( - !jSubmitBlob.isMember(jss::error) && - !jSubmitBlobResult.isMember(jss::error)); + BEAST_EXPECT(!jSubmitBlob.isMember(jss::error) && !jSubmitBlobResult.isMember(jss::error)); // 4-alt. Lender submits the transaction json originally // received from the Borrower. It gets signed, but is now a // duplicate, so fails. Borrower could done this instead of // steps 4 and 5. lowerFee(); - auto const jSubmitJson = - env.rpc("json", "submit", to_string(lenderSignParams)); + auto const jSubmitJson = env.rpc("json", "submit", to_string(lenderSignParams)); BEAST_EXPECT(jSubmitJson.isMember(jss::result)); auto const jSubmitJsonResult = jSubmitJson[jss::result]; BEAST_EXPECT(jSubmitJsonResult.isMember(jss::tx_json)); @@ -4317,13 +3755,10 @@ protected: // going anywhere BEAST_EXPECTS( jSubmitJsonResult.isMember(jss::engine_result) && - jSubmitJsonResult[jss::engine_result].asString() == - "tefPAST_SEQ", + jSubmitJsonResult[jss::engine_result].asString() == "tefPAST_SEQ", to_string(jSubmitJsonResult)); - BEAST_EXPECT( - !jSubmitJson.isMember(jss::error) && - !jSubmitJsonResult.isMember(jss::error)); + BEAST_EXPECT(!jSubmitJson.isMember(jss::error) && !jSubmitJsonResult.isMember(jss::error)); BEAST_EXPECT(jSubmitBlobTx == jSubmitJsonTx); } @@ -4354,15 +3789,10 @@ protected: params[jss::tx_json] = txJson; return params; }(); - auto const jSignLender = - env.rpc("json", "sign", to_string(lenderSignParams)); - BEAST_EXPECT( - jSignLender.isMember(jss::result) && - jSignLender[jss::result].isMember(jss::tx_json)); - auto const txLenderSignResult = - jSignLender[jss::result][jss::tx_json]; - auto const txLenderSignBlob = - jSignLender[jss::result][jss::tx_blob].asString(); + auto const jSignLender = env.rpc("json", "sign", to_string(lenderSignParams)); + BEAST_EXPECT(jSignLender.isMember(jss::result) && jSignLender[jss::result].isMember(jss::tx_json)); + auto const txLenderSignResult = jSignLender[jss::result][jss::tx_json]; + auto const txLenderSignBlob = jSignLender[jss::result][jss::tx_blob].asString(); // 2a. Lender attempts to submit the transaction. It doesn't // work @@ -4376,8 +3806,7 @@ protected: // missing BEAST_EXPECT( jSubmitBlobResult.isMember(jss::engine_result) && - jSubmitBlobResult[jss::engine_result].asString() == - "temBAD_SIGNER"); + jSubmitBlobResult[jss::engine_result].asString() == "temBAD_SIGNER"); } // 3. Lender sends the signed transaction to the Borrower @@ -4390,15 +3819,10 @@ protected: params[jss::tx_json] = txLenderSignResult; return params; }(); - auto const jSignBorrower = - env.rpc("json", "sign", to_string(borrowerSignParams)); - BEAST_EXPECT( - jSignBorrower.isMember(jss::result) && - jSignBorrower[jss::result].isMember(jss::tx_json)); - auto const txBorrowerSignResult = - jSignBorrower[jss::result][jss::tx_json]; - auto const txBorrowerSignBlob = - jSignBorrower[jss::result][jss::tx_blob].asString(); + auto const jSignBorrower = env.rpc("json", "sign", to_string(borrowerSignParams)); + BEAST_EXPECT(jSignBorrower.isMember(jss::result) && jSignBorrower[jss::result].isMember(jss::tx_json)); + auto const txBorrowerSignResult = jSignBorrower[jss::result][jss::tx_json]; + auto const txBorrowerSignBlob = jSignBorrower[jss::result][jss::tx_blob].asString(); // 5. Borrower submits the signed transaction blob lowerFee(); @@ -4412,21 +3836,17 @@ protected: // succeed because no Vault or Broker were created. BEAST_EXPECTS( jSubmitBlobResult.isMember(jss::engine_result) && - jSubmitBlobResult[jss::engine_result].asString() == - "tecNO_ENTRY", + jSubmitBlobResult[jss::engine_result].asString() == "tecNO_ENTRY", to_string(jSubmitBlobResult)); - BEAST_EXPECT( - !jSubmitBlob.isMember(jss::error) && - !jSubmitBlobResult.isMember(jss::error)); + BEAST_EXPECT(!jSubmitBlob.isMember(jss::error) && !jSubmitBlobResult.isMember(jss::error)); // 4-alt. Borrower submits the transaction json originally // received from the Lender. It gets signed, but is now a // duplicate, so fails. Lender could done this instead of steps // 4 and 5. lowerFee(); - auto const jSubmitJson = - env.rpc("json", "submit", to_string(borrowerSignParams)); + auto const jSubmitJson = env.rpc("json", "submit", to_string(borrowerSignParams)); BEAST_EXPECT(jSubmitJson.isMember(jss::result)); auto const jSubmitJsonResult = jSubmitJson[jss::result]; BEAST_EXPECT(jSubmitJsonResult.isMember(jss::tx_json)); @@ -4435,13 +3855,10 @@ protected: // going anywhere BEAST_EXPECTS( jSubmitJsonResult.isMember(jss::engine_result) && - jSubmitJsonResult[jss::engine_result].asString() == - "tefPAST_SEQ", + jSubmitJsonResult[jss::engine_result].asString() == "tefPAST_SEQ", to_string(jSubmitJsonResult)); - BEAST_EXPECT( - !jSubmitJson.isMember(jss::error) && - !jSubmitJsonResult.isMember(jss::error)); + BEAST_EXPECT(!jSubmitJson.isMember(jss::error) && !jSubmitJsonResult.isMember(jss::error)); BEAST_EXPECT(jSubmitBlobTx == jSubmitJsonTx); } @@ -4462,15 +3879,11 @@ protected: { Env env(*this); - auto getCoverBalance = [&](BrokerInfo const& brokerInfo, - auto const& accountField) { - if (auto const le = - env.le(keylet::loanbroker(brokerInfo.brokerID)); - BEAST_EXPECT(le)) + auto getCoverBalance = [&](BrokerInfo const& brokerInfo, auto const& accountField) { + if (auto const le = env.le(keylet::loanbroker(brokerInfo.brokerID)); BEAST_EXPECT(le)) { auto const account = le->at(accountField); - if (auto const sleLine = env.le(keylet::line(account, IOU)); - BEAST_EXPECT(sleLine)) + if (auto const sleLine = env.le(keylet::line(account, IOU)); BEAST_EXPECT(sleLine)) { STAmount balance = sleLine->at(sfBalance); if (account > issuer.id()) @@ -4507,15 +3920,11 @@ protected: env(pay(issuer, borrower, IOU(500))); env.close(); - if (auto const le = env.le(keylet::loan(keylet.key)); - BEAST_EXPECT(le)) + if (auto const le = env.le(keylet::loan(keylet.key)); BEAST_EXPECT(le)) { if (deepFreeze) { - env(trust( - issuer, - broker["IOU"](0), - tfSetFreeze | tfSetDeepFreeze)); + env(trust(issuer, broker["IOU"](0), tfSetFreeze | tfSetDeepFreeze)); env.close(); } @@ -4525,18 +3934,14 @@ protected: if (deepFreeze) { // The fee goes to the broker pseudo-account - BEAST_EXPECT( - getCoverBalance(brokerInfo, sfAccount) == IOU(1'100)); - BEAST_EXPECT( - getCoverBalance(brokerInfo, sfOwner) == IOU(8'999'000)); + BEAST_EXPECT(getCoverBalance(brokerInfo, sfAccount) == IOU(1'100)); + BEAST_EXPECT(getCoverBalance(brokerInfo, sfOwner) == IOU(8'999'000)); } else { // The fee goes to the broker account - BEAST_EXPECT( - getCoverBalance(brokerInfo, sfOwner) == IOU(8'999'100)); - BEAST_EXPECT( - getCoverBalance(brokerInfo, sfAccount) == IOU(1'000)); + BEAST_EXPECT(getCoverBalance(brokerInfo, sfOwner) == IOU(8'999'100)); + BEAST_EXPECT(getCoverBalance(brokerInfo, sfAccount) == IOU(1'000)); } } }; @@ -4557,22 +3962,15 @@ protected: env.fund(XRP(1'000), issuer, lender); std::int64_t constexpr issuerBalance = 10'000'000; - MPTTester asset( - {.env = env, - .issuer = issuer, - .holders = {lender}, - .pay = issuerBalance}); + MPTTester asset({.env = env, .issuer = issuer, .holders = {lender}, .pay = issuerBalance}); BrokerParameters const brokerParams{ .debtMax = 200, }; - auto const broker = - createVaultAndBroker(env, asset, lender, brokerParams); + auto const broker = createVaultAndBroker(env, asset, lender, brokerParams); auto const loanSetFee = fee(env.current()->fees().base * 2); // Create Loan - env(set(borrower, broker.brokerID, 200), - sig(sfCounterpartySignature, lender), - loanSetFee); + env(set(borrower, broker.brokerID, 200), sig(sfCounterpartySignature, lender), loanSetFee); env.close(); // Issuer should not create MPToken BEAST_EXPECT(!env.le(keylet::mptoken(asset.issuanceID(), issuer))); @@ -4655,18 +4053,14 @@ protected: env.close(); // preclaim: tecFROZEN - env(pay(borrower, loanKeylet.key, debtMaximumRequest), - ter(tecFROZEN), - THISLINE); + env(pay(borrower, loanKeylet.key, debtMaximumRequest), ter(tecFROZEN), THISLINE); env.close(); env(fclear(issuer, asfGlobalFreeze), THISLINE); env.close(); auto const pseudoBroker = [&]() -> std::optional { - if (auto brokerSle = - env.le(keylet::loanbroker(brokerInfo.brokerID)); - BEAST_EXPECT(brokerSle)) + if (auto brokerSle = env.le(keylet::loanbroker(brokerInfo.brokerID)); BEAST_EXPECT(brokerSle)) { return Account{"pseudo", brokerSle->at(sfAccount)}; } @@ -4679,52 +4073,28 @@ protected: return; // Lender and pseudoaccount must both be frozen - env(trust( - issuer, - lender["IOU"](1'000), - lender, - tfSetFreeze | tfSetDeepFreeze), - THISLINE); - env(trust( - issuer, - (*pseudoBroker)["IOU"](1'000), - *pseudoBroker, - tfSetFreeze | tfSetDeepFreeze), - THISLINE); + env(trust(issuer, lender["IOU"](1'000), lender, tfSetFreeze | tfSetDeepFreeze), THISLINE); + env(trust(issuer, (*pseudoBroker)["IOU"](1'000), *pseudoBroker, tfSetFreeze | tfSetDeepFreeze), THISLINE); env.close(); // preclaim: tecFROZEN due to deep frozen - env(pay(borrower, loanKeylet.key, debtMaximumRequest), - ter(tecFROZEN), - THISLINE); + env(pay(borrower, loanKeylet.key, debtMaximumRequest), ter(tecFROZEN), THISLINE); env.close(); // Only one needs to be unfrozen - env(trust( - issuer, - lender["IOU"](1'000), - tfClearFreeze | tfClearDeepFreeze), - THISLINE); + env(trust(issuer, lender["IOU"](1'000), tfClearFreeze | tfClearDeepFreeze), THISLINE); env.close(); // The payment is late by this point - env(pay(borrower, loanKeylet.key, debtMaximumRequest), - ter(tecEXPIRED), - THISLINE); + env(pay(borrower, loanKeylet.key, debtMaximumRequest), ter(tecEXPIRED), THISLINE); env.close(); - env(pay(borrower, - loanKeylet.key, - debtMaximumRequest, - tfLoanLatePayment), - THISLINE); + env(pay(borrower, loanKeylet.key, debtMaximumRequest, tfLoanLatePayment), THISLINE); env.close(); // preclaim: tecKILLED // note that tecKILLED in loanMakePayment() // doesn't happen because of the preclaim check. - env(pay(borrower, loanKeylet.key, debtMaximumRequest), - ter(tecKILLED), - THISLINE); + env(pay(borrower, loanKeylet.key, debtMaximumRequest), ter(tecKILLED), THISLINE); } void @@ -4743,8 +4113,7 @@ protected: env.fund(XRP(1'000), lender, issuer, borrower); env(trust(lender, IOU(10'000'000))); env(pay(issuer, lender, IOU(5'000'000))); - BrokerInfo brokerInfo{ - createVaultAndBroker(env, issuer["IOU"], lender)}; + BrokerInfo brokerInfo{createVaultAndBroker(env, issuer["IOU"], lender)}; auto const loanSetFee = fee(env.current()->fees().base * 2); Number const debtMaximumRequest = brokerInfo.asset(1'000).value(); @@ -4752,122 +4121,108 @@ protected: }; // preflight: - testWrapper([&](Env& env, - BrokerInfo const& brokerInfo, - jtx::fee const& loanSetFee, - Number const& debtMaximumRequest) { - // first temBAD_SIGNER: TODO - // invalid grace period - { - // zero grace period - env(set(borrower, brokerInfo.brokerID, debtMaximumRequest), - sig(sfCounterpartySignature, lender), - gracePeriod(0), - loanSetFee, - ter(temINVALID)); - - // grace period less than default minimum - env(set(borrower, brokerInfo.brokerID, debtMaximumRequest), - sig(sfCounterpartySignature, lender), - gracePeriod(LoanSet::defaultGracePeriod - 1), - loanSetFee, - ter(temINVALID)); - - // grace period greater than payment interval - env(set(borrower, brokerInfo.brokerID, debtMaximumRequest), - sig(sfCounterpartySignature, lender), - paymentInterval(120), - gracePeriod(121), - loanSetFee, - ter(temINVALID)); - } - // empty/zero broker ID - { - auto jv = set(borrower, uint256{}, debtMaximumRequest); - - auto testZeroBrokerID = [&](std::string const& id, - std::uint32_t flags = 0) { - // empty broker ID - jv[sfLoanBrokerID] = id; - env(jv, + testWrapper( + [&](Env& env, BrokerInfo const& brokerInfo, jtx::fee const& loanSetFee, Number const& debtMaximumRequest) { + // first temBAD_SIGNER: TODO + // invalid grace period + { + // zero grace period + env(set(borrower, brokerInfo.brokerID, debtMaximumRequest), sig(sfCounterpartySignature, lender), + gracePeriod(0), loanSetFee, - txflags(flags), ter(temINVALID)); - }; - // empty broker ID - testZeroBrokerID(std::string("")); - // zero broker ID - // needs a flag to distinguish the parsed STTx from the prior - // test - testZeroBrokerID(to_string(uint256{}), tfFullyCanonicalSig); - } - // preflightCheckSigningKey() failure: - // can it happen? the signature is checked before transactor - // executes + // grace period less than default minimum + env(set(borrower, brokerInfo.brokerID, debtMaximumRequest), + sig(sfCounterpartySignature, lender), + gracePeriod(LoanSet::defaultGracePeriod - 1), + loanSetFee, + ter(temINVALID)); - JTx tx = env.jt( - set(borrower, brokerInfo.brokerID, debtMaximumRequest), - sig(sfCounterpartySignature, lender), - loanSetFee); - STTx local = *(tx.stx); - auto counterpartySig = - local.getFieldObject(sfCounterpartySignature); - auto badPubKey = counterpartySig.getFieldVL(sfSigningPubKey); - badPubKey[20] ^= 0xAA; - counterpartySig.setFieldVL(sfSigningPubKey, badPubKey); - local.setFieldObject(sfCounterpartySignature, counterpartySig); - Json::Value jvResult; - jvResult[jss::tx_blob] = strHex(local.getSerializer().slice()); - auto res = env.rpc("json", "submit", to_string(jvResult))["result"]; - BEAST_EXPECT( - res[jss::error] == "invalidTransaction" && - res[jss::error_exception] == - "fails local checks: Counterparty: Invalid signature."); - }); + // grace period greater than payment interval + env(set(borrower, brokerInfo.brokerID, debtMaximumRequest), + sig(sfCounterpartySignature, lender), + paymentInterval(120), + gracePeriod(121), + loanSetFee, + ter(temINVALID)); + } + // empty/zero broker ID + { + auto jv = set(borrower, uint256{}, debtMaximumRequest); + + auto testZeroBrokerID = [&](std::string const& id, std::uint32_t flags = 0) { + // empty broker ID + jv[sfLoanBrokerID] = id; + env(jv, sig(sfCounterpartySignature, lender), loanSetFee, txflags(flags), ter(temINVALID)); + }; + // empty broker ID + testZeroBrokerID(std::string("")); + // zero broker ID + // needs a flag to distinguish the parsed STTx from the prior + // test + testZeroBrokerID(to_string(uint256{}), tfFullyCanonicalSig); + } + + // preflightCheckSigningKey() failure: + // can it happen? the signature is checked before transactor + // executes + + JTx tx = env.jt( + set(borrower, brokerInfo.brokerID, debtMaximumRequest), + sig(sfCounterpartySignature, lender), + loanSetFee); + STTx local = *(tx.stx); + auto counterpartySig = local.getFieldObject(sfCounterpartySignature); + auto badPubKey = counterpartySig.getFieldVL(sfSigningPubKey); + badPubKey[20] ^= 0xAA; + counterpartySig.setFieldVL(sfSigningPubKey, badPubKey); + local.setFieldObject(sfCounterpartySignature, counterpartySig); + Json::Value jvResult; + jvResult[jss::tx_blob] = strHex(local.getSerializer().slice()); + auto res = env.rpc("json", "submit", to_string(jvResult))["result"]; + BEAST_EXPECT( + res[jss::error] == "invalidTransaction" && + res[jss::error_exception] == "fails local checks: Counterparty: Invalid signature."); + }); // preclaim: - testWrapper([&](Env& env, - BrokerInfo const& brokerInfo, - jtx::fee const& loanSetFee, - Number const& debtMaximumRequest) { - // canAddHoldingFailure (IOU only, if MPT doesn't have - // MPTCanTransfer set, then can't create Vault/LoanBroker, - // and LoanSet will fail with different error - env(fclear(issuer, asfDefaultRipple)); - env.close(); - env(set(borrower, brokerInfo.brokerID, debtMaximumRequest), - sig(sfCounterpartySignature, lender), - loanSetFee, - ter(terNO_RIPPLE)); - }); + testWrapper( + [&](Env& env, BrokerInfo const& brokerInfo, jtx::fee const& loanSetFee, Number const& debtMaximumRequest) { + // canAddHoldingFailure (IOU only, if MPT doesn't have + // MPTCanTransfer set, then can't create Vault/LoanBroker, + // and LoanSet will fail with different error + env(fclear(issuer, asfDefaultRipple)); + env.close(); + env(set(borrower, brokerInfo.brokerID, debtMaximumRequest), + sig(sfCounterpartySignature, lender), + loanSetFee, + ter(terNO_RIPPLE)); + }); // doApply: - testWrapper([&](Env& env, - BrokerInfo const& brokerInfo, - jtx::fee const& loanSetFee, - Number const& debtMaximumRequest) { - auto const amt = env.balance(borrower) - - env.current()->fees().accountReserve(env.ownerCount(borrower)); - env(pay(borrower, issuer, amt)); + testWrapper( + [&](Env& env, BrokerInfo const& brokerInfo, jtx::fee const& loanSetFee, Number const& debtMaximumRequest) { + auto const amt = env.balance(borrower) - env.current()->fees().accountReserve(env.ownerCount(borrower)); + env(pay(borrower, issuer, amt)); - // tecINSUFFICIENT_RESERVE - env(set(borrower, brokerInfo.brokerID, debtMaximumRequest), - sig(sfCounterpartySignature, lender), - loanSetFee, - ter(tecINSUFFICIENT_RESERVE)); + // tecINSUFFICIENT_RESERVE + env(set(borrower, brokerInfo.brokerID, debtMaximumRequest), + sig(sfCounterpartySignature, lender), + loanSetFee, + ter(tecINSUFFICIENT_RESERVE)); - // addEmptyHolding failure - env(pay(issuer, borrower, amt)); - env(fset(issuer, asfGlobalFreeze)); - env.close(); + // addEmptyHolding failure + env(pay(issuer, borrower, amt)); + env(fset(issuer, asfGlobalFreeze)); + env.close(); - env(set(borrower, brokerInfo.brokerID, debtMaximumRequest), - sig(sfCounterpartySignature, lender), - loanSetFee, - ter(tecFROZEN)); - }); + env(set(borrower, brokerInfo.brokerID, debtMaximumRequest), + sig(sfCounterpartySignature, lender), + loanSetFee, + ter(tecFROZEN)); + }); } void @@ -4889,8 +4244,7 @@ protected: env.close(); MPTTester mptt{env, issuer, mptInitNoFund}; - mptt.create( - {.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock}); + mptt.create({.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock}); PrettyAsset const mptAsset = mptt.issuanceID(); mptt.authorize({.account = lender}); mptt.authorize({.account = borrower}); @@ -4924,8 +4278,7 @@ protected: createJson["PaymentTotal"] = "2891743748"; createJson["PrincipalRequested"] = "8516.98"; - auto const brokerStateBefore = - env.le(keylet::loanbroker(broker.brokerID)); + auto const brokerStateBefore = env.le(keylet::loanbroker(broker.brokerID)); createJson = env.json(createJson, sig(sfCounterpartySignature, lender)); env(createJson, ter(temINVALID)); @@ -4954,8 +4307,7 @@ protected: PrettyAsset const iouAsset = issuer[iouCurrency]; auto trustLenderTx = env.json(trust(lender, iouAsset(1'000'000'000))); env(trustLenderTx); - auto trustBorrowerTx = - env.json(trust(borrower, iouAsset(1'000'000'000))); + auto trustBorrowerTx = env.json(trust(borrower, iouAsset(1'000'000'000))); env(trustBorrowerTx); auto payLenderTx = pay(issuer, lender, iouAsset(100'000'000)); env(payLenderTx); @@ -4987,8 +4339,7 @@ protected: createJson["PaymentTotal"] = 5678; createJson["PrincipalRequested"] = "9924.81"; - auto const brokerStateBefore = - env.le(keylet::loanbroker(broker.brokerID)); + auto const brokerStateBefore = env.le(keylet::loanbroker(broker.brokerID)); auto const loanSequence = brokerStateBefore->at(sfLoanSequence); auto const keylet = keylet::loan(broker.brokerID, loanSequence); @@ -5009,32 +4360,17 @@ protected: verifyLoanStatus(originalState); Number const payment{3'269'349'176'470'588, -12}; - XRPAmount const payFee{ - baseFee * - ((payment / originalState.periodicPayment) / - loanPaymentsPerFeeIncrement + - 1)}; - auto loanPayTx = env.json( - pay(borrower, keylet.key, STAmount{broker.asset, payment}), - fee(payFee)); + XRPAmount const payFee{baseFee * ((payment / originalState.periodicPayment) / loanPaymentsPerFeeIncrement + 1)}; + auto loanPayTx = env.json(pay(borrower, keylet.key, STAmount{broker.asset, payment}), fee(payFee)); BEAST_EXPECT(to_string(payment) == "3269.349176470588"); env(loanPayTx, ter(tesSUCCESS)); env.close(); auto const newState = getCurrentState(env, broker, keylet); - BEAST_EXPECT(isRounded( - broker.asset, - newState.managementFeeOutstanding, - originalState.loanScale)); - BEAST_EXPECT( - newState.managementFeeOutstanding < - originalState.managementFeeOutstanding); - BEAST_EXPECT(isRounded( - broker.asset, newState.totalValue, originalState.loanScale)); - BEAST_EXPECT(isRounded( - broker.asset, - newState.principalOutstanding, - originalState.loanScale)); + BEAST_EXPECT(isRounded(broker.asset, newState.managementFeeOutstanding, originalState.loanScale)); + BEAST_EXPECT(newState.managementFeeOutstanding < originalState.managementFeeOutstanding); + BEAST_EXPECT(isRounded(broker.asset, newState.totalValue, originalState.loanScale)); + BEAST_EXPECT(isRounded(broker.asset, newState.principalOutstanding, originalState.loanScale)); } void @@ -5057,8 +4393,7 @@ protected: PrettyAsset const iouAsset = issuer[iouCurrency]; auto trustLenderTx = env.json(trust(lender, iouAsset(1'000'000'000))); env(trustLenderTx); - auto trustBorrowerTx = - env.json(trust(borrower, iouAsset(1'000'000'000))); + auto trustBorrowerTx = env.json(trust(borrower, iouAsset(1'000'000'000))); env(trustBorrowerTx); auto payLenderTx = pay(issuer, lender, iouAsset(100'000'000)); env(payLenderTx); @@ -5089,8 +4424,7 @@ protected: createJson["PaymentTotal"] = 1; createJson["PrincipalRequested"] = "0.000763058"; - auto const brokerStateBefore = - env.le(keylet::loanbroker(broker.brokerID)); + auto const brokerStateBefore = env.le(keylet::loanbroker(broker.brokerID)); auto const loanSequence = brokerStateBefore->at(sfLoanSequence); auto const keylet = keylet::loan(broker.brokerID, loanSequence); @@ -5098,8 +4432,7 @@ protected: env(createJson, THISLINE); env.close(); - auto loanPayTx = env.json( - pay(borrower, keylet.key, STAmount{broker.asset, Number{}})); + auto loanPayTx = env.json(pay(borrower, keylet.key, STAmount{broker.asset, Number{}})); loanPayTx["Amount"]["value"] = "0.000281284125490196"; env(loanPayTx, ter(tecINSUFFICIENT_PAYMENT), THISLINE); env.close(); @@ -5155,8 +4488,7 @@ protected: createJson["PaymentTotal"] = 3239184; createJson["PrincipalRequested"] = "3959.37"; - auto const brokerStateBefore = - env.le(keylet::loanbroker(broker.brokerID)); + auto const brokerStateBefore = env.le(keylet::loanbroker(broker.brokerID)); auto const loanSequence = brokerStateBefore->at(sfLoanSequence); auto const keylet = keylet::loan(broker.brokerID, loanSequence); @@ -5166,26 +4498,18 @@ protected: auto const stateBefore = getCurrentState(env, broker, keylet); BEAST_EXPECT(stateBefore.paymentRemaining == 3239184); - BEAST_EXPECT( - stateBefore.paymentRemaining > loanMaximumPaymentsPerTransaction); + BEAST_EXPECT(stateBefore.paymentRemaining > loanMaximumPaymentsPerTransaction); - auto loanPayTx = env.json( - pay(borrower, keylet.key, STAmount{broker.asset, Number{}})); + auto loanPayTx = env.json(pay(borrower, keylet.key, STAmount{broker.asset, Number{}})); Number const amount{395937, -2}; loanPayTx["Amount"]["value"] = to_string(amount); XRPAmount const payFee{ - baseFee * - std::int64_t( - amount / stateBefore.periodicPayment / - loanPaymentsPerFeeIncrement + - 1)}; + baseFee * std::int64_t(amount / stateBefore.periodicPayment / loanPaymentsPerFeeIncrement + 1)}; env(loanPayTx, ter(tesSUCCESS), fee(payFee)); env.close(); auto const stateAfter = getCurrentState(env, broker, keylet); - BEAST_EXPECT( - stateAfter.paymentRemaining == - stateBefore.paymentRemaining - loanMaximumPaymentsPerTransaction); + BEAST_EXPECT(stateAfter.paymentRemaining == stateBefore.paymentRemaining - loanMaximumPaymentsPerTransaction); } void @@ -5210,8 +4534,7 @@ protected: PrettyAsset const iouAsset = issuer[iouCurrency]; auto trustLenderTx = env.json(trust(lender, iouAsset(1'000'000'000))); env(trustLenderTx); - auto trustBorrowerTx = - env.json(trust(borrower, iouAsset(1'000'000'000))); + auto trustBorrowerTx = env.json(trust(borrower, iouAsset(1'000'000'000))); env(trustBorrowerTx); auto payLenderTx = pay(issuer, lender, iouAsset(100'000'000)); env(payLenderTx); @@ -5241,8 +4564,7 @@ protected: createJson["PaymentTotal"] = 5678; createJson["PrincipalRequested"] = "9924.81"; - auto const brokerStateBefore = - env.le(keylet::loanbroker(broker.brokerID)); + auto const brokerStateBefore = env.le(keylet::loanbroker(broker.brokerID)); auto const loanSequence = brokerStateBefore->at(sfLoanSequence); auto const keylet = keylet::loan(broker.brokerID, loanSequence); @@ -5255,30 +4577,20 @@ protected: auto const stateBefore = getCurrentState(env, broker, keylet); { - auto loanPayTx = env.json( - pay(borrower, keylet.key, STAmount{broker.asset, Number{}})); + auto loanPayTx = env.json(pay(borrower, keylet.key, STAmount{broker.asset, Number{}})); Number const amount{3074'745'058'823'529, -12}; BEAST_EXPECT(to_string(amount) == "3074.745058823529"); - XRPAmount const payFee{ - baseFee * - (amount / stateBefore.periodicPayment / - loanPaymentsPerFeeIncrement + - 1)}; + XRPAmount const payFee{baseFee * (amount / stateBefore.periodicPayment / loanPaymentsPerFeeIncrement + 1)}; loanPayTx["Amount"]["value"] = to_string(amount); env(loanPayTx, fee(payFee), ter(tesSUCCESS)); env.close(); } { - auto loanPayTx = env.json( - pay(borrower, keylet.key, STAmount{broker.asset, Number{}})); + auto loanPayTx = env.json(pay(borrower, keylet.key, STAmount{broker.asset, Number{}})); Number const amount{6732'118'170'944'051, -12}; BEAST_EXPECT(to_string(amount) == "6732.118170944051"); - XRPAmount const payFee{ - baseFee * - (amount / stateBefore.periodicPayment / - loanPaymentsPerFeeIncrement + - 1)}; + XRPAmount const payFee{baseFee * (amount / stateBefore.periodicPayment / loanPaymentsPerFeeIncrement + 1)}; loanPayTx["Amount"]["value"] = to_string(amount); env(loanPayTx, fee(payFee), ter(tesSUCCESS)); env.close(); @@ -5288,17 +4600,14 @@ protected: // Total interest outstanding is non-negative BEAST_EXPECT(stateAfter.totalValue >= stateAfter.principalOutstanding); // Principal paid is non-negative - BEAST_EXPECT( - stateBefore.principalOutstanding >= - stateAfter.principalOutstanding); + BEAST_EXPECT(stateBefore.principalOutstanding >= stateAfter.principalOutstanding); // Total value change is non-negative BEAST_EXPECT(stateBefore.totalValue >= stateAfter.totalValue); // Value delta is larger or same as principal delta (meaning // non-negative interest paid) BEAST_EXPECT( (stateBefore.totalValue - stateAfter.totalValue) >= - (stateBefore.principalOutstanding - - stateAfter.principalOutstanding)); + (stateBefore.principalOutstanding - stateAfter.principalOutstanding)); } void @@ -5322,8 +4631,7 @@ protected: PrettyAsset const iouAsset = issuer[iouCurrency]; auto trustLenderTx = env.json(trust(lender, iouAsset(1'000'000'000))); env(trustLenderTx); - auto trustBorrowerTx = - env.json(trust(borrower, iouAsset(1'000'000'000))); + auto trustBorrowerTx = env.json(trust(borrower, iouAsset(1'000'000'000))); env(trustBorrowerTx); auto payLenderTx = pay(issuer, lender, iouAsset(100'000'000)); env(payLenderTx); @@ -5333,10 +4641,8 @@ protected: BrokerInfo broker{createVaultAndBroker(env, iouAsset, lender)}; { - auto const coverDepositValue = - broker.asset(broker.params.coverDeposit * 10).value(); - env(loanBroker::coverDeposit( - lender, broker.brokerID, coverDepositValue)); + auto const coverDepositValue = broker.asset(broker.params.coverDeposit * 10).value(); + env(loanBroker::coverDeposit(lender, broker.brokerID, coverDepositValue)); env.close(); } @@ -5360,8 +4666,7 @@ protected: createJson["PaymentTotal"] = 5678; createJson["PrincipalRequested"] = "9924.81"; - auto const brokerStateBefore = - env.le(keylet::loanbroker(broker.brokerID)); + auto const brokerStateBefore = env.le(keylet::loanbroker(broker.brokerID)); auto const loanSequence = brokerStateBefore->at(sfLoanSequence); auto const keylet = keylet::loan(broker.brokerID, loanSequence); @@ -5373,26 +4678,18 @@ protected: auto const stateBefore = getCurrentState(env, broker, keylet); BEAST_EXPECT(stateBefore.paymentRemaining == 5678); - BEAST_EXPECT( - stateBefore.paymentRemaining > loanMaximumPaymentsPerTransaction); + BEAST_EXPECT(stateBefore.paymentRemaining > loanMaximumPaymentsPerTransaction); - auto loanPayTx = env.json( - pay(borrower, keylet.key, STAmount{broker.asset, Number{}})); + auto loanPayTx = env.json(pay(borrower, keylet.key, STAmount{broker.asset, Number{}})); Number const amount{9924'81, -2}; BEAST_EXPECT(to_string(amount) == "9924.81"); - XRPAmount const payFee{ - baseFee * - (amount / stateBefore.periodicPayment / - loanPaymentsPerFeeIncrement + - 1)}; + XRPAmount const payFee{baseFee * (amount / stateBefore.periodicPayment / loanPaymentsPerFeeIncrement + 1)}; loanPayTx["Amount"]["value"] = to_string(amount); env(loanPayTx, fee(payFee), ter(tesSUCCESS)); env.close(); auto const stateAfter = getCurrentState(env, broker, keylet); - BEAST_EXPECT( - stateAfter.paymentRemaining == - stateBefore.paymentRemaining - loanMaximumPaymentsPerTransaction); + BEAST_EXPECT(stateAfter.paymentRemaining == stateBefore.paymentRemaining - loanMaximumPaymentsPerTransaction); } void @@ -5416,8 +4713,7 @@ protected: PrettyAsset const iouAsset = issuer[iouCurrency]; auto trustLenderTx = env.json(trust(lender, iouAsset(1'000'000'000))); env(trustLenderTx); - auto trustBorrowerTx = - env.json(trust(borrower, iouAsset(1'000'000'000))); + auto trustBorrowerTx = env.json(trust(borrower, iouAsset(1'000'000'000))); env(trustBorrowerTx); auto payLenderTx = pay(issuer, lender, iouAsset(100'000'000)); env(payLenderTx); @@ -5425,10 +4721,8 @@ protected: env(payIssuerTx); env.close(); - BrokerParameters const brokerParams{ - .debtMax = Number{0}, .coverRateMin = TenthBips32{1}}; - BrokerInfo broker{ - createVaultAndBroker(env, iouAsset, lender, brokerParams)}; + BrokerParameters const brokerParams{.debtMax = Number{0}, .coverRateMin = TenthBips32{1}}; + BrokerInfo broker{createVaultAndBroker(env, iouAsset, lender, brokerParams)}; using namespace loan; @@ -5458,9 +4752,7 @@ protected: auto const baseFee = env.current()->fees().base; - auto parentCloseTime = [&]() { - return env.current()->parentCloseTime().time_since_epoch().count(); - }; + auto parentCloseTime = [&]() { return env.current()->parentCloseTime().time_since_epoch().count(); }; auto maxLoanTime = [&]() { auto const startDate = parentCloseTime(); @@ -5473,12 +4765,9 @@ protected: // straight-up overflow: interval auto const interval = maxLoanTime() + 1; auto const total = 1; - auto createJson = env.json( - baseJson, paymentInterval(interval), paymentTotal(total)); + auto createJson = env.json(baseJson, paymentInterval(interval), paymentTotal(total)); - env(createJson, - sig(sfCounterpartySignature, lender), - ter(tecKILLED)); + env(createJson, sig(sfCounterpartySignature, lender), ter(tecKILLED)); env.close(); } { @@ -5486,12 +4775,9 @@ protected: // min interval is 60 auto const interval = 60; auto const total = maxLoanTime() + 1; - auto createJson = env.json( - baseJson, paymentInterval(interval), paymentTotal(total)); + auto createJson = env.json(baseJson, paymentInterval(interval), paymentTotal(total)); - env(createJson, - sig(sfCounterpartySignature, lender), - ter(tecKILLED)); + env(createJson, sig(sfCounterpartySignature, lender), ter(tecKILLED)); env.close(); } { @@ -5500,28 +4786,19 @@ protected: auto const interval = maxLoanTime() + 1; auto const total = 1; auto const grace = interval; - auto createJson = env.json( - baseJson, - paymentInterval(interval), - paymentTotal(total), - gracePeriod(grace)); + auto createJson = env.json(baseJson, paymentInterval(interval), paymentTotal(total), gracePeriod(grace)); // The grace period can't be larger than the interval. - env(createJson, - sig(sfCounterpartySignature, lender), - ter(tecKILLED)); + env(createJson, sig(sfCounterpartySignature, lender), ter(tecKILLED)); env.close(); } { // Overflow with multiplication of a few large intervals auto const interval = 1'000'000'000; auto const total = 10; - auto createJson = env.json( - baseJson, paymentInterval(interval), paymentTotal(total)); + auto createJson = env.json(baseJson, paymentInterval(interval), paymentTotal(total)); - env(createJson, - sig(sfCounterpartySignature, lender), - ter(tecKILLED)); + env(createJson, sig(sfCounterpartySignature, lender), ter(tecKILLED)); env.close(); } { @@ -5529,12 +4806,9 @@ protected: // min interval is 60 auto const interval = 60; auto const total = 1'000'000'000; - auto createJson = env.json( - baseJson, paymentInterval(interval), paymentTotal(total)); + auto createJson = env.json(baseJson, paymentInterval(interval), paymentTotal(total)); - env(createJson, - sig(sfCounterpartySignature, lender), - ter(tecKILLED)); + env(createJson, sig(sfCounterpartySignature, lender), ter(tecKILLED)); env.close(); } { @@ -5543,36 +4817,23 @@ protected: auto const total = 60; auto const interval = (maxLoanTime() - total) / total; auto const grace = interval; - auto createJson = env.json( - baseJson, - paymentInterval(interval), - paymentTotal(total), - gracePeriod(grace)); + auto createJson = env.json(baseJson, paymentInterval(interval), paymentTotal(total), gracePeriod(grace)); - env(createJson, - sig(sfCounterpartySignature, lender), - ter(tecKILLED)); + env(createJson, sig(sfCounterpartySignature, lender), ter(tecKILLED)); env.close(); } { // Start date when the ledger is closed will be larger - auto const brokerStateBefore = - env.le(keylet::loanbroker(broker.brokerID)); + auto const brokerStateBefore = env.le(keylet::loanbroker(broker.brokerID)); auto const loanSequence = brokerStateBefore->at(sfLoanSequence); auto const keylet = keylet::loan(broker.brokerID, loanSequence); auto const grace = 100; auto const interval = maxLoanTime() - grace; auto const total = 1; - auto createJson = env.json( - baseJson, - paymentInterval(interval), - paymentTotal(total), - gracePeriod(grace)); + auto createJson = env.json(baseJson, paymentInterval(interval), paymentTotal(total), gracePeriod(grace)); - env(createJson, - sig(sfCounterpartySignature, lender), - ter(tesSUCCESS)); + env(createJson, sig(sfCounterpartySignature, lender), ter(tesSUCCESS)); env.close(); // The transaction is killed in the closed ledger @@ -5589,8 +4850,7 @@ protected: } { // Start date when the ledger is closed will be larger - auto const brokerStateBefore = - env.le(keylet::loanbroker(broker.brokerID)); + auto const brokerStateBefore = env.le(keylet::loanbroker(broker.brokerID)); auto const loanSequence = brokerStateBefore->at(sfLoanSequence); auto const keylet = keylet::loan(broker.brokerID, loanSequence); @@ -5598,15 +4858,9 @@ protected: auto const grace = 5'000; auto const interval = maxTime - closeStartDate - grace; auto const total = 1; - auto createJson = env.json( - baseJson, - paymentInterval(interval), - paymentTotal(total), - gracePeriod(grace)); + auto createJson = env.json(baseJson, paymentInterval(interval), paymentTotal(total), gracePeriod(grace)); - env(createJson, - sig(sfCounterpartySignature, lender), - ter(tesSUCCESS)); + env(createJson, sig(sfCounterpartySignature, lender), ter(tesSUCCESS)); env.close(); // The transaction succeeds in the closed ledger @@ -5643,28 +4897,20 @@ protected: if (!BEAST_EXPECT(total != 0)) return; - auto const brokerState = - env.le(keylet::loanbroker(broker.brokerID)); + auto const brokerState = env.le(keylet::loanbroker(broker.brokerID)); // Intentionally shadow the outer values auto const loanSequence = brokerState->at(sfLoanSequence); auto const keylet = keylet::loan(broker.brokerID, loanSequence); auto const interval = maxLoanTime / total; - auto createJson = env.json( - baseJson, - paymentInterval(interval), - paymentTotal(total), - gracePeriod(grace)); + auto createJson = env.json(baseJson, paymentInterval(interval), paymentTotal(total), gracePeriod(grace)); - env(createJson, - sig(sfCounterpartySignature, lender), - ter(tesSUCCESS)); + env(createJson, sig(sfCounterpartySignature, lender), ter(tesSUCCESS)); env.close(); // This loan exists auto const beforeState = getCurrentState(env, broker, keylet); - BEAST_EXPECT( - beforeState.nextPaymentDate == closeStartDate + interval); + BEAST_EXPECT(beforeState.nextPaymentDate == closeStartDate + interval); BEAST_EXPECT(beforeState.previousPaymentDate == 0); BEAST_EXPECT(beforeState.paymentRemaining == total); BEAST_EXPECT(beforeState.periodicPayment > 0); @@ -5672,14 +4918,10 @@ protected: // pay all but the last payment { NumberRoundModeGuard mg{Number::upward}; - Number const payment = - beforeState.periodicPayment * (total - 1); - XRPAmount const payFee{ - baseFee * ((total - 1) / loanPaymentsPerFeeIncrement + 1)}; - STAmount const paymentAmount = roundToScale( - STAmount{broker.asset, payment}, beforeState.loanScale); - auto loanPayTx = env.json( - pay(borrower, keylet.key, paymentAmount), fee(payFee)); + Number const payment = beforeState.periodicPayment * (total - 1); + XRPAmount const payFee{baseFee * ((total - 1) / loanPaymentsPerFeeIncrement + 1)}; + STAmount const paymentAmount = roundToScale(STAmount{broker.asset, payment}, beforeState.loanScale); + auto loanPayTx = env.json(pay(borrower, keylet.key, paymentAmount), fee(payFee)); env(loanPayTx, ter(tesSUCCESS)); env.close(); } @@ -5688,8 +4930,7 @@ protected: auto const afterState = getCurrentState(env, broker, keylet); BEAST_EXPECT(afterState.paymentRemaining == 1); BEAST_EXPECT(afterState.nextPaymentDate == maxTime - grace); - BEAST_EXPECT( - afterState.previousPaymentDate == maxTime - grace - interval); + BEAST_EXPECT(afterState.previousPaymentDate == maxTime - grace - interval); } } @@ -5711,8 +4952,7 @@ protected: .env = env, .issuer = issuer, .holders = {lender, borrower}, - .flags = MPTDEXFlags | tfMPTRequireAuth | tfMPTCanClawback | - tfMPTCanLock, + .flags = MPTDEXFlags | tfMPTRequireAuth | tfMPTCanClawback | tfMPTCanLock, .authHolder = true, }); @@ -5725,8 +4965,7 @@ protected: auto forUnauthAuth = [&](auto&& doTx) { for (auto const flag : {tfMPTUnauthorize, 0u}) { - asset.authorize( - {.account = issuer, .holder = borrower, .flags = flag}); + asset.authorize({.account = issuer, .holder = borrower, .flags = flag}); env.close(); doTx(flag == 0); env.close(); @@ -5755,8 +4994,7 @@ protected: void testCoverDepositWithdrawNonTransferableMPT() { - testcase( - "CoverDeposit and CoverWithdraw reject MPT without CanTransfer"); + testcase("CoverDeposit and CoverWithdraw reject MPT without CanTransfer"); using namespace jtx; using namespace loanBroker; @@ -5770,9 +5008,7 @@ protected: MPTTester mpt{env, issuer, mptInitNoFund}; - mpt.create( - {.flags = tfMPTCanTransfer, - .mutableFlags = tmfMPTCanMutateCanTransfer}); + mpt.create({.flags = tfMPTCanTransfer, .mutableFlags = tmfMPTCanMutateCanTransfer}); env.close(); @@ -5785,13 +5021,11 @@ protected: env.close(); Vault vault{env}; - auto const [createTx, vaultKeylet] = - vault.create({.owner = alice, .asset = asset}); + auto const [createTx, vaultKeylet] = vault.create({.owner = alice, .asset = asset}); env(createTx); env.close(); - auto const brokerKeylet = - keylet::loanbroker(alice.id(), env.seq(alice)); + auto const brokerKeylet = keylet::loanbroker(alice.id(), env.seq(alice)); env(set(alice, vaultKeylet.key)); env.close(); @@ -5799,8 +5033,7 @@ protected: if (!BEAST_EXPECT(brokerSle)) return; - Account const pseudoAccount{ - "Loan Broker pseudo-account", brokerSle->at(sfAccount)}; + Account const pseudoAccount{"Loan Broker pseudo-account", brokerSle->at(sfAccount)}; // Remove CanTransfer after the broker is set up. mpt.set({.mutableFlags = tmfMPTClearCanTransfer}); @@ -5812,12 +5045,10 @@ protected: // Cover cannot be transferred to broker account auto const depositAmount = asset(1); - env(coverDeposit(alice, brokerKeylet.key, depositAmount), - ter{tecNO_AUTH}); + env(coverDeposit(alice, brokerKeylet.key, depositAmount), ter{tecNO_AUTH}); env.close(); - if (auto const refreshed = env.le(brokerKeylet); - BEAST_EXPECT(refreshed)) + if (auto const refreshed = env.le(brokerKeylet); BEAST_EXPECT(refreshed)) { BEAST_EXPECT(refreshed->at(sfCoverAvailable) == 0); env.require(balance(pseudoAccount, asset(0))); @@ -5830,8 +5061,7 @@ protected: env(coverDeposit(alice, brokerKeylet.key, depositAmount)); env.close(); - if (auto const refreshed = env.le(brokerKeylet); - BEAST_EXPECT(refreshed)) + if (auto const refreshed = env.le(brokerKeylet); BEAST_EXPECT(refreshed)) { BEAST_EXPECT(refreshed->at(sfCoverAvailable) == 1); env.require(balance(pseudoAccount, depositAmount)); @@ -5842,8 +5072,7 @@ protected: env.close(); // Cover cannot be transferred from broker account - env(coverWithdraw(alice, brokerKeylet.key, depositAmount), - ter{tecNO_AUTH}); + env(coverWithdraw(alice, brokerKeylet.key, depositAmount), ter{tecNO_AUTH}); env.close(); // Set CanTransfer again and withdraw @@ -5853,8 +5082,7 @@ protected: env(coverWithdraw(alice, brokerKeylet.key, depositAmount)); env.close(); - if (auto const refreshed = env.le(brokerKeylet); - BEAST_EXPECT(refreshed)) + if (auto const refreshed = env.le(brokerKeylet); BEAST_EXPECT(refreshed)) { BEAST_EXPECT(refreshed->at(sfCoverAvailable) == 0); env.require(balance(pseudoAccount, asset(0))); @@ -5922,8 +5150,7 @@ protected: using d = NetClock::duration; using tp = NetClock::time_point; - auto const overdueClose = - tp{d{state1.nextPaymentDate + state1.paymentInterval}}; + auto const overdueClose = tp{d{state1.nextPaymentDate + state1.paymentInterval}}; env.close(overdueClose); auto const brokerSle = env.le(keylet::loanbroker(broker.brokerID)); @@ -5935,33 +5162,23 @@ protected: TenthBips16 const managementFeeRate{brokerSle->at(sfManagementFeeRate)}; TenthBips32 const interestRateValue{loanSle->at(sfInterestRate)}; - TenthBips32 const lateInterestRateValue{ - loanSle->at(sfLateInterestRate)}; - TenthBips32 const closeInterestRateValue{ - loanSle->at(sfCloseInterestRate)}; + TenthBips32 const lateInterestRateValue{loanSle->at(sfLateInterestRate)}; + TenthBips32 const closeInterestRateValue{loanSle->at(sfCloseInterestRate)}; - Number const closePaymentFeeRounded = roundToAsset( - broker.asset, loanSle->at(sfClosePaymentFee), state.loanScale); - Number const latePaymentFeeRounded = roundToAsset( - broker.asset, loanSle->at(sfLatePaymentFee), state.loanScale); + Number const closePaymentFeeRounded = + roundToAsset(broker.asset, loanSle->at(sfClosePaymentFee), state.loanScale); + Number const latePaymentFeeRounded = roundToAsset(broker.asset, loanSle->at(sfLatePaymentFee), state.loanScale); - auto const roundedLoanState = constructLoanState( - state.totalValue, - state.principalOutstanding, - state.managementFeeOutstanding); + auto const roundedLoanState = + constructLoanState(state.totalValue, state.principalOutstanding, state.managementFeeOutstanding); Number const totalInterestOutstanding = roundedLoanState.interestDue; - auto const periodicRate = - loanPeriodicRate(interestRateValue, state.paymentInterval); - auto const rawLoanState = computeTheoreticalLoanState( - state.periodicPayment, - periodicRate, - state.paymentRemaining, - managementFeeRate); + auto const periodicRate = loanPeriodicRate(interestRateValue, state.paymentInterval); + auto const rawLoanState = + computeTheoreticalLoanState(state.periodicPayment, periodicRate, state.paymentRemaining, managementFeeRate); auto const parentCloseTime = env.current()->parentCloseTime(); - auto const startDateSeconds = static_cast( - state.startDate.time_since_epoch().count()); + auto const startDateSeconds = static_cast(state.startDate.time_since_epoch().count()); Number const fullPaymentInterest = computeFullPaymentInterest( rawLoanState.principalOutstanding, @@ -5972,46 +5189,30 @@ protected: startDateSeconds, closeInterestRateValue); - Number const roundedFullInterestAmount = - roundToAsset(broker.asset, fullPaymentInterest, state.loanScale); - Number const roundedFullManagementFee = computeManagementFee( - broker.asset, - roundedFullInterestAmount, - managementFeeRate, - state.loanScale); - Number const roundedFullInterest = - roundedFullInterestAmount - roundedFullManagementFee; + Number const roundedFullInterestAmount = roundToAsset(broker.asset, fullPaymentInterest, state.loanScale); + Number const roundedFullManagementFee = + computeManagementFee(broker.asset, roundedFullInterestAmount, managementFeeRate, state.loanScale); + Number const roundedFullInterest = roundedFullInterestAmount - roundedFullManagementFee; - Number const trackedValueDelta = state.principalOutstanding + - totalInterestOutstanding + state.managementFeeOutstanding; - Number const untrackedManagementFee = closePaymentFeeRounded + - roundedFullManagementFee - state.managementFeeOutstanding; - Number const untrackedInterest = - roundedFullInterest - totalInterestOutstanding; + Number const trackedValueDelta = + state.principalOutstanding + totalInterestOutstanding + state.managementFeeOutstanding; + Number const untrackedManagementFee = + closePaymentFeeRounded + roundedFullManagementFee - state.managementFeeOutstanding; + Number const untrackedInterest = roundedFullInterest - totalInterestOutstanding; - Number const baseFullDue = - trackedValueDelta + untrackedInterest + untrackedManagementFee; - BEAST_EXPECT( - baseFullDue == - roundToAsset(broker.asset, baseFullDue, state.loanScale)); + Number const baseFullDue = trackedValueDelta + untrackedInterest + untrackedManagementFee; + BEAST_EXPECT(baseFullDue == roundToAsset(broker.asset, baseFullDue, state.loanScale)); - auto const overdueSeconds = - parentCloseTime.time_since_epoch().count() - state.nextPaymentDate; + auto const overdueSeconds = parentCloseTime.time_since_epoch().count() - state.nextPaymentDate; if (!BEAST_EXPECT(overdueSeconds > 0)) return; - Number const overdueRate = - loanPeriodicRate(lateInterestRateValue, overdueSeconds); + Number const overdueRate = loanPeriodicRate(lateInterestRateValue, overdueSeconds); Number const lateInterestRaw = state.principalOutstanding * overdueRate; - Number const lateInterestRounded = - roundToAsset(broker.asset, lateInterestRaw, state.loanScale); - Number const lateManagementFeeRounded = computeManagementFee( - broker.asset, - lateInterestRounded, - managementFeeRate, - state.loanScale); - Number const penaltyDue = lateInterestRounded + - lateManagementFeeRounded + latePaymentFeeRounded; + Number const lateInterestRounded = roundToAsset(broker.asset, lateInterestRaw, state.loanScale); + Number const lateManagementFeeRounded = + computeManagementFee(broker.asset, lateInterestRounded, managementFeeRate, state.loanScale); + Number const penaltyDue = lateInterestRounded + lateManagementFeeRounded + latePaymentFeeRounded; BEAST_EXPECT(penaltyDue > Number{}); auto const balanceBefore = env.balance(borrower, broker.asset).number(); @@ -6035,88 +5236,79 @@ protected: void testLoanCoverMinimumRoundingExploit() { - auto testLoanCoverMinimumRoundingExploit = - [&, this](Number const& principalRequest) { - testcase << "LoanBrokerCoverClawback drains cover via rounding" - << " principalRequested=" - << to_string(principalRequest); + auto testLoanCoverMinimumRoundingExploit = [&, this](Number const& principalRequest) { + testcase << "LoanBrokerCoverClawback drains cover via rounding" + << " principalRequested=" << to_string(principalRequest); - using namespace jtx; - using namespace loan; - using namespace loanBroker; + using namespace jtx; + using namespace loan; + using namespace loanBroker; - Env env(*this, all); + Env env(*this, all); - Account const issuer{"issuer"}; - Account const lender{"lender"}; - Account const borrower{"borrower"}; + Account const issuer{"issuer"}; + Account const lender{"lender"}; + Account const borrower{"borrower"}; - env.fund(XRP(1'000'000'000), issuer, lender, borrower); - env.close(); + env.fund(XRP(1'000'000'000), issuer, lender, borrower); + env.close(); - env(fset(issuer, asfAllowTrustLineClawback)); - env.close(); + env(fset(issuer, asfAllowTrustLineClawback)); + env.close(); - PrettyAsset const asset = issuer[iouCurrency]; - env(trust(lender, asset(2'000'0000))); - env(trust(borrower, asset(2'000'0000))); - env.close(); + PrettyAsset const asset = issuer[iouCurrency]; + env(trust(lender, asset(2'000'0000))); + env(trust(borrower, asset(2'000'0000))); + env.close(); - env(pay(issuer, lender, asset(2'000'0000))); - env.close(); + env(pay(issuer, lender, asset(2'000'0000))); + env.close(); - BrokerParameters brokerParams{ - .debtMax = 0, .coverRateMin = TenthBips32{10'000}}; - BrokerInfo broker{ - createVaultAndBroker(env, asset, lender, brokerParams)}; + BrokerParameters brokerParams{.debtMax = 0, .coverRateMin = TenthBips32{10'000}}; + BrokerInfo broker{createVaultAndBroker(env, asset, lender, brokerParams)}; - auto const loanSetFee = fee(env.current()->fees().base * 2); - auto createTx = env.jt( - set(borrower, broker.brokerID, principalRequest), - sig(sfCounterpartySignature, lender), - loanSetFee, - paymentInterval(600), - paymentTotal(1), - gracePeriod(60)); - env(createTx); - env.close(); + auto const loanSetFee = fee(env.current()->fees().base * 2); + auto createTx = env.jt( + set(borrower, broker.brokerID, principalRequest), + sig(sfCounterpartySignature, lender), + loanSetFee, + paymentInterval(600), + paymentTotal(1), + gracePeriod(60)); + env(createTx); + env.close(); - auto const brokerBefore = - env.le(keylet::loanbroker(broker.brokerID)); - BEAST_EXPECT(brokerBefore); - if (!brokerBefore) - return; + auto const brokerBefore = env.le(keylet::loanbroker(broker.brokerID)); + BEAST_EXPECT(brokerBefore); + if (!brokerBefore) + return; - Number const debtOutstanding = brokerBefore->at(sfDebtTotal); - Number const coverAvailableBefore = - brokerBefore->at(sfCoverAvailable); + Number const debtOutstanding = brokerBefore->at(sfDebtTotal); + Number const coverAvailableBefore = brokerBefore->at(sfCoverAvailable); - BEAST_EXPECT(debtOutstanding > Number{}); - BEAST_EXPECT(coverAvailableBefore > Number{}); + BEAST_EXPECT(debtOutstanding > Number{}); + BEAST_EXPECT(coverAvailableBefore > Number{}); - log << "debt=" << to_string(debtOutstanding) - << " cover_available=" << to_string(coverAvailableBefore); + log << "debt=" << to_string(debtOutstanding) << " cover_available=" << to_string(coverAvailableBefore); - env(coverClawback(issuer, 0), loanBrokerID(broker.brokerID)); - env.close(); + env(coverClawback(issuer, 0), loanBrokerID(broker.brokerID)); + env.close(); - auto const brokerAfter = - env.le(keylet::loanbroker(broker.brokerID)); - BEAST_EXPECT(brokerAfter); - if (!brokerAfter) - return; + auto const brokerAfter = env.le(keylet::loanbroker(broker.brokerID)); + BEAST_EXPECT(brokerAfter); + if (!brokerAfter) + return; - Number const debtAfter = brokerAfter->at(sfDebtTotal); - // the debt has not changed - BEAST_EXPECT(debtAfter == debtOutstanding); + Number const debtAfter = brokerAfter->at(sfDebtTotal); + // the debt has not changed + BEAST_EXPECT(debtAfter == debtOutstanding); - Number const coverAvailableAfter = - brokerAfter->at(sfCoverAvailable); + Number const coverAvailableAfter = brokerAfter->at(sfCoverAvailable); - // since the cover rate min != 0, the cover available should not - // be zero - BEAST_EXPECT(coverAvailableAfter != Number{}); - }; + // since the cover rate min != 0, the cover available should not + // be zero + BEAST_EXPECT(coverAvailableAfter != Number{}); + }; // Call the lambda with different principal values testLoanCoverMinimumRoundingExploit(Number{1, -30}); // 1e-30 units @@ -6143,8 +5335,7 @@ protected: // and LoanPay applies the inflated valueChange to the vault // (sfAssetsTotal), increasing NAV. // -------------------------------------------------------------------- - testcase( - "PoC: Unsigned-underflow full-pay accrual after early periodic"); + testcase("PoC: Unsigned-underflow full-pay accrual after early periodic"); using namespace jtx; using namespace loan; @@ -6159,8 +5350,7 @@ protected: PrettyAsset const asset{xrpIssue(), 1'000'000}; BrokerParameters brokerParams{}; - auto const broker = - createVaultAndBroker(env, asset, lender, brokerParams); + auto const broker = createVaultAndBroker(env, asset, lender, brokerParams); // Create a 3-payment loan so full-payment path is enabled after 1 // periodic payment. @@ -6206,8 +5396,7 @@ protected: // Compute a regular periodic due and pay it early (before next due). auto state = getCurrentState(env, broker, loanKeylet); - Number const periodicRate = - loanPeriodicRate(state.interestRate, state.paymentInterval); + Number const periodicRate = loanPeriodicRate(state.interestRate, state.paymentInterval); auto const components = detail::computePaymentComponents( asset.raw(), state.loanScale, @@ -6218,8 +5407,7 @@ protected: periodicRate, state.paymentRemaining, brokerParams.managementFeeRate); - STAmount const regularDue{ - asset, components.trackedValueDelta + serviceFeePA.number()}; + STAmount const regularDue{asset, components.trackedValueDelta + serviceFeePA.number()}; // now < nextDue immediately after creation, so this is an early pay. env(pay(borrower, loanKeylet.key, regularDue)); env.close(); @@ -6232,103 +5420,72 @@ protected: auto const brokerSle2 = env.le(keylet::loanbroker(broker.brokerID)); BEAST_EXPECT(brokerSle2); - auto const closePaymentFee = - loanSle ? loanSle->at(sfClosePaymentFee) : Number{}; - auto const closeInterestRate = loanSle - ? TenthBips32{loanSle->at(sfCloseInterestRate)} - : TenthBips32{}; - auto const managementFeeRate = brokerSle2 - ? TenthBips16{brokerSle2->at(sfManagementFeeRate)} - : TenthBips16{}; + auto const closePaymentFee = loanSle ? loanSle->at(sfClosePaymentFee) : Number{}; + auto const closeInterestRate = loanSle ? TenthBips32{loanSle->at(sfCloseInterestRate)} : TenthBips32{}; + auto const managementFeeRate = brokerSle2 ? TenthBips16{brokerSle2->at(sfManagementFeeRate)} : TenthBips16{}; - Number const periodicRate2 = - loanPeriodicRate(after.interestRate, after.paymentInterval); + Number const periodicRate2 = loanPeriodicRate(after.interestRate, after.paymentInterval); // Accrued + prepayment-penalty interest based on current periodic // schedule auto const fullPaymentInterest = computeFullPaymentInterest( - detail::loanPrincipalFromPeriodicPayment( - after.periodicPayment, periodicRate2, after.paymentRemaining), + detail::loanPrincipalFromPeriodicPayment(after.periodicPayment, periodicRate2, after.paymentRemaining), periodicRate2, env.current()->parentCloseTime(), after.paymentInterval, after.previousPaymentDate, - static_cast( - after.startDate.time_since_epoch().count()), + static_cast(after.startDate.time_since_epoch().count()), closeInterestRate); // Round to asset scale and split interest/fee parts - auto const roundedInterest = - roundToAsset(asset.raw(), fullPaymentInterest, after.loanScale); - Number const roundedFullMgmtFee = computeManagementFee( - asset.raw(), roundedInterest, managementFeeRate, after.loanScale); + auto const roundedInterest = roundToAsset(asset.raw(), fullPaymentInterest, after.loanScale); + Number const roundedFullMgmtFee = + computeManagementFee(asset.raw(), roundedInterest, managementFeeRate, after.loanScale); Number const roundedFullInterest = roundedInterest - roundedFullMgmtFee; // Show both signed and unsigned deltas to highlight the underflow. - auto const nowSecs = static_cast( - env.current()->parentCloseTime().time_since_epoch().count()); - auto const startSecs = static_cast( - after.startDate.time_since_epoch().count()); - auto const lastPaymentDate = - std::max(after.previousPaymentDate, startSecs); - auto const signedDelta = static_cast(nowSecs) - - static_cast(lastPaymentDate); - auto const unsignedDelta = - static_cast(nowSecs - lastPaymentDate); - log << "PoC window: prev=" << after.previousPaymentDate - << " start=" << startSecs << " now=" << nowSecs - << " signedDelta=" << signedDelta - << " unsignedDelta=" << unsignedDelta << std::endl; + auto const nowSecs = static_cast(env.current()->parentCloseTime().time_since_epoch().count()); + auto const startSecs = static_cast(after.startDate.time_since_epoch().count()); + auto const lastPaymentDate = std::max(after.previousPaymentDate, startSecs); + auto const signedDelta = static_cast(nowSecs) - static_cast(lastPaymentDate); + auto const unsignedDelta = static_cast(nowSecs - lastPaymentDate); + log << "PoC window: prev=" << after.previousPaymentDate << " start=" << startSecs << " now=" << nowSecs + << " signedDelta=" << signedDelta << " unsignedDelta=" << unsignedDelta << std::endl; // Reference (clamped) computation: emulate a non-negative accrual // window by clamping prevPaymentDate to 'now' for the full-pay path. auto const prevClamped = std::min(after.previousPaymentDate, nowSecs); auto const fullPaymentInterestClamped = computeFullPaymentInterest( - detail::loanPrincipalFromPeriodicPayment( - after.periodicPayment, periodicRate2, after.paymentRemaining), + detail::loanPrincipalFromPeriodicPayment(after.periodicPayment, periodicRate2, after.paymentRemaining), periodicRate2, env.current()->parentCloseTime(), after.paymentInterval, prevClamped, startSecs, closeInterestRate); - auto const roundedInterestClamped = roundToAsset( - asset.raw(), fullPaymentInterestClamped, after.loanScale); - Number const roundedFullMgmtFeeClamped = computeManagementFee( - asset.raw(), - roundedInterestClamped, - managementFeeRate, - after.loanScale); - Number const roundedFullInterestClamped = - roundedInterestClamped - roundedFullMgmtFeeClamped; + auto const roundedInterestClamped = roundToAsset(asset.raw(), fullPaymentInterestClamped, after.loanScale); + Number const roundedFullMgmtFeeClamped = + computeManagementFee(asset.raw(), roundedInterestClamped, managementFeeRate, after.loanScale); + Number const roundedFullInterestClamped = roundedInterestClamped - roundedFullMgmtFeeClamped; STAmount const fullDueClamped{ asset, - after.principalOutstanding + roundedFullInterestClamped + - roundedFullMgmtFeeClamped + closePaymentFee}; + after.principalOutstanding + roundedFullInterestClamped + roundedFullMgmtFeeClamped + closePaymentFee}; // Collect vault NAV before closing payment - auto const vaultId2 = - brokerSle2 ? brokerSle2->at(sfVaultID) : uint256{}; + auto const vaultId2 = brokerSle2 ? brokerSle2->at(sfVaultID) : uint256{}; auto const vaultKey2 = keylet::vault(vaultId2); auto const vaultBefore = env.le(vaultKey2); BEAST_EXPECT(vaultBefore); - Number const assetsTotalBefore = - vaultBefore ? vaultBefore->at(sfAssetsTotal) : Number{}; + Number const assetsTotalBefore = vaultBefore ? vaultBefore->at(sfAssetsTotal) : Number{}; STAmount const fullDue{ - asset, - after.principalOutstanding + roundedFullInterest + - roundedFullMgmtFee + closePaymentFee}; + asset, after.principalOutstanding + roundedFullInterest + roundedFullMgmtFee + closePaymentFee}; log << "PoC payoff: principalOutstanding=" << after.principalOutstanding - << " roundedFullInterest=" << roundedFullInterest - << " roundedFullMgmtFee=" << roundedFullMgmtFee - << " closeFee=" << closePaymentFee - << " fullDue=" << to_string(fullDue.getJson()) << std::endl; - log << "PoC reference (clamped): roundedFullInterestClamped=" - << roundedFullInterestClamped + << " roundedFullInterest=" << roundedFullInterest << " roundedFullMgmtFee=" << roundedFullMgmtFee + << " closeFee=" << closePaymentFee << " fullDue=" << to_string(fullDue.getJson()) << std::endl; + log << "PoC reference (clamped): roundedFullInterestClamped=" << roundedFullInterestClamped << " roundedFullMgmtFeeClamped=" << roundedFullMgmtFeeClamped - << " fullDueClamped=" << to_string(fullDueClamped.getJson()) - << std::endl; + << " fullDueClamped=" << to_string(fullDueClamped.getJson()) << std::endl; env(pay(borrower, loanKeylet.key, fullDue), txflags(tfLoanFullPayment)); env.close(); @@ -6343,10 +5500,8 @@ protected: if (vaultAfter) { auto const assetsTotalAfter = vaultAfter->at(sfAssetsTotal); - log << "PoC NAV: assetsTotalBefore=" << assetsTotalBefore - << " assetsTotalAfter=" << assetsTotalAfter - << " delta=" << (assetsTotalAfter - assetsTotalBefore) - << std::endl; + log << "PoC NAV: assetsTotalBefore=" << assetsTotalBefore << " assetsTotalAfter=" << assetsTotalAfter + << " delta=" << (assetsTotalAfter - assetsTotalBefore) << std::endl; // Value-based proof: underflowed window yields a payoff larger than // the clamped (non-underflow) reference. @@ -6431,9 +5586,7 @@ protected: // before the loan the assets total and available should be equal BEAST_EXPECT(assetsAvail == assetsTotal); - BEAST_EXPECT( - assetsAvail == - broker.asset(brokerParams.vaultDeposit).number()); + BEAST_EXPECT(assetsAvail == broker.asset(brokerParams.vaultDeposit).number()); } Keylet const& loanKeylet = *loanKeyletOpt; @@ -6470,28 +5623,17 @@ protected: auto const state = constructRoundedLoanState(loanSle); log << "Loan state:" << std::endl; - log << " ValueOutstanding: " << state.valueOutstanding - << std::endl; - log << " PrincipalOutstanding: " << state.principalOutstanding - << std::endl; - log << " InterestOutstanding: " << state.interestOutstanding() - << std::endl; + log << " ValueOutstanding: " << state.valueOutstanding << std::endl; + log << " PrincipalOutstanding: " << state.principalOutstanding << std::endl; + log << " InterestOutstanding: " << state.interestOutstanding() << std::endl; log << " InterestDue: " << state.interestDue << std::endl; log << " FeeDue: " << state.managementFeeDue << std::endl; // after loan creation the assets total and available should // reflect the value of the loan BEAST_EXPECT(assetsAvail < assetsTotal); - BEAST_EXPECT( - assetsAvail == - broker - .asset( - brokerParams.vaultDeposit - loanParams.principalRequest) - .number()); - BEAST_EXPECT( - assetsTotal == - broker.asset(brokerParams.vaultDeposit + state.interestDue) - .number()); + BEAST_EXPECT(assetsAvail == broker.asset(brokerParams.vaultDeposit - loanParams.principalRequest).number()); + BEAST_EXPECT(assetsTotal == broker.asset(brokerParams.vaultDeposit + state.interestDue).number()); } // Step 7: Trigger default (dust adjustment will occur) @@ -6507,8 +5649,7 @@ protected: log << "After default:" << std::endl; log << " AssetsTotal: " << assetsTotal2 << std::endl; log << " AssetsAvailable: " << assetsAvail2 << std::endl; - log << " Difference: " << (assetsTotal2 - assetsAvail2) - << std::endl; + log << " Difference: " << (assetsTotal2 - assetsAvail2) << std::endl; // after a default the assets total and available should be equal BEAST_EXPECT(assetsAvail2 == assetsTotal2); @@ -6545,8 +5686,7 @@ protected: Env env(*this, all); - auto loanResult = createLoan( - env, assetType, brokerParams, loanParams, issuer, lender, borrower); + auto loanResult = createLoan(env, assetType, brokerParams, loanParams, issuer, lender, borrower); if (!BEAST_EXPECT(loanResult)) return; @@ -6560,17 +5700,14 @@ protected: auto state = getCurrentState(env, broker, loanKeylet); if (auto loan = env.le(loanKeylet); BEAST_EXPECT(loan)) { - env.close(tp{d{ - loan->at(sfNextPaymentDueDate) + loan->at(sfGracePeriod) + 1}}); + env.close(tp{d{loan->at(sfNextPaymentDueDate) + loan->at(sfGracePeriod) + 1}}); } - topUpBorrower( - env, broker, issuer, borrower, state, loanParams.serviceFee); + topUpBorrower(env, broker, issuer, borrower, state, loanParams.serviceFee); using namespace jtx::loan; - auto jv = - pay(borrower, loanKeylet.key, drops(XRPAmount(state.totalValue))); + auto jv = pay(borrower, loanKeylet.key, drops(XRPAmount(state.totalValue))); { auto const submitParam = to_string(jv); @@ -6619,8 +5756,7 @@ protected: Env env(*this, all); - auto loanResult = createLoan( - env, assetType, brokerParams, loanParams, issuer, lender, borrower); + auto loanResult = createLoan(env, assetType, brokerParams, loanParams, issuer, lender, borrower); if (!BEAST_EXPECT(loanResult)) return; @@ -6631,14 +5767,11 @@ protected: VerifyLoanStatus verifyLoanStatus(env, broker, pseudoAcct, loanKeylet); - if (auto const brokerSle = env.le(broker.brokerKeylet()); - BEAST_EXPECT(brokerSle)) + if (auto const brokerSle = env.le(broker.brokerKeylet()); BEAST_EXPECT(brokerSle)) { if (auto const loanSle = env.le(loanKeylet); BEAST_EXPECT(loanSle)) { - BEAST_EXPECT( - brokerSle->at(sfDebtTotal) == - loanSle->at(sfTotalValueOutstanding)); + BEAST_EXPECT(brokerSle->at(sfDebtTotal) == loanSle->at(sfTotalValueOutstanding)); } } @@ -6653,14 +5786,11 @@ protected: borrower, PaymentParameters{.showStepBalances = true}); - if (auto const brokerSle = env.le(broker.brokerKeylet()); - BEAST_EXPECT(brokerSle)) + if (auto const brokerSle = env.le(broker.brokerKeylet()); BEAST_EXPECT(brokerSle)) { if (auto const loanSle = env.le(loanKeylet); BEAST_EXPECT(loanSle)) { - BEAST_EXPECT( - brokerSle->at(sfDebtTotal) == - loanSle->at(sfTotalValueOutstanding)); + BEAST_EXPECT(brokerSle->at(sfDebtTotal) == loanSle->at(sfTotalValueOutstanding)); BEAST_EXPECT(brokerSle->at(sfDebtTotal) == beast::zero); } } @@ -6684,20 +5814,14 @@ protected: env.fund(XRP(10'000), lender, issuer, borrower, depositor); env.close(); - auto [tx, vaultKeyLet] = - vault.create({.owner = lender, .asset = xrpIssue()}); + auto [tx, vaultKeyLet] = vault.create({.owner = lender, .asset = xrpIssue()}); env(tx, txfee); env.close(); - env(vault.deposit( - {.depositor = depositor, - .id = vaultKeyLet.key, - .amount = XRP(1'000)}), - txfee); + env(vault.deposit({.depositor = depositor, .id = vaultKeyLet.key, .amount = XRP(1'000)}), txfee); env.close(); - auto const brokerKeyLet = - keylet::loanbroker(lender.id(), env.seq(lender)); + auto const brokerKeyLet = keylet::loanbroker(lender.id(), env.seq(lender)); env(loanBroker::set(lender, vaultKeyLet.key), txfee); env.close(); @@ -6720,9 +5844,7 @@ protected: if (auto loan = env.le(loanKeylet); env.test.BEAST_EXPECT(loan)) { - env(loan::pay(borrower, loanKeylet.key, XRPAmount(150'001)), - txflags(tfLoanOverpayment), - txfee); + env(loan::pay(borrower, loanKeylet.key, XRPAmount(150'001)), txflags(tfLoanOverpayment), txfee); env.close(); } } @@ -6745,8 +5867,7 @@ protected: // Vault with XRP asset Vault vault{env}; - auto [vaultCreate, vaultKeylet] = - vault.create({.owner = lender, .asset = xrpIssue()}); + auto [vaultCreate, vaultKeylet] = vault.create({.owner = lender, .asset = xrpIssue()}); env(vaultCreate); env.close(); BEAST_EXPECT(env.le(vaultKeylet)); @@ -6761,8 +5882,7 @@ protected: .coverDeposit = 82, }; - auto const brokerInfo = - createVaultAndBroker(env, xrpAsset, lender, brokerParams); + auto const brokerInfo = createVaultAndBroker(env, xrpAsset, lender, brokerParams); // Create a loan with principal 804 XRP and 0% interest (so // DebtTotal increases by exactly 804) env(loan::set(borrower, brokerInfo.brokerID, xrpAsset(804).value()), @@ -6773,9 +5893,7 @@ protected: env.close(); // Verify DebtTotal is exactly 804 - if (auto const brokerSle = - env.le(keylet::loanbroker(brokerInfo.brokerID)); - BEAST_EXPECT(brokerSle)) + if (auto const brokerSle = env.le(keylet::loanbroker(brokerInfo.brokerID)); BEAST_EXPECT(brokerSle)) { log << *brokerSle << std::endl; BEAST_EXPECT(brokerSle->at(sfDebtTotal) == Number(804)); @@ -6783,8 +5901,7 @@ protected: // Attempt to withdraw 2 XRP to self, leaving 80 XRP CoverAvailable. // The minimum is 80.4 XRP, which rounds up to 81 XRP, so this fails. - env(coverWithdraw(lender, brokerInfo.brokerID, xrpAsset(2).value()), - ter(tecINSUFFICIENT_FUNDS)); + env(coverWithdraw(lender, brokerInfo.brokerID, xrpAsset(2).value()), ter(tecINSUFFICIENT_FUNDS)); BEAST_EXPECT(env.ter() == tecINSUFFICIENT_FUNDS); env.close(); @@ -6795,18 +5912,14 @@ protected: env.close(); // Validate CoverAvailable == 80 XRP and DebtTotal remains 804 - if (auto const brokerSle = - env.le(keylet::loanbroker(brokerInfo.brokerID)); - BEAST_EXPECT(brokerSle)) + if (auto const brokerSle = env.le(keylet::loanbroker(brokerInfo.brokerID)); BEAST_EXPECT(brokerSle)) { log << *brokerSle << std::endl; - BEAST_EXPECT( - brokerSle->at(sfCoverAvailable) == xrpAsset(81).value()); + BEAST_EXPECT(brokerSle->at(sfCoverAvailable) == xrpAsset(81).value()); BEAST_EXPECT(brokerSle->at(sfDebtTotal) == Number(804)); // Also demonstrate that the true minimum (804 * 10%) exceeds 80 - auto const theoreticalMin = - tenthBipsOfValue(Number(804), TenthBips32(10'000)); + auto const theoreticalMin = tenthBipsOfValue(Number(804), TenthBips32(10'000)); log << "Theoretical min cover: " << theoreticalMin << std::endl; BEAST_EXPECT(Number(804, -1) == theoreticalMin); } @@ -6842,8 +5955,7 @@ protected: Env env(*this, all); - auto loanResult = createLoan( - env, assetType, brokerParams, loanParams, issuer, lender, borrower); + auto loanResult = createLoan(env, assetType, brokerParams, loanParams, issuer, lender, borrower); if (!BEAST_EXPECT(loanResult)) return; @@ -6895,20 +6007,14 @@ protected: auto const& asset = debtMaximumRequest.asset(); auto const initialVault = asset(debtMaximumRequest * 100); - auto [tx, vaultKeylet] = - vault.create({.owner = broker, .asset = asset}); + auto [tx, vaultKeylet] = vault.create({.owner = broker, .asset = asset}); env(tx, txFee); env.close(); - env(vault.deposit( - {.depositor = depositor, - .id = vaultKeylet.key, - .amount = initialVault}), - txFee); + env(vault.deposit({.depositor = depositor, .id = vaultKeylet.key, .amount = initialVault}), txFee); env.close(); - auto const brokerKeylet = - keylet::loanbroker(broker.id(), env.seq(broker)); + auto const brokerKeylet = keylet::loanbroker(broker.id(), env.seq(broker)); env(loanBroker::set(broker, vaultKeylet.key), txFee); env.close(); @@ -6924,21 +6030,17 @@ protected: env.close(); std::uint32_t const loanSequence = 1; - auto const loanKeylet = - keylet::loan(brokerKeylet.key, loanSequence); + auto const loanKeylet = keylet::loan(brokerKeylet.key, loanSequence); auto const brokerBalanceBefore = env.balance(broker, asset); - if (auto const loanSle = env.le(loanKeylet); - env.test.BEAST_EXPECT(loanSle)) + if (auto const loanSle = env.le(loanKeylet); env.test.BEAST_EXPECT(loanSle)) { auto const payment = loanSle->at(sfPeriodicPayment); auto const totalPayment = payment + serviceFee; - env(loan::pay(borrower, loanKeylet.key, asset(totalPayment)), - txFee); + env(loan::pay(borrower, loanKeylet.key, asset(totalPayment)), txFee); env.close(); - if (auto const vaultSle = env.le(vaultKeylet); - BEAST_EXPECT(vaultSle)) + if (auto const vaultSle = env.le(vaultKeylet); BEAST_EXPECT(vaultSle)) { auto const expected = [&]() { // The service fee is transferred to the broker if @@ -6950,13 +6052,10 @@ protected: // the service fee. // If the asset is XRP then the broker pays the txfee. if (asset.native()) - return brokerBalanceBefore.number() - payment - - xrpFee.number(); + return brokerBalanceBefore.number() - payment - xrpFee.number(); return brokerBalanceBefore.number() - payment; }(); - BEAST_EXPECT( - env.balance(broker, asset).value() == - asset(expected).value()); + BEAST_EXPECT(env.balance(broker, asset).value() == asset(expected).value()); } } }; @@ -6964,9 +6063,7 @@ protected: // service fee transfer in both cases. for (auto const& borrowerAcct : {broker, borrower_}) { - testLoanAsset( - [&](Env&) -> STAmount { return STAmount{XRPAmount{200'000}}; }, - borrowerAcct); + testLoanAsset([&](Env&) -> STAmount { return STAmount{XRPAmount{200'000}}; }, borrowerAcct); testLoanAsset( [&](Env& env) -> STAmount { auto const IOU = issuer["USD"]; @@ -6980,11 +6077,7 @@ protected: borrowerAcct); testLoanAsset( [&](Env& env) -> STAmount { - MPTTester mpt( - {.env = env, - .issuer = issuer, - .holders = {broker, depositor}, - .pay = 100'000'000}); + MPTTester mpt({.env = env, .issuer = issuer, .holders = {broker, depositor}, .pay = 100'000'000}); return mpt(200'000); }, borrowerAcct); @@ -7007,17 +6100,13 @@ protected: .coverRateMin = TenthBips32{0}, .managementFeeRate = TenthBips16{0}, .coverRateLiquidation = TenthBips32{0}}; - LoanParameters const loanParams{ - .account = lender, - .counter = issuer, - .principalRequest = Number{10000}}; + LoanParameters const loanParams{.account = lender, .counter = issuer, .principalRequest = Number{10000}}; auto const assetType = AssetType::IOU; Env env(*this, all); - auto loanResult = createLoan( - env, assetType, brokerParams, loanParams, issuer, lender, issuer); + auto loanResult = createLoan(env, assetType, brokerParams, loanParams, issuer, lender, issuer); if (!BEAST_EXPECT(loanResult)) return; @@ -7070,15 +6159,9 @@ protected: auto const assetType = AssetType::XRP; - Env env( - *this, - makeConfig(), - all, - nullptr, - beast::severities::Severity::kWarning); + Env env(*this, makeConfig(), all, nullptr, beast::severities::Severity::kWarning); - auto loanResult = createLoan( - env, assetType, brokerParams, loanParams, issuer, lender, borrower); + auto loanResult = createLoan(env, assetType, brokerParams, loanParams, issuer, lender, borrower); if (!BEAST_EXPECT(loanResult)) return; @@ -7092,10 +6175,7 @@ protected: auto const state = getCurrentState(env, broker, loanKeylet); env(loan::pay( - borrower, - loanKeylet.key, - STAmount{broker.asset, state.periodicPayment * 3 / 2 + 1}, - tfLoanOverpayment)); + borrower, loanKeylet.key, STAmount{broker.asset, state.periodicPayment * 3 / 2 + 1}, tfLoanOverpayment)); env.close(); PaymentParameters paymentParams{ @@ -7104,15 +6184,7 @@ protected: }; makeLoanPayments( - env, - broker, - loanParams, - loanKeylet, - verifyLoanStatus, - issuer, - lender, - borrower, - paymentParams); + env, broker, loanParams, loanKeylet, verifyLoanStatus, issuer, lender, borrower, paymentParams); } void @@ -7143,19 +6215,13 @@ protected: auto const loanSetFee = fee(env.current()->fees().base * 2); - auto const loanKeylet = keylet::loan( - result.brokerKeylet().key, - (env.le(result.brokerKeylet()))->at(sfLoanSequence)); - env(loan::set( - borrower, - result.brokerKeylet().key, - asset(10'000).value(), - tfLoanOverpayment), + auto const loanKeylet = + keylet::loan(result.brokerKeylet().key, (env.le(result.brokerKeylet()))->at(sfLoanSequence)); + env(loan::set(borrower, result.brokerKeylet().key, asset(10'000).value(), tfLoanOverpayment), sig(sfCounterpartySignature, lender), loan::paymentInterval(86400 * 30), loan::paymentTotal(3), - loan::overpaymentInterestRate( - TenthBips32(percentageToTenthBips(20))), + loan::overpaymentInterestRate(TenthBips32(percentageToTenthBips(20))), loanSetFee); // From calculator @@ -7163,19 +6229,13 @@ protected: auto const loanBrokerBalanceBefore = env.balance(lender); auto const loanPayFee = fee(env.current()->fees().base * 2); - env(pay(borrower, - loanKeylet.key, - asset(5'000).value(), - tfLoanOverpayment), - loanPayFee); + env(pay(borrower, loanKeylet.key, asset(5'000).value(), tfLoanOverpayment), loanPayFee); env.close(); BEAST_EXPECTS( - env.balance(lender) - loanBrokerBalanceBefore == - expectedOverpaymentManagementFee, - "overpayment management fee missmatch; expected:" + - to_string(expectedOverpaymentManagementFee) + " got: " + - to_string(env.balance(lender) - loanBrokerBalanceBefore)); + env.balance(lender) - loanBrokerBalanceBefore == expectedOverpaymentManagementFee, + "overpayment management fee missmatch; expected:" + to_string(expectedOverpaymentManagementFee) + + " got: " + to_string(env.balance(lender) - loanBrokerBalanceBefore)); } void @@ -7214,8 +6274,7 @@ protected: // at least 1,000 cover. Default cover is 1,000, so we add more to be // safe. auto const additionalCover = IOU(50'000).value(); - env(loanBroker::coverDeposit( - broker, brokerInfo.brokerID, STAmount{IOU, additionalCover})); + env(loanBroker::coverDeposit(broker, brokerInfo.brokerID, STAmount{IOU, additionalCover})); env.close(); // Verify broker owner has a trustline auto const brokerTrustline = keylet::line(broker, IOU); @@ -7232,22 +6291,17 @@ protected: BEAST_EXPECT(env.le(brokerTrustline) == nullptr); // Now borrower tries to make a payment // We should get a tesSUCCESS instead of a tecNO_LINE. - env(pay(borrower, keylet.key, IOU(10'100)), - fee(XRP(100)), - ter(tesSUCCESS)); + env(pay(borrower, keylet.key, IOU(10'100)), fee(XRP(100)), ter(tesSUCCESS)); env.close(); // Verify trustline is still deleted BEAST_EXPECT(env.le(brokerTrustline) == nullptr); // Verify the service fee went to the broker pseudo-account - if (auto const brokerSle = - env.le(keylet::loanbroker(brokerInfo.brokerID)); - BEAST_EXPECT(brokerSle)) + if (auto const brokerSle = env.le(keylet::loanbroker(brokerInfo.brokerID)); BEAST_EXPECT(brokerSle)) { Account const pseudo("pseudo-account", brokerSle->at(sfAccount)); auto const balance = env.balance(pseudo, IOU); // 1,000 default + 50,000 extra + 100 service fee from LoanPay - BEAST_EXPECTS( - balance == IOU(51'100), to_string(Json::Value(balance))); + BEAST_EXPECTS(balance == IOU(51'100), to_string(Json::Value(balance))); } } @@ -7267,8 +6321,7 @@ protected: env.close(); MPTTester mptt{env, issuer, mptInitNoFund}; - mptt.create( - {.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock}); + mptt.create({.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock}); PrettyAsset const MPT{mptt.issuanceID()}; @@ -7300,8 +6353,7 @@ protected: // at least 1,000 cover. Default cover is 1,000, so we add more to be // safe. auto const additionalCover = MPT(50'000).value(); - env(loanBroker::coverDeposit( - broker, brokerInfo.brokerID, STAmount{MPT, additionalCover})); + env(loanBroker::coverDeposit(broker, brokerInfo.brokerID, STAmount{MPT, additionalCover})); env.close(); // Verify broker owner is authorized auto const brokerMpt = keylet::mptoken(mptt.issuanceID(), broker); @@ -7319,30 +6371,24 @@ protected: // Now borrower tries to make a payment // We should get a tesSUCCESS instead of a tecNO_AUTH. auto const borrowerBalance = env.balance(borrower, MPT); - env(pay(borrower, keylet.key, MPT(10'100)), - fee(XRP(100)), - ter(tesSUCCESS)); + env(pay(borrower, keylet.key, MPT(10'100)), fee(XRP(100)), ter(tesSUCCESS)); env.close(); // Verify the MPT is still unauthorized. BEAST_EXPECT(env.le(brokerMpt) == nullptr); // Verify the service fee went to the broker pseudo-account - if (auto const brokerSle = - env.le(keylet::loanbroker(brokerInfo.brokerID)); - BEAST_EXPECT(brokerSle)) + if (auto const brokerSle = env.le(keylet::loanbroker(brokerInfo.brokerID)); BEAST_EXPECT(brokerSle)) { Account const pseudo("pseudo-account", brokerSle->at(sfAccount)); auto const balance = env.balance(pseudo, MPT); // 1,000 default + 50,000 extra + 100 service fee from LoanPay - BEAST_EXPECTS( - balance == MPT(51'100), to_string(Json::Value(balance))); + BEAST_EXPECTS(balance == MPT(51'100), to_string(Json::Value(balance))); } } void testLoanPayBrokerOwnerNoPermissionedDomainMPT() { - testcase - << "LoanPay Broker Owner without permissioned domain of the MPT"; + testcase << "LoanPay Broker Owner without permissioned domain of the MPT"; using namespace jtx; using namespace loan; @@ -7372,8 +6418,7 @@ protected: MPTTester mptt{env, issuer, mptInitNoFund}; mptt.create({ - .flags = tfMPTCanClawback | tfMPTRequireAuth | tfMPTCanTransfer | - tfMPTCanLock, + .flags = tfMPTCanClawback | tfMPTRequireAuth | tfMPTCanTransfer | tfMPTCanLock, .domainID = domainID, }); @@ -7407,8 +6452,7 @@ protected: // at least 1,000 cover. Default cover is 1,000, so we add more to be // safe. auto const additionalCover = MPT(50'000).value(); - env(loanBroker::coverDeposit( - broker, brokerInfo.brokerID, STAmount{MPT, additionalCover})); + env(loanBroker::coverDeposit(broker, brokerInfo.brokerID, STAmount{MPT, additionalCover})); env.close(); // Verify broker owner is authorized auto const brokerMpt = keylet::mptoken(mptt.issuanceID(), broker); @@ -7429,30 +6473,24 @@ protected: // Now borrower tries to make a payment // We should get a tesSUCCESS instead of a tecNO_AUTH. auto const borrowerBalance = env.balance(borrower, MPT); - env(pay(borrower, keylet.key, MPT(10'100)), - fee(XRP(100)), - ter(tesSUCCESS)); + env(pay(borrower, keylet.key, MPT(10'100)), fee(XRP(100)), ter(tesSUCCESS)); env.close(); // Verify broker is still not authorized env(pay(issuer, broker, MPT(1'000)), ter(tecNO_AUTH)); // Verify the service fee went to the broker pseudo-account - if (auto const brokerSle = - env.le(keylet::loanbroker(brokerInfo.brokerID)); - BEAST_EXPECT(brokerSle)) + if (auto const brokerSle = env.le(keylet::loanbroker(brokerInfo.brokerID)); BEAST_EXPECT(brokerSle)) { Account const pseudo("pseudo-account", brokerSle->at(sfAccount)); auto const balance = env.balance(pseudo, MPT); // 1,000 default + 50,000 extra + 100 service fee from LoanPay - BEAST_EXPECTS( - balance == MPT(51'100), to_string(Json::Value(balance))); + BEAST_EXPECTS(balance == MPT(51'100), to_string(Json::Value(balance))); } } void testLoanSetBrokerOwnerNoPermissionedDomainMPT() { - testcase - << "LoanSet Broker Owner without permissioned domain of the MPT"; + testcase << "LoanSet Broker Owner without permissioned domain of the MPT"; using namespace jtx; using namespace loan; @@ -7483,8 +6521,7 @@ protected: MPTTester mptt{env, issuer, mptInitNoFund}; mptt.create({ - .flags = tfMPTCanClawback | tfMPTRequireAuth | tfMPTCanTransfer | - tfMPTCanLock, + .flags = tfMPTCanClawback | tfMPTRequireAuth | tfMPTCanTransfer | tfMPTCanLock, .domainID = domainID, }); @@ -7542,8 +6579,7 @@ protected: env.close(); PrettyAsset const asset = xrpIssue(); - auto const vaultDepositAmount = - asset(200'000); // Enough for 2 x 50k loans plus interest/fees + auto const vaultDepositAmount = asset(200'000); // Enough for 2 x 50k loans plus interest/fees auto const brokerInfo = createVaultAndBroker( env, @@ -7703,15 +6739,11 @@ protected: beast::xor_shift_engine engine_; std::uniform_int_distribution<> assetDist{0, 2}; - std::uniform_int_distribution principalDist{ - 100'000, - 1'000'000'000}; + std::uniform_int_distribution principalDist{100'000, 1'000'000'000}; std::uniform_int_distribution interestRateDist{0, 10000}; std::uniform_int_distribution<> paymentTotalDist{12, 10000}; std::uniform_int_distribution<> paymentIntervalDist{60, 3600 * 24 * 30}; - std::uniform_int_distribution managementFeeRateDist{ - 0, - 10'000}; + std::uniform_int_distribution managementFeeRateDist{0, 10'000}; std::uniform_int_distribution<> serviceFeeDist{0, 20}; /* # Generate parameters that are more likely to be valid @@ -7795,8 +6827,7 @@ public: for (int i = 0; i < numIterations; ++i) { if (i % updateInterval == 0) - testcase << "Random Loan Test iteration " << (i + 1) << "/" - << numIterations; + testcase << "Random Loan Test iteration " << (i + 1) << "/" << numIterations; testRandomLoan(); } } diff --git a/src/test/app/MPToken_test.cpp b/src/test/app/MPToken_test.cpp index 65cb753755..965dd86475 100644 --- a/src/test/app/MPToken_test.cpp +++ b/src/test/app/MPToken_test.cpp @@ -42,11 +42,7 @@ class MPToken_test : public beast::unit_test::suite // tries to set a txfee while not enabling in the flag mptAlice.create( - {.maxAmt = 100, - .assetScale = 0, - .transferFee = 1, - .metadata = "test", - .err = temMALFORMED}); + {.maxAmt = 100, .assetScale = 0, .transferFee = 1, .metadata = "test", .err = temMALFORMED}); if (!features[featureSingleAssetVault]) { @@ -74,11 +70,7 @@ class MPToken_test : public beast::unit_test::suite { // tries to set DomainID when RequireAuth is not set mptAlice.create( - {.maxAmt = 100, - .assetScale = 0, - .metadata = "test", - .domainID = uint256(42), - .err = temMALFORMED}); + {.maxAmt = 100, .assetScale = 0, .metadata = "test", .domainID = uint256(42), .err = temMALFORMED}); // tries to set zero DomainID mptAlice.create( @@ -108,20 +100,10 @@ class MPToken_test : public beast::unit_test::suite .err = temMALFORMED}); // empty metadata returns error - mptAlice.create( - {.maxAmt = 100, - .assetScale = 0, - .transferFee = 0, - .metadata = "", - .err = temMALFORMED}); + mptAlice.create({.maxAmt = 100, .assetScale = 0, .transferFee = 0, .metadata = "", .err = temMALFORMED}); // MaximumAmount of 0 returns error - mptAlice.create( - {.maxAmt = 0, - .assetScale = 1, - .transferFee = 1, - .metadata = "test", - .err = temMALFORMED}); + mptAlice.create({.maxAmt = 0, .assetScale = 1, .transferFee = 1, .metadata = "test", .err = temMALFORMED}); // MaximumAmount larger than 63 bit returns error mptAlice.create( @@ -158,16 +140,14 @@ class MPToken_test : public beast::unit_test::suite .transferFee = 10, .metadata = "123", .ownerCount = 1, - .flags = tfMPTCanLock | tfMPTRequireAuth | tfMPTCanEscrow | - tfMPTCanTrade | tfMPTCanTransfer | tfMPTCanClawback}); + .flags = tfMPTCanLock | tfMPTRequireAuth | tfMPTCanEscrow | tfMPTCanTrade | tfMPTCanTransfer | + tfMPTCanClawback}); // Get the hash for the most recent transaction. - std::string const txHash{ - env.tx()->getJson(JsonOptions::none)[jss::hash].asString()}; + std::string const txHash{env.tx()->getJson(JsonOptions::none)[jss::hash].asString()}; Json::Value const result = env.rpc("tx", txHash)[jss::result]; - BEAST_EXPECT( - result[sfMaximumAmount.getJsonName()] == "9223372036854775807"); + BEAST_EXPECT(result[sfMaximumAmount.getJsonName()] == "9223372036854775807"); } if (features[featureSingleAssetVault]) @@ -176,8 +156,7 @@ class MPToken_test : public beast::unit_test::suite Account const credIssuer1{"credIssuer1"}; std::string const credType = "credential"; - pdomain::Credentials const credentials1{ - {.issuer = credIssuer1, .credType = credType}}; + pdomain::Credentials const credentials1{{.issuer = credIssuer1, .credType = credType}}; { Env env{*this, features}; @@ -196,19 +175,16 @@ class MPToken_test : public beast::unit_test::suite .transferFee = 10, .metadata = "123", .ownerCount = 1, - .flags = tfMPTCanLock | tfMPTRequireAuth | tfMPTCanEscrow | - tfMPTCanTrade | tfMPTCanTransfer | tfMPTCanClawback, + .flags = tfMPTCanLock | tfMPTRequireAuth | tfMPTCanEscrow | tfMPTCanTrade | tfMPTCanTransfer | + tfMPTCanClawback, .domainID = domainId1, }); // Get the hash for the most recent transaction. - std::string const txHash{ - env.tx()->getJson(JsonOptions::none)[jss::hash].asString()}; + std::string const txHash{env.tx()->getJson(JsonOptions::none)[jss::hash].asString()}; Json::Value const result = env.rpc("tx", txHash)[jss::result]; - BEAST_EXPECT( - result[sfMaximumAmount.getJsonName()] == - "9223372036854775807"); + BEAST_EXPECT(result[sfMaximumAmount.getJsonName()] == "9223372036854775807"); } } } @@ -230,8 +206,7 @@ class MPToken_test : public beast::unit_test::suite env.enableFeature(featureMPTokensV1); - mptAlice.destroy( - {.id = id, .flags = 0x00000001, .err = temINVALID_FLAG}); + mptAlice.destroy({.id = id, .flags = 0x00000001, .err = temINVALID_FLAG}); } // MPTokenIssuanceDestroy (preclaim) @@ -239,10 +214,7 @@ class MPToken_test : public beast::unit_test::suite Env env{*this, features}; MPTTester mptAlice(env, alice, {.holders = {bob}}); - mptAlice.destroy( - {.id = makeMptID(env.seq(alice), alice), - .ownerCount = 0, - .err = tecOBJECT_NOT_FOUND}); + mptAlice.destroy({.id = makeMptID(env.seq(alice), alice), .ownerCount = 0, .err = tecOBJECT_NOT_FOUND}); mptAlice.create({.ownerCount = 1}); @@ -295,10 +267,7 @@ class MPToken_test : public beast::unit_test::suite Env env{*this, features - featureMPTokensV1}; MPTTester mptAlice(env, alice, {.holders = {bob}}); - mptAlice.authorize( - {.account = bob, - .id = makeMptID(env.seq(alice), alice), - .err = temDISABLED}); + mptAlice.authorize({.account = bob, .id = makeMptID(env.seq(alice), alice), .err = temDISABLED}); } // Validate fields in MPTokenAuthorize (preflight) @@ -310,11 +279,9 @@ class MPToken_test : public beast::unit_test::suite // The only valid MPTokenAuthorize flag is tfMPTUnauthorize, which // has a value of 1 - mptAlice.authorize( - {.account = bob, .flags = 0x00000002, .err = temINVALID_FLAG}); + mptAlice.authorize({.account = bob, .flags = 0x00000002, .err = temINVALID_FLAG}); - mptAlice.authorize( - {.account = bob, .holder = bob, .err = temMALFORMED}); + mptAlice.authorize({.account = bob, .holder = bob, .err = temMALFORMED}); mptAlice.authorize({.holder = alice, .err = temMALFORMED}); } @@ -326,11 +293,9 @@ class MPToken_test : public beast::unit_test::suite MPTTester mptAlice(env, alice, {.holders = {bob}}); auto const id = makeMptID(env.seq(alice), alice); - mptAlice.authorize( - {.holder = bob, .id = id, .err = tecOBJECT_NOT_FOUND}); + mptAlice.authorize({.holder = bob, .id = id, .err = tecOBJECT_NOT_FOUND}); - mptAlice.authorize( - {.account = bob, .id = id, .err = tecOBJECT_NOT_FOUND}); + mptAlice.authorize({.account = bob, .id = id, .err = tecOBJECT_NOT_FOUND}); } // Test bad scenarios without allowlisting in MPTokenAuthorize @@ -342,8 +307,7 @@ class MPToken_test : public beast::unit_test::suite mptAlice.create({.ownerCount = 1}); // bob submits a tx with a holder field - mptAlice.authorize( - {.account = bob, .holder = alice, .err = tecNO_PERMISSION}); + mptAlice.authorize({.account = bob, .holder = alice, .err = tecNO_PERMISSION}); // alice tries to hold onto her own token mptAlice.authorize({.account = alice, .err = tecNO_PERMISSION}); @@ -365,10 +329,7 @@ class MPToken_test : public beast::unit_test::suite // bob tries to delete his MPToken, but fails since he still // holds tokens - mptAlice.authorize( - {.account = bob, - .flags = tfMPTUnauthorize, - .err = tecHAS_OBLIGATIONS}); + mptAlice.authorize({.account = bob, .flags = tfMPTUnauthorize, .err = tecHAS_OBLIGATIONS}); // bob pays back alice 100 tokens mptAlice.pay(bob, alice, 100); @@ -380,10 +341,7 @@ class MPToken_test : public beast::unit_test::suite // bob receives error when he tries to delete his MPToken that has // already been deleted mptAlice.authorize( - {.account = bob, - .holderCount = 0, - .flags = tfMPTUnauthorize, - .err = tecOBJECT_NOT_FOUND}); + {.account = bob, .holderCount = 0, .flags = tfMPTUnauthorize, .err = tecOBJECT_NOT_FOUND}); } // Test bad scenarios with allow-listing in MPTokenAuthorize (preclaim) @@ -421,8 +379,7 @@ class MPToken_test : public beast::unit_test::suite mptAlice.authorize({.holder = bob}); // bob deletes his mptoken - mptAlice.authorize( - {.account = bob, .holderCount = 0, .flags = tfMPTUnauthorize}); + mptAlice.authorize({.account = bob, .holderCount = 0, .flags = tfMPTUnauthorize}); } // Test mptoken reserve requirement - first two mpts free (doApply) @@ -433,11 +390,7 @@ class MPToken_test : public beast::unit_test::suite // 1 drop BEAST_EXPECT(incReserve > XRPAmount(1)); - MPTTester mptAlice1( - env, - alice, - {.holders = {bob}, - .xrpHolders = acctReserve + (incReserve - 1)}); + MPTTester mptAlice1(env, alice, {.holders = {bob}, .xrpHolders = acctReserve + (incReserve - 1)}); mptAlice1.create(); MPTTester mptAlice2(env, alice, {.fund = false}); @@ -452,11 +405,9 @@ class MPToken_test : public beast::unit_test::suite // second mpt free mptAlice2.authorize({.account = bob, .holderCount = 2}); - mptAlice3.authorize( - {.account = bob, .err = tecINSUFFICIENT_RESERVE}); + mptAlice3.authorize({.account = bob, .err = tecINSUFFICIENT_RESERVE}); - env(pay( - env.master, bob, drops(incReserve + incReserve + incReserve))); + env(pay(env.master, bob, drops(incReserve + incReserve + incReserve))); env.close(); mptAlice3.authorize({.account = bob, .holderCount = 3}); @@ -483,12 +434,10 @@ class MPToken_test : public beast::unit_test::suite // bob creates a mptoken mptAlice.authorize({.account = bob, .holderCount = 1}); - mptAlice.authorize( - {.account = bob, .holderCount = 1, .err = tecDUPLICATE}); + mptAlice.authorize({.account = bob, .holderCount = 1, .err = tecDUPLICATE}); // bob deletes his mptoken - mptAlice.authorize( - {.account = bob, .holderCount = 0, .flags = tfMPTUnauthorize}); + mptAlice.authorize({.account = bob, .holderCount = 0, .flags = tfMPTUnauthorize}); } // With allowlisting @@ -507,14 +456,9 @@ class MPToken_test : public beast::unit_test::suite mptAlice.authorize({.account = alice, .holder = bob}); // Unauthorize bob's mptoken - mptAlice.authorize( - {.account = alice, - .holder = bob, - .holderCount = 1, - .flags = tfMPTUnauthorize}); + mptAlice.authorize({.account = alice, .holder = bob, .holderCount = 1, .flags = tfMPTUnauthorize}); - mptAlice.authorize( - {.account = bob, .holderCount = 0, .flags = tfMPTUnauthorize}); + mptAlice.authorize({.account = bob, .holderCount = 0, .flags = tfMPTUnauthorize}); } // Holder can have dangling MPToken even if issuance has been destroyed. @@ -533,8 +477,7 @@ class MPToken_test : public beast::unit_test::suite // bob can delete his mptoken even though issuance is no longer // existent - mptAlice.authorize( - {.account = bob, .holderCount = 0, .flags = tfMPTUnauthorize}); + mptAlice.authorize({.account = bob, .holderCount = 0, .flags = tfMPTUnauthorize}); } } @@ -552,10 +495,7 @@ class MPToken_test : public beast::unit_test::suite Env env{*this, features - featureMPTokensV1}; MPTTester mptAlice(env, alice, {.holders = {bob}}); - mptAlice.set( - {.account = bob, - .id = makeMptID(env.seq(alice), alice), - .err = temDISABLED}); + mptAlice.set({.account = bob, .id = makeMptID(env.seq(alice), alice), .err = temDISABLED}); env.enableFeature(featureMPTokensV1); @@ -565,79 +505,43 @@ class MPToken_test : public beast::unit_test::suite // test invalid flag - only valid flags are tfMPTLock (1) and Unlock // (2) - mptAlice.set( - {.account = alice, - .flags = 0x00000008, - .err = temINVALID_FLAG}); + mptAlice.set({.account = alice, .flags = 0x00000008, .err = temINVALID_FLAG}); - if (!features[featureSingleAssetVault] && - !features[featureDynamicMPT]) + if (!features[featureSingleAssetVault] && !features[featureDynamicMPT]) { // test invalid flags - nothing is being changed - mptAlice.set( - {.account = alice, - .flags = 0x00000000, - .err = tecNO_PERMISSION}); + mptAlice.set({.account = alice, .flags = 0x00000000, .err = tecNO_PERMISSION}); - mptAlice.set( - {.account = alice, - .holder = bob, - .flags = 0x00000000, - .err = tecNO_PERMISSION}); + mptAlice.set({.account = alice, .holder = bob, .flags = 0x00000000, .err = tecNO_PERMISSION}); // cannot set DomainID since SAV is not enabled - mptAlice.set( - {.account = alice, - .domainID = uint256(42), - .err = temDISABLED}); + mptAlice.set({.account = alice, .domainID = uint256(42), .err = temDISABLED}); } else { // test invalid flags - nothing is being changed - mptAlice.set( - {.account = alice, - .flags = 0x00000000, - .err = temMALFORMED}); + mptAlice.set({.account = alice, .flags = 0x00000000, .err = temMALFORMED}); - mptAlice.set( - {.account = alice, - .holder = bob, - .flags = 0x00000000, - .err = temMALFORMED}); + mptAlice.set({.account = alice, .holder = bob, .flags = 0x00000000, .err = temMALFORMED}); - if (!features[featurePermissionedDomains] || - !features[featureSingleAssetVault]) + if (!features[featurePermissionedDomains] || !features[featureSingleAssetVault]) { // cannot set DomainID since PD is not enabled - mptAlice.set( - {.account = alice, - .domainID = uint256(42), - .err = temDISABLED}); + mptAlice.set({.account = alice, .domainID = uint256(42), .err = temDISABLED}); } else if (features[featureSingleAssetVault]) { // cannot set DomainID since Holder is set - mptAlice.set( - {.account = alice, - .holder = bob, - .domainID = uint256(42), - .err = temMALFORMED}); + mptAlice.set({.account = alice, .holder = bob, .domainID = uint256(42), .err = temMALFORMED}); } } // set both lock and unlock flags at the same time will fail - mptAlice.set( - {.account = alice, - .flags = tfMPTLock | tfMPTUnlock, - .err = temINVALID_FLAG}); + mptAlice.set({.account = alice, .flags = tfMPTLock | tfMPTUnlock, .err = temINVALID_FLAG}); // if the holder is the same as the acct that submitted the tx, // tx fails - mptAlice.set( - {.account = alice, - .holder = alice, - .flags = tfMPTLock, - .err = temMALFORMED}); + mptAlice.set({.account = alice, .holder = alice, .flags = tfMPTLock, .err = temMALFORMED}); } // Validate fields in MPTokenIssuanceSet (preclaim) @@ -650,32 +554,18 @@ class MPToken_test : public beast::unit_test::suite mptAlice.create({.ownerCount = 1}); // alice tries to lock a mptissuance that has disabled locking - mptAlice.set( - {.account = alice, - .flags = tfMPTLock, - .err = tecNO_PERMISSION}); + mptAlice.set({.account = alice, .flags = tfMPTLock, .err = tecNO_PERMISSION}); // alice tries to unlock mptissuance that has disabled locking - mptAlice.set( - {.account = alice, - .flags = tfMPTUnlock, - .err = tecNO_PERMISSION}); + mptAlice.set({.account = alice, .flags = tfMPTUnlock, .err = tecNO_PERMISSION}); // issuer tries to lock a bob's mptoken that has disabled // locking - mptAlice.set( - {.account = alice, - .holder = bob, - .flags = tfMPTLock, - .err = tecNO_PERMISSION}); + mptAlice.set({.account = alice, .holder = bob, .flags = tfMPTLock, .err = tecNO_PERMISSION}); // issuer tries to unlock a bob's mptoken that has disabled // locking - mptAlice.set( - {.account = alice, - .holder = bob, - .flags = tfMPTUnlock, - .err = tecNO_PERMISSION}); + mptAlice.set({.account = alice, .holder = bob, .flags = tfMPTUnlock, .err = tecNO_PERMISSION}); } // Validate fields in MPTokenIssuanceSet (preclaim) @@ -686,38 +576,28 @@ class MPToken_test : public beast::unit_test::suite MPTTester mptAlice(env, alice, {.holders = {bob}}); // alice trying to set when the mptissuance doesn't exist yet - mptAlice.set( - {.id = makeMptID(env.seq(alice), alice), - .flags = tfMPTLock, - .err = tecOBJECT_NOT_FOUND}); + mptAlice.set({.id = makeMptID(env.seq(alice), alice), .flags = tfMPTLock, .err = tecOBJECT_NOT_FOUND}); // create a mptokenissuance with locking mptAlice.create({.ownerCount = 1, .flags = tfMPTCanLock}); // a non-issuer acct tries to set the mptissuance - mptAlice.set( - {.account = bob, .flags = tfMPTLock, .err = tecNO_PERMISSION}); + mptAlice.set({.account = bob, .flags = tfMPTLock, .err = tecNO_PERMISSION}); // trying to set a holder who doesn't have a mptoken - mptAlice.set( - {.holder = bob, - .flags = tfMPTLock, - .err = tecOBJECT_NOT_FOUND}); + mptAlice.set({.holder = bob, .flags = tfMPTLock, .err = tecOBJECT_NOT_FOUND}); // trying to set a holder who doesn't exist - mptAlice.set( - {.holder = cindy, .flags = tfMPTLock, .err = tecNO_DST}); + mptAlice.set({.holder = cindy, .flags = tfMPTLock, .err = tecNO_DST}); } - if (features[featureSingleAssetVault] && - features[featurePermissionedDomains]) + if (features[featureSingleAssetVault] && features[featurePermissionedDomains]) { // Add permissioned domain Account const credIssuer1{"credIssuer1"}; std::string const credType = "credential"; - pdomain::Credentials const credentials1{ - {.issuer = credIssuer1, .credType = credType}}; + pdomain::Credentials const credentials1{{.issuer = credIssuer1, .credType = credType}}; { Env env{*this, features}; @@ -726,11 +606,9 @@ class MPToken_test : public beast::unit_test::suite mptAlice.create({}); // Trying to set DomainID on a public MPTokenIssuance - mptAlice.set( - {.domainID = uint256(42), .err = tecNO_PERMISSION}); + mptAlice.set({.domainID = uint256(42), .err = tecNO_PERMISSION}); - mptAlice.set( - {.domainID = beast::zero, .err = tecNO_PERMISSION}); + mptAlice.set({.domainID = beast::zero, .err = tecNO_PERMISSION}); } { @@ -740,19 +618,12 @@ class MPToken_test : public beast::unit_test::suite mptAlice.create({.flags = tfMPTRequireAuth}); // Trying to set non-existing DomainID - mptAlice.set( - {.domainID = uint256(42), .err = tecOBJECT_NOT_FOUND}); + mptAlice.set({.domainID = uint256(42), .err = tecOBJECT_NOT_FOUND}); // Trying to lock but locking is disabled - mptAlice.set( - {.flags = tfMPTUnlock, - .domainID = uint256(42), - .err = tecNO_PERMISSION}); + mptAlice.set({.flags = tfMPTUnlock, .domainID = uint256(42), .err = tecNO_PERMISSION}); - mptAlice.set( - {.flags = tfMPTUnlock, - .domainID = beast::zero, - .err = tecNO_PERMISSION}); + mptAlice.set({.flags = tfMPTUnlock, .domainID = beast::zero, .err = tecNO_PERMISSION}); } } } @@ -773,8 +644,7 @@ class MPToken_test : public beast::unit_test::suite MPTTester mptAlice(env, alice, {.holders = {bob}}); // create a mptokenissuance with locking - mptAlice.create( - {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanLock}); + mptAlice.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanLock}); mptAlice.authorize({.account = bob, .holderCount = 1}); @@ -794,43 +664,33 @@ class MPToken_test : public beast::unit_test::suite mptAlice.set({.account = alice, .holder = bob, .flags = tfMPTLock}); // alice unlocks bob's mptoken - mptAlice.set( - {.account = alice, .holder = bob, .flags = tfMPTUnlock}); + mptAlice.set({.account = alice, .holder = bob, .flags = tfMPTUnlock}); // locks up bob's mptoken again mptAlice.set({.account = alice, .holder = bob, .flags = tfMPTLock}); if (!features[featureSingleAssetVault]) { - // Delete bobs' mptoken even though it is locked + // Delete bob's mptoken even though it is locked mptAlice.authorize({.account = bob, .flags = tfMPTUnauthorize}); - mptAlice.set( - {.account = alice, - .holder = bob, - .flags = tfMPTUnlock, - .err = tecOBJECT_NOT_FOUND}); + mptAlice.set({.account = alice, .holder = bob, .flags = tfMPTUnlock, .err = tecOBJECT_NOT_FOUND}); return; } // Cannot delete locked MPToken - mptAlice.authorize( - {.account = bob, - .flags = tfMPTUnauthorize, - .err = tecNO_PERMISSION}); + mptAlice.authorize({.account = bob, .flags = tfMPTUnauthorize, .err = tecNO_PERMISSION}); // alice unlocks mptissuance mptAlice.set({.account = alice, .flags = tfMPTUnlock}); // alice unlocks bob's mptoken - mptAlice.set( - {.account = alice, .holder = bob, .flags = tfMPTUnlock}); + mptAlice.set({.account = alice, .holder = bob, .flags = tfMPTUnlock}); // alice unlocks mptissuance and bob's mptoken again despite that // they are already unlocked. Make sure this will not change the // flags - mptAlice.set( - {.account = alice, .holder = bob, .flags = tfMPTUnlock}); + mptAlice.set({.account = alice, .holder = bob, .flags = tfMPTUnlock}); mptAlice.set({.account = alice, .flags = tfMPTUnlock}); } @@ -846,8 +706,7 @@ class MPToken_test : public beast::unit_test::suite Account const credIssuer1{"credIssuer1"}; env.fund(XRP(1000), credIssuer1); - pdomain::Credentials const credentials1{ - {.issuer = credIssuer1, .credType = credType}}; + pdomain::Credentials const credentials1{{.issuer = credIssuer1, .credType = credType}}; env(pdomain::setTx(credIssuer1, credentials1)); return [&]() { @@ -860,8 +719,7 @@ class MPToken_test : public beast::unit_test::suite Account const credIssuer2{"credIssuer2"}; env.fund(XRP(1000), credIssuer2); - pdomain::Credentials const credentials2{ - {.issuer = credIssuer2, .credType = credType}}; + pdomain::Credentials const credentials2{{.issuer = credIssuer2, .credType = credType}}; env(pdomain::setTx(credIssuer2, credentials2)); return [&]() { @@ -873,8 +731,7 @@ class MPToken_test : public beast::unit_test::suite MPTTester mptAlice(env, alice, {.holders = {bob}}); // create a mptokenissuance with auth. - mptAlice.create( - {.ownerCount = 1, .holderCount = 0, .flags = tfMPTRequireAuth}); + mptAlice.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTRequireAuth}); BEAST_EXPECT(mptAlice.checkDomainID(std::nullopt)); // reset "domain not set" to "domain not set", i.e. no change @@ -951,9 +808,7 @@ class MPToken_test : public beast::unit_test::suite mptAlice.authorize({.account = bob}); for (auto flags : {tfNoRippleDirect, tfLimitQuality}) - env(pay(alice, bob, MPT(10)), - txflags(flags), - ter(temINVALID_FLAG)); + env(pay(alice, bob, MPT(10)), txflags(flags), ter(temINVALID_FLAG)); } // Invalid combination of send, sendMax, deliverMin, paths @@ -971,32 +826,17 @@ class MPToken_test : public beast::unit_test::suite // sendMax and DeliverMin are valid XRP amount, // but is invalid combination with MPT amount auto const MPT = mptAlice["MPT"]; - env(pay(alice, carol, MPT(100)), - sendmax(XRP(100)), - ter(temMALFORMED)); - env(pay(alice, carol, MPT(100)), - deliver_min(XRP(100)), - ter(temBAD_AMOUNT)); + env(pay(alice, carol, MPT(100)), sendmax(XRP(100)), ter(temMALFORMED)); + env(pay(alice, carol, MPT(100)), deliver_min(XRP(100)), ter(temBAD_AMOUNT)); // sendMax MPT is invalid with IOU or XRP auto const USD = alice["USD"]; - env(pay(alice, carol, USD(100)), - sendmax(MPT(100)), - ter(temMALFORMED)); - env(pay(alice, carol, XRP(100)), - sendmax(MPT(100)), - ter(temMALFORMED)); - env(pay(alice, carol, USD(100)), - deliver_min(MPT(100)), - ter(temBAD_AMOUNT)); - env(pay(alice, carol, XRP(100)), - deliver_min(MPT(100)), - ter(temBAD_AMOUNT)); + env(pay(alice, carol, USD(100)), sendmax(MPT(100)), ter(temMALFORMED)); + env(pay(alice, carol, XRP(100)), sendmax(MPT(100)), ter(temMALFORMED)); + env(pay(alice, carol, USD(100)), deliver_min(MPT(100)), ter(temBAD_AMOUNT)); + env(pay(alice, carol, XRP(100)), deliver_min(MPT(100)), ter(temBAD_AMOUNT)); // sendmax and amount are different MPT issue - test::jtx::MPT const MPT1( - "MPT", makeMptID(env.seq(alice) + 10, alice)); - env(pay(alice, carol, MPT1(100)), - sendmax(MPT(100)), - ter(temMALFORMED)); + test::jtx::MPT const MPT1("MPT", makeMptID(env.seq(alice) + 10, alice)); + env(pay(alice, carol, MPT1(100)), sendmax(MPT(100)), ter(temMALFORMED)); // paths is invalid env(pay(alice, carol, MPT(100)), path(~USD), ter(temMALFORMED)); } @@ -1021,9 +861,7 @@ class MPToken_test : public beast::unit_test::suite payment[jss::build_path] = true; auto jrr = env.rpc("json", "submit", to_string(payment)); BEAST_EXPECT(jrr[jss::result][jss::error] == "invalidParams"); - BEAST_EXPECT( - jrr[jss::result][jss::error_message] == - "Field 'build_path' not allowed in this context."); + BEAST_EXPECT(jrr[jss::result][jss::error_message] == "Field 'build_path' not allowed in this context."); } // Can't pay negative amount @@ -1087,10 +925,7 @@ class MPToken_test : public beast::unit_test::suite MPTTester mptAlice(env, alice, {.holders = {bob}}); - mptAlice.create( - {.ownerCount = 1, - .holderCount = 0, - .flags = tfMPTRequireAuth | tfMPTCanTransfer}); + mptAlice.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTRequireAuth | tfMPTCanTransfer}); mptAlice.authorize({.account = bob}); @@ -1104,10 +939,7 @@ class MPToken_test : public beast::unit_test::suite MPTTester mptAlice(env, alice, {.holders = {bob}}); - mptAlice.create( - {.ownerCount = 1, - .holderCount = 0, - .flags = tfMPTRequireAuth | tfMPTCanTransfer}); + mptAlice.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTRequireAuth | tfMPTCanTransfer}); // bob creates an empty MPToken mptAlice.authorize({.account = bob}); @@ -1119,16 +951,14 @@ class MPToken_test : public beast::unit_test::suite mptAlice.pay(alice, bob, 100); // alice UNAUTHORIZES bob - mptAlice.authorize( - {.account = alice, .holder = bob, .flags = tfMPTUnauthorize}); + mptAlice.authorize({.account = alice, .holder = bob, .flags = tfMPTUnauthorize}); // bob fails to send back to alice because he is no longer // authorize to move his funds! mptAlice.pay(bob, alice, 100, tecNO_AUTH); } - if (features[featureSingleAssetVault] && - features[featurePermissionedDomains]) + if (features[featureSingleAssetVault] && features[featurePermissionedDomains]) { // If RequireAuth is enabled and domain is a match, payment succeeds { @@ -1138,8 +968,7 @@ class MPToken_test : public beast::unit_test::suite env.fund(XRP(1000), credIssuer1, bob); auto const domainId1 = [&]() { - pdomain::Credentials const credentials1{ - {.issuer = credIssuer1, .credType = credType}}; + pdomain::Credentials const credentials1{{.issuer = credIssuer1, .credType = credType}}; env(pdomain::setTx(credIssuer1, credentials1)); return [&]() { @@ -1180,8 +1009,7 @@ class MPToken_test : public beast::unit_test::suite env.fund(XRP(1000), credIssuer1, bob); auto const domainId1 = [&]() { - pdomain::Credentials const credentials1{ - {.issuer = credIssuer1, .credType = credType}}; + pdomain::Credentials const credentials1{{.issuer = credIssuer1, .credType = credType}}; env(pdomain::setTx(credIssuer1, credentials1)); return [&]() { @@ -1214,10 +1042,7 @@ class MPToken_test : public beast::unit_test::suite mptAlice.pay(alice, bob, 100); // alice UNAUTHORIZES bob - mptAlice.authorize( - {.account = alice, - .holder = bob, - .flags = tfMPTUnauthorize}); + mptAlice.authorize({.account = alice, .holder = bob, .flags = tfMPTUnauthorize}); // bob is still authorized, via domain mptAlice.pay(bob, alice, 10); @@ -1240,8 +1065,7 @@ class MPToken_test : public beast::unit_test::suite env.fund(XRP(1000), credIssuer1, credIssuer2, bob, carol); auto const domainId1 = [&]() { - pdomain::Credentials const credentials{ - {.issuer = credIssuer1, .credType = credType}}; + pdomain::Credentials const credentials{{.issuer = credIssuer1, .credType = credType}}; env(pdomain::setTx(credIssuer1, credentials)); return [&]() { @@ -1252,8 +1076,7 @@ class MPToken_test : public beast::unit_test::suite auto const domainId2 = [&]() { pdomain::Credentials const credentials{ - {.issuer = credIssuer1, .credType = credType}, - {.issuer = credIssuer2, .credType = credType}}; + {.issuer = credIssuer1, .credType = credType}, {.issuer = credIssuer2, .credType = credType}}; env(pdomain::setTx(credIssuer2, credentials)); return [&]() { @@ -1312,8 +1135,7 @@ class MPToken_test : public beast::unit_test::suite env.close(); // bob loses his authorization and can no longer send MPT - env(credentials::deleteCred( - credIssuer1, bob, credIssuer1, credType)); + env(credentials::deleteCred(credIssuer1, bob, credIssuer1, credType)); env.close(); mptAlice.pay(bob, carol, 10, tecNO_AUTH); @@ -1356,8 +1178,7 @@ class MPToken_test : public beast::unit_test::suite MPTTester mptAlice(env, alice, {.holders = {bob, carol}}); - mptAlice.create( - {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer}); + mptAlice.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer}); // issuer to holder mptAlice.pay(alice, bob, 100, tecNO_AUTH); @@ -1395,8 +1216,7 @@ class MPToken_test : public beast::unit_test::suite MPTTester mptAlice(env, alice, {.holders = {bob, carol}}); - mptAlice.create( - {.ownerCount = 1, .flags = tfMPTCanLock | tfMPTCanTransfer}); + mptAlice.create({.ownerCount = 1, .flags = tfMPTCanLock | tfMPTCanTransfer}); mptAlice.authorize({.account = bob}); mptAlice.authorize({.account = carol}); @@ -1434,11 +1254,7 @@ class MPToken_test : public beast::unit_test::suite MPTTester mptAlice(env, alice, {.holders = {bob, carol}}); // Transfer fee is 10% - mptAlice.create( - {.transferFee = 10'000, - .ownerCount = 1, - .holderCount = 0, - .flags = tfMPTCanTransfer}); + mptAlice.create({.transferFee = 10'000, .ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer}); // Holders create MPToken mptAlice.authorize({.account = bob}); @@ -1461,9 +1277,7 @@ class MPToken_test : public beast::unit_test::suite auto const MPT = mptAlice["MPT"]; // SendMax doesn't cover the fee - env(pay(bob, carol, MPT(100)), - sendmax(MPT(109)), - ter(tecPATH_PARTIAL)); + env(pay(bob, carol, MPT(100)), sendmax(MPT(109)), ter(tecPATH_PARTIAL)); // Payment succeeds if sufficient SendMax is included. // 100 to carol, 10 to issuer @@ -1474,9 +1288,7 @@ class MPToken_test : public beast::unit_test::suite BEAST_EXPECT(mptAlice.checkMPTokenAmount(carol, 200)); // Payment succeeds if partial payment even if // SendMax is less than deliver amount - env(pay(bob, carol, MPT(100)), - sendmax(MPT(90)), - txflags(tfPartialPayment)); + env(pay(bob, carol, MPT(100)), sendmax(MPT(90)), txflags(tfPartialPayment)); // 82 to carol, 8 to issuer (90 / 1.1 ~ 81.81 (rounded to nearest) = // 82) BEAST_EXPECT(mptAlice.checkMPTokenAmount(bob, 690)); @@ -1489,8 +1301,7 @@ class MPToken_test : public beast::unit_test::suite MPTTester mptAlice(env, alice, {.holders = {bob, carol}}); - mptAlice.create( - {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer}); + mptAlice.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer}); // Holders create MPToken mptAlice.authorize({.account = bob}); @@ -1499,20 +1310,14 @@ class MPToken_test : public beast::unit_test::suite auto const MPT = mptAlice["MPT"]; // SendMax is less than the amount - env(pay(bob, carol, MPT(100)), - sendmax(MPT(99)), - ter(tecPATH_PARTIAL)); - env(pay(bob, alice, MPT(100)), - sendmax(MPT(99)), - ter(tecPATH_PARTIAL)); + env(pay(bob, carol, MPT(100)), sendmax(MPT(99)), ter(tecPATH_PARTIAL)); + env(pay(bob, alice, MPT(100)), sendmax(MPT(99)), ter(tecPATH_PARTIAL)); // Payment succeeds if sufficient SendMax is included. env(pay(bob, carol, MPT(100)), sendmax(MPT(100))); BEAST_EXPECT(mptAlice.checkMPTokenAmount(carol, 100)); // Payment succeeds if partial payment - env(pay(bob, carol, MPT(100)), - sendmax(MPT(99)), - txflags(tfPartialPayment)); + env(pay(bob, carol, MPT(100)), sendmax(MPT(99)), txflags(tfPartialPayment)); BEAST_EXPECT(mptAlice.checkMPTokenAmount(carol, 199)); } @@ -1522,8 +1327,7 @@ class MPToken_test : public beast::unit_test::suite MPTTester mptAlice(env, alice, {.holders = {bob, carol}}); - mptAlice.create( - {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer}); + mptAlice.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer}); // Holders create MPToken mptAlice.authorize({.account = bob}); @@ -1539,10 +1343,7 @@ class MPToken_test : public beast::unit_test::suite txflags(tfPartialPayment), ter(tecPATH_PARTIAL)); // Payment succeeds if deliver amount >= deliverMin - env(pay(bob, alice, MPT(100)), - sendmax(MPT(99)), - deliver_min(MPT(99)), - txflags(tfPartialPayment)); + env(pay(bob, alice, MPT(100)), sendmax(MPT(99)), deliver_min(MPT(99)), txflags(tfPartialPayment)); } // Issuer fails trying to send more than the maximum amount allowed @@ -1551,11 +1352,7 @@ class MPToken_test : public beast::unit_test::suite MPTTester mptAlice(env, alice, {.holders = {bob}}); - mptAlice.create( - {.maxAmt = 100, - .ownerCount = 1, - .holderCount = 0, - .flags = tfMPTCanTransfer}); + mptAlice.create({.maxAmt = 100, .ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer}); mptAlice.authorize({.account = bob}); @@ -1593,8 +1390,7 @@ class MPToken_test : public beast::unit_test::suite Json::Value jv; jv[jss::secret] = alice.name(); jv[jss::tx_json] = pay(alice, bob, mpt); - jv[jss::tx_json][jss::Amount][jss::value] = - std::to_string(maxMPTokenAmount + 1); + jv[jss::tx_json][jss::Amount][jss::value] = std::to_string(maxMPTokenAmount + 1); auto const jrr = env.rpc("json", "submit", to_string(jv)); BEAST_EXPECT(jrr[jss::result][jss::error] == "invalidParams"); } @@ -1607,11 +1403,7 @@ class MPToken_test : public beast::unit_test::suite MPTTester mptAlice(env, alice, {.holders = {bob, carol}}); mptAlice.create( - {.maxAmt = 10'000, - .transferFee = 100, - .ownerCount = 1, - .holderCount = 0, - .flags = tfMPTCanTransfer}); + {.maxAmt = 10'000, .transferFee = 100, .ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer}); auto const MPT = mptAlice["MPT"]; mptAlice.authorize({.account = bob}); @@ -1621,33 +1413,22 @@ class MPToken_test : public beast::unit_test::suite mptAlice.pay(alice, bob, 10'000); // payment between the holders - env(pay(bob, carol, MPT(10'000)), - sendmax(MPT(10'000)), - txflags(tfPartialPayment)); + env(pay(bob, carol, MPT(10'000)), sendmax(MPT(10'000)), txflags(tfPartialPayment)); // Verify the metadata - auto const meta = env.meta()->getJson( - JsonOptions::none)[sfAffectedNodes.fieldName]; + auto const meta = env.meta()->getJson(JsonOptions::none)[sfAffectedNodes.fieldName]; // Issuer got 10 in the transfer fees BEAST_EXPECT( - meta[0u][sfModifiedNode.fieldName][sfFinalFields.fieldName] - [sfOutstandingAmount.fieldName] == "9990"); + meta[0u][sfModifiedNode.fieldName][sfFinalFields.fieldName][sfOutstandingAmount.fieldName] == "9990"); // Destination account got 9'990 - BEAST_EXPECT( - meta[1u][sfModifiedNode.fieldName][sfFinalFields.fieldName] - [sfMPTAmount.fieldName] == "9990"); + BEAST_EXPECT(meta[1u][sfModifiedNode.fieldName][sfFinalFields.fieldName][sfMPTAmount.fieldName] == "9990"); // Source account spent 10'000 BEAST_EXPECT( - meta[2u][sfModifiedNode.fieldName][sfPreviousFields.fieldName] - [sfMPTAmount.fieldName] == "10000"); - BEAST_EXPECT( - !meta[2u][sfModifiedNode.fieldName][sfFinalFields.fieldName] - .isMember(sfMPTAmount.fieldName)); + meta[2u][sfModifiedNode.fieldName][sfPreviousFields.fieldName][sfMPTAmount.fieldName] == "10000"); + BEAST_EXPECT(!meta[2u][sfModifiedNode.fieldName][sfFinalFields.fieldName].isMember(sfMPTAmount.fieldName)); // payment between the holders fails without // partial payment - env(pay(bob, carol, MPT(10'000)), - sendmax(MPT(10'000)), - ter(tecPATH_PARTIAL)); + env(pay(bob, carol, MPT(10'000)), sendmax(MPT(10'000)), ter(tecPATH_PARTIAL)); } // Pay maximum allowed amount @@ -1656,11 +1437,7 @@ class MPToken_test : public beast::unit_test::suite MPTTester mptAlice(env, alice, {.holders = {bob, carol}}); - mptAlice.create( - {.maxAmt = maxMPTokenAmount, - .ownerCount = 1, - .holderCount = 0, - .flags = tfMPTCanTransfer}); + mptAlice.create({.maxAmt = maxMPTokenAmount, .ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer}); auto const MPT = mptAlice["MPT"]; mptAlice.authorize({.account = bob}); @@ -1668,13 +1445,11 @@ class MPToken_test : public beast::unit_test::suite // issuer sends holder the max amount allowed mptAlice.pay(alice, bob, maxMPTokenAmount); - BEAST_EXPECT( - mptAlice.checkMPTokenOutstandingAmount(maxMPTokenAmount)); + BEAST_EXPECT(mptAlice.checkMPTokenOutstandingAmount(maxMPTokenAmount)); // payment between the holders mptAlice.pay(bob, carol, maxMPTokenAmount); - BEAST_EXPECT( - mptAlice.checkMPTokenOutstandingAmount(maxMPTokenAmount)); + BEAST_EXPECT(mptAlice.checkMPTokenOutstandingAmount(maxMPTokenAmount)); // holder pays back to the issuer mptAlice.pay(carol, alice, maxMPTokenAmount); BEAST_EXPECT(mptAlice.checkMPTokenOutstandingAmount(0)); @@ -1735,8 +1510,7 @@ class MPToken_test : public beast::unit_test::suite MPTTester mptAlice(env, alice, {.holders = {bob, carol}}); - mptAlice.create( - {.maxAmt = 100, .ownerCount = 1, .flags = tfMPTCanTransfer}); + mptAlice.create({.maxAmt = 100, .ownerCount = 1, .flags = tfMPTCanTransfer}); mptAlice.authorize({.account = bob}); mptAlice.authorize({.account = carol}); @@ -1753,8 +1527,7 @@ class MPToken_test : public beast::unit_test::suite MPTTester mptAlice(env, alice, {.holders = {bob, carol}}); - mptAlice.create( - {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer}); + mptAlice.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer}); mptAlice.authorize({.account = bob}); mptAlice.authorize({.account = carol}); @@ -1792,10 +1565,7 @@ class MPToken_test : public beast::unit_test::suite env.close(); MPTTester mptAlice(env, alice, {.holders = {bob}}); - mptAlice.create( - {.ownerCount = 1, - .holderCount = 0, - .flags = tfMPTRequireAuth | tfMPTCanTransfer}); + mptAlice.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTRequireAuth | tfMPTCanTransfer}); env(pay(diana, bob, XRP(500))); env.close(); @@ -1826,8 +1596,7 @@ class MPToken_test : public beast::unit_test::suite env.close(); env(credentials::accept(alice, dpIssuer, credType)); env.close(); - auto const jv = - credentials::ledgerEntry(env, alice, dpIssuer, credType); + auto const jv = credentials::ledgerEntry(env, alice, dpIssuer, credType); std::string const credIdx = jv[jss::result][jss::index].asString(); // alice sends 100 MPT to bob with credentials which aren't required @@ -1871,10 +1640,7 @@ class MPToken_test : public beast::unit_test::suite env.close(); MPTTester mptAlice(env, alice, {.holders = {bob}}); - mptAlice.create( - {.ownerCount = 1, - .holderCount = 0, - .flags = tfMPTRequireAuth | tfMPTCanTransfer}); + mptAlice.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTRequireAuth | tfMPTCanTransfer}); env(pay(diana, bob, XRP(500))); env.close(); @@ -1941,12 +1707,10 @@ class MPToken_test : public beast::unit_test::suite // Transaction has amount/issue fields. // Exclude pseudo-transaction SetFee. Don't consider // the Fee field since it's included in every transaction. - if (e.supportMPT() == soeMPTNotSupported && - e.sField().getName() != jss::Fee && + if (e.supportMPT() == soeMPTNotSupported && e.sField().getName() != jss::Fee && format.getName() != jss::SetFee) { - txWithAmounts.insert( - format.getName() + e.sField().fieldName); + txWithAmounts.insert(format.getName() + e.sField().fieldName); break; } } @@ -1963,18 +1727,15 @@ class MPToken_test : public beast::unit_test::suite Env env{*this, feature}; env.fund(XRP(1'000), alice); env.fund(XRP(1'000), carol); - auto test = [&](Json::Value const& jv, - std::string const& mptField) { - txWithAmounts.erase( - jv[jss::TransactionType].asString() + mptField); + auto test = [&](Json::Value const& jv, std::string const& mptField) { + txWithAmounts.erase(jv[jss::TransactionType].asString() + mptField); // tx is signed auto jtx = env.jt(jv); Serializer s; jtx.stx->add(s); auto jrr = env.rpc("submit", strHex(s.slice())); - BEAST_EXPECT( - jrr[jss::result][jss::error] == "invalidTransaction"); + BEAST_EXPECT(jrr[jss::result][jss::error] == "invalidTransaction"); // tx is unsigned Json::Value jv1; @@ -1986,17 +1747,12 @@ class MPToken_test : public beast::unit_test::suite jrr = env.rpc("json", "sign", to_string(jv1)); BEAST_EXPECT(jrr[jss::result][jss::error] == "invalidParams"); }; - auto toSFieldRef = [](SField const& field) { - return std::ref(field); - }; - auto setMPTFields = [&](SField const& field, - Json::Value& jv, - bool withAmount = true) { + auto toSFieldRef = [](SField const& field) { return std::ref(field); }; + auto setMPTFields = [&](SField const& field, Json::Value& jv, bool withAmount = true) { jv[jss::Asset] = to_json(xrpIssue()); jv[jss::Asset2] = to_json(USD.issue()); if (withAmount) - jv[field.fieldName] = - USD(10).value().getJson(JsonOptions::none); + jv[field.fieldName] = USD(10).value().getJson(JsonOptions::none); if (field == sfAsset) jv[jss::Asset] = to_json(mpt.get()); else if (field == sfAsset2) @@ -2013,12 +1769,10 @@ class MPToken_test : public beast::unit_test::suite Json::Value jv; jv[jss::TransactionType] = jss::AMMCreate; jv[jss::Account] = alice.human(); - jv[jss::Amount] = (field.fieldName == sfAmount.fieldName) - ? mpt.getJson(JsonOptions::none) - : "100000000"; - jv[jss::Amount2] = (field.fieldName == sfAmount2.fieldName) - ? mpt.getJson(JsonOptions::none) - : "100000000"; + jv[jss::Amount] = + (field.fieldName == sfAmount.fieldName) ? mpt.getJson(JsonOptions::none) : "100000000"; + jv[jss::Amount2] = + (field.fieldName == sfAmount2.fieldName) ? mpt.getJson(JsonOptions::none) : "100000000"; jv[jss::TradingFee] = 0; test(jv, field.fieldName); }; @@ -2067,10 +1821,7 @@ class MPToken_test : public beast::unit_test::suite test(jv, field.fieldName); }; for (SField const& field : - {toSFieldRef(sfBidMin), - toSFieldRef(sfBidMax), - toSFieldRef(sfAsset), - toSFieldRef(sfAsset2)}) + {toSFieldRef(sfBidMin), toSFieldRef(sfBidMax), toSFieldRef(sfAsset), toSFieldRef(sfAsset2)}) ammBid(field); // AMMClawback auto ammClawback = [&](SField const& field) { @@ -2081,10 +1832,7 @@ class MPToken_test : public beast::unit_test::suite setMPTFields(field, jv); test(jv, field.fieldName); }; - for (SField const& field : - {toSFieldRef(sfAmount), - toSFieldRef(sfAsset), - toSFieldRef(sfAsset2)}) + for (SField const& field : {toSFieldRef(sfAmount), toSFieldRef(sfAsset), toSFieldRef(sfAsset2)}) ammClawback(field); // AMMDelete auto ammDelete = [&](SField const& field) { @@ -2177,8 +1925,7 @@ class MPToken_test : public beast::unit_test::suite Json::Value jv; jv[jss::TransactionType] = jss::NFTokenAcceptOffer; jv[jss::Account] = alice.human(); - jv[sfNFTokenBrokerFee.fieldName] = - mpt.getJson(JsonOptions::none); + jv[sfNFTokenBrokerFee.fieldName] = mpt.getJson(JsonOptions::none); test(jv, sfNFTokenBrokerFee.fieldName); } // NFTokenMint @@ -2213,39 +1960,19 @@ class MPToken_test : public beast::unit_test::suite } // XChainCreateClaimID { - Json::Value const jv = - xchain_create_claim_id(alice, jvb, mpt, alice); + Json::Value const jv = xchain_create_claim_id(alice, jvb, mpt, alice); test(jv, sfSignatureReward.fieldName); } // XChainAddClaimAttestation { - Json::Value const jv = claim_attestation( - alice, - jvb, - alice, - mpt, - alice, - true, - 1, - alice, - signer(alice)); + Json::Value const jv = claim_attestation(alice, jvb, alice, mpt, alice, true, 1, alice, signer(alice)); test(jv, jss::Amount.c_str()); } // XChainAddAccountCreateAttestation { - Json::Value jv = create_account_attestation( - alice, - jvb, - alice, - mpt, - XRP(10), - alice, - false, - 1, - alice, - signer(alice)); - for (auto const& field : - {sfAmount.fieldName, sfSignatureReward.fieldName}) + Json::Value jv = + create_account_attestation(alice, jvb, alice, mpt, XRP(10), alice, false, 1, alice, signer(alice)); + for (auto const& field : {sfAmount.fieldName, sfSignatureReward.fieldName}) { jv[field] = mpt.getJson(JsonOptions::none); test(jv, field); @@ -2253,10 +1980,8 @@ class MPToken_test : public beast::unit_test::suite } // XChainAccountCreateCommit { - Json::Value jv = sidechain_xchain_account_create( - alice, jvb, alice, mpt, XRP(10)); - for (auto const& field : - {sfAmount.fieldName, sfSignatureReward.fieldName}) + Json::Value jv = sidechain_xchain_account_create(alice, jvb, alice, mpt, XRP(10)); + for (auto const& field : {sfAmount.fieldName, sfSignatureReward.fieldName}) { jv[field] = mpt.getJson(JsonOptions::none); test(jv, field); @@ -2271,28 +1996,16 @@ class MPToken_test : public beast::unit_test::suite jv[jss::TransactionType] = tt; jv[jss::Account] = alice.human(); jv[sfXChainBridge.fieldName] = jvb; - jv[sfSignatureReward.fieldName] = - rewardAmount.getJson(JsonOptions::none); - jv[sfMinAccountCreateAmount.fieldName] = - minAccountAmount.getJson(JsonOptions::none); + jv[sfSignatureReward.fieldName] = rewardAmount.getJson(JsonOptions::none); + jv[sfMinAccountCreateAmount.fieldName] = minAccountAmount.getJson(JsonOptions::none); test(jv, field); }; auto reward = STAmount{sfSignatureReward, mpt}; auto minAmount = STAmount{sfMinAccountCreateAmount, USD(10)}; - for (SField const& field : - {std::ref(sfSignatureReward), - std::ref(sfMinAccountCreateAmount)}) + for (SField const& field : {std::ref(sfSignatureReward), std::ref(sfMinAccountCreateAmount)}) { - bridgeTx( - jss::XChainCreateBridge, - reward, - minAmount, - field.fieldName); - bridgeTx( - jss::XChainModifyBridge, - reward, - minAmount, - field.fieldName); + bridgeTx(jss::XChainCreateBridge, reward, minAmount, field.fieldName); + bridgeTx(jss::XChainModifyBridge, reward, minAmount, field.fieldName); reward = STAmount{sfSignatureReward, USD(10)}; minAmount = STAmount{sfMinAccountCreateAmount, mpt}; } @@ -2317,8 +2030,7 @@ class MPToken_test : public beast::unit_test::suite mptAlice.create(); - std::string const txHash{ - env.tx()->getJson(JsonOptions::none)[jss::hash].asString()}; + std::string const txHash{env.tx()->getJson(JsonOptions::none)[jss::hash].asString()}; BEAST_EXPECTS( txHash == "E11F0E0CA14219922B7881F060B9CEE67CFBC87E4049A441ED2AE348FF8FAC" @@ -2329,8 +2041,7 @@ class MPToken_test : public beast::unit_test::suite // Expect mpt_issuance_id field BEAST_EXPECT(meta.isMember(jss::mpt_issuance_id)); BEAST_EXPECT(id == to_string(mptAlice.issuanceID())); - BEAST_EXPECTS( - id == "00000004AE123A8556F3CF91154711376AFB0F894F832B3D", id); + BEAST_EXPECTS(id == "00000004AE123A8556F3CF91154711376AFB0F894F832B3D", id); } void @@ -2349,8 +2060,7 @@ class MPToken_test : public beast::unit_test::suite env.close(); auto const USD = alice["USD"]; - auto const mpt = xrpl::test::jtx::MPT( - alice.name(), makeMptID(env.seq(alice), alice)); + auto const mpt = xrpl::test::jtx::MPT(alice.name(), makeMptID(env.seq(alice), alice)); env(claw(alice, bob["USD"](5), bob), ter(temMALFORMED)); env.close(); @@ -2372,8 +2082,7 @@ class MPToken_test : public beast::unit_test::suite env.close(); auto const USD = alice["USD"]; - auto const mpt = xrpl::test::jtx::MPT( - alice.name(), makeMptID(env.seq(alice), alice)); + auto const mpt = xrpl::test::jtx::MPT(alice.name(), makeMptID(env.seq(alice), alice)); // clawing back IOU from a MPT holder fails env(claw(alice, bob["USD"](5), bob), ter(temMALFORMED)); @@ -2431,16 +2140,14 @@ class MPToken_test : public beast::unit_test::suite env.close(); MPTTester mptAlice(env, alice, {.holders = {bob}}); - auto const fakeMpt = xrpl::test::jtx::MPT( - alice.name(), makeMptID(env.seq(alice), alice)); + auto const fakeMpt = xrpl::test::jtx::MPT(alice.name(), makeMptID(env.seq(alice), alice)); // issuer tries to clawback MPT where issuance doesn't exist env(claw(alice, fakeMpt(5), bob), ter(tecOBJECT_NOT_FOUND)); env.close(); // alice creates issuance - mptAlice.create( - {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanClawback}); + mptAlice.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanClawback}); // alice tries to clawback from someone who doesn't have MPToken mptAlice.claw(alice, bob, 1, tecOBJECT_NOT_FOUND); @@ -2470,8 +2177,7 @@ class MPToken_test : public beast::unit_test::suite env.fund(XRP(1000), alice, bob); env.close(); - auto const mpt = xrpl::test::jtx::MPT( - alice.name(), makeMptID(env.seq(alice), alice)); + auto const mpt = xrpl::test::jtx::MPT(alice.name(), makeMptID(env.seq(alice), alice)); Json::Value jv = claw(alice, mpt(1), bob); jv[jss::Amount][jss::value] = std::to_string(maxMPTokenAmount + 1); @@ -2497,8 +2203,7 @@ class MPToken_test : public beast::unit_test::suite MPTTester mptAlice(env, alice, {.holders = {bob}}); // alice creates issuance - mptAlice.create( - {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanClawback}); + mptAlice.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanClawback}); // bob creates a MPToken mptAlice.authorize({.account = bob}); @@ -2523,10 +2228,7 @@ class MPToken_test : public beast::unit_test::suite MPTTester mptAlice(env, alice, {.holders = {bob}}); // alice creates issuance - mptAlice.create( - {.ownerCount = 1, - .holderCount = 0, - .flags = tfMPTCanLock | tfMPTCanClawback}); + mptAlice.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanLock | tfMPTCanClawback}); // bob creates a MPToken mptAlice.authorize({.account = bob}); @@ -2548,10 +2250,7 @@ class MPToken_test : public beast::unit_test::suite MPTTester mptAlice(env, alice, {.holders = {bob}}); // alice creates issuance - mptAlice.create( - {.ownerCount = 1, - .holderCount = 0, - .flags = tfMPTCanLock | tfMPTCanClawback}); + mptAlice.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanLock | tfMPTCanClawback}); // bob creates a MPToken mptAlice.authorize({.account = bob}); @@ -2573,10 +2272,7 @@ class MPToken_test : public beast::unit_test::suite MPTTester mptAlice(env, alice, {.holders = {bob}}); // alice creates issuance - mptAlice.create( - {.ownerCount = 1, - .holderCount = 0, - .flags = tfMPTCanClawback | tfMPTRequireAuth}); + mptAlice.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanClawback | tfMPTRequireAuth}); // bob creates a MPToken mptAlice.authorize({.account = bob}); @@ -2588,8 +2284,7 @@ class MPToken_test : public beast::unit_test::suite mptAlice.pay(alice, bob, 100); // alice unauthorizes bob - mptAlice.authorize( - {.account = alice, .holder = bob, .flags = tfMPTUnauthorize}); + mptAlice.authorize({.account = alice, .holder = bob, .flags = tfMPTUnauthorize}); mptAlice.claw(alice, bob, 100); } @@ -2703,16 +2398,14 @@ class MPToken_test : public beast::unit_test::suite testcase("Test MPTIssue from/to Json"); MPTIssue const issue1{asset1.get()}; Json::Value const jv = to_json(issue1); - BEAST_EXPECT( - jv[jss::mpt_issuance_id] == to_string(asset1.get())); + BEAST_EXPECT(jv[jss::mpt_issuance_id] == to_string(asset1.get())); BEAST_EXPECT(issue1 == mptIssueFromJson(jv)); } { testcase("Test Asset from/to Json"); Json::Value const jv = to_json(asset1); - BEAST_EXPECT( - jv[jss::mpt_issuance_id] == to_string(asset1.get())); + BEAST_EXPECT(jv[jss::mpt_issuance_id] == to_string(asset1.get())); BEAST_EXPECT( to_string(jv) == "{\"mpt_issuance_id\":" @@ -2733,10 +2426,8 @@ class MPToken_test : public beast::unit_test::suite { Env env{*this, features - featureDynamicMPT}; MPTTester mptAlice(env, alice); - mptAlice.create( - {.ownerCount = 0, .mutableFlags = 2, .err = temDISABLED}); - mptAlice.create( - {.ownerCount = 0, .mutableFlags = 0, .err = temDISABLED}); + mptAlice.create({.ownerCount = 0, .mutableFlags = 2, .err = temDISABLED}); + mptAlice.create({.ownerCount = 0, .mutableFlags = 0, .err = temDISABLED}); } // MutableFlags contains invalid values @@ -2745,18 +2436,12 @@ class MPToken_test : public beast::unit_test::suite MPTTester mptAlice(env, alice); // Value 1 is reserved for MPT lock. - mptAlice.create( - {.ownerCount = 0, .mutableFlags = 1, .err = temINVALID_FLAG}); - mptAlice.create( - {.ownerCount = 0, .mutableFlags = 17, .err = temINVALID_FLAG}); - mptAlice.create( - {.ownerCount = 0, - .mutableFlags = 65535, - .err = temINVALID_FLAG}); + mptAlice.create({.ownerCount = 0, .mutableFlags = 1, .err = temINVALID_FLAG}); + mptAlice.create({.ownerCount = 0, .mutableFlags = 17, .err = temINVALID_FLAG}); + mptAlice.create({.ownerCount = 0, .mutableFlags = 65535, .err = temINVALID_FLAG}); // MutableFlags can not be 0 - mptAlice.create( - {.ownerCount = 0, .mutableFlags = 0, .err = temINVALID_FLAG}); + mptAlice.create({.ownerCount = 0, .mutableFlags = 0, .err = temINVALID_FLAG}); } } @@ -2777,40 +2462,16 @@ class MPToken_test : public beast::unit_test::suite auto const mptID = makeMptID(env.seq(alice), alice); // MutableFlags is not allowed when DynamicMPT is not enabled - mptAlice.set( - {.account = alice, - .id = mptID, - .mutableFlags = 2, - .err = temDISABLED}); - mptAlice.set( - {.account = alice, - .id = mptID, - .mutableFlags = 0, - .err = temDISABLED}); + mptAlice.set({.account = alice, .id = mptID, .mutableFlags = 2, .err = temDISABLED}); + mptAlice.set({.account = alice, .id = mptID, .mutableFlags = 0, .err = temDISABLED}); // MPTokenMetadata is not allowed when DynamicMPT is not enabled - mptAlice.set( - {.account = alice, - .id = mptID, - .metadata = "test", - .err = temDISABLED}); - mptAlice.set( - {.account = alice, - .id = mptID, - .metadata = "", - .err = temDISABLED}); + mptAlice.set({.account = alice, .id = mptID, .metadata = "test", .err = temDISABLED}); + mptAlice.set({.account = alice, .id = mptID, .metadata = "", .err = temDISABLED}); // TransferFee is not allowed when DynamicMPT is not enabled - mptAlice.set( - {.account = alice, - .id = mptID, - .transferFee = 100, - .err = temDISABLED}); - mptAlice.set( - {.account = alice, - .id = mptID, - .transferFee = 0, - .err = temDISABLED}); + mptAlice.set({.account = alice, .id = mptID, .transferFee = 100, .err = temDISABLED}); + mptAlice.set({.account = alice, .id = mptID, .transferFee = 0, .err = temDISABLED}); } // Can not provide holder when MutableFlags, MPTokenMetadata or @@ -2821,28 +2482,13 @@ class MPToken_test : public beast::unit_test::suite auto const mptID = makeMptID(env.seq(alice), alice); // Holder is not allowed when MutableFlags is present - mptAlice.set( - {.account = alice, - .holder = bob, - .id = mptID, - .mutableFlags = 2, - .err = temMALFORMED}); + mptAlice.set({.account = alice, .holder = bob, .id = mptID, .mutableFlags = 2, .err = temMALFORMED}); // Holder is not allowed when MPTokenMetadata is present - mptAlice.set( - {.account = alice, - .holder = bob, - .id = mptID, - .metadata = "test", - .err = temMALFORMED}); + mptAlice.set({.account = alice, .holder = bob, .id = mptID, .metadata = "test", .err = temMALFORMED}); // Holder is not allowed when TransferFee is present - mptAlice.set( - {.account = alice, - .holder = bob, - .id = mptID, - .transferFee = 100, - .err = temMALFORMED}); + mptAlice.set({.account = alice, .holder = bob, .id = mptID, .transferFee = 100, .err = temMALFORMED}); } // Can not set Flags when MutableFlags, MPTokenMetadata or @@ -2852,29 +2498,16 @@ class MPToken_test : public beast::unit_test::suite MPTTester mptAlice(env, alice, {.holders = {bob}}); mptAlice.create( {.ownerCount = 1, - .mutableFlags = tmfMPTCanMutateMetadata | - tmfMPTCanMutateCanLock | tmfMPTCanMutateTransferFee}); + .mutableFlags = tmfMPTCanMutateMetadata | tmfMPTCanMutateCanLock | tmfMPTCanMutateTransferFee}); // Setting flags is not allowed when MutableFlags is present - mptAlice.set( - {.account = alice, - .flags = tfMPTCanLock, - .mutableFlags = 2, - .err = temMALFORMED}); + mptAlice.set({.account = alice, .flags = tfMPTCanLock, .mutableFlags = 2, .err = temMALFORMED}); // Setting flags is not allowed when MPTokenMetadata is present - mptAlice.set( - {.account = alice, - .flags = tfMPTCanLock, - .metadata = "test", - .err = temMALFORMED}); + mptAlice.set({.account = alice, .flags = tfMPTCanLock, .metadata = "test", .err = temMALFORMED}); // setting flags is not allowed when TransferFee is present - mptAlice.set( - {.account = alice, - .flags = tfMPTCanLock, - .transferFee = 100, - .err = temMALFORMED}); + mptAlice.set({.account = alice, .flags = tfMPTCanLock, .transferFee = 100, .err = temMALFORMED}); } // Flags being 0 or tfFullyCanonicalSig is fine @@ -2886,19 +2519,10 @@ class MPToken_test : public beast::unit_test::suite {.transferFee = 10, .ownerCount = 1, .flags = tfMPTCanTransfer, - .mutableFlags = - tmfMPTCanMutateTransferFee | tmfMPTCanMutateMetadata}); + .mutableFlags = tmfMPTCanMutateTransferFee | tmfMPTCanMutateMetadata}); - mptAlice.set( - {.account = alice, - .flags = 0, - .transferFee = 100, - .metadata = "test"}); - mptAlice.set( - {.account = alice, - .flags = tfFullyCanonicalSig, - .transferFee = 200, - .metadata = "test2"}); + mptAlice.set({.account = alice, .flags = 0, .transferFee = 100, .metadata = "test"}); + mptAlice.set({.account = alice, .flags = tfFullyCanonicalSig, .transferFee = 200, .metadata = "test2"}); } // Invalid MutableFlags @@ -2909,11 +2533,7 @@ class MPToken_test : public beast::unit_test::suite for (auto const flags : {10000, 0, 5000}) { - mptAlice.set( - {.account = alice, - .id = mptID, - .mutableFlags = flags, - .err = temINVALID_FLAG}); + mptAlice.set({.account = alice, .id = mptID, .mutableFlags = flags, .err = temINVALID_FLAG}); } } @@ -2931,16 +2551,11 @@ class MPToken_test : public beast::unit_test::suite tmfMPTSetCanTransfer | tmfMPTClearCanTransfer, tmfMPTSetCanClawback | tmfMPTClearCanClawback, tmfMPTSetCanLock | tmfMPTClearCanLock | tmfMPTClearCanTrade, - tmfMPTSetCanTransfer | tmfMPTClearCanTransfer | - tmfMPTSetCanEscrow | tmfMPTClearCanClawback}; + tmfMPTSetCanTransfer | tmfMPTClearCanTransfer | tmfMPTSetCanEscrow | tmfMPTClearCanClawback}; for (auto const& mutableFlags : flagCombinations) { - mptAlice.set( - {.account = alice, - .id = mptID, - .mutableFlags = mutableFlags, - .err = temINVALID_FLAG}); + mptAlice.set({.account = alice, .id = mptID, .mutableFlags = mutableFlags, .err = temINVALID_FLAG}); } } @@ -2967,10 +2582,7 @@ class MPToken_test : public beast::unit_test::suite for (auto const& mutableFlag : mutableFlags) { - mptAlice.set( - {.account = alice, - .mutableFlags = mutableFlag, - .err = tecNO_PERMISSION}); + mptAlice.set({.account = alice, .mutableFlags = mutableFlag, .err = tecNO_PERMISSION}); } } @@ -2979,12 +2591,10 @@ class MPToken_test : public beast::unit_test::suite Env env{*this, features}; MPTTester mptAlice(env, alice, {.holders = {bob}}); - mptAlice.create( - {.ownerCount = 1, .mutableFlags = tmfMPTCanMutateMetadata}); + mptAlice.create({.ownerCount = 1, .mutableFlags = tmfMPTCanMutateMetadata}); std::string metadata(maxMPTokenMetadataLength + 1, 'a'); - mptAlice.set( - {.account = alice, .metadata = metadata, .err = temMALFORMED}); + mptAlice.set({.account = alice, .metadata = metadata, .err = temMALFORMED}); } // Can not mutate metadata when it is not mutable @@ -2993,10 +2603,7 @@ class MPToken_test : public beast::unit_test::suite MPTTester mptAlice(env, alice, {.holders = {bob}}); mptAlice.create({.ownerCount = 1}); - mptAlice.set( - {.account = alice, - .metadata = "test", - .err = tecNO_PERMISSION}); + mptAlice.set({.account = alice, .metadata = "test", .err = tecNO_PERMISSION}); } // Transfer fee exceeding the max value @@ -3005,14 +2612,10 @@ class MPToken_test : public beast::unit_test::suite MPTTester mptAlice(env, alice, {.holders = {bob}}); auto const mptID = makeMptID(env.seq(alice), alice); - mptAlice.create( - {.ownerCount = 1, .mutableFlags = tmfMPTCanMutateTransferFee}); + mptAlice.create({.ownerCount = 1, .mutableFlags = tmfMPTCanMutateTransferFee}); mptAlice.set( - {.account = alice, - .id = mptID, - .transferFee = maxTransferFee + 1, - .err = temBAD_TRANSFER_FEE}); + {.account = alice, .id = mptID, .transferFee = maxTransferFee + 1, .err = temBAD_TRANSFER_FEE}); } // Test setting non-zero transfer fee and clearing MPTCanTransfer at the @@ -3025,24 +2628,17 @@ class MPToken_test : public beast::unit_test::suite {.transferFee = 100, .ownerCount = 1, .flags = tfMPTCanTransfer, - .mutableFlags = - tmfMPTCanMutateTransferFee | tmfMPTCanMutateCanTransfer}); + .mutableFlags = tmfMPTCanMutateTransferFee | tmfMPTCanMutateCanTransfer}); // Can not set non-zero transfer fee and clear MPTCanTransfer at the // same time mptAlice.set( - {.account = alice, - .mutableFlags = tmfMPTClearCanTransfer, - .transferFee = 1, - .err = temMALFORMED}); + {.account = alice, .mutableFlags = tmfMPTClearCanTransfer, .transferFee = 1, .err = temMALFORMED}); // Can set transfer fee to zero and clear MPTCanTransfer at the same // time. tfMPTCanTransfer will be cleared and TransferFee field will // be removed. - mptAlice.set( - {.account = alice, - .mutableFlags = tmfMPTClearCanTransfer, - .transferFee = 0}); + mptAlice.set({.account = alice, .mutableFlags = tmfMPTClearCanTransfer, .transferFee = 0}); BEAST_EXPECT(!mptAlice.isTransferFeePresent()); } @@ -3051,24 +2647,15 @@ class MPToken_test : public beast::unit_test::suite Env env{*this, features}; MPTTester mptAlice(env, alice, {.holders = {bob}}); - mptAlice.create( - {.ownerCount = 1, - .mutableFlags = - tmfMPTCanMutateTransferFee | tmfMPTCanMutateCanTransfer}); + mptAlice.create({.ownerCount = 1, .mutableFlags = tmfMPTCanMutateTransferFee | tmfMPTCanMutateCanTransfer}); - mptAlice.set( - {.account = alice, - .transferFee = 100, - .err = tecNO_PERMISSION}); + mptAlice.set({.account = alice, .transferFee = 100, .err = tecNO_PERMISSION}); // Can not set transfer fee even when trying to set MPTCanTransfer // at the same time. MPTCanTransfer must be set first, then transfer // fee can be set in a separate transaction. mptAlice.set( - {.account = alice, - .mutableFlags = tmfMPTSetCanTransfer, - .transferFee = 100, - .err = tecNO_PERMISSION}); + {.account = alice, .mutableFlags = tmfMPTSetCanTransfer, .transferFee = 100, .err = tecNO_PERMISSION}); } // Can not mutate transfer fee when it is not mutable @@ -3076,18 +2663,11 @@ class MPToken_test : public beast::unit_test::suite Env env{*this, features}; MPTTester mptAlice(env, alice, {.holders = {bob}}); - mptAlice.create( - {.transferFee = 10, - .ownerCount = 1, - .flags = tfMPTCanTransfer}); + mptAlice.create({.transferFee = 10, .ownerCount = 1, .flags = tfMPTCanTransfer}); - mptAlice.set( - {.account = alice, - .transferFee = 100, - .err = tecNO_PERMISSION}); + mptAlice.set({.account = alice, .transferFee = 100, .err = tecNO_PERMISSION}); - mptAlice.set( - {.account = alice, .transferFee = 0, .err = tecNO_PERMISSION}); + mptAlice.set({.account = alice, .transferFee = 0, .err = tecNO_PERMISSION}); } // Set some flags mutable. Can not mutate the others @@ -3097,14 +2677,10 @@ class MPToken_test : public beast::unit_test::suite mptAlice.create( {.ownerCount = 1, - .mutableFlags = tmfMPTCanMutateCanTrade | - tmfMPTCanMutateCanTransfer | tmfMPTCanMutateMetadata}); + .mutableFlags = tmfMPTCanMutateCanTrade | tmfMPTCanMutateCanTransfer | tmfMPTCanMutateMetadata}); // Can not mutate transfer fee - mptAlice.set( - {.account = alice, - .transferFee = 100, - .err = tecNO_PERMISSION}); + mptAlice.set({.account = alice, .transferFee = 100, .err = tecNO_PERMISSION}); auto const invalidFlags = { tmfMPTSetCanLock, @@ -3119,22 +2695,16 @@ class MPToken_test : public beast::unit_test::suite // Can not mutate flags which are not mutable for (auto const& mutableFlag : invalidFlags) { - mptAlice.set( - {.account = alice, - .mutableFlags = mutableFlag, - .err = tecNO_PERMISSION}); + mptAlice.set({.account = alice, .mutableFlags = mutableFlag, .err = tecNO_PERMISSION}); } // Can mutate MPTCanTrade mptAlice.set({.account = alice, .mutableFlags = tmfMPTSetCanTrade}); - mptAlice.set( - {.account = alice, .mutableFlags = tmfMPTClearCanTrade}); + mptAlice.set({.account = alice, .mutableFlags = tmfMPTClearCanTrade}); // Can mutate MPTCanTransfer - mptAlice.set( - {.account = alice, .mutableFlags = tmfMPTSetCanTransfer}); - mptAlice.set( - {.account = alice, .mutableFlags = tmfMPTClearCanTransfer}); + mptAlice.set({.account = alice, .mutableFlags = tmfMPTSetCanTransfer}); + mptAlice.set({.account = alice, .mutableFlags = tmfMPTClearCanTransfer}); // Can mutate metadata mptAlice.set({.account = alice, .metadata = "test"}); @@ -3154,10 +2724,7 @@ class MPToken_test : public beast::unit_test::suite { Env env{*this, features}; MPTTester mptAlice(env, alice); - mptAlice.create( - {.metadata = "test", - .ownerCount = 1, - .mutableFlags = tmfMPTCanMutateMetadata}); + mptAlice.create({.metadata = "test", .ownerCount = 1, .mutableFlags = tmfMPTCanMutateMetadata}); std::vector metadatas = { "mutate metadata", @@ -3189,8 +2756,8 @@ class MPToken_test : public beast::unit_test::suite .flags = tfMPTCanTransfer, .mutableFlags = tmfMPTCanMutateTransferFee}); - for (std::uint16_t const fee : std::initializer_list{ - 1, 10, 100, 200, 500, 1000, maxTransferFee}) + for (std::uint16_t const fee : + std::initializer_list{1, 10, 100, 200, 500, 1000, maxTransferFee}) { mptAlice.set({.account = alice, .transferFee = fee}); BEAST_EXPECT(mptAlice.checkTransferFee(fee)); @@ -3207,17 +2774,12 @@ class MPToken_test : public beast::unit_test::suite // Test flag toggling { - auto testFlagToggle = [&](std::uint32_t createFlags, - std::uint32_t setFlags, - std::uint32_t clearFlags) { + auto testFlagToggle = [&](std::uint32_t createFlags, std::uint32_t setFlags, std::uint32_t clearFlags) { Env env{*this, features}; MPTTester mptAlice(env, alice); // Create the MPT object with the specified initial flags - mptAlice.create( - {.metadata = "test", - .ownerCount = 1, - .mutableFlags = createFlags}); + mptAlice.create({.metadata = "test", .ownerCount = 1, .mutableFlags = createFlags}); // Set and clear the flag multiple times mptAlice.set({.account = alice, .mutableFlags = setFlags}); @@ -3230,28 +2792,12 @@ class MPToken_test : public beast::unit_test::suite mptAlice.set({.account = alice, .mutableFlags = clearFlags}); }; - testFlagToggle( - tmfMPTCanMutateCanLock, tfMPTCanLock, tmfMPTClearCanLock); - testFlagToggle( - tmfMPTCanMutateRequireAuth, - tmfMPTSetRequireAuth, - tmfMPTClearRequireAuth); - testFlagToggle( - tmfMPTCanMutateCanEscrow, - tmfMPTSetCanEscrow, - tmfMPTClearCanEscrow); - testFlagToggle( - tmfMPTCanMutateCanTrade, - tmfMPTSetCanTrade, - tmfMPTClearCanTrade); - testFlagToggle( - tmfMPTCanMutateCanTransfer, - tmfMPTSetCanTransfer, - tmfMPTClearCanTransfer); - testFlagToggle( - tmfMPTCanMutateCanClawback, - tmfMPTSetCanClawback, - tmfMPTClearCanClawback); + testFlagToggle(tmfMPTCanMutateCanLock, tfMPTCanLock, tmfMPTClearCanLock); + testFlagToggle(tmfMPTCanMutateRequireAuth, tmfMPTSetRequireAuth, tmfMPTClearRequireAuth); + testFlagToggle(tmfMPTCanMutateCanEscrow, tmfMPTSetCanEscrow, tmfMPTClearCanEscrow); + testFlagToggle(tmfMPTCanMutateCanTrade, tmfMPTSetCanTrade, tmfMPTClearCanTrade); + testFlagToggle(tmfMPTCanMutateCanTransfer, tmfMPTSetCanTransfer, tmfMPTClearCanTransfer); + testFlagToggle(tmfMPTCanMutateCanClawback, tmfMPTSetCanClawback, tmfMPTClearCanClawback); } } @@ -3272,22 +2818,18 @@ class MPToken_test : public beast::unit_test::suite {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanLock | tfMPTCanTransfer, - .mutableFlags = tmfMPTCanMutateCanLock | - tmfMPTCanMutateCanTrade | tmfMPTCanMutateTransferFee}); + .mutableFlags = tmfMPTCanMutateCanLock | tmfMPTCanMutateCanTrade | tmfMPTCanMutateTransferFee}); mptAlice.authorize({.account = bob, .holderCount = 1}); // Lock bob's mptoken mptAlice.set({.account = alice, .holder = bob, .flags = tfMPTLock}); // Can mutate the mutable flags and fields - mptAlice.set( - {.account = alice, .mutableFlags = tmfMPTClearCanLock}); + mptAlice.set({.account = alice, .mutableFlags = tmfMPTClearCanLock}); mptAlice.set({.account = alice, .mutableFlags = tmfMPTSetCanLock}); - mptAlice.set( - {.account = alice, .mutableFlags = tmfMPTClearCanLock}); + mptAlice.set({.account = alice, .mutableFlags = tmfMPTClearCanLock}); mptAlice.set({.account = alice, .mutableFlags = tmfMPTSetCanTrade}); - mptAlice.set( - {.account = alice, .mutableFlags = tmfMPTClearCanTrade}); + mptAlice.set({.account = alice, .mutableFlags = tmfMPTClearCanTrade}); mptAlice.set({.account = alice, .transferFee = 200}); } @@ -3299,23 +2841,18 @@ class MPToken_test : public beast::unit_test::suite {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanLock, - .mutableFlags = tmfMPTCanMutateCanLock | - tmfMPTCanMutateCanClawback | tmfMPTCanMutateMetadata}); + .mutableFlags = tmfMPTCanMutateCanLock | tmfMPTCanMutateCanClawback | tmfMPTCanMutateMetadata}); mptAlice.authorize({.account = bob, .holderCount = 1}); // Lock issuance mptAlice.set({.account = alice, .flags = tfMPTLock}); // Can mutate the mutable flags and fields - mptAlice.set( - {.account = alice, .mutableFlags = tmfMPTClearCanLock}); + mptAlice.set({.account = alice, .mutableFlags = tmfMPTClearCanLock}); mptAlice.set({.account = alice, .mutableFlags = tmfMPTSetCanLock}); - mptAlice.set( - {.account = alice, .mutableFlags = tmfMPTClearCanLock}); - mptAlice.set( - {.account = alice, .mutableFlags = tmfMPTSetCanClawback}); - mptAlice.set( - {.account = alice, .mutableFlags = tmfMPTClearCanClawback}); + mptAlice.set({.account = alice, .mutableFlags = tmfMPTClearCanLock}); + mptAlice.set({.account = alice, .mutableFlags = tmfMPTSetCanClawback}); + mptAlice.set({.account = alice, .mutableFlags = tmfMPTClearCanClawback}); mptAlice.set({.account = alice, .metadata = "mutate"}); } @@ -3327,40 +2864,23 @@ class MPToken_test : public beast::unit_test::suite {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanLock, - .mutableFlags = tmfMPTCanMutateCanLock | - tmfMPTCanMutateCanClawback | tmfMPTCanMutateMetadata}); + .mutableFlags = tmfMPTCanMutateCanLock | tmfMPTCanMutateCanClawback | tmfMPTCanMutateMetadata}); mptAlice.authorize({.account = bob, .holderCount = 1}); // Can lock and unlock mptAlice.set({.account = alice, .flags = tfMPTLock}); mptAlice.set({.account = alice, .holder = bob, .flags = tfMPTLock}); mptAlice.set({.account = alice, .flags = tfMPTUnlock}); - mptAlice.set( - {.account = alice, .holder = bob, .flags = tfMPTUnlock}); + mptAlice.set({.account = alice, .holder = bob, .flags = tfMPTUnlock}); // Clear lsfMPTCanLock - mptAlice.set( - {.account = alice, .mutableFlags = tmfMPTClearCanLock}); + mptAlice.set({.account = alice, .mutableFlags = tmfMPTClearCanLock}); // Can not lock or unlock - mptAlice.set( - {.account = alice, - .flags = tfMPTLock, - .err = tecNO_PERMISSION}); - mptAlice.set( - {.account = alice, - .flags = tfMPTUnlock, - .err = tecNO_PERMISSION}); - mptAlice.set( - {.account = alice, - .holder = bob, - .flags = tfMPTLock, - .err = tecNO_PERMISSION}); - mptAlice.set( - {.account = alice, - .holder = bob, - .flags = tfMPTUnlock, - .err = tecNO_PERMISSION}); + mptAlice.set({.account = alice, .flags = tfMPTLock, .err = tecNO_PERMISSION}); + mptAlice.set({.account = alice, .flags = tfMPTUnlock, .err = tecNO_PERMISSION}); + mptAlice.set({.account = alice, .holder = bob, .flags = tfMPTLock, .err = tecNO_PERMISSION}); + mptAlice.set({.account = alice, .holder = bob, .flags = tfMPTUnlock, .err = tecNO_PERMISSION}); // Set MPTCanLock again mptAlice.set({.account = alice, .mutableFlags = tmfMPTSetCanLock}); @@ -3369,8 +2889,7 @@ class MPToken_test : public beast::unit_test::suite mptAlice.set({.account = alice, .flags = tfMPTLock}); mptAlice.set({.account = alice, .holder = bob, .flags = tfMPTLock}); mptAlice.set({.account = alice, .flags = tfMPTUnlock}); - mptAlice.set( - {.account = alice, .holder = bob, .flags = tfMPTUnlock}); + mptAlice.set({.account = alice, .holder = bob, .flags = tfMPTUnlock}); } } @@ -3385,10 +2904,7 @@ class MPToken_test : public beast::unit_test::suite Account const bob("bob"); MPTTester mptAlice(env, alice, {.holders = {bob}}); - mptAlice.create( - {.ownerCount = 1, - .flags = tfMPTRequireAuth, - .mutableFlags = tmfMPTCanMutateRequireAuth}); + mptAlice.create({.ownerCount = 1, .flags = tfMPTRequireAuth, .mutableFlags = tmfMPTCanMutateRequireAuth}); mptAlice.authorize({.account = bob}); mptAlice.authorize({.account = alice, .holder = bob}); @@ -3397,15 +2913,13 @@ class MPToken_test : public beast::unit_test::suite mptAlice.pay(alice, bob, 1000); // Unauthorize bob - mptAlice.authorize( - {.account = alice, .holder = bob, .flags = tfMPTUnauthorize}); + mptAlice.authorize({.account = alice, .holder = bob, .flags = tfMPTUnauthorize}); // Can not pay to bob mptAlice.pay(bob, alice, 100, tecNO_AUTH); // Clear RequireAuth - mptAlice.set( - {.account = alice, .mutableFlags = tmfMPTClearRequireAuth}); + mptAlice.set({.account = alice, .mutableFlags = tmfMPTClearRequireAuth}); // Can pay to bob mptAlice.pay(alice, bob, 1000); @@ -3438,10 +2952,7 @@ class MPToken_test : public beast::unit_test::suite MPTTester mptAlice(env, alice, {.holders = {carol, bob}}); mptAlice.create( - {.ownerCount = 1, - .holderCount = 0, - .flags = tfMPTCanTransfer, - .mutableFlags = tmfMPTCanMutateCanEscrow}); + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer, .mutableFlags = tmfMPTCanMutateCanEscrow}); mptAlice.authorize({.account = carol}); mptAlice.authorize({.account = bob}); @@ -3487,10 +2998,7 @@ class MPToken_test : public beast::unit_test::suite Env env{*this, features}; MPTTester mptAlice(env, alice, {.holders = {bob, carol}}); - mptAlice.create( - {.ownerCount = 1, - .mutableFlags = - tmfMPTCanMutateCanTransfer | tmfMPTCanMutateTransferFee}); + mptAlice.create({.ownerCount = 1, .mutableFlags = tmfMPTCanMutateCanTransfer | tmfMPTCanMutateTransferFee}); mptAlice.authorize({.account = bob}); mptAlice.authorize({.account = carol}); @@ -3502,22 +3010,15 @@ class MPToken_test : public beast::unit_test::suite mptAlice.pay(bob, carol, 50, tecNO_AUTH); // Can not set non-zero transfer fee when MPTCanTransfer is not set - mptAlice.set( - {.account = alice, - .transferFee = 100, - .err = tecNO_PERMISSION}); + mptAlice.set({.account = alice, .transferFee = 100, .err = tecNO_PERMISSION}); // Can not set non-zero transfer fee even when trying to set // MPTCanTransfer at the same time mptAlice.set( - {.account = alice, - .mutableFlags = tmfMPTSetCanTransfer, - .transferFee = 100, - .err = tecNO_PERMISSION}); + {.account = alice, .mutableFlags = tmfMPTSetCanTransfer, .transferFee = 100, .err = tecNO_PERMISSION}); // Alice sets MPTCanTransfer - mptAlice.set( - {.account = alice, .mutableFlags = tmfMPTSetCanTransfer}); + mptAlice.set({.account = alice, .mutableFlags = tmfMPTSetCanTransfer}); // Can set transfer fee now BEAST_EXPECT(!mptAlice.isTransferFeePresent()); @@ -3528,8 +3029,7 @@ class MPToken_test : public beast::unit_test::suite mptAlice.pay(bob, carol, 50); // Alice clears MPTCanTransfer - mptAlice.set( - {.account = alice, .mutableFlags = tmfMPTClearCanTransfer}); + mptAlice.set({.account = alice, .mutableFlags = tmfMPTClearCanTransfer}); // TransferFee field is removed when MPTCanTransfer is cleared BEAST_EXPECT(!mptAlice.isTransferFeePresent()); @@ -3548,14 +3048,12 @@ class MPToken_test : public beast::unit_test::suite {.transferFee = 100, .ownerCount = 1, .flags = tfMPTCanTransfer, - .mutableFlags = - tmfMPTCanMutateTransferFee | tmfMPTCanMutateCanTransfer}); + .mutableFlags = tmfMPTCanMutateTransferFee | tmfMPTCanMutateCanTransfer}); BEAST_EXPECT(mptAlice.checkTransferFee(100)); // Clear MPTCanTransfer and transfer fee is removed - mptAlice.set( - {.account = alice, .mutableFlags = tmfMPTClearCanTransfer}); + mptAlice.set({.account = alice, .mutableFlags = tmfMPTClearCanTransfer}); BEAST_EXPECT(!mptAlice.isTransferFeePresent()); // Can still set transfer fee to zero, although it is already zero @@ -3578,10 +3076,7 @@ class MPToken_test : public beast::unit_test::suite MPTTester mptAlice(env, alice, {.holders = {bob}}); - mptAlice.create( - {.ownerCount = 1, - .holderCount = 0, - .mutableFlags = tmfMPTCanMutateCanClawback}); + mptAlice.create({.ownerCount = 1, .holderCount = 0, .mutableFlags = tmfMPTCanMutateCanClawback}); // Bob creates an MPToken mptAlice.authorize({.account = bob}); @@ -3599,8 +3094,7 @@ class MPToken_test : public beast::unit_test::suite mptAlice.claw(alice, bob, 1); // Clear MPTCanClawback - mptAlice.set( - {.account = alice, .mutableFlags = tmfMPTClearCanClawback}); + mptAlice.set({.account = alice, .mutableFlags = tmfMPTClearCanClawback}); // Can not clawback mptAlice.claw(alice, bob, 1, tecNO_PERMISSION); diff --git a/src/test/app/Manifest_test.cpp b/src/test/app/Manifest_test.cpp index 09054658c9..5b7e34ad5b 100644 --- a/src/test/app/Manifest_test.cpp +++ b/src/test/app/Manifest_test.cpp @@ -1,15 +1,15 @@ #include -#include -#include #include -#include #include #include #include #include #include +#include +#include +#include #include #include @@ -55,8 +55,7 @@ private: if (!is_directory(dbPath)) { // someone created a file where we want to put our directory - Throw( - "Cannot create directory: " + dbPath.string()); + Throw("Cannot create directory: " + dbPath.string()); } } static boost::filesystem::path @@ -88,12 +87,7 @@ public: } std::string - makeManifestString( - PublicKey const& pk, - SecretKey const& sk, - PublicKey const& spk, - SecretKey const& ssk, - int seq) + makeManifestString(PublicKey const& pk, SecretKey const& sk, PublicKey const& spk, SecretKey const& ssk, int seq) { STObject st(sfGeneric); st[sfSequence] = seq; @@ -101,25 +95,16 @@ public: st[sfSigningPubKey] = spk; sign(st, HashPrefix::manifest, *publicKeyType(spk), ssk); - sign( - st, - HashPrefix::manifest, - *publicKeyType(pk), - sk, - sfMasterSignature); + sign(st, HashPrefix::manifest, *publicKeyType(pk), sk, sfMasterSignature); Serializer s; st.add(s); - return base64_encode( - std::string(static_cast(s.data()), s.size())); + return base64_encode(std::string(static_cast(s.data()), s.size())); } std::string - makeRevocationString( - SecretKey const& sk, - KeyType type, - bool invalidSig = false) + makeRevocationString(SecretKey const& sk, KeyType type, bool invalidSig = false) { auto const pk = derivePublicKey(type, sk); @@ -127,21 +112,13 @@ public: st[sfSequence] = std::numeric_limits::max(); st[sfPublicKey] = pk; - sign( - st, - HashPrefix::manifest, - type, - invalidSig ? randomSecretKey() : sk, - sfMasterSignature); - BEAST_EXPECT( - invalidSig ^ - verify(st, HashPrefix::manifest, pk, sfMasterSignature)); + sign(st, HashPrefix::manifest, type, invalidSig ? randomSecretKey() : sk, sfMasterSignature); + BEAST_EXPECT(invalidSig ^ verify(st, HashPrefix::manifest, pk, sfMasterSignature)); Serializer s; st.add(s); - return base64_encode( - std::string(static_cast(s.data()), s.size())); + return base64_encode(std::string(static_cast(s.data()), s.size())); } Manifest @@ -153,15 +130,8 @@ public: st[sfSequence] = std::numeric_limits::max(); st[sfPublicKey] = pk; - sign( - st, - HashPrefix::manifest, - type, - invalidSig ? randomSecretKey() : sk, - sfMasterSignature); - BEAST_EXPECT( - invalidSig ^ - verify(st, HashPrefix::manifest, pk, sfMasterSignature)); + sign(st, HashPrefix::manifest, type, invalidSig ? randomSecretKey() : sk, sfMasterSignature); + BEAST_EXPECT(invalidSig ^ verify(st, HashPrefix::manifest, pk, sfMasterSignature)); Serializer s; st.add(s); @@ -171,8 +141,7 @@ public: if (auto r = deserializeManifest(std::move(m))) return std::move(*r); Throw("Could not create a revocation manifest"); - return *deserializeManifest( - std::string{}); // Silence compiler warning. + return *deserializeManifest(std::string{}); // Silence compiler warning. } Manifest @@ -195,34 +164,24 @@ public: sign(st, HashPrefix::manifest, stype, ssk); BEAST_EXPECT(verify(st, HashPrefix::manifest, spk)); - sign( - st, - HashPrefix::manifest, - type, - invalidSig ? randomSecretKey() : sk, - sfMasterSignature); - BEAST_EXPECT( - invalidSig ^ - verify(st, HashPrefix::manifest, pk, sfMasterSignature)); + sign(st, HashPrefix::manifest, type, invalidSig ? randomSecretKey() : sk, sfMasterSignature); + BEAST_EXPECT(invalidSig ^ verify(st, HashPrefix::manifest, pk, sfMasterSignature)); Serializer s; st.add(s); - std::string m( - static_cast(s.data()), - s.size()); // non-const so can be moved + std::string m(static_cast(s.data()), + s.size()); // non-const so can be moved if (auto r = deserializeManifest(std::move(m))) return std::move(*r); Throw("Could not create a manifest"); - return *deserializeManifest( - std::string{}); // Silence compiler warning. + return *deserializeManifest(std::string{}); // Silence compiler warning. } Manifest clone(Manifest const& m) { - Manifest m2( - m.serialized, m.masterKey, m.signingKey, m.sequence, m.domain); + Manifest m2(m.serialized, m.masterKey, m.signingKey, m.sequence, m.domain); return m2; } @@ -240,52 +199,35 @@ public: auto dbCon = makeTestWalletDB(setup, dbName, env.journal); - auto getPopulatedManifests = - [](ManifestCache const& cache) -> std::vector { + auto getPopulatedManifests = [](ManifestCache const& cache) -> std::vector { std::vector result; result.reserve(32); - cache.for_each_manifest( - [&result](Manifest const& man) { result.push_back(&man); }); + cache.for_each_manifest([&result](Manifest const& man) { result.push_back(&man); }); return result; }; - auto sort = [](std::vector mv) - -> std::vector { - std::sort( - mv.begin(), - mv.end(), - [](Manifest const* lhs, Manifest const* rhs) { - return lhs->serialized < rhs->serialized; - }); + auto sort = [](std::vector mv) -> std::vector { + std::sort(mv.begin(), mv.end(), [](Manifest const* lhs, Manifest const* rhs) { + return lhs->serialized < rhs->serialized; + }); return mv; }; - std::vector const inManifests( - sort(getPopulatedManifests(m))); + std::vector const inManifests(sort(getPopulatedManifests(m))); auto& app = env.app(); auto unl = std::make_unique( - m, - m, - env.timeKeeper(), - app.config().legacy("database_path"), - env.journal); + m, m, env.timeKeeper(), app.config().legacy("database_path"), env.journal); { // save should not store untrusted master keys to db // except for revocations - m.save( - *dbCon, - "ValidatorManifests", - [&unl](PublicKey const& pubKey) { - return unl->listed(pubKey); - }); + m.save(*dbCon, "ValidatorManifests", [&unl](PublicKey const& pubKey) { return unl->listed(pubKey); }); ManifestCache loaded; loaded.load(*dbCon, "ValidatorManifests"); // check that all loaded manifests are revocations - std::vector const loadedManifests( - sort(getPopulatedManifests(loaded))); + std::vector const loadedManifests(sort(getPopulatedManifests(loaded))); for (auto const& man : loadedManifests) BEAST_EXPECT(man->revoked()); @@ -296,22 +238,15 @@ public: std::vector keys; std::string cfgManifest; for (auto const& man : inManifests) - s1.push_back( - toBase58(TokenType::NodePublic, man->masterKey)); + s1.push_back(toBase58(TokenType::NodePublic, man->masterKey)); unl->load({}, s1, keys); - m.save( - *dbCon, - "ValidatorManifests", - [&unl](PublicKey const& pubKey) { - return unl->listed(pubKey); - }); + m.save(*dbCon, "ValidatorManifests", [&unl](PublicKey const& pubKey) { return unl->listed(pubKey); }); ManifestCache loaded; loaded.load(*dbCon, "ValidatorManifests"); // check that the manifest caches are the same - std::vector const loadedManifests( - sort(getPopulatedManifests(loaded))); + std::vector const loadedManifests(sort(getPopulatedManifests(loaded))); if (inManifests.size() == loadedManifests.size()) { @@ -319,9 +254,7 @@ public: inManifests.begin(), inManifests.end(), loadedManifests.begin(), - [](Manifest const* lhs, Manifest const* rhs) { - return *lhs == *rhs; - })); + [](Manifest const* lhs, Manifest const* rhs) { return *lhs == *rhs; })); } else { @@ -334,74 +267,44 @@ public: std::vector const emptyRevocation; std::string const badManifest = "bad manifest"; - BEAST_EXPECT(!loaded.load( - *dbCon, - "ValidatorManifests", - badManifest, - emptyRevocation)); + BEAST_EXPECT(!loaded.load(*dbCon, "ValidatorManifests", badManifest, emptyRevocation)); auto const sk = randomSecretKey(); auto const pk = derivePublicKey(KeyType::ed25519, sk); auto const kp = randomKeyPair(KeyType::secp256k1); - std::string const cfgManifest = - makeManifestString(pk, sk, kp.first, kp.second, 0); + std::string const cfgManifest = makeManifestString(pk, sk, kp.first, kp.second, 0); - BEAST_EXPECT(loaded.load( - *dbCon, - "ValidatorManifests", - cfgManifest, - emptyRevocation)); + BEAST_EXPECT(loaded.load(*dbCon, "ValidatorManifests", cfgManifest, emptyRevocation)); } { // load config revocation ManifestCache loaded; std::string const emptyManifest; - std::vector const badRevocation = { - "bad revocation"}; - BEAST_EXPECT(!loaded.load( - *dbCon, - "ValidatorManifests", - emptyManifest, - badRevocation)); + std::vector const badRevocation = {"bad revocation"}; + BEAST_EXPECT(!loaded.load(*dbCon, "ValidatorManifests", emptyManifest, badRevocation)); auto const sk = randomSecretKey(); auto const keyType = KeyType::ed25519; auto const pk = derivePublicKey(keyType, sk); auto const kp = randomKeyPair(KeyType::secp256k1); - std::vector const nonRevocation = { - makeManifestString(pk, sk, kp.first, kp.second, 0)}; + std::vector const nonRevocation = {makeManifestString(pk, sk, kp.first, kp.second, 0)}; - BEAST_EXPECT(!loaded.load( - *dbCon, - "ValidatorManifests", - emptyManifest, - nonRevocation)); + BEAST_EXPECT(!loaded.load(*dbCon, "ValidatorManifests", emptyManifest, nonRevocation)); BEAST_EXPECT(!loaded.revoked(pk)); - std::vector const badSigRevocation = { - makeRevocationString(sk, keyType, true)}; - BEAST_EXPECT(!loaded.load( - *dbCon, - "ValidatorManifests", - emptyManifest, - badSigRevocation)); + std::vector const badSigRevocation = {makeRevocationString(sk, keyType, true)}; + BEAST_EXPECT(!loaded.load(*dbCon, "ValidatorManifests", emptyManifest, badSigRevocation)); BEAST_EXPECT(!loaded.revoked(pk)); - std::vector const cfgRevocation = { - makeRevocationString(sk, keyType)}; - BEAST_EXPECT(loaded.load( - *dbCon, - "ValidatorManifests", - emptyManifest, - cfgRevocation)); + std::vector const cfgRevocation = {makeRevocationString(sk, keyType)}; + BEAST_EXPECT(loaded.load(*dbCon, "ValidatorManifests", emptyManifest, cfgRevocation)); BEAST_EXPECT(loaded.revoked(pk)); } } - boost::filesystem::remove( - getDatabasePath() / boost::filesystem::path(dbName)); + boost::filesystem::remove(getDatabasePath() / boost::filesystem::path(dbName)); } void @@ -411,8 +314,7 @@ public: auto const sk = randomSecretKey(); auto const pk = derivePublicKey(KeyType::ed25519, sk); auto const kp = randomKeyPair(KeyType::secp256k1); - auto const m = makeManifest( - sk, KeyType::ed25519, kp.second, KeyType::secp256k1, 0); + auto const m = makeManifest(sk, KeyType::ed25519, kp.second, KeyType::secp256k1, 0); STObject st(sfGeneric); st[sfSequence] = 0; @@ -447,8 +349,7 @@ public: auto const kp0 = randomKeyPair(KeyType::secp256k1); BEAST_EXPECT( ManifestDisposition::accepted == - cache.applyManifest(makeManifest( - sk, KeyType::ed25519, kp0.second, KeyType::secp256k1, 0))); + cache.applyManifest(makeManifest(sk, KeyType::ed25519, kp0.second, KeyType::secp256k1, 0))); BEAST_EXPECT(cache.getSigningKey(pk) == kp0.first); BEAST_EXPECT(cache.getMasterKey(kp0.first) == pk); @@ -459,8 +360,7 @@ public: auto const kp1 = randomKeyPair(KeyType::secp256k1); BEAST_EXPECT( ManifestDisposition::accepted == - cache.applyManifest(makeManifest( - sk, KeyType::ed25519, kp1.second, KeyType::secp256k1, 1))); + cache.applyManifest(makeManifest(sk, KeyType::ed25519, kp1.second, KeyType::secp256k1, 1))); BEAST_EXPECT(cache.getSigningKey(pk) == kp1.first); BEAST_EXPECT(cache.getMasterKey(kp1.first) == pk); BEAST_EXPECT(cache.getMasterKey(kp0.first) == kp0.first); @@ -469,8 +369,7 @@ public: // applied with the same signing key but a higher sequence BEAST_EXPECT( ManifestDisposition::badEphemeralKey == - cache.applyManifest(makeManifest( - sk, KeyType::ed25519, kp1.second, KeyType::secp256k1, 2))); + cache.applyManifest(makeManifest(sk, KeyType::ed25519, kp1.second, KeyType::secp256k1, 2))); BEAST_EXPECT(cache.getSigningKey(pk) == kp1.first); BEAST_EXPECT(cache.getMasterKey(kp1.first) == pk); BEAST_EXPECT(cache.getMasterKey(kp0.first) == kp0.first); @@ -478,9 +377,7 @@ public: // getSigningKey should return std::nullopt for a revoked master public // key getMasterKey should return std::nullopt for an ephemeral public // key from a revoked master public key - BEAST_EXPECT( - ManifestDisposition::accepted == - cache.applyManifest(makeRevocation(sk, KeyType::ed25519))); + BEAST_EXPECT(ManifestDisposition::accepted == cache.applyManifest(makeRevocation(sk, KeyType::ed25519))); BEAST_EXPECT(cache.revoked(pk)); BEAST_EXPECT(cache.getSigningKey(pk) == pk); BEAST_EXPECT(cache.getMasterKey(kp0.first) == kp0.first); @@ -493,9 +390,8 @@ public: testcase("validator token"); { - auto const valSecret = parseBase58( - TokenType::NodePrivate, - "paQmjZ37pKKPMrgadBLsuf9ab7Y7EUNzh27LQrZqoexpAs31nJi"); + auto const valSecret = + parseBase58(TokenType::NodePrivate, "paQmjZ37pKKPMrgadBLsuf9ab7Y7EUNzh27LQrZqoexpAs31nJi"); // Format token string to test trim() std::vector const tokenBlob = { @@ -560,12 +456,7 @@ public: if (version != 0) st[sfVersion] = version; - sign( - st, - HashPrefix::manifest, - KeyType::ed25519, - sk, - sfMasterSignature); + sign(st, HashPrefix::manifest, KeyType::ed25519, sk, sfMasterSignature); sign(st, HashPrefix::manifest, KeyType::secp256k1, ssk); Serializer s; @@ -585,35 +476,18 @@ public: void testManifestDeserialization() { - std::array const keyTypes{ - {KeyType::ed25519, KeyType::secp256k1}}; + std::array const keyTypes{{KeyType::ed25519, KeyType::secp256k1}}; std::uint32_t sequence = 0; // public key with invalid type - std::array const badKey{ - 0x99, 0x30, 0xE7, 0xFC, 0x9D, 0x56, 0xBB, 0x25, 0xD6, 0x89, 0x3B, - 0xA3, 0xF3, 0x17, 0xAE, 0x5B, 0xCF, 0x33, 0xB3, 0x29, 0x1B, 0xD6, - 0x3D, 0xB3, 0x26, 0x54, 0xA3, 0x13, 0x22, 0x2F, 0x7F, 0xD0, 0x20}; + std::array const badKey{0x99, 0x30, 0xE7, 0xFC, 0x9D, 0x56, 0xBB, 0x25, 0xD6, 0x89, 0x3B, + 0xA3, 0xF3, 0x17, 0xAE, 0x5B, 0xCF, 0x33, 0xB3, 0x29, 0x1B, 0xD6, + 0x3D, 0xB3, 0x26, 0x54, 0xA3, 0x13, 0x22, 0x2F, 0x7F, 0xD0, 0x20}; // Short public key: std::array const shortKey{ - 0x03, - 0x30, - 0xE7, - 0xFC, - 0x9D, - 0x56, - 0xBB, - 0x25, - 0xD6, - 0x89, - 0x3B, - 0xA3, - 0xF3, - 0x17, - 0xAE, - 0x5B}; + 0x03, 0x30, 0xE7, 0xFC, 0x9D, 0x56, 0xBB, 0x25, 0xD6, 0x89, 0x3B, 0xA3, 0xF3, 0x17, 0xAE, 0x5B}; auto toString = [](STObject const& st) { Serializer s; @@ -632,42 +506,34 @@ public: auto const ssk = generateSecretKey(sKeyType, randomSeed()); auto const spk = derivePublicKey(sKeyType, ssk); - auto buildManifestObject = - [&](std::uint32_t seq, - std::optional domain, - bool noSigningPublic = false, - bool noSignature = false) { - STObject st(sfGeneric); - st[sfSequence] = seq; - st[sfPublicKey] = pk; + auto buildManifestObject = [&](std::uint32_t seq, + std::optional domain, + bool noSigningPublic = false, + bool noSignature = false) { + STObject st(sfGeneric); + st[sfSequence] = seq; + st[sfPublicKey] = pk; - if (domain) - st[sfDomain] = makeSlice(*domain); + if (domain) + st[sfDomain] = makeSlice(*domain); - if (!noSigningPublic) - st[sfSigningPubKey] = spk; + if (!noSigningPublic) + st[sfSigningPubKey] = spk; - sign( - st, - HashPrefix::manifest, - keyType, - sk, - sfMasterSignature); + sign(st, HashPrefix::manifest, keyType, sk, sfMasterSignature); - if (!noSignature) - sign(st, HashPrefix::manifest, sKeyType, ssk); + if (!noSignature) + sign(st, HashPrefix::manifest, sKeyType, ssk); - return st; - }; + return st; + }; { - testcase << "deserializeManifest: normal manifest (" - << to_string(keyType) << " + " + testcase << "deserializeManifest: normal manifest (" << to_string(keyType) << " + " << to_string(sKeyType) << ")"; { // valid manifest without domain - auto const st = - buildManifestObject(++sequence, std::nullopt); + auto const st = buildManifestObject(++sequence, std::nullopt); auto const m = toString(st); auto const manifest = deserializeManifest(m); @@ -682,32 +548,27 @@ public: } { // invalid manifest (empty domain) - auto const st = - buildManifestObject(++sequence, std::string{}); + auto const st = buildManifestObject(++sequence, std::string{}); BEAST_EXPECT(!deserializeManifest(toString(st))); } { // invalid manifest (domain too short) - auto const st = - buildManifestObject(++sequence, std::string{"a.b"}); + auto const st = buildManifestObject(++sequence, std::string{"a.b"}); BEAST_EXPECT(!deserializeManifest(toString(st))); } { // invalid manifest (domain too long) std::string s(254, 'a'); - auto const st = - buildManifestObject(++sequence, s + ".example.com"); + auto const st = buildManifestObject(++sequence, s + ".example.com"); BEAST_EXPECT(!deserializeManifest(toString(st))); } { // invalid manifest (domain component too long) std::string s(72, 'a'); - auto const st = - buildManifestObject(++sequence, s + ".example.com"); + auto const st = buildManifestObject(++sequence, s + ".example.com"); BEAST_EXPECT(!deserializeManifest(toString(st))); } - auto const st = buildManifestObject( - ++sequence, std::string{"example.com"}); + auto const st = buildManifestObject(++sequence, std::string{"example.com"}); { // valid manifest with domain @@ -799,12 +660,7 @@ public: st[sfPublicKey] = pk; st[sfSigningPubKey] = pk; - sign( - st, - HashPrefix::manifest, - keyType, - sk, - sfMasterSignature); + sign(st, HashPrefix::manifest, keyType, sk, sfMasterSignature); sign(st, HashPrefix::manifest, sKeyType, sk); @@ -813,17 +669,13 @@ public: } { - testcase << "deserializeManifest: revocation manifest (" - << to_string(keyType) << " + " + testcase << "deserializeManifest: revocation manifest (" << to_string(keyType) << " + " << to_string(sKeyType) << ")"; // valid revocation { - auto const st = buildManifestObject( - std::numeric_limits::max(), - std::nullopt, - true, - true); + auto const st = + buildManifestObject(std::numeric_limits::max(), std::nullopt, true, true); auto const m = toString(st); auto const manifest = deserializeManifest(m); @@ -841,29 +693,20 @@ public: } { // can't specify an ephemeral signing key - auto const st = buildManifestObject( - std::numeric_limits::max(), - std::nullopt, - true, - false); + auto const st = + buildManifestObject(std::numeric_limits::max(), std::nullopt, true, false); BEAST_EXPECT(!deserializeManifest(toString(st))); } { // can't specify an ephemeral signature - auto const st = buildManifestObject( - std::numeric_limits::max(), - std::nullopt, - false, - true); + auto const st = + buildManifestObject(std::numeric_limits::max(), std::nullopt, false, true); BEAST_EXPECT(!deserializeManifest(toString(st))); } { // can't specify an ephemeral key & signature - auto const st = buildManifestObject( - std::numeric_limits::max(), - std::nullopt, - false, - false); + auto const st = + buildManifestObject(std::numeric_limits::max(), std::nullopt, false, false); BEAST_EXPECT(!deserializeManifest(toString(st))); } @@ -890,19 +733,13 @@ public: st[sfDomain] = makeSlice(domain); st[sfSigningPubKey] = pk2; - sign( - st, - HashPrefix::manifest, - KeyType::secp256k1, - sk1, - sfMasterSignature); + sign(st, HashPrefix::manifest, KeyType::secp256k1, sk1, sfMasterSignature); sign(st, HashPrefix::manifest, KeyType::secp256k1, sk2); Serializer s; st.add(s); - return deserializeManifest( - std::string(static_cast(s.data()), s.size())); + return deserializeManifest(std::string(static_cast(s.data()), s.size())); }; BEAST_EXPECT(test("example.com")); @@ -953,9 +790,7 @@ public: BEAST_EXPECT(!test(std::string(64, 'a') + "." + std::string(64, 'b'))); // Overall too long: - BEAST_EXPECT(!test( - std::string(63, 'a') + "." + std::string(63, 'b') + - ".example.com")); + BEAST_EXPECT(!test(std::string(63, 'a') + "." + std::string(63, 'b') + ".example.com")); } void @@ -969,20 +804,16 @@ public: auto const pk_a = derivePublicKey(KeyType::ed25519, sk_a); auto const kp_a0 = randomKeyPair(KeyType::secp256k1); auto const kp_a1 = randomKeyPair(KeyType::secp256k1); - auto const s_a0 = makeManifest( - sk_a, KeyType::ed25519, kp_a0.second, KeyType::secp256k1, 0); - auto const s_a1 = makeManifest( - sk_a, KeyType::ed25519, kp_a1.second, KeyType::secp256k1, 1); - auto const s_a2 = makeManifest( - sk_a, KeyType::ed25519, kp_a1.second, KeyType::secp256k1, 2); + auto const s_a0 = makeManifest(sk_a, KeyType::ed25519, kp_a0.second, KeyType::secp256k1, 0); + auto const s_a1 = makeManifest(sk_a, KeyType::ed25519, kp_a1.second, KeyType::secp256k1, 1); + auto const s_a2 = makeManifest(sk_a, KeyType::ed25519, kp_a1.second, KeyType::secp256k1, 2); auto const s_aMax = makeRevocation(sk_a, KeyType::ed25519); auto const sk_b = randomSecretKey(); auto const kp_b0 = randomKeyPair(KeyType::secp256k1); auto const kp_b1 = randomKeyPair(KeyType::secp256k1); auto const kp_b2 = randomKeyPair(KeyType::secp256k1); - auto const s_b0 = makeManifest( - sk_b, KeyType::ed25519, kp_b0.second, KeyType::secp256k1, 0); + auto const s_b0 = makeManifest(sk_b, KeyType::ed25519, kp_b0.second, KeyType::secp256k1, 0); auto const s_b1 = makeManifest( sk_b, KeyType::ed25519, @@ -990,70 +821,45 @@ public: KeyType::secp256k1, 1, true); // invalidSig - auto const s_b2 = makeManifest( - sk_b, KeyType::ed25519, kp_b2.second, KeyType::ed25519, 2); + auto const s_b2 = makeManifest(sk_b, KeyType::ed25519, kp_b2.second, KeyType::ed25519, 2); auto const fake = s_b2.serialized + '\0'; // applyManifest should accept new manifests with // higher sequence numbers - BEAST_EXPECT( - cache.applyManifest(clone(s_a0)) == - ManifestDisposition::accepted); - BEAST_EXPECT( - cache.applyManifest(clone(s_a0)) == ManifestDisposition::stale); + auto const seq0 = cache.sequence(); + BEAST_EXPECT(cache.applyManifest(clone(s_a0)) == ManifestDisposition::accepted); + BEAST_EXPECT(cache.sequence() > seq0); - BEAST_EXPECT( - cache.applyManifest(clone(s_a1)) == - ManifestDisposition::accepted); - BEAST_EXPECT( - cache.applyManifest(clone(s_a1)) == ManifestDisposition::stale); - BEAST_EXPECT( - cache.applyManifest(clone(s_a0)) == ManifestDisposition::stale); + auto const seq1 = cache.sequence(); + BEAST_EXPECT(cache.applyManifest(clone(s_a0)) == ManifestDisposition::stale); + BEAST_EXPECT(cache.sequence() == seq1); - BEAST_EXPECT( - cache.applyManifest(clone(s_a2)) == - ManifestDisposition::badEphemeralKey); + BEAST_EXPECT(cache.applyManifest(clone(s_a1)) == ManifestDisposition::accepted); + BEAST_EXPECT(cache.applyManifest(clone(s_a1)) == ManifestDisposition::stale); + BEAST_EXPECT(cache.applyManifest(clone(s_a0)) == ManifestDisposition::stale); + + BEAST_EXPECT(cache.applyManifest(clone(s_a2)) == ManifestDisposition::badEphemeralKey); // applyManifest should accept manifests with max sequence numbers // that revoke the master public key BEAST_EXPECT(!cache.revoked(pk_a)); BEAST_EXPECT(s_aMax.revoked()); - BEAST_EXPECT( - cache.applyManifest(clone(s_aMax)) == - ManifestDisposition::accepted); - BEAST_EXPECT( - cache.applyManifest(clone(s_aMax)) == - ManifestDisposition::stale); - BEAST_EXPECT( - cache.applyManifest(clone(s_a1)) == ManifestDisposition::stale); - BEAST_EXPECT( - cache.applyManifest(clone(s_a0)) == ManifestDisposition::stale); + BEAST_EXPECT(cache.applyManifest(clone(s_aMax)) == ManifestDisposition::accepted); + BEAST_EXPECT(cache.applyManifest(clone(s_aMax)) == ManifestDisposition::stale); + BEAST_EXPECT(cache.applyManifest(clone(s_a1)) == ManifestDisposition::stale); + BEAST_EXPECT(cache.applyManifest(clone(s_a0)) == ManifestDisposition::stale); BEAST_EXPECT(cache.revoked(pk_a)); // applyManifest should reject manifests with invalid signatures - BEAST_EXPECT( - cache.applyManifest(clone(s_b0)) == - ManifestDisposition::accepted); - BEAST_EXPECT( - cache.applyManifest(clone(s_b0)) == ManifestDisposition::stale); + BEAST_EXPECT(cache.applyManifest(clone(s_b0)) == ManifestDisposition::accepted); + BEAST_EXPECT(cache.applyManifest(clone(s_b0)) == ManifestDisposition::stale); BEAST_EXPECT(!deserializeManifest(fake)); - BEAST_EXPECT( - cache.applyManifest(clone(s_b1)) == - ManifestDisposition::invalid); - BEAST_EXPECT( - cache.applyManifest(clone(s_b2)) == - ManifestDisposition::accepted); + BEAST_EXPECT(cache.applyManifest(clone(s_b1)) == ManifestDisposition::invalid); + BEAST_EXPECT(cache.applyManifest(clone(s_b2)) == ManifestDisposition::accepted); - auto const s_c0 = makeManifest( - kp_b2.second, - KeyType::ed25519, - randomSecretKey(), - KeyType::ed25519, - 47); - BEAST_EXPECT( - cache.applyManifest(clone(s_c0)) == - ManifestDisposition::badMasterKey); + auto const s_c0 = makeManifest(kp_b2.second, KeyType::ed25519, randomSecretKey(), KeyType::ed25519, 47); + BEAST_EXPECT(cache.applyManifest(clone(s_c0)) == ManifestDisposition::badMasterKey); } testLoadStore(cache); diff --git a/src/test/app/MultiSign_test.cpp b/src/test/app/MultiSign_test.cpp index 5c5404c17e..3d732ee2e0 100644 --- a/src/test/app/MultiSign_test.cpp +++ b/src/test/app/MultiSign_test.cpp @@ -84,14 +84,7 @@ public: Json::Value bigSigners = signers( alice, 1, - {{bogie, 1}, - {demon, 1}, - {ghost, 1}, - {haunt, 1}, - {jinni, 1}, - {phase, 1}, - {shade, 1}, - {spook, 1}}); + {{bogie, 1}, {demon, 1}, {ghost, 1}, {haunt, 1}, {jinni, 1}, {phase, 1}, {shade, 1}, {spook, 1}}); env(bigSigners, ter(tecINSUFFICIENT_RESERVE)); env.close(); env.require(owners(alice, 1)); @@ -136,14 +129,7 @@ public: env(signers( alice, 1, - {{bogie, 1}, - {demon, 1}, - {ghost, 1}, - {haunt, 1}, - {jinni, 1}, - {phase, 1}, - {demon, 1}, - {spook, 1}}), + {{bogie, 1}, {demon, 1}, {ghost, 1}, {haunt, 1}, {jinni, 1}, {phase, 1}, {demon, 1}, {spook, 1}}), ter(temBAD_SIGNER)); // Set a quorum of zero. Should fail. @@ -153,14 +139,7 @@ public: env(signers( alice, 9, - {{bogie, 1}, - {demon, 1}, - {ghost, 1}, - {haunt, 1}, - {jinni, 1}, - {phase, 1}, - {shade, 1}, - {spook, 1}}), + {{bogie, 1}, {demon, 1}, {ghost, 1}, {haunt, 1}, {jinni, 1}, {phase, 1}, {shade, 1}, {spook, 1}}), ter(temBAD_QUORUM)); // clang-format off @@ -225,17 +204,13 @@ public: env(noop(alice), msig(demon, demon), fee(3 * baseFee), - rpc("invalidTransaction", - "fails local checks: Duplicate Signers not allowed.")); + rpc("invalidTransaction", "fails local checks: Duplicate Signers not allowed.")); env.close(); BEAST_EXPECT(env.seq(alice) == aliceSeq); // A non-signer should fail. aliceSeq = env.seq(alice); - env(noop(alice), - msig(bogie, spook), - fee(3 * baseFee), - ter(tefBAD_SIGNATURE)); + env(noop(alice), msig(bogie, spook), fee(3 * baseFee), ter(tefBAD_SIGNATURE)); env.close(); BEAST_EXPECT(env.seq(alice) == aliceSeq); @@ -268,14 +243,7 @@ public: env(signers( alice, 1, - {{bogie, 1}, - {demon, 1}, - {ghost, 1}, - {haunt, 1}, - {jinni, 1}, - {phase, 1}, - {shade, 1}, - {spook, 1}})); + {{bogie, 1}, {demon, 1}, {ghost, 1}, {haunt, 1}, {jinni, 1}, {phase, 1}, {shade, 1}, {spook, 1}})); env.close(); env.require(owners(alice, 1)); @@ -289,19 +257,14 @@ public: // This should fail because the fee is too small. aliceSeq = env.seq(alice); - env(noop(alice), - msig(bogie), - fee((2 * baseFee) - 1), - ter(telINSUF_FEE_P)); + env(noop(alice), msig(bogie), fee((2 * baseFee) - 1), ter(telINSUF_FEE_P)); env.close(); BEAST_EXPECT(env.seq(alice) == aliceSeq); // This should work. aliceSeq = env.seq(alice); - env(noop(alice), - msig(bogie, demon, ghost, haunt, jinni, phase, shade, spook), - fee(9 * baseFee)); + env(noop(alice), msig(bogie, demon, ghost, haunt, jinni, phase, shade, spook), fee(9 * baseFee)); env.close(); BEAST_EXPECT(env.seq(alice) == aliceSeq + 1); @@ -337,10 +300,7 @@ public: msig phantoms{bogie, demon}; std::reverse(phantoms.signers.begin(), phantoms.signers.end()); std::uint32_t const aliceSeq = env.seq(alice); - env(noop(alice), - phantoms, - rpc("invalidTransaction", - "fails local checks: Unsorted Signers array.")); + env(noop(alice), phantoms, rpc("invalidTransaction", "fails local checks: Unsorted Signers array.")); env.close(); BEAST_EXPECT(env.seq(alice) == aliceSeq); } @@ -438,10 +398,7 @@ public: // cheri should not be able to multisign using her master key. aliceSeq = env.seq(alice); - env(noop(alice), - msig(cheri), - fee(2 * baseFee), - ter(tefMASTER_DISABLED)); + env(noop(alice), msig(cheri), fee(2 * baseFee), ter(tefMASTER_DISABLED)); env.close(); BEAST_EXPECT(env.seq(alice) == aliceSeq); @@ -458,9 +415,7 @@ public: // Both becky and cheri should be able to sign using regular keys. aliceSeq = env.seq(alice); - env(noop(alice), - fee(3 * baseFee), - msig(Reg{becky, beck}, Reg{cheri, cher})); + env(noop(alice), fee(3 * baseFee), msig(Reg{becky, beck}, Reg{cheri, cher})); env.close(); BEAST_EXPECT(env.seq(alice) == aliceSeq + 1); } @@ -527,8 +482,7 @@ public: aliceSeq = env.seq(alice); Json::Value jv_one = setup_tx(); cheri_sign(jv_one); - auto jrr = - env.rpc("json", "sign_for", to_string(jv_one))[jss::result]; + auto jrr = env.rpc("json", "sign_for", to_string(jv_one))[jss::result]; BEAST_EXPECT(jrr[jss::status] == "success"); // for the second sign_for, use the returned tx_json with @@ -541,10 +495,7 @@ public: Json::Value jv_submit; jv_submit[jss::tx_json] = jrr[jss::tx_json]; - jrr = env.rpc( - "json", - "submit_multisigned", - to_string(jv_submit))[jss::result]; + jrr = env.rpc("json", "submit_multisigned", to_string(jv_submit))[jss::result]; BEAST_EXPECT(jrr[jss::status] == "success"); env.close(); BEAST_EXPECT(env.seq(alice) == aliceSeq + 1); @@ -554,16 +505,12 @@ public: // failure case -- SigningPubKey not empty aliceSeq = env.seq(alice); Json::Value jv_one = setup_tx(); - jv_one[jss::tx_json][jss::SigningPubKey] = - strHex(alice.pk().slice()); + jv_one[jss::tx_json][jss::SigningPubKey] = strHex(alice.pk().slice()); cheri_sign(jv_one); - auto jrr = - env.rpc("json", "sign_for", to_string(jv_one))[jss::result]; + auto jrr = env.rpc("json", "sign_for", to_string(jv_one))[jss::result]; BEAST_EXPECT(jrr[jss::status] == "error"); BEAST_EXPECT(jrr[jss::error] == "invalidParams"); - BEAST_EXPECT( - jrr[jss::error_message] == - "When multi-signing 'tx_json.SigningPubKey' must be empty."); + BEAST_EXPECT(jrr[jss::error_message] == "When multi-signing 'tx_json.SigningPubKey' must be empty."); } { @@ -572,8 +519,7 @@ public: Json::Value jv_one = setup_tx(); jv_one[jss::tx_json][jss::Fee] = -1; cheri_sign(jv_one); - auto jrr = - env.rpc("json", "sign_for", to_string(jv_one))[jss::result]; + auto jrr = env.rpc("json", "sign_for", to_string(jv_one))[jss::result]; BEAST_EXPECT(jrr[jss::status] == "success"); // for the second sign_for, use the returned tx_json with @@ -586,26 +532,19 @@ public: Json::Value jv_submit; jv_submit[jss::tx_json] = jrr[jss::tx_json]; - jrr = env.rpc( - "json", - "submit_multisigned", - to_string(jv_submit))[jss::result]; + jrr = env.rpc("json", "submit_multisigned", to_string(jv_submit))[jss::result]; BEAST_EXPECT(jrr[jss::status] == "error"); BEAST_EXPECT(jrr[jss::error] == "invalidParams"); - BEAST_EXPECT( - jrr[jss::error_message] == - "Invalid Fee field. Fees must be greater than zero."); + BEAST_EXPECT(jrr[jss::error_message] == "Invalid Fee field. Fees must be greater than zero."); } { // failure case - bad fee v2 aliceSeq = env.seq(alice); Json::Value jv_one = setup_tx(); - jv_one[jss::tx_json][jss::Fee] = - alice["USD"](10).value().getFullText(); + jv_one[jss::tx_json][jss::Fee] = alice["USD"](10).value().getFullText(); cheri_sign(jv_one); - auto jrr = - env.rpc("json", "sign_for", to_string(jv_one))[jss::result]; + auto jrr = env.rpc("json", "sign_for", to_string(jv_one))[jss::result]; BEAST_EXPECT(jrr[jss::status] == "success"); // for the second sign_for, use the returned tx_json with @@ -618,10 +557,7 @@ public: Json::Value jv_submit; jv_submit[jss::tx_json] = jrr[jss::tx_json]; - jrr = env.rpc( - "json", - "submit_multisigned", - to_string(jv_submit))[jss::result]; + jrr = env.rpc("json", "submit_multisigned", to_string(jv_submit))[jss::result]; BEAST_EXPECT(jrr[jss::status] == "error"); BEAST_EXPECT(jrr[jss::error] == "internal"); BEAST_EXPECT(jrr[jss::error_message] == "Internal error."); @@ -646,8 +582,7 @@ public: aliceSeq = env.seq(alice); Json::Value jv_one = setup_tx(); cheri_sign(jv_one); - auto jrr = - env.rpc("json", "sign_for", to_string(jv_one))[jss::result]; + auto jrr = env.rpc("json", "sign_for", to_string(jv_one))[jss::result]; BEAST_EXPECT(jrr[jss::status] == "success"); // for the second sign_for, use the returned tx_json with @@ -662,10 +597,7 @@ public: Json::Value jv_submit; jv_submit[jss::tx_json] = jrr[jss::tx_json]; - jrr = env.rpc( - "json", - "submit_multisigned", - to_string(jv_submit))[jss::result]; + jrr = env.rpc("json", "submit_multisigned", to_string(jv_submit))[jss::result]; BEAST_EXPECT(jrr[jss::status] == "success"); env.close(); BEAST_EXPECT(env.seq(alice) == aliceSeq + 1); @@ -690,16 +622,12 @@ public: { aliceSeq = env.seq(alice); Json::Value jv = setup_tx(); - jv[jss::tx_json][sfSigners.fieldName] = - Json::Value{Json::arrayValue}; + jv[jss::tx_json][sfSigners.fieldName] = Json::Value{Json::arrayValue}; becky_sign(jv); - auto jrr = env.rpc( - "json", "submit_multisigned", to_string(jv))[jss::result]; + auto jrr = env.rpc("json", "submit_multisigned", to_string(jv))[jss::result]; BEAST_EXPECT(jrr[jss::status] == "error"); BEAST_EXPECT(jrr[jss::error] == "invalidParams"); - BEAST_EXPECT( - jrr[jss::error_message] == - "tx_json.Signers array may not be empty."); + BEAST_EXPECT(jrr[jss::error_message] == "tx_json.Signers array may not be empty."); env.close(); BEAST_EXPECT(env.seq(alice) == aliceSeq); } @@ -737,8 +665,7 @@ public: env.close(); // Attach signers to alice. - env(signers(alice, 1, {{becky, 1}, {cheri, 1}, {daria, 1}, {jinni, 1}}), - sig(alie)); + env(signers(alice, 1, {{becky, 1}, {cheri, 1}, {daria, 1}, {jinni, 1}}), sig(alie)); env.close(); env.require(owners(alice, 1)); @@ -771,36 +698,23 @@ public: // Should also work if all signers sign. aliceSeq = env.seq(alice); - env(noop(alice), - fee(5 * baseFee), - msig(becky, Reg{cheri, cher}, Reg{daria, dari}, jinni)); + env(noop(alice), fee(5 * baseFee), msig(becky, Reg{cheri, cher}, Reg{daria, dari}, jinni)); env.close(); BEAST_EXPECT(env.seq(alice) == aliceSeq + 1); // Require all signers to sign. - env(signers( - alice, - 0x3FFFC, - {{becky, 0xFFFF}, - {cheri, 0xFFFF}, - {daria, 0xFFFF}, - {jinni, 0xFFFF}}), - sig(alie)); + env(signers(alice, 0x3FFFC, {{becky, 0xFFFF}, {cheri, 0xFFFF}, {daria, 0xFFFF}, {jinni, 0xFFFF}}), sig(alie)); env.close(); env.require(owners(alice, 1)); aliceSeq = env.seq(alice); - env(noop(alice), - fee(9 * baseFee), - msig(becky, Reg{cheri, cher}, Reg{daria, dari}, jinni)); + env(noop(alice), fee(9 * baseFee), msig(becky, Reg{cheri, cher}, Reg{daria, dari}, jinni)); env.close(); BEAST_EXPECT(env.seq(alice) == aliceSeq + 1); // Try cheri with both key types. aliceSeq = env.seq(alice); - env(noop(alice), - fee(5 * baseFee), - msig(becky, cheri, Reg{daria, dari}, jinni)); + env(noop(alice), fee(5 * baseFee), msig(becky, cheri, Reg{daria, dari}, jinni)); env.close(); BEAST_EXPECT(env.seq(alice) == aliceSeq + 1); @@ -823,24 +737,13 @@ public: aliceSeq = env.seq(alice); env(noop(alice), fee(9 * baseFee), - msig( - becky, - Reg{cheri, cher}, - Reg{daria, dari}, - haunt, - jinni, - phase, - shade, - spook)); + msig(becky, Reg{cheri, cher}, Reg{daria, dari}, haunt, jinni, phase, shade, spook)); env.close(); BEAST_EXPECT(env.seq(alice) == aliceSeq + 1); // One signer short should fail. aliceSeq = env.seq(alice); - env(noop(alice), - msig(becky, cheri, haunt, jinni, phase, shade, spook), - fee(8 * baseFee), - ter(tefBAD_QUORUM)); + env(noop(alice), msig(becky, cheri, haunt, jinni, phase, shade, spook), fee(8 * baseFee), ter(tefBAD_QUORUM)); env.close(); BEAST_EXPECT(env.seq(alice) == aliceSeq); @@ -880,9 +783,7 @@ public: // Master key tests. // M0: A lone master key cannot be disabled. - env(fset(alice, asfDisableMaster), - sig(alice), - ter(tecNO_ALTERNATIVE_KEY)); + env(fset(alice, asfDisableMaster), sig(alice), ter(tecNO_ALTERNATIVE_KEY)); // Add a regular key. Account const alie{"alie", KeyType::ed25519}; @@ -902,10 +803,7 @@ public: // L0: A lone signer list cannot be removed. auto const baseFee = env.current()->fees().base; - env(signers(alice, jtx::none), - msig(bogie), - fee(2 * baseFee), - ter(tecNO_ALTERNATIVE_KEY)); + env(signers(alice, jtx::none), msig(bogie), fee(2 * baseFee), ter(tecNO_ALTERNATIVE_KEY)); // Enable the master key. env(fclear(alice, asfDisableMaster), msig(bogie), fee(2 * baseFee)); @@ -999,9 +897,7 @@ public: // Multisign a ttPAYMENT. auto const baseFee = env.current()->fees().base; std::uint32_t aliceSeq = env.seq(alice); - env(pay(alice, env.master, XRP(1)), - msig(becky, bogie), - fee(3 * baseFee)); + env(pay(alice, env.master, XRP(1)), msig(becky, bogie), fee(3 * baseFee)); env.close(); BEAST_EXPECT(env.seq(alice) == aliceSeq + 1); @@ -1019,10 +915,7 @@ public: BEAST_EXPECT(env.seq(alice) == aliceSeq + 1); // Multisign a ttTRUST_SET - env(trust("alice", USD(100)), - msig(becky, bogie), - fee(3 * baseFee), - require(lines("alice", 1))); + env(trust("alice", USD(100)), msig(becky, bogie), fee(3 * baseFee), require(lines("alice", 1))); env.close(); env.require(owners(alice, 2)); @@ -1033,28 +926,21 @@ public: env.require(balance(gw, alice["USD"](-50))); std::uint32_t const offerSeq = env.seq(alice); - env(offer(alice, XRP(50), USD(50)), - msig(becky, bogie), - fee(3 * baseFee)); + env(offer(alice, XRP(50), USD(50)), msig(becky, bogie), fee(3 * baseFee)); env.close(); env.require(owners(alice, 3)); // Now multisign a ttOFFER_CANCEL canceling the offer we just created. { aliceSeq = env.seq(alice); - env(offer_cancel(alice, offerSeq), - seq(aliceSeq), - msig(becky, bogie), - fee(3 * baseFee)); + env(offer_cancel(alice, offerSeq), seq(aliceSeq), msig(becky, bogie), fee(3 * baseFee)); env.close(); BEAST_EXPECT(env.seq(alice) == aliceSeq + 1); env.require(owners(alice, 2)); } // Multisign a ttSIGNER_LIST_SET. - env(signers(alice, 3, {{becky, 1}, {bogie, 1}, {demon, 1}}), - msig(becky, bogie), - fee(3 * baseFee)); + env(signers(alice, 3, {{becky, 1}, {bogie, 1}, {demon, 1}}), msig(becky, bogie), fee(3 * baseFee)); env.close(); env.require(owners(alice, 2)); } @@ -1088,9 +974,7 @@ public: STTx local = *(tx.stx); local.setFieldVL(sfSigningPubKey, Blob()); // Empty SigningPubKey auto const info = submitSTTx(local); - BEAST_EXPECT( - info[jss::result][jss::error_exception] == - "fails local checks: Empty SigningPubKey."); + BEAST_EXPECT(info[jss::result][jss::error_exception] == "fails local checks: Empty SigningPubKey."); } { // Single-sign, but invalidate the signature. @@ -1102,9 +986,7 @@ public: local.setFieldVL(sfTxnSignature, badSig); // Signature should fail. auto const info = submitSTTx(local); - BEAST_EXPECT( - info[jss::result][jss::error_exception] == - "fails local checks: Invalid signature."); + BEAST_EXPECT(info[jss::result][jss::error_exception] == "fails local checks: Invalid signature."); } { // Single-sign, but invalidate the sequence number. @@ -1115,9 +997,7 @@ public: local.setFieldU32(sfSequence, seq + 1); // Signature should fail. auto const info = submitSTTx(local); - BEAST_EXPECT( - info[jss::result][jss::error_exception] == - "fails local checks: Invalid signature."); + BEAST_EXPECT(info[jss::result][jss::error_exception] == "fails local checks: Invalid signature."); } { // Multisign, but leave a nonempty sfSigningPubKey. @@ -1126,8 +1006,7 @@ public: local[sfSigningPubKey] = alice.pk(); // Insert sfSigningPubKey auto const info = submitSTTx(local); BEAST_EXPECT( - info[jss::result][jss::error_exception] == - "fails local checks: Cannot both single- and multi-sign."); + info[jss::result][jss::error_exception] == "fails local checks: Cannot both single- and multi-sign."); } { // Both multi- and single-sign with an empty SigningPubKey. @@ -1137,8 +1016,7 @@ public: local.setFieldVL(sfSigningPubKey, Blob()); // Empty SigningPubKey auto const info = submitSTTx(local); BEAST_EXPECT( - info[jss::result][jss::error_exception] == - "fails local checks: Cannot both single- and multi-sign."); + info[jss::result][jss::error_exception] == "fails local checks: Cannot both single- and multi-sign."); } { // Multisign but invalidate one of the signatures. @@ -1152,8 +1030,8 @@ public: // Signature should fail. auto const info = submitSTTx(local); BEAST_EXPECT( - info[jss::result][jss::error_exception].asString().find( - "Invalid signature on account r") != std::string::npos); + info[jss::result][jss::error_exception].asString().find("Invalid signature on account r") != + std::string::npos); } { // Multisign with an empty signers array should fail. @@ -1161,9 +1039,7 @@ public: STTx local = *(tx.stx); local.peekFieldArray(sfSigners).clear(); // Empty Signers array. auto const info = submitSTTx(local); - BEAST_EXPECT( - info[jss::result][jss::error_exception] == - "fails local checks: Invalid Signers array size."); + BEAST_EXPECT(info[jss::result][jss::error_exception] == "fails local checks: Invalid Signers array size."); } { JTx tx = env.jt( @@ -1206,18 +1082,14 @@ public: bogie)); STTx local = *(tx.stx); auto const info = submitSTTx(local); - BEAST_EXPECT( - info[jss::result][jss::error_exception] == - "fails local checks: Invalid Signers array size."); + BEAST_EXPECT(info[jss::result][jss::error_exception] == "fails local checks: Invalid Signers array size."); } { // The account owner may not multisign for themselves. JTx tx = env.jt(noop(alice), fee(2 * baseFee), msig(alice)); STTx local = *(tx.stx); auto const info = submitSTTx(local); - BEAST_EXPECT( - info[jss::result][jss::error_exception] == - "fails local checks: Invalid multisigner."); + BEAST_EXPECT(info[jss::result][jss::error_exception] == "fails local checks: Invalid multisigner."); } { // No duplicate multisignatures allowed. @@ -1225,8 +1097,7 @@ public: STTx local = *(tx.stx); auto const info = submitSTTx(local); BEAST_EXPECT( - info[jss::result][jss::error_exception] == - "fails local checks: Duplicate Signers not allowed."); + info[jss::result][jss::error_exception] == "fails local checks: Duplicate Signers not allowed."); } { // Multisignatures must be submitted in sorted order. @@ -1237,9 +1108,7 @@ public: std::reverse(signers.begin(), signers.end()); // Signature should fail. auto const info = submitSTTx(local); - BEAST_EXPECT( - info[jss::result][jss::error_exception] == - "fails local checks: Unsorted Signers array."); + BEAST_EXPECT(info[jss::result][jss::error_exception] == "fails local checks: Unsorted Signers array."); } } @@ -1256,10 +1125,7 @@ public: env.close(); auto const baseFee = env.current()->fees().base; - env(noop(alice), - msig(becky, demon), - fee(3 * baseFee), - ter(tefNOT_MULTI_SIGNING)); + env(noop(alice), msig(becky, demon), fee(3 * baseFee), ter(tefNOT_MULTI_SIGNING)); } void @@ -1299,27 +1165,18 @@ public: // Since becky's master key is disabled she can no longer // multisign for alice. - env(noop(alice), - msig(becky), - fee(2 * baseFee), - ter(tefMASTER_DISABLED)); + env(noop(alice), msig(becky), fee(2 * baseFee), ter(tefMASTER_DISABLED)); env.close(); // Becky cannot 2-level multisign for alice. 2-level multisigning // is not supported. - env(noop(alice), - msig(Reg{becky, bogie}), - fee(2 * baseFee), - ter(tefBAD_SIGNATURE)); + env(noop(alice), msig(Reg{becky, bogie}), fee(2 * baseFee), ter(tefBAD_SIGNATURE)); env.close(); // Verify that becky cannot sign with a regular key that she has // not yet enabled. Account const beck{"beck", KeyType::ed25519}; - env(noop(alice), - msig(Reg{becky, beck}), - fee(2 * baseFee), - ter(tefBAD_SIGNATURE)); + env(noop(alice), msig(Reg{becky, beck}), fee(2 * baseFee), ter(tefBAD_SIGNATURE)); env.close(); // Once becky gives herself the regular key, she can sign for alice @@ -1332,10 +1189,7 @@ public: // The presence of becky's regular key does not influence whether she // can 2-level multisign; it still won't work. - env(noop(alice), - msig(Reg{becky, demon}), - fee(2 * baseFee), - ter(tefBAD_SIGNATURE)); + env(noop(alice), msig(Reg{becky, demon}), fee(2 * baseFee), ter(tefBAD_SIGNATURE)); env.close(); } @@ -1381,35 +1235,26 @@ public: BEAST_EXPECT(jvSig2[jss::result][jss::status].asString() == "success"); // Save the hash with one signature for use later. - std::string const hash1 = - jvSig2[jss::result][jss::tx_json][jss::hash].asString(); + std::string const hash1 = jvSig2[jss::result][jss::tx_json][jss::hash].asString(); // Add the next signature and sign again. jvSig2[jss::result][jss::account] = ghost.human(); jvSig2[jss::result][jss::secret] = ghost.name(); - Json::Value jvSubmit = - env.rpc("json", "sign_for", to_string(jvSig2[jss::result])); - BEAST_EXPECT( - jvSubmit[jss::result][jss::status].asString() == "success"); + Json::Value jvSubmit = env.rpc("json", "sign_for", to_string(jvSig2[jss::result])); + BEAST_EXPECT(jvSubmit[jss::result][jss::status].asString() == "success"); // Save the hash with two signatures for use later. - std::string const hash2 = - jvSubmit[jss::result][jss::tx_json][jss::hash].asString(); + std::string const hash2 = jvSubmit[jss::result][jss::tx_json][jss::hash].asString(); BEAST_EXPECT(hash1 != hash2); // Submit the result of the two signatures. - Json::Value jvResult = env.rpc( - "json", "submit_multisigned", to_string(jvSubmit[jss::result])); - BEAST_EXPECT( - jvResult[jss::result][jss::status].asString() == "success"); - BEAST_EXPECT( - jvResult[jss::result][jss::engine_result].asString() == - "tesSUCCESS"); + Json::Value jvResult = env.rpc("json", "submit_multisigned", to_string(jvSubmit[jss::result])); + BEAST_EXPECT(jvResult[jss::result][jss::status].asString() == "success"); + BEAST_EXPECT(jvResult[jss::result][jss::engine_result].asString() == "tesSUCCESS"); // The hash from the submit should be the same as the hash from the // second signing. - BEAST_EXPECT( - hash2 == jvResult[jss::result][jss::tx_json][jss::hash].asString()); + BEAST_EXPECT(hash2 == jvResult[jss::result][jss::tx_json][jss::hash].asString()); env.close(); // The transaction we just submitted should now be available and @@ -1417,9 +1262,7 @@ public: Json::Value jvTx = env.rpc("tx", hash2); BEAST_EXPECT(jvTx[jss::result][jss::status].asString() == "success"); BEAST_EXPECT(jvTx[jss::result][jss::validated].asString() == "true"); - BEAST_EXPECT( - jvTx[jss::result][jss::meta][sfTransactionResult.jsonName] - .asString() == "tesSUCCESS"); + BEAST_EXPECT(jvTx[jss::result][jss::meta][sfTransactionResult.jsonName].asString() == "tesSUCCESS"); } void @@ -1440,18 +1283,14 @@ public: std::uint32_t const aliceSeq = env.seq(alice); // Attach phantom signers to alice using a ticket. - env(signers(alice, 1, {{bogie, 1}, {demon, 1}}), - ticket::use(aliceTicketSeq++)); + env(signers(alice, 1, {{bogie, 1}, {demon, 1}}), ticket::use(aliceTicketSeq++)); env.close(); env.require(tickets(alice, env.seq(alice) - aliceTicketSeq)); BEAST_EXPECT(env.seq(alice) == aliceSeq); // This should work. auto const baseFee = env.current()->fees().base; - env(noop(alice), - msig(bogie, demon), - fee(3 * baseFee), - ticket::use(aliceTicketSeq++)); + env(noop(alice), msig(bogie, demon), fee(3 * baseFee), ticket::use(aliceTicketSeq++)); env.close(); env.require(tickets(alice, env.seq(alice) - aliceTicketSeq)); BEAST_EXPECT(env.seq(alice) == aliceSeq); @@ -1473,13 +1312,11 @@ public: Account const alice{"alice", KeyType::ed25519}; env.fund(XRP(1000), alice); env.close(); - uint8_t tag1[] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, - 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, - 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, - 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}; + uint8_t tag1[] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, + 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, + 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}; - uint8_t tag2[] = - "hello world some ascii 32b long"; // including 1 byte for NUL + uint8_t tag2[] = "hello world some ascii 32b long"; // including 1 byte for NUL uint256 bogie_tag = xrpl::base_uint<256>::fromVoid(tag1); uint256 demon_tag = xrpl::base_uint<256>::fromVoid(tag2); @@ -1512,17 +1349,13 @@ public: env(noop(alice), msig(demon, demon), fee(3 * baseFee), - rpc("invalidTransaction", - "fails local checks: Duplicate Signers not allowed.")); + rpc("invalidTransaction", "fails local checks: Duplicate Signers not allowed.")); env.close(); BEAST_EXPECT(env.seq(alice) == aliceSeq); // A non-signer should fail. aliceSeq = env.seq(alice); - env(noop(alice), - msig(bogie, spook), - fee(3 * baseFee), - ter(tefBAD_SIGNATURE)); + env(noop(alice), msig(bogie, spook), fee(3 * baseFee), ter(tefBAD_SIGNATURE)); env.close(); BEAST_EXPECT(env.seq(alice) == aliceSeq); @@ -1552,14 +1385,10 @@ public: env.close(); bool const enabled = features[fixInvalidTxFlags]; - testcase( - std::string("SignerListSet flag, fix ") + - (enabled ? "enabled" : "disabled")); + testcase(std::string("SignerListSet flag, fix ") + (enabled ? "enabled" : "disabled")); ter const expected(enabled ? TER(temINVALID_FLAG) : TER(tesSUCCESS)); - env(signers(alice, 2, {{bogie, 1}, {ghost, 1}}), - expected, - txflags(tfPassive)); + env(signers(alice, 2, {{bogie, 1}, {ghost, 1}}), expected, txflags(tfPassive)); env.close(); } diff --git a/src/test/app/NFTokenAuth_test.cpp b/src/test/app/NFTokenAuth_test.cpp index dce8da0042..1e7afc9bb0 100644 --- a/src/test/app/NFTokenAuth_test.cpp +++ b/src/test/app/NFTokenAuth_test.cpp @@ -14,16 +14,12 @@ class NFTokenAuth_test : public beast::unit_test::suite uint32_t xfee = 0u) { using namespace test::jtx; - auto const nftID{ - token::getNextID(env, account, 0u, tfTransferable, xfee)}; - env(token::mint(account, 0), - token::xferFee(xfee), - txflags(tfTransferable)); + auto const nftID{token::getNextID(env, account, 0u, tfTransferable, xfee)}; + env(token::mint(account, 0), token::xferFee(xfee), txflags(tfTransferable)); env.close(); auto const sellIdx = keylet::nftoffer(account, env.seq(account)).key; - env(token::createOffer(account, nftID, currency), - txflags(tfSellNFToken)); + env(token::createOffer(account, nftID, currency), txflags(tfSellNFToken)); env.close(); return std::make_tuple(nftID, sellIdx); @@ -102,18 +98,14 @@ public: auto const [nftID, _] = mintAndOfferNFT(env, A2, drops(1)); // test: check that buyer can't make an offer if they're not authorized. - env(token::createOffer(A1, nftID, USD(10)), - token::owner(A2), - ter(tecUNFUNDED_OFFER)); + env(token::createOffer(A1, nftID, USD(10)), token::owner(A2), ter(tecUNFUNDED_OFFER)); env.close(); // Artificially create an unauthorized trustline with balance. Don't // close ledger before running the actual tests against this trustline. // After ledger is closed, the trustline will not exist. - auto const unauthTrustline = [&](OpenView& view, - beast::Journal) -> bool { - auto const sleA1 = - std::make_shared(keylet::line(A1, G1, G1["USD"].currency)); + auto const unauthTrustline = [&](OpenView& view, beast::Journal) -> bool { + auto const sleA1 = std::make_shared(keylet::line(A1, G1, G1["USD"].currency)); sleA1->setFieldAmount(sfBalance, A1["USD"](-1000)); view.rawInsert(sleA1); return true; @@ -123,9 +115,7 @@ public: if (features[fixEnforceNFTokenTrustlineV2]) { // test: check that buyer can't make an offer even with balance - env(token::createOffer(A1, nftID, USD(10)), - token::owner(A2), - ter(tecNO_AUTH)); + env(token::createOffer(A1, nftID, USD(10)), token::owner(A2), ter(tecNO_AUTH)); } else { @@ -177,10 +167,8 @@ public: // trustline with balance. Don't close ledger before running the actual // tests against this trustline. After ledger is closed, the trustline // will not exist. - auto const unauthTrustline = [&](OpenView& view, - beast::Journal) -> bool { - auto const sleA1 = - std::make_shared(keylet::line(A1, G1, G1["USD"].currency)); + auto const unauthTrustline = [&](OpenView& view, beast::Journal) -> bool { + auto const sleA1 = std::make_shared(keylet::line(A1, G1, G1["USD"].currency)); sleA1->setFieldAmount(sfBalance, A1["USD"](-1000)); view.rawInsert(sleA1); return true; @@ -222,15 +210,11 @@ public: { // test: can't create sell offer if there is no trustline but auth // required - env(token::createOffer(A2, nftID, USD(10)), - txflags(tfSellNFToken), - ter(tecNO_LINE)); + env(token::createOffer(A2, nftID, USD(10)), txflags(tfSellNFToken), ter(tecNO_LINE)); env(trust(A2, limit)); // test: can't create sell offer if not authorized to hold token - env(token::createOffer(A2, nftID, USD(10)), - txflags(tfSellNFToken), - ter(tecNO_AUTH)); + env(token::createOffer(A2, nftID, USD(10)), txflags(tfSellNFToken), ter(tecNO_AUTH)); // Authorizing trustline to make an offer creation possible env(trust(G1, USD(0), A2, tfSetfAuth)); @@ -303,10 +287,8 @@ public: env.close(); // Creating an artificial unauth trustline - auto const unauthTrustline = [&](OpenView& view, - beast::Journal) -> bool { - auto const sleA1 = - std::make_shared(keylet::line(A1, G1, G1["USD"].currency)); + auto const unauthTrustline = [&](OpenView& view, beast::Journal) -> bool { + auto const sleA1 = std::make_shared(keylet::line(A1, G1, G1["USD"].currency)); sleA1->setFieldAmount(sfBalance, A1["USD"](-1000)); view.rawInsert(sleA1); return true; @@ -353,9 +335,7 @@ public: if (features[fixEnforceNFTokenTrustlineV2]) { // test: G1 requires authorization of broker, no trust line exists - env(token::brokerOffers(broker, buyIdx, sellIdx), - token::brokerFee(USD(1)), - ter(tecNO_LINE)); + env(token::brokerOffers(broker, buyIdx, sellIdx), token::brokerFee(USD(1)), ter(tecNO_LINE)); env.close(); // trust line created, but not authorized @@ -363,9 +343,7 @@ public: env.close(); // test: G1 requires authorization of broker - env(token::brokerOffers(broker, buyIdx, sellIdx), - token::brokerFee(USD(1)), - ter(tecNO_AUTH)); + env(token::brokerOffers(broker, buyIdx, sellIdx), token::brokerFee(USD(1)), ter(tecNO_AUTH)); env.close(); // test: can still be brokered without broker fee. @@ -375,8 +353,7 @@ public: else { // Old behavior: broker can receive IOUs without the authorization - env(token::brokerOffers(broker, buyIdx, sellIdx), - token::brokerFee(USD(1))); + env(token::brokerOffers(broker, buyIdx, sellIdx), token::brokerFee(USD(1))); env.close(); BEAST_EXPECT(env.balance(broker, USD) == USD(1)); @@ -425,10 +402,8 @@ public: env(trust(A1, USD(0))); env.close(); - auto const unauthTrustline = [&](OpenView& view, - beast::Journal) -> bool { - auto const sleA1 = - std::make_shared(keylet::line(A1, G1, G1["USD"].currency)); + auto const unauthTrustline = [&](OpenView& view, beast::Journal) -> bool { + auto const sleA1 = std::make_shared(keylet::line(A1, G1, G1["USD"].currency)); sleA1->setFieldAmount(sfBalance, A1["USD"](-1000)); view.rawInsert(sleA1); return true; @@ -438,9 +413,7 @@ public: if (features[fixEnforceNFTokenTrustlineV2]) { // test: G1 requires authorization of A2 - env(token::brokerOffers(broker, buyIdx, sellIdx), - token::brokerFee(USD(1)), - ter(tecNO_AUTH)); + env(token::brokerOffers(broker, buyIdx, sellIdx), token::brokerFee(USD(1)), ter(tecNO_AUTH)); env.close(); } } @@ -491,9 +464,7 @@ public: if (features[fixEnforceNFTokenTrustlineV2]) { // test: G1 requires authorization of broker, no trust line exists - env(token::brokerOffers(broker, buyIdx, sellIdx), - token::brokerFee(USD(1)), - ter(tecNO_LINE)); + env(token::brokerOffers(broker, buyIdx, sellIdx), token::brokerFee(USD(1)), ter(tecNO_LINE)); env.close(); // trust line created, but not authorized @@ -501,9 +472,7 @@ public: env.close(); // test: G1 requires authorization of A2 - env(token::brokerOffers(broker, buyIdx, sellIdx), - token::brokerFee(USD(1)), - ter(tecNO_AUTH)); + env(token::brokerOffers(broker, buyIdx, sellIdx), token::brokerFee(USD(1)), ter(tecNO_AUTH)); env.close(); // test: cannot be brokered even without broker fee. @@ -513,8 +482,7 @@ public: else { // Old behavior: broker can receive IOUs without the authorization - env(token::brokerOffers(broker, buyIdx, sellIdx), - token::brokerFee(USD(1))); + env(token::brokerOffers(broker, buyIdx, sellIdx), token::brokerFee(USD(1))); env.close(); BEAST_EXPECT(env.balance(A2, USD) == USD(10)); @@ -553,8 +521,7 @@ public: // We authorized A1 and A2, but not the minter. // Now mint NFT - auto const [nftID, minterSellIdx] = - mintAndOfferNFT(env, minter, drops(1), 1); + auto const [nftID, minterSellIdx] = mintAndOfferNFT(env, minter, drops(1), 1); env(token::acceptSellOffer(A1, minterSellIdx)); uint256 const sellIdx = keylet::nftoffer(A1, env.seq(A1)).key; @@ -582,8 +549,7 @@ public: using namespace test::jtx; static FeatureBitset const all{testable_amendments()}; - static std::array const features = { - all - fixEnforceNFTokenTrustlineV2, all}; + static std::array const features = {all - fixEnforceNFTokenTrustlineV2, all}; for (auto const feature : features) { diff --git a/src/test/app/NFTokenBurn_test.cpp b/src/test/app/NFTokenBurn_test.cpp index a1c6ffb6de..915bb6ec79 100644 --- a/src/test/app/NFTokenBurn_test.cpp +++ b/src/test/app/NFTokenBurn_test.cpp @@ -32,11 +32,8 @@ class NFTokenBurn_test : public beast::unit_test::suite size_t const tokenCancelCount) { using namespace test::jtx; - uint256 const nftokenID = - token::getNextID(env, owner, 0, tfTransferable); - env(token::mint(owner, 0), - token::uri(std::string(maxTokenURILength, 'u')), - txflags(tfTransferable)); + uint256 const nftokenID = token::getNextID(env, owner, 0, tfTransferable); + env(token::mint(owner, 0), token::uri(std::string(maxTokenURILength, 'u')), txflags(tfTransferable)); env.close(); offerIndexes.reserve(tokenCancelCount); @@ -45,8 +42,7 @@ class NFTokenBurn_test : public beast::unit_test::suite { // Create sell offer offerIndexes.push_back(keylet::nftoffer(owner, env.seq(owner)).key); - env(token::createOffer(owner, nftokenID, drops(1)), - txflags(tfSellNFToken)); + env(token::createOffer(owner, nftokenID, drops(1)), txflags(tfSellNFToken)); env.close(); } @@ -69,12 +65,10 @@ class NFTokenBurn_test : public beast::unit_test::suite jvParams[jss::ledger_index] = "current"; jvParams[jss::binary] = false; { - Json::Value jrr = - env.rpc("json", "ledger_data", to_string(jvParams)); + Json::Value jrr = env.rpc("json", "ledger_data", to_string(jvParams)); // Iterate the state and print all NFTokenPages. - if (!jrr.isMember(jss::result) || - !jrr[jss::result].isMember(jss::state)) + if (!jrr.isMember(jss::result) || !jrr[jss::result].isMember(jss::state)) { std::cout << "No ledger state found!" << std::endl; return; @@ -87,13 +81,10 @@ class NFTokenBurn_test : public beast::unit_test::suite } for (Json::UInt i = 0; i < state.size(); ++i) { - if (state[i].isMember(sfNFTokens.jsonName) && - state[i][sfNFTokens.jsonName].isArray()) + if (state[i].isMember(sfNFTokens.jsonName) && state[i][sfNFTokens.jsonName].isArray()) { - std::uint32_t tokenCount = - state[i][sfNFTokens.jsonName].size(); - std::cout << tokenCount << " NFtokens in page " - << state[i][jss::index].asString() << std::endl; + std::uint32_t tokenCount = state[i][sfNFTokens.jsonName].size(); + std::cout << tokenCount << " NFtokens in page " << state[i][jss::index].asString() << std::endl; if (vol == noisy) { @@ -102,16 +93,10 @@ class NFTokenBurn_test : public beast::unit_test::suite else { if (tokenCount > 0) - std::cout << "first: " - << state[i][sfNFTokens.jsonName][0u] - .toStyledString() - << std::endl; + std::cout << "first: " << state[i][sfNFTokens.jsonName][0u].toStyledString() << std::endl; if (tokenCount > 1) - std::cout - << "last: " - << state[i][sfNFTokens.jsonName][tokenCount - 1] - .toStyledString() - << std::endl; + std::cout << "last: " << state[i][sfNFTokens.jsonName][tokenCount - 1].toStyledString() + << std::endl; } } } @@ -169,18 +154,14 @@ class NFTokenBurn_test : public beast::unit_test::suite // effect of random numbers, but we want the test to run the same // way each time. std::mt19937 engine; - std::uniform_int_distribution feeDist( - decltype(maxTransferFee){}, maxTransferFee); + std::uniform_int_distribution feeDist(decltype(maxTransferFee){}, maxTransferFee); alice.nfts.reserve(105); while (alice.nfts.size() < 105) { std::uint16_t const xferFee = feeDist(engine); - alice.nfts.push_back(token::getNextID( - env, alice, 0u, tfTransferable | tfBurnable, xferFee)); - env(token::mint(alice), - txflags(tfTransferable | tfBurnable), - token::xferFee(xferFee)); + alice.nfts.push_back(token::getNextID(env, alice, 0u, tfTransferable | tfBurnable, xferFee)); + env(token::mint(alice), txflags(tfTransferable | tfBurnable), token::xferFee(xferFee)); env.close(); } @@ -188,8 +169,7 @@ class NFTokenBurn_test : public beast::unit_test::suite while (minter.nfts.size() < 105) { std::uint16_t const xferFee = feeDist(engine); - minter.nfts.push_back(token::getNextID( - env, alice, 0u, tfTransferable | tfBurnable, xferFee)); + minter.nfts.push_back(token::getNextID(env, alice, 0u, tfTransferable | tfBurnable, xferFee)); env(token::mint(minter), txflags(tfTransferable | tfBurnable), token::xferFee(xferFee), @@ -207,10 +187,8 @@ class NFTokenBurn_test : public beast::unit_test::suite { // We do the same work on alice and minter, so make a lambda. auto xferNFT = [&env, &becky](AcctStat& acct, auto& iter) { - uint256 offerIndex = - keylet::nftoffer(acct.acct, env.seq(acct.acct)).key; - env(token::createOffer(acct, *iter, XRP(0)), - txflags(tfSellNFToken)); + uint256 offerIndex = keylet::nftoffer(acct.acct, env.seq(acct.acct)).key; + env(token::createOffer(acct, *iter, XRP(0)), txflags(tfSellNFToken)); env.close(); env(token::acceptSellOffer(becky, offerIndex)); env.close(); @@ -232,33 +210,24 @@ class NFTokenBurn_test : public beast::unit_test::suite // Next we'll create offers for all of those NFTs. This calls for // another lambda. - auto addOffers = - [&env](AcctStat& owner, AcctStat& other1, AcctStat& other2) { - for (uint256 nft : owner.nfts) - { - // Create sell offers for owner. - env(token::createOffer(owner, nft, drops(1)), - txflags(tfSellNFToken), - token::destination(other1)); - env(token::createOffer(owner, nft, drops(1)), - txflags(tfSellNFToken), - token::destination(other2)); - env.close(); + auto addOffers = [&env](AcctStat& owner, AcctStat& other1, AcctStat& other2) { + for (uint256 nft : owner.nfts) + { + // Create sell offers for owner. + env(token::createOffer(owner, nft, drops(1)), txflags(tfSellNFToken), token::destination(other1)); + env(token::createOffer(owner, nft, drops(1)), txflags(tfSellNFToken), token::destination(other2)); + env.close(); - // Create buy offers for other1 and other2. - env(token::createOffer(other1, nft, drops(1)), - token::owner(owner)); - env(token::createOffer(other2, nft, drops(1)), - token::owner(owner)); - env.close(); + // Create buy offers for other1 and other2. + env(token::createOffer(other1, nft, drops(1)), token::owner(owner)); + env(token::createOffer(other2, nft, drops(1)), token::owner(owner)); + env.close(); - env(token::createOffer(other2, nft, drops(2)), - token::owner(owner)); - env(token::createOffer(other1, nft, drops(2)), - token::owner(owner)); - env.close(); - } - }; + env(token::createOffer(other2, nft, drops(2)), token::owner(owner)); + env(token::createOffer(other1, nft, drops(2)), token::owner(owner)); + env.close(); + } + }; addOffers(alice, becky, minter); addOffers(becky, minter, alice); addOffers(minter, alice, becky); @@ -273,8 +242,7 @@ class NFTokenBurn_test : public beast::unit_test::suite std::uniform_int_distribution acctDist(0, 2); std::uniform_int_distribution mintDist(0, 1); - while (stats[0]->nfts.size() > 0 || stats[1]->nfts.size() > 0 || - stats[2]->nfts.size() > 0) + while (stats[0]->nfts.size() > 0 || stats[1]->nfts.size() > 0 || stats[2]->nfts.size() > 0) { // Pick an account to burn an nft. If there are no nfts left // pick again. @@ -283,8 +251,7 @@ class NFTokenBurn_test : public beast::unit_test::suite continue; // Pick one of the nfts. - std::uniform_int_distribution nftDist( - 0lu, owner.nfts.size() - 1); + std::uniform_int_distribution nftDist(0lu, owner.nfts.size() - 1); auto nftIter = owner.nfts.begin() + nftDist(engine); uint256 const nft = *nftIter; owner.nfts.erase(nftIter); @@ -292,10 +259,9 @@ class NFTokenBurn_test : public beast::unit_test::suite // Decide which of the accounts should burn the nft. If the // owner is becky then any of the three accounts can burn. // Otherwise either alice or minter can burn. - AcctStat& burner = owner.acct == becky.acct - ? *(stats[acctDist(engine)]) - : mintDist(engine) ? alice - : minter; + AcctStat& burner = owner.acct == becky.acct ? *(stats[acctDist(engine)]) + : mintDist(engine) ? alice + : minter; if (owner.acct == burner.acct) env(token::burn(burner, nft)); @@ -350,19 +316,13 @@ class NFTokenBurn_test : public beast::unit_test::suite // creation of NFT pages that are completely full. This lambda // tells us the taxon value we should pass in in order for the // internal representation to match the passed in value. - auto internalTaxon = [&env]( - Account const& acct, - std::uint32_t taxon) -> std::uint32_t { - std::uint32_t tokenSeq = - env.le(acct)->at(~sfMintedNFTokens).value_or(0); + auto internalTaxon = [&env](Account const& acct, std::uint32_t taxon) -> std::uint32_t { + std::uint32_t tokenSeq = env.le(acct)->at(~sfMintedNFTokens).value_or(0); // We must add FirstNFTokenSequence. - tokenSeq += env.le(acct) - ->at(~sfFirstNFTokenSequence) - .value_or(env.seq(acct)); + tokenSeq += env.le(acct)->at(~sfFirstNFTokenSequence).value_or(env.seq(acct)); - return toUInt32( - nft::cipheredTaxon(tokenSeq, nft::toTaxon(taxon))); + return toUInt32(nft::cipheredTaxon(tokenSeq, nft::toTaxon(taxon))); }; for (std::uint32_t i = 0; i < 96; ++i) @@ -390,19 +350,16 @@ class NFTokenBurn_test : public beast::unit_test::suite jvParams[jss::ledger_index] = "current"; jvParams[jss::binary] = false; { - Json::Value jrr = - env.rpc("json", "ledger_data", to_string(jvParams)); + Json::Value jrr = env.rpc("json", "ledger_data", to_string(jvParams)); Json::Value& state = jrr[jss::result][jss::state]; int pageCount = 0; for (Json::UInt i = 0; i < state.size(); ++i) { - if (state[i].isMember(sfNFTokens.jsonName) && - state[i][sfNFTokens.jsonName].isArray()) + if (state[i].isMember(sfNFTokens.jsonName) && state[i][sfNFTokens.jsonName].isArray()) { - BEAST_EXPECT( - state[i][sfNFTokens.jsonName].size() == 32); + BEAST_EXPECT(state[i][sfNFTokens.jsonName].size() == 32); ++pageCount; } } @@ -435,8 +392,7 @@ class NFTokenBurn_test : public beast::unit_test::suite jvParams[jss::ledger_index] = "current"; jvParams[jss::binary] = false; { - Json::Value jrr = - env.rpc("json", "ledger_data", to_string(jvParams)); + Json::Value jrr = env.rpc("json", "ledger_data", to_string(jvParams)); Json::Value& state = jrr[jss::result][jss::state]; @@ -461,17 +417,13 @@ class NFTokenBurn_test : public beast::unit_test::suite if (!BEAST_EXPECT(lastNFTokenPage)) return; - uint256 const middleNFTokenPageIndex = - lastNFTokenPage->at(sfPreviousPageMin); - auto middleNFTokenPage = env.le(keylet::nftpage( - keylet::nftpage_min(alice), middleNFTokenPageIndex)); + uint256 const middleNFTokenPageIndex = lastNFTokenPage->at(sfPreviousPageMin); + auto middleNFTokenPage = env.le(keylet::nftpage(keylet::nftpage_min(alice), middleNFTokenPageIndex)); if (!BEAST_EXPECT(middleNFTokenPage)) return; - uint256 const firstNFTokenPageIndex = - middleNFTokenPage->at(sfPreviousPageMin); - auto firstNFTokenPage = env.le(keylet::nftpage( - keylet::nftpage_min(alice), firstNFTokenPageIndex)); + uint256 const firstNFTokenPageIndex = middleNFTokenPage->at(sfPreviousPageMin); + auto firstNFTokenPage = env.le(keylet::nftpage(keylet::nftpage_min(alice), firstNFTokenPageIndex)); if (!BEAST_EXPECT(firstNFTokenPage)) return; @@ -489,8 +441,7 @@ class NFTokenBurn_test : public beast::unit_test::suite if (!BEAST_EXPECT(lastNFTokenPage)) return; - BEAST_EXPECT( - lastNFTokenPage->getFieldArray(sfNFTokens).size() == 1); + BEAST_EXPECT(lastNFTokenPage->getFieldArray(sfNFTokens).size() == 1); BEAST_EXPECT(lastNFTokenPage->isFieldPresent(sfPreviousPageMin)); BEAST_EXPECT(!lastNFTokenPage->isFieldPresent(sfNextPageMin)); @@ -507,30 +458,21 @@ class NFTokenBurn_test : public beast::unit_test::suite // are moved into the last page. lastNFTokenPage = env.le(keylet::nftpage_max(alice)); BEAST_EXPECT(lastNFTokenPage); - BEAST_EXPECT( - lastNFTokenPage->at(~sfPreviousPageMin) == - firstNFTokenPageIndex); + BEAST_EXPECT(lastNFTokenPage->at(~sfPreviousPageMin) == firstNFTokenPageIndex); BEAST_EXPECT(!lastNFTokenPage->isFieldPresent(sfNextPageMin)); - BEAST_EXPECT( - lastNFTokenPage->getFieldArray(sfNFTokens).size() == 32); + BEAST_EXPECT(lastNFTokenPage->getFieldArray(sfNFTokens).size() == 32); // The "middle" page should be gone. - middleNFTokenPage = env.le(keylet::nftpage( - keylet::nftpage_min(alice), middleNFTokenPageIndex)); + middleNFTokenPage = env.le(keylet::nftpage(keylet::nftpage_min(alice), middleNFTokenPageIndex)); BEAST_EXPECT(!middleNFTokenPage); // The "first" page should still be present and linked to // the last page. - firstNFTokenPage = env.le(keylet::nftpage( - keylet::nftpage_min(alice), firstNFTokenPageIndex)); + firstNFTokenPage = env.le(keylet::nftpage(keylet::nftpage_min(alice), firstNFTokenPageIndex)); BEAST_EXPECT(firstNFTokenPage); - BEAST_EXPECT( - !firstNFTokenPage->isFieldPresent(sfPreviousPageMin)); - BEAST_EXPECT( - firstNFTokenPage->at(~sfNextPageMin) == - lastNFTokenPage->key()); - BEAST_EXPECT( - lastNFTokenPage->getFieldArray(sfNFTokens).size() == 32); + BEAST_EXPECT(!firstNFTokenPage->isFieldPresent(sfPreviousPageMin)); + BEAST_EXPECT(firstNFTokenPage->at(~sfNextPageMin) == lastNFTokenPage->key()); + BEAST_EXPECT(lastNFTokenPage->getFieldArray(sfNFTokens).size() == 32); } else { @@ -542,12 +484,10 @@ class NFTokenBurn_test : public beast::unit_test::suite // The "middle" page is still present, but has lost the // NextPageMin field. - middleNFTokenPage = env.le(keylet::nftpage( - keylet::nftpage_min(alice), middleNFTokenPageIndex)); + middleNFTokenPage = env.le(keylet::nftpage(keylet::nftpage_min(alice), middleNFTokenPageIndex)); if (!BEAST_EXPECT(middleNFTokenPage)) return; - BEAST_EXPECT( - middleNFTokenPage->isFieldPresent(sfPreviousPageMin)); + BEAST_EXPECT(middleNFTokenPage->isFieldPresent(sfPreviousPageMin)); BEAST_EXPECT(!middleNFTokenPage->isFieldPresent(sfNextPageMin)); } @@ -576,17 +516,13 @@ class NFTokenBurn_test : public beast::unit_test::suite if (!BEAST_EXPECT(lastNFTokenPage)) return; - uint256 const middleNFTokenPageIndex = - lastNFTokenPage->at(sfPreviousPageMin); - auto middleNFTokenPage = env.le(keylet::nftpage( - keylet::nftpage_min(alice), middleNFTokenPageIndex)); + uint256 const middleNFTokenPageIndex = lastNFTokenPage->at(sfPreviousPageMin); + auto middleNFTokenPage = env.le(keylet::nftpage(keylet::nftpage_min(alice), middleNFTokenPageIndex)); if (!BEAST_EXPECT(middleNFTokenPage)) return; - uint256 const firstNFTokenPageIndex = - middleNFTokenPage->at(sfPreviousPageMin); - auto firstNFTokenPage = env.le(keylet::nftpage( - keylet::nftpage_min(alice), firstNFTokenPageIndex)); + uint256 const firstNFTokenPageIndex = middleNFTokenPage->at(sfPreviousPageMin); + auto firstNFTokenPage = env.le(keylet::nftpage(keylet::nftpage_min(alice), firstNFTokenPageIndex)); if (!BEAST_EXPECT(firstNFTokenPage)) return; @@ -601,21 +537,15 @@ class NFTokenBurn_test : public beast::unit_test::suite // Verify that middle page is gone and the links in the two // remaining pages are correct. - middleNFTokenPage = env.le(keylet::nftpage( - keylet::nftpage_min(alice), middleNFTokenPageIndex)); + middleNFTokenPage = env.le(keylet::nftpage(keylet::nftpage_min(alice), middleNFTokenPageIndex)); BEAST_EXPECT(!middleNFTokenPage); lastNFTokenPage = env.le(keylet::nftpage_max(alice)); BEAST_EXPECT(!lastNFTokenPage->isFieldPresent(sfNextPageMin)); - BEAST_EXPECT( - lastNFTokenPage->getFieldH256(sfPreviousPageMin) == - firstNFTokenPageIndex); + BEAST_EXPECT(lastNFTokenPage->getFieldH256(sfPreviousPageMin) == firstNFTokenPageIndex); - firstNFTokenPage = env.le(keylet::nftpage( - keylet::nftpage_min(alice), firstNFTokenPageIndex)); - BEAST_EXPECT( - firstNFTokenPage->getFieldH256(sfNextPageMin) == - keylet::nftpage_max(alice).key); + firstNFTokenPage = env.le(keylet::nftpage(keylet::nftpage_min(alice), firstNFTokenPageIndex)); + BEAST_EXPECT(firstNFTokenPage->getFieldH256(sfNextPageMin) == keylet::nftpage_max(alice).key); BEAST_EXPECT(!firstNFTokenPage->isFieldPresent(sfPreviousPageMin)); // Burn the remaining nfts. @@ -642,17 +572,13 @@ class NFTokenBurn_test : public beast::unit_test::suite if (!BEAST_EXPECT(lastNFTokenPage)) return; - uint256 const middleNFTokenPageIndex = - lastNFTokenPage->at(sfPreviousPageMin); - auto middleNFTokenPage = env.le(keylet::nftpage( - keylet::nftpage_min(alice), middleNFTokenPageIndex)); + uint256 const middleNFTokenPageIndex = lastNFTokenPage->at(sfPreviousPageMin); + auto middleNFTokenPage = env.le(keylet::nftpage(keylet::nftpage_min(alice), middleNFTokenPageIndex)); if (!BEAST_EXPECT(middleNFTokenPage)) return; - uint256 const firstNFTokenPageIndex = - middleNFTokenPage->at(sfPreviousPageMin); - auto firstNFTokenPage = env.le(keylet::nftpage( - keylet::nftpage_min(alice), firstNFTokenPageIndex)); + uint256 const firstNFTokenPageIndex = middleNFTokenPage->at(sfPreviousPageMin); + auto firstNFTokenPage = env.le(keylet::nftpage(keylet::nftpage_min(alice), firstNFTokenPageIndex)); if (!BEAST_EXPECT(firstNFTokenPage)) return; @@ -666,13 +592,11 @@ class NFTokenBurn_test : public beast::unit_test::suite } // Verify the first page is gone. - firstNFTokenPage = env.le(keylet::nftpage( - keylet::nftpage_min(alice), firstNFTokenPageIndex)); + firstNFTokenPage = env.le(keylet::nftpage(keylet::nftpage_min(alice), firstNFTokenPageIndex)); BEAST_EXPECT(!firstNFTokenPage); // Check the links in the other two pages. - middleNFTokenPage = env.le(keylet::nftpage( - keylet::nftpage_min(alice), middleNFTokenPageIndex)); + middleNFTokenPage = env.le(keylet::nftpage(keylet::nftpage_min(alice), middleNFTokenPageIndex)); if (!BEAST_EXPECT(middleNFTokenPage)) return; BEAST_EXPECT(!middleNFTokenPage->isFieldPresent(sfPreviousPageMin)); @@ -701,20 +625,16 @@ class NFTokenBurn_test : public beast::unit_test::suite // are moved into the last page. lastNFTokenPage = env.le(keylet::nftpage_max(alice)); BEAST_EXPECT(lastNFTokenPage); - BEAST_EXPECT( - !lastNFTokenPage->isFieldPresent(sfPreviousPageMin)); + BEAST_EXPECT(!lastNFTokenPage->isFieldPresent(sfPreviousPageMin)); BEAST_EXPECT(!lastNFTokenPage->isFieldPresent(sfNextPageMin)); - BEAST_EXPECT( - lastNFTokenPage->getFieldArray(sfNFTokens).size() == 32); + BEAST_EXPECT(lastNFTokenPage->getFieldArray(sfNFTokens).size() == 32); // The "middle" page should be gone. - middleNFTokenPage = env.le(keylet::nftpage( - keylet::nftpage_min(alice), middleNFTokenPageIndex)); + middleNFTokenPage = env.le(keylet::nftpage(keylet::nftpage_min(alice), middleNFTokenPageIndex)); BEAST_EXPECT(!middleNFTokenPage); // The "first" page should still be gone. - firstNFTokenPage = env.le(keylet::nftpage( - keylet::nftpage_min(alice), firstNFTokenPageIndex)); + firstNFTokenPage = env.le(keylet::nftpage(keylet::nftpage_min(alice), firstNFTokenPageIndex)); BEAST_EXPECT(!firstNFTokenPage); } else @@ -727,12 +647,10 @@ class NFTokenBurn_test : public beast::unit_test::suite // The "middle" page is still present, but has lost the // NextPageMin field. - middleNFTokenPage = env.le(keylet::nftpage( - keylet::nftpage_min(alice), middleNFTokenPageIndex)); + middleNFTokenPage = env.le(keylet::nftpage(keylet::nftpage_min(alice), middleNFTokenPageIndex)); if (!BEAST_EXPECT(middleNFTokenPage)) return; - BEAST_EXPECT( - !middleNFTokenPage->isFieldPresent(sfPreviousPageMin)); + BEAST_EXPECT(!middleNFTokenPage->isFieldPresent(sfPreviousPageMin)); BEAST_EXPECT(!middleNFTokenPage->isFieldPresent(sfNextPageMin)); } @@ -779,40 +697,28 @@ class NFTokenBurn_test : public beast::unit_test::suite STTx tx{ttACCOUNT_SET, [](STObject&) {}}; test::StreamSink sink{beast::severities::kWarning}; beast::Journal jlog{sink}; - ApplyContext ac{ - env.app(), - ov, - tx, - tesSUCCESS, - env.current()->fees().base, - tapNONE, - jlog}; + ApplyContext ac{env.app(), ov, tx, tesSUCCESS, env.current()->fees().base, tapNONE, jlog}; // Verify that the last page is present and contains one NFT. - auto lastNFTokenPage = - ac.view().peek(keylet::nftpage_max(alice)); + auto lastNFTokenPage = ac.view().peek(keylet::nftpage_max(alice)); if (!BEAST_EXPECT(lastNFTokenPage)) return; - BEAST_EXPECT( - lastNFTokenPage->getFieldArray(sfNFTokens).size() == 1); + BEAST_EXPECT(lastNFTokenPage->getFieldArray(sfNFTokens).size() == 1); // Erase that last page. ac.view().erase(lastNFTokenPage); // Exercise the invariant. TER terActual = tesSUCCESS; - for (TER const& terExpect : - {TER(tecINVARIANT_FAILED), TER(tefINVARIANT_FAILED)}) + for (TER const& terExpect : {TER(tecINVARIANT_FAILED), TER(tefINVARIANT_FAILED)}) { terActual = ac.checkInvariants(terActual, XRPAmount{}); BEAST_EXPECT(terExpect == terActual); - BEAST_EXPECT( - sink.messages().str().starts_with("Invariant failed:")); + BEAST_EXPECT(sink.messages().str().starts_with("Invariant failed:")); // uncomment to log the invariant failure message // log << " --> " << sink.messages().str() << std::endl; BEAST_EXPECT( - sink.messages().str().find( - "Last NFT page deleted with non-empty directory") != + sink.messages().str().find("Last NFT page deleted with non-empty directory") != std::string::npos); } } @@ -823,21 +729,12 @@ class NFTokenBurn_test : public beast::unit_test::suite STTx tx{ttACCOUNT_SET, [](STObject&) {}}; test::StreamSink sink{beast::severities::kWarning}; beast::Journal jlog{sink}; - ApplyContext ac{ - env.app(), - ov, - tx, - tesSUCCESS, - env.current()->fees().base, - tapNONE, - jlog}; + ApplyContext ac{env.app(), ov, tx, tesSUCCESS, env.current()->fees().base, tapNONE, jlog}; // Verify that the middle page is present. - auto lastNFTokenPage = - ac.view().peek(keylet::nftpage_max(alice)); - auto middleNFTokenPage = ac.view().peek(keylet::nftpage( - keylet::nftpage_min(alice), - lastNFTokenPage->getFieldH256(sfPreviousPageMin))); + auto lastNFTokenPage = ac.view().peek(keylet::nftpage_max(alice)); + auto middleNFTokenPage = ac.view().peek( + keylet::nftpage(keylet::nftpage_min(alice), lastNFTokenPage->getFieldH256(sfPreviousPageMin))); BEAST_EXPECT(middleNFTokenPage); // Remove the NextMinPage link from the middle page to fire @@ -847,18 +744,14 @@ class NFTokenBurn_test : public beast::unit_test::suite // Exercise the invariant. TER terActual = tesSUCCESS; - for (TER const& terExpect : - {TER(tecINVARIANT_FAILED), TER(tefINVARIANT_FAILED)}) + for (TER const& terExpect : {TER(tecINVARIANT_FAILED), TER(tefINVARIANT_FAILED)}) { terActual = ac.checkInvariants(terActual, XRPAmount{}); BEAST_EXPECT(terExpect == terActual); - BEAST_EXPECT( - sink.messages().str().starts_with("Invariant failed:")); + BEAST_EXPECT(sink.messages().str().starts_with("Invariant failed:")); // uncomment to log the invariant failure message // log << " --> " << sink.messages().str() << std::endl; - BEAST_EXPECT( - sink.messages().str().find("Lost NextMinPage link") != - std::string::npos); + BEAST_EXPECT(sink.messages().str().find("Lost NextMinPage link") != std::string::npos); } } } @@ -887,8 +780,7 @@ class NFTokenBurn_test : public beast::unit_test::suite // When the token is burned, 498 sell offers and 1 buy offer are // removed. In total, 499 offers are removed std::vector offerIndexes; - auto const nftokenID = createNftAndOffers( - env, alice, offerIndexes, maxDeletableTokenOfferEntries - 2); + auto const nftokenID = createNftAndOffers(env, alice, offerIndexes, maxDeletableTokenOfferEntries - 2); // Verify all sell offers are present in the ledger. for (uint256 const& offerIndex : offerIndexes) @@ -897,10 +789,8 @@ class NFTokenBurn_test : public beast::unit_test::suite } // Becky creates a buy offer - uint256 const beckyOfferIndex = - keylet::nftoffer(becky, env.seq(becky)).key; - env(token::createOffer(becky, nftokenID, drops(1)), - token::owner(alice)); + uint256 const beckyOfferIndex = keylet::nftoffer(becky, env.seq(becky)).key; + env(token::createOffer(becky, nftokenID, drops(1)), token::owner(alice)); env.close(); // Burn the token @@ -936,8 +826,7 @@ class NFTokenBurn_test : public beast::unit_test::suite // After we burn the token, 500 of the sell offers should be // removed, and one is left over std::vector offerIndexes; - auto const nftokenID = createNftAndOffers( - env, alice, offerIndexes, maxDeletableTokenOfferEntries + 1); + auto const nftokenID = createNftAndOffers(env, alice, offerIndexes, maxDeletableTokenOfferEntries + 1); // Verify all sell offers are present in the ledger. for (uint256 const& offerIndex : offerIndexes) @@ -980,8 +869,7 @@ class NFTokenBurn_test : public beast::unit_test::suite // are removed. // In total, 500 offers are removed std::vector offerIndexes; - auto const nftokenID = createNftAndOffers( - env, alice, offerIndexes, maxDeletableTokenOfferEntries - 1); + auto const nftokenID = createNftAndOffers(env, alice, offerIndexes, maxDeletableTokenOfferEntries - 1); // Verify all sell offers are present in the ledger. for (uint256 const& offerIndex : offerIndexes) @@ -990,11 +878,9 @@ class NFTokenBurn_test : public beast::unit_test::suite } // becky creates 2 buy offers - env(token::createOffer(becky, nftokenID, drops(1)), - token::owner(alice)); + env(token::createOffer(becky, nftokenID, drops(1)), token::owner(alice)); env.close(); - env(token::createOffer(becky, nftokenID, drops(1)), - token::owner(alice)); + env(token::createOffer(becky, nftokenID, drops(1)), token::owner(alice)); env.close(); // Burn the token @@ -1052,19 +938,13 @@ class NFTokenBurn_test : public beast::unit_test::suite // creation of NFT pages that are completely full. This lambda // tells us the taxon value we should pass in in order for the // internal representation to match the passed in value. - auto internalTaxon = [&env]( - Account const& acct, - std::uint32_t taxon) -> std::uint32_t { - std::uint32_t tokenSeq = - env.le(acct)->at(~sfMintedNFTokens).value_or(0); + auto internalTaxon = [&env](Account const& acct, std::uint32_t taxon) -> std::uint32_t { + std::uint32_t tokenSeq = env.le(acct)->at(~sfMintedNFTokens).value_or(0); // We must add FirstNFTokenSequence. - tokenSeq += env.le(acct) - ->at(~sfFirstNFTokenSequence) - .value_or(env.seq(acct)); + tokenSeq += env.le(acct)->at(~sfFirstNFTokenSequence).value_or(env.seq(acct)); - return toUInt32( - nft::cipheredTaxon(tokenSeq, nft::toTaxon(taxon))); + return toUInt32(nft::cipheredTaxon(tokenSeq, nft::toTaxon(taxon))); }; for (std::uint32_t i = 0; i < 96; ++i) @@ -1077,16 +957,13 @@ class NFTokenBurn_test : public beast::unit_test::suite // populated. std::uint32_t const intTaxon = (i / 16) + (i & 0b10000 ? 2 : 0); uint32_t const extTaxon = internalTaxon(minter, intTaxon); - nfts.push_back( - token::getNextID(env, minter, extTaxon, tfTransferable)); + nfts.push_back(token::getNextID(env, minter, extTaxon, tfTransferable)); env(token::mint(minter, extTaxon), txflags(tfTransferable)); env.close(); // Minter creates an offer for the NFToken. - uint256 const minterOfferIndex = - keylet::nftoffer(minter, env.seq(minter)).key; - env(token::createOffer(minter, nfts.back(), XRP(0)), - txflags(tfSellNFToken)); + uint256 const minterOfferIndex = keylet::nftoffer(minter, env.seq(minter)).key; + env(token::createOffer(minter, nfts.back(), XRP(0)), txflags(tfSellNFToken)); env.close(); // alice accepts the offer. @@ -1104,19 +981,16 @@ class NFTokenBurn_test : public beast::unit_test::suite jvParams[jss::ledger_index] = "current"; jvParams[jss::binary] = false; { - Json::Value jrr = - env.rpc("json", "ledger_data", to_string(jvParams)); + Json::Value jrr = env.rpc("json", "ledger_data", to_string(jvParams)); Json::Value& state = jrr[jss::result][jss::state]; int pageCount = 0; for (Json::UInt i = 0; i < state.size(); ++i) { - if (state[i].isMember(sfNFTokens.jsonName) && - state[i][sfNFTokens.jsonName].isArray()) + if (state[i].isMember(sfNFTokens.jsonName) && state[i][sfNFTokens.jsonName].isArray()) { - BEAST_EXPECT( - state[i][sfNFTokens.jsonName].size() == 32); + BEAST_EXPECT(state[i][sfNFTokens.jsonName].size() == 32); ++pageCount; } } @@ -1138,17 +1012,13 @@ class NFTokenBurn_test : public beast::unit_test::suite if (!BEAST_EXPECT(lastNFTokenPage)) return; - uint256 const middleNFTokenPageIndex = - lastNFTokenPage->at(sfPreviousPageMin); - auto middleNFTokenPage = env.le(keylet::nftpage( - keylet::nftpage_min(alice), middleNFTokenPageIndex)); + uint256 const middleNFTokenPageIndex = lastNFTokenPage->at(sfPreviousPageMin); + auto middleNFTokenPage = env.le(keylet::nftpage(keylet::nftpage_min(alice), middleNFTokenPageIndex)); if (!BEAST_EXPECT(middleNFTokenPage)) return; - uint256 const firstNFTokenPageIndex = - middleNFTokenPage->at(sfPreviousPageMin); - auto firstNFTokenPage = env.le( - keylet::nftpage(keylet::nftpage_min(alice), firstNFTokenPageIndex)); + uint256 const firstNFTokenPageIndex = middleNFTokenPage->at(sfPreviousPageMin); + auto firstNFTokenPage = env.le(keylet::nftpage(keylet::nftpage_min(alice), firstNFTokenPageIndex)); if (!BEAST_EXPECT(firstNFTokenPage)) return; @@ -1160,10 +1030,8 @@ class NFTokenBurn_test : public beast::unit_test::suite nfts.pop_back(); // alice creates an offer for the NFToken. - uint256 const aliceOfferIndex = - keylet::nftoffer(alice, env.seq(alice)).key; - env(token::createOffer(alice, last32NFTs.back(), XRP(0)), - txflags(tfSellNFToken)); + uint256 const aliceOfferIndex = keylet::nftoffer(alice, env.seq(alice)).key; + env(token::createOffer(alice, last32NFTs.back(), XRP(0)), txflags(tfSellNFToken)); env.close(); // minter accepts the offer. @@ -1180,8 +1048,7 @@ class NFTokenBurn_test : public beast::unit_test::suite // The "middle" page is still present, but has lost the // NextPageMin field. - middleNFTokenPage = env.le(keylet::nftpage( - keylet::nftpage_min(alice), middleNFTokenPageIndex)); + middleNFTokenPage = env.le(keylet::nftpage(keylet::nftpage_min(alice), middleNFTokenPageIndex)); if (!BEAST_EXPECT(middleNFTokenPage)) return; BEAST_EXPECT(middleNFTokenPage->isFieldPresent(sfPreviousPageMin)); @@ -1189,19 +1056,15 @@ class NFTokenBurn_test : public beast::unit_test::suite // Attempt to delete alice's account, but fail because she owns NFTs. auto const acctDelFee{drops(env.current()->fees().increment)}; - env(acctdelete(alice, minter), - fee(acctDelFee), - ter(tecHAS_OBLIGATIONS)); + env(acctdelete(alice, minter), fee(acctDelFee), ter(tecHAS_OBLIGATIONS)); env.close(); // minter sells the last 32 NFTs back to alice. for (uint256 nftID : last32NFTs) { // minter creates an offer for the NFToken. - uint256 const minterOfferIndex = - keylet::nftoffer(minter, env.seq(minter)).key; - env(token::createOffer(minter, nftID, XRP(0)), - txflags(tfSellNFToken)); + uint256 const minterOfferIndex = keylet::nftoffer(minter, env.seq(minter)).key; + env(token::createOffer(minter, nftID, XRP(0)), txflags(tfSellNFToken)); env.close(); // alice accepts the offer. @@ -1220,8 +1083,7 @@ class NFTokenBurn_test : public beast::unit_test::suite return env.rpc("json", "account_objects", to_string(params)); }(); BEAST_EXPECT(!acctObjs.isMember(jss::marker)); - BEAST_EXPECT( - acctObjs[jss::result][jss::account_objects].size() == 2); + BEAST_EXPECT(acctObjs[jss::result][jss::account_objects].size() == 2); } { // Try the account_nfts RPC command. It only returns 64 NFTs @@ -1233,8 +1095,7 @@ class NFTokenBurn_test : public beast::unit_test::suite return env.rpc("json", "account_nfts", to_string(params)); }(); BEAST_EXPECT(!aliceNFTs.isMember(jss::marker)); - BEAST_EXPECT( - aliceNFTs[jss::result][jss::account_nfts].size() == 64); + BEAST_EXPECT(aliceNFTs[jss::result][jss::account_nfts].size() == 64); } } diff --git a/src/test/app/NFTokenDir_test.cpp b/src/test/app/NFTokenDir_test.cpp index 9718a5d073..65bd97ec32 100644 --- a/src/test/app/NFTokenDir_test.cpp +++ b/src/test/app/NFTokenDir_test.cpp @@ -28,12 +28,10 @@ class NFTokenDir_test : public beast::unit_test::suite jvParams[jss::ledger_index] = "current"; jvParams[jss::binary] = false; { - Json::Value jrr = - env.rpc("json", "ledger_data", to_string(jvParams)); + Json::Value jrr = env.rpc("json", "ledger_data", to_string(jvParams)); // Iterate the state and print all NFTokenPages. - if (!jrr.isMember(jss::result) || - !jrr[jss::result].isMember(jss::state)) + if (!jrr.isMember(jss::result) || !jrr[jss::result].isMember(jss::state)) { std::cout << "No ledger state found!" << std::endl; return; @@ -46,13 +44,10 @@ class NFTokenDir_test : public beast::unit_test::suite } for (Json::UInt i = 0; i < state.size(); ++i) { - if (state[i].isMember(sfNFTokens.jsonName) && - state[i][sfNFTokens.jsonName].isArray()) + if (state[i].isMember(sfNFTokens.jsonName) && state[i][sfNFTokens.jsonName].isArray()) { - std::uint32_t tokenCount = - state[i][sfNFTokens.jsonName].size(); - std::cout << tokenCount << " NFtokens in page " - << state[i][jss::index].asString() << std::endl; + std::uint32_t tokenCount = state[i][sfNFTokens.jsonName].size(); + std::cout << tokenCount << " NFtokens in page " << state[i][jss::index].asString() << std::endl; if (vol == noisy) { @@ -61,16 +56,10 @@ class NFTokenDir_test : public beast::unit_test::suite else { if (tokenCount > 0) - std::cout << "first: " - << state[i][sfNFTokens.jsonName][0u] - .toStyledString() - << std::endl; + std::cout << "first: " << state[i][sfNFTokens.jsonName][0u].toStyledString() << std::endl; if (tokenCount > 1) - std::cout - << "last: " - << state[i][sfNFTokens.jsonName][tokenCount - 1] - .toStyledString() - << std::endl; + std::cout << "last: " << state[i][sfNFTokens.jsonName][tokenCount - 1].toStyledString() + << std::endl; } } } @@ -106,10 +95,8 @@ class NFTokenDir_test : public beast::unit_test::suite nftIDs.reserve(nftCount); for (int i = 0; i < nftCount; ++i) { - std::uint32_t taxon = - toUInt32(nft::cipheredTaxon(i, nft::toTaxon(0))); - nftIDs.emplace_back( - token::getNextID(env, issuer, taxon, tfTransferable)); + std::uint32_t taxon = toUInt32(nft::cipheredTaxon(i, nft::toTaxon(0))); + nftIDs.emplace_back(token::getNextID(env, issuer, taxon, tfTransferable)); env(token::mint(issuer, taxon), txflags(tfTransferable)); env.close(); } @@ -120,8 +107,7 @@ class NFTokenDir_test : public beast::unit_test::suite for (uint256 const& nftID : nftIDs) { offers.emplace_back(keylet::nftoffer(issuer, env.seq(issuer)).key); - env(token::createOffer(issuer, nftID, XRP(0)), - txflags((tfSellNFToken))); + env(token::createOffer(issuer, nftID, XRP(0)), txflags((tfSellNFToken))); env.close(); } @@ -153,203 +139,187 @@ class NFTokenDir_test : public beast::unit_test::suite // with identical 96-low-bits are all kept on the same page. // Lambda that exercises the lopsided splits. - auto exerciseLopsided = - [this, - &features](std::initializer_list seeds) { - Env env{*this, features}; + auto exerciseLopsided = [this, &features](std::initializer_list seeds) { + Env env{*this, features}; - // Eventually all of the NFTokens will be owned by buyer. - Account const buyer{"buyer"}; - env.fund(XRP(10000), buyer); + // Eventually all of the NFTokens will be owned by buyer. + Account const buyer{"buyer"}; + env.fund(XRP(10000), buyer); + env.close(); + + // Create accounts for all of the seeds and fund those accounts. + std::vector accounts; + accounts.reserve(seeds.size()); + for (std::string_view seed : seeds) + { + Account const& account = accounts.emplace_back(Account::base58Seed, std::string(seed)); + env.fund(XRP(10000), account); + + // Do not close the ledger inside the loop. If accounts are + // initialized at different ledgers, they will have + // different account sequences. That would cause the + // accounts to have different NFTokenID sequence numbers. + } + env.close(); + + // All of the accounts create one NFT and and offer that NFT to + // buyer. + std::vector nftIDs; + std::vector offers; + offers.reserve(accounts.size()); + for (Account const& account : accounts) + { + // Mint the NFT. + uint256 const& nftID = nftIDs.emplace_back(token::getNextID(env, account, 0, tfTransferable)); + env(token::mint(account, 0), txflags(tfTransferable)); env.close(); - // Create accounts for all of the seeds and fund those accounts. - std::vector accounts; - accounts.reserve(seeds.size()); - for (std::string_view seed : seeds) - { - Account const& account = accounts.emplace_back( - Account::base58Seed, std::string(seed)); - env.fund(XRP(10000), account); + // Create an offer to give the NFT to buyer for free. + offers.emplace_back(keylet::nftoffer(account, env.seq(account)).key); + env(token::createOffer(account, nftID, XRP(0)), token::destination(buyer), txflags((tfSellNFToken))); + } + env.close(); - // Do not close the ledger inside the loop. If accounts are - // initialized at different ledgers, they will have - // different account sequences. That would cause the - // accounts to have different NFTokenID sequence numbers. - } + // buyer accepts all of the offers. + for (uint256 const& offer : offers) + { + env(token::acceptSellOffer(buyer, offer)); + env.close(); + } + + // This can be a good time to look at the NFT pages. + // printNFTPages(env, noisy); + + // Verify that all NFTs are owned by buyer and findable in the + // ledger by having buyer create sell offers for all of their + // NFTs. Attempting to sell an offer that the ledger can't find + // generates a non-tesSUCCESS error code. + for (uint256 const& nftID : nftIDs) + { + uint256 const offerID = keylet::nftoffer(buyer, env.seq(buyer)).key; + env(token::createOffer(buyer, nftID, XRP(100)), txflags(tfSellNFToken)); env.close(); - // All of the accounts create one NFT and and offer that NFT to - // buyer. - std::vector nftIDs; - std::vector offers; - offers.reserve(accounts.size()); - for (Account const& account : accounts) - { - // Mint the NFT. - uint256 const& nftID = nftIDs.emplace_back( - token::getNextID(env, account, 0, tfTransferable)); - env(token::mint(account, 0), txflags(tfTransferable)); - env.close(); + env(token::cancelOffer(buyer, {offerID})); + } - // Create an offer to give the NFT to buyer for free. - offers.emplace_back( - keylet::nftoffer(account, env.seq(account)).key); - env(token::createOffer(account, nftID, XRP(0)), - token::destination(buyer), - txflags((tfSellNFToken))); - } - env.close(); + // Verify that all the NFTs are owned by buyer. + Json::Value buyerNFTs = [&env, &buyer]() { + Json::Value params; + params[jss::account] = buyer.human(); + params[jss::type] = "state"; + return env.rpc("json", "account_nfts", to_string(params)); + }(); - // buyer accepts all of the offers. - for (uint256 const& offer : offers) - { - env(token::acceptSellOffer(buyer, offer)); - env.close(); - } + BEAST_EXPECT(buyerNFTs[jss::result][jss::account_nfts].size() == nftIDs.size()); + for (Json::Value const& ownedNFT : buyerNFTs[jss::result][jss::account_nfts]) + { + uint256 ownedID; + BEAST_EXPECT(ownedID.parseHex(ownedNFT[sfNFTokenID.jsonName].asString())); + auto const foundIter = std::find(nftIDs.begin(), nftIDs.end(), ownedID); - // This can be a good time to look at the NFT pages. - // printNFTPages(env, noisy); + // Assuming we find the NFT, erase it so we know it's been + // found and can't be found again. + if (BEAST_EXPECT(foundIter != nftIDs.end())) + nftIDs.erase(foundIter); + } - // Verify that all NFTs are owned by buyer and findable in the - // ledger by having buyer create sell offers for all of their - // NFTs. Attempting to sell an offer that the ledger can't find - // generates a non-tesSUCCESS error code. - for (uint256 const& nftID : nftIDs) - { - uint256 const offerID = - keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftID, XRP(100)), - txflags(tfSellNFToken)); - env.close(); - - env(token::cancelOffer(buyer, {offerID})); - } - - // Verify that all the NFTs are owned by buyer. - Json::Value buyerNFTs = [&env, &buyer]() { - Json::Value params; - params[jss::account] = buyer.human(); - params[jss::type] = "state"; - return env.rpc("json", "account_nfts", to_string(params)); - }(); - - BEAST_EXPECT( - buyerNFTs[jss::result][jss::account_nfts].size() == - nftIDs.size()); - for (Json::Value const& ownedNFT : - buyerNFTs[jss::result][jss::account_nfts]) - { - uint256 ownedID; - BEAST_EXPECT(ownedID.parseHex( - ownedNFT[sfNFTokenID.jsonName].asString())); - auto const foundIter = - std::find(nftIDs.begin(), nftIDs.end(), ownedID); - - // Assuming we find the NFT, erase it so we know it's been - // found and can't be found again. - if (BEAST_EXPECT(foundIter != nftIDs.end())) - nftIDs.erase(foundIter); - } - - // All NFTs should now be accounted for, so nftIDs should be - // empty. - BEAST_EXPECT(nftIDs.empty()); - }; + // All NFTs should now be accounted for, so nftIDs should be + // empty. + BEAST_EXPECT(nftIDs.empty()); + }; // These seeds cause a lopsided split where the new NFT is added // to the upper page. - static std::initializer_list const - splitAndAddToHi{ - "sp6JS7f14BuwFY8Mw5p3b8jjQBBTK", // 0. 0x1d2932ea - "sp6JS7f14BuwFY8Mw6F7X3EiGKazu", // 1. 0x1d2932ea - "sp6JS7f14BuwFY8Mw6FxjntJJfKXq", // 2. 0x1d2932ea - "sp6JS7f14BuwFY8Mw6eSF1ydEozJg", // 3. 0x1d2932ea - "sp6JS7f14BuwFY8Mw6koPB91um2ej", // 4. 0x1d2932ea - "sp6JS7f14BuwFY8Mw6m6D64iwquSe", // 5. 0x1d2932ea + static std::initializer_list const splitAndAddToHi{ + "sp6JS7f14BuwFY8Mw5p3b8jjQBBTK", // 0. 0x1d2932ea + "sp6JS7f14BuwFY8Mw6F7X3EiGKazu", // 1. 0x1d2932ea + "sp6JS7f14BuwFY8Mw6FxjntJJfKXq", // 2. 0x1d2932ea + "sp6JS7f14BuwFY8Mw6eSF1ydEozJg", // 3. 0x1d2932ea + "sp6JS7f14BuwFY8Mw6koPB91um2ej", // 4. 0x1d2932ea + "sp6JS7f14BuwFY8Mw6m6D64iwquSe", // 5. 0x1d2932ea - "sp6JS7f14BuwFY8Mw5rC43sN4adC2", // 6. 0x208dbc24 - "sp6JS7f14BuwFY8Mw65L9DDQqgebz", // 7. 0x208dbc24 - "sp6JS7f14BuwFY8Mw65nKvU8pPQNn", // 8. 0x208dbc24 - "sp6JS7f14BuwFY8Mw6bxZLyTrdipw", // 9. 0x208dbc24 - "sp6JS7f14BuwFY8Mw6d5abucntSoX", // 10. 0x208dbc24 - "sp6JS7f14BuwFY8Mw6qXK5awrRRP8", // 11. 0x208dbc24 + "sp6JS7f14BuwFY8Mw5rC43sN4adC2", // 6. 0x208dbc24 + "sp6JS7f14BuwFY8Mw65L9DDQqgebz", // 7. 0x208dbc24 + "sp6JS7f14BuwFY8Mw65nKvU8pPQNn", // 8. 0x208dbc24 + "sp6JS7f14BuwFY8Mw6bxZLyTrdipw", // 9. 0x208dbc24 + "sp6JS7f14BuwFY8Mw6d5abucntSoX", // 10. 0x208dbc24 + "sp6JS7f14BuwFY8Mw6qXK5awrRRP8", // 11. 0x208dbc24 - // These eight need to be kept together by the implementation. - "sp6JS7f14BuwFY8Mw66EBtMxoMcCa", // 12. 0x309b67ed - "sp6JS7f14BuwFY8Mw66dGfE9jVfGv", // 13. 0x309b67ed - "sp6JS7f14BuwFY8Mw6APdZa7PH566", // 14. 0x309b67ed - "sp6JS7f14BuwFY8Mw6C3QX5CZyET5", // 15. 0x309b67ed - "sp6JS7f14BuwFY8Mw6CSysFf8GvaR", // 16. 0x309b67ed - "sp6JS7f14BuwFY8Mw6c7QSDmoAeRV", // 17. 0x309b67ed - "sp6JS7f14BuwFY8Mw6mvonveaZhW7", // 18. 0x309b67ed - "sp6JS7f14BuwFY8Mw6vtHHG7dYcXi", // 19. 0x309b67ed + // These eight need to be kept together by the implementation. + "sp6JS7f14BuwFY8Mw66EBtMxoMcCa", // 12. 0x309b67ed + "sp6JS7f14BuwFY8Mw66dGfE9jVfGv", // 13. 0x309b67ed + "sp6JS7f14BuwFY8Mw6APdZa7PH566", // 14. 0x309b67ed + "sp6JS7f14BuwFY8Mw6C3QX5CZyET5", // 15. 0x309b67ed + "sp6JS7f14BuwFY8Mw6CSysFf8GvaR", // 16. 0x309b67ed + "sp6JS7f14BuwFY8Mw6c7QSDmoAeRV", // 17. 0x309b67ed + "sp6JS7f14BuwFY8Mw6mvonveaZhW7", // 18. 0x309b67ed + "sp6JS7f14BuwFY8Mw6vtHHG7dYcXi", // 19. 0x309b67ed - "sp6JS7f14BuwFY8Mw66yppUNxESaw", // 20. 0x40d4b96f - "sp6JS7f14BuwFY8Mw6ATYQvobXiDT", // 21. 0x40d4b96f - "sp6JS7f14BuwFY8Mw6bis8D1Wa9Uy", // 22. 0x40d4b96f - "sp6JS7f14BuwFY8Mw6cTiGCWA8Wfa", // 23. 0x40d4b96f - "sp6JS7f14BuwFY8Mw6eAy2fpXmyYf", // 24. 0x40d4b96f - "sp6JS7f14BuwFY8Mw6icn58TRs8YG", // 25. 0x40d4b96f + "sp6JS7f14BuwFY8Mw66yppUNxESaw", // 20. 0x40d4b96f + "sp6JS7f14BuwFY8Mw6ATYQvobXiDT", // 21. 0x40d4b96f + "sp6JS7f14BuwFY8Mw6bis8D1Wa9Uy", // 22. 0x40d4b96f + "sp6JS7f14BuwFY8Mw6cTiGCWA8Wfa", // 23. 0x40d4b96f + "sp6JS7f14BuwFY8Mw6eAy2fpXmyYf", // 24. 0x40d4b96f + "sp6JS7f14BuwFY8Mw6icn58TRs8YG", // 25. 0x40d4b96f - "sp6JS7f14BuwFY8Mw68tj2eQEWoJt", // 26. 0x503b6ba9 - "sp6JS7f14BuwFY8Mw6AjnAinNnMHT", // 27. 0x503b6ba9 - "sp6JS7f14BuwFY8Mw6CKDUwB4LrhL", // 28. 0x503b6ba9 - "sp6JS7f14BuwFY8Mw6d2yPszEFA6J", // 29. 0x503b6ba9 - "sp6JS7f14BuwFY8Mw6jcBQBH3PfnB", // 30. 0x503b6ba9 - "sp6JS7f14BuwFY8Mw6qxx19KSnN1w", // 31. 0x503b6ba9 + "sp6JS7f14BuwFY8Mw68tj2eQEWoJt", // 26. 0x503b6ba9 + "sp6JS7f14BuwFY8Mw6AjnAinNnMHT", // 27. 0x503b6ba9 + "sp6JS7f14BuwFY8Mw6CKDUwB4LrhL", // 28. 0x503b6ba9 + "sp6JS7f14BuwFY8Mw6d2yPszEFA6J", // 29. 0x503b6ba9 + "sp6JS7f14BuwFY8Mw6jcBQBH3PfnB", // 30. 0x503b6ba9 + "sp6JS7f14BuwFY8Mw6qxx19KSnN1w", // 31. 0x503b6ba9 - // Adding this NFT splits the page. It is added to the upper - // page. - "sp6JS7f14BuwFY8Mw6ut1hFrqWoY5", // 32. 0x503b6ba9 - }; + // Adding this NFT splits the page. It is added to the upper + // page. + "sp6JS7f14BuwFY8Mw6ut1hFrqWoY5", // 32. 0x503b6ba9 + }; // These seeds cause a lopsided split where the new NFT is added // to the lower page. - static std::initializer_list const - splitAndAddToLo{ - "sp6JS7f14BuwFY8Mw5p3b8jjQBBTK", // 0. 0x1d2932ea - "sp6JS7f14BuwFY8Mw6F7X3EiGKazu", // 1. 0x1d2932ea - "sp6JS7f14BuwFY8Mw6FxjntJJfKXq", // 2. 0x1d2932ea - "sp6JS7f14BuwFY8Mw6eSF1ydEozJg", // 3. 0x1d2932ea - "sp6JS7f14BuwFY8Mw6koPB91um2ej", // 4. 0x1d2932ea - "sp6JS7f14BuwFY8Mw6m6D64iwquSe", // 5. 0x1d2932ea + static std::initializer_list const splitAndAddToLo{ + "sp6JS7f14BuwFY8Mw5p3b8jjQBBTK", // 0. 0x1d2932ea + "sp6JS7f14BuwFY8Mw6F7X3EiGKazu", // 1. 0x1d2932ea + "sp6JS7f14BuwFY8Mw6FxjntJJfKXq", // 2. 0x1d2932ea + "sp6JS7f14BuwFY8Mw6eSF1ydEozJg", // 3. 0x1d2932ea + "sp6JS7f14BuwFY8Mw6koPB91um2ej", // 4. 0x1d2932ea + "sp6JS7f14BuwFY8Mw6m6D64iwquSe", // 5. 0x1d2932ea - "sp6JS7f14BuwFY8Mw5rC43sN4adC2", // 6. 0x208dbc24 - "sp6JS7f14BuwFY8Mw65L9DDQqgebz", // 7. 0x208dbc24 - "sp6JS7f14BuwFY8Mw65nKvU8pPQNn", // 8. 0x208dbc24 - "sp6JS7f14BuwFY8Mw6bxZLyTrdipw", // 9. 0x208dbc24 - "sp6JS7f14BuwFY8Mw6d5abucntSoX", // 10. 0x208dbc24 - "sp6JS7f14BuwFY8Mw6qXK5awrRRP8", // 11. 0x208dbc24 + "sp6JS7f14BuwFY8Mw5rC43sN4adC2", // 6. 0x208dbc24 + "sp6JS7f14BuwFY8Mw65L9DDQqgebz", // 7. 0x208dbc24 + "sp6JS7f14BuwFY8Mw65nKvU8pPQNn", // 8. 0x208dbc24 + "sp6JS7f14BuwFY8Mw6bxZLyTrdipw", // 9. 0x208dbc24 + "sp6JS7f14BuwFY8Mw6d5abucntSoX", // 10. 0x208dbc24 + "sp6JS7f14BuwFY8Mw6qXK5awrRRP8", // 11. 0x208dbc24 - // These eight need to be kept together by the implementation. - "sp6JS7f14BuwFY8Mw66EBtMxoMcCa", // 12. 0x309b67ed - "sp6JS7f14BuwFY8Mw66dGfE9jVfGv", // 13. 0x309b67ed - "sp6JS7f14BuwFY8Mw6APdZa7PH566", // 14. 0x309b67ed - "sp6JS7f14BuwFY8Mw6C3QX5CZyET5", // 15. 0x309b67ed - "sp6JS7f14BuwFY8Mw6CSysFf8GvaR", // 16. 0x309b67ed - "sp6JS7f14BuwFY8Mw6c7QSDmoAeRV", // 17. 0x309b67ed - "sp6JS7f14BuwFY8Mw6mvonveaZhW7", // 18. 0x309b67ed - "sp6JS7f14BuwFY8Mw6vtHHG7dYcXi", // 19. 0x309b67ed + // These eight need to be kept together by the implementation. + "sp6JS7f14BuwFY8Mw66EBtMxoMcCa", // 12. 0x309b67ed + "sp6JS7f14BuwFY8Mw66dGfE9jVfGv", // 13. 0x309b67ed + "sp6JS7f14BuwFY8Mw6APdZa7PH566", // 14. 0x309b67ed + "sp6JS7f14BuwFY8Mw6C3QX5CZyET5", // 15. 0x309b67ed + "sp6JS7f14BuwFY8Mw6CSysFf8GvaR", // 16. 0x309b67ed + "sp6JS7f14BuwFY8Mw6c7QSDmoAeRV", // 17. 0x309b67ed + "sp6JS7f14BuwFY8Mw6mvonveaZhW7", // 18. 0x309b67ed + "sp6JS7f14BuwFY8Mw6vtHHG7dYcXi", // 19. 0x309b67ed - "sp6JS7f14BuwFY8Mw66yppUNxESaw", // 20. 0x40d4b96f - "sp6JS7f14BuwFY8Mw6ATYQvobXiDT", // 21. 0x40d4b96f - "sp6JS7f14BuwFY8Mw6bis8D1Wa9Uy", // 22. 0x40d4b96f - "sp6JS7f14BuwFY8Mw6cTiGCWA8Wfa", // 23. 0x40d4b96f - "sp6JS7f14BuwFY8Mw6eAy2fpXmyYf", // 24. 0x40d4b96f - "sp6JS7f14BuwFY8Mw6icn58TRs8YG", // 25. 0x40d4b96f + "sp6JS7f14BuwFY8Mw66yppUNxESaw", // 20. 0x40d4b96f + "sp6JS7f14BuwFY8Mw6ATYQvobXiDT", // 21. 0x40d4b96f + "sp6JS7f14BuwFY8Mw6bis8D1Wa9Uy", // 22. 0x40d4b96f + "sp6JS7f14BuwFY8Mw6cTiGCWA8Wfa", // 23. 0x40d4b96f + "sp6JS7f14BuwFY8Mw6eAy2fpXmyYf", // 24. 0x40d4b96f + "sp6JS7f14BuwFY8Mw6icn58TRs8YG", // 25. 0x40d4b96f - "sp6JS7f14BuwFY8Mw68tj2eQEWoJt", // 26. 0x503b6ba9 - "sp6JS7f14BuwFY8Mw6AjnAinNnMHT", // 27. 0x503b6ba9 - "sp6JS7f14BuwFY8Mw6CKDUwB4LrhL", // 28. 0x503b6ba9 - "sp6JS7f14BuwFY8Mw6d2yPszEFA6J", // 29. 0x503b6ba9 - "sp6JS7f14BuwFY8Mw6jcBQBH3PfnB", // 30. 0x503b6ba9 - "sp6JS7f14BuwFY8Mw6qxx19KSnN1w", // 31. 0x503b6ba9 + "sp6JS7f14BuwFY8Mw68tj2eQEWoJt", // 26. 0x503b6ba9 + "sp6JS7f14BuwFY8Mw6AjnAinNnMHT", // 27. 0x503b6ba9 + "sp6JS7f14BuwFY8Mw6CKDUwB4LrhL", // 28. 0x503b6ba9 + "sp6JS7f14BuwFY8Mw6d2yPszEFA6J", // 29. 0x503b6ba9 + "sp6JS7f14BuwFY8Mw6jcBQBH3PfnB", // 30. 0x503b6ba9 + "sp6JS7f14BuwFY8Mw6qxx19KSnN1w", // 31. 0x503b6ba9 - // Adding this NFT splits the page. It is added to the lower - // page. - "sp6JS7f14BuwFY8Mw6xCigaMwC6Dp", // 32. 0x309b67ed - }; + // Adding this NFT splits the page. It is added to the lower + // page. + "sp6JS7f14BuwFY8Mw6xCigaMwC6Dp", // 32. 0x309b67ed + }; // Run the test cases. exerciseLopsided(splitAndAddToHi); @@ -369,118 +339,99 @@ class NFTokenDir_test : public beast::unit_test::suite // the index for the new page. This test recreates the problem. // Lambda that exercises the split. - auto exercise = - [this, - &features](std::initializer_list seeds) { - Env env{ - *this, - envconfig(), - features, - nullptr, - beast::severities::kDisabled}; + auto exercise = [this, &features](std::initializer_list seeds) { + Env env{*this, envconfig(), features, nullptr, beast::severities::kDisabled}; - // Eventually all of the NFTokens will be owned by buyer. - Account const buyer{"buyer"}; - env.fund(XRP(10000), buyer); + // Eventually all of the NFTokens will be owned by buyer. + Account const buyer{"buyer"}; + env.fund(XRP(10000), buyer); + env.close(); + + // Create accounts for all of the seeds and fund those accounts. + std::vector accounts; + accounts.reserve(seeds.size()); + for (std::string_view seed : seeds) + { + Account const& account = accounts.emplace_back(Account::base58Seed, std::string(seed)); + env.fund(XRP(10000), account); + + // Do not close the ledger inside the loop. If accounts are + // initialized at different ledgers, they will have + // different account sequences. That would cause the + // accounts to have different NFTokenID sequence numbers. + } + env.close(); + + // All of the accounts create one NFT and and offer that NFT to + // buyer. + std::vector nftIDs; + std::vector offers; + offers.reserve(accounts.size()); + for (Account const& account : accounts) + { + // Mint the NFT. + uint256 const& nftID = nftIDs.emplace_back(token::getNextID(env, account, 0, tfTransferable)); + env(token::mint(account, 0), txflags(tfTransferable)); env.close(); - // Create accounts for all of the seeds and fund those accounts. - std::vector accounts; - accounts.reserve(seeds.size()); - for (std::string_view seed : seeds) - { - Account const& account = accounts.emplace_back( - Account::base58Seed, std::string(seed)); - env.fund(XRP(10000), account); + // Create an offer to give the NFT to buyer for free. + offers.emplace_back(keylet::nftoffer(account, env.seq(account)).key); + env(token::createOffer(account, nftID, XRP(0)), token::destination(buyer), txflags((tfSellNFToken))); + } + env.close(); - // Do not close the ledger inside the loop. If accounts are - // initialized at different ledgers, they will have - // different account sequences. That would cause the - // accounts to have different NFTokenID sequence numbers. - } + // buyer accepts all of the but the last. The last offer + // causes the page to split. + for (std::size_t i = 0; i < offers.size() - 1; ++i) + { + env(token::acceptSellOffer(buyer, offers[i])); + env.close(); + } + + env(token::acceptSellOffer(buyer, offers.back())); + env.close(); + + // This can be a good time to look at the NFT pages. + // printNFTPages(env, noisy); + + // Verify that all NFTs are owned by buyer and findable in the + // ledger by having buyer create sell offers for all of their + // NFTs. Attempting to sell an offer that the ledger can't find + // generates a non-tesSUCCESS error code. + for (uint256 const& nftID : nftIDs) + { + uint256 const offerID = keylet::nftoffer(buyer, env.seq(buyer)).key; + env(token::createOffer(buyer, nftID, XRP(100)), txflags(tfSellNFToken)); env.close(); - // All of the accounts create one NFT and and offer that NFT to - // buyer. - std::vector nftIDs; - std::vector offers; - offers.reserve(accounts.size()); - for (Account const& account : accounts) - { - // Mint the NFT. - uint256 const& nftID = nftIDs.emplace_back( - token::getNextID(env, account, 0, tfTransferable)); - env(token::mint(account, 0), txflags(tfTransferable)); - env.close(); + env(token::cancelOffer(buyer, {offerID})); + } - // Create an offer to give the NFT to buyer for free. - offers.emplace_back( - keylet::nftoffer(account, env.seq(account)).key); - env(token::createOffer(account, nftID, XRP(0)), - token::destination(buyer), - txflags((tfSellNFToken))); - } - env.close(); + // Verify that all the NFTs are owned by buyer. + Json::Value buyerNFTs = [&env, &buyer]() { + Json::Value params; + params[jss::account] = buyer.human(); + params[jss::type] = "state"; + return env.rpc("json", "account_nfts", to_string(params)); + }(); - // buyer accepts all of the but the last. The last offer - // causes the page to split. - for (std::size_t i = 0; i < offers.size() - 1; ++i) - { - env(token::acceptSellOffer(buyer, offers[i])); - env.close(); - } + BEAST_EXPECT(buyerNFTs[jss::result][jss::account_nfts].size() == nftIDs.size()); + for (Json::Value const& ownedNFT : buyerNFTs[jss::result][jss::account_nfts]) + { + uint256 ownedID; + BEAST_EXPECT(ownedID.parseHex(ownedNFT[sfNFTokenID.jsonName].asString())); + auto const foundIter = std::find(nftIDs.begin(), nftIDs.end(), ownedID); - env(token::acceptSellOffer(buyer, offers.back())); - env.close(); + // Assuming we find the NFT, erase it so we know it's been + // found and can't be found again. + if (BEAST_EXPECT(foundIter != nftIDs.end())) + nftIDs.erase(foundIter); + } - // This can be a good time to look at the NFT pages. - // printNFTPages(env, noisy); - - // Verify that all NFTs are owned by buyer and findable in the - // ledger by having buyer create sell offers for all of their - // NFTs. Attempting to sell an offer that the ledger can't find - // generates a non-tesSUCCESS error code. - for (uint256 const& nftID : nftIDs) - { - uint256 const offerID = - keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftID, XRP(100)), - txflags(tfSellNFToken)); - env.close(); - - env(token::cancelOffer(buyer, {offerID})); - } - - // Verify that all the NFTs are owned by buyer. - Json::Value buyerNFTs = [&env, &buyer]() { - Json::Value params; - params[jss::account] = buyer.human(); - params[jss::type] = "state"; - return env.rpc("json", "account_nfts", to_string(params)); - }(); - - BEAST_EXPECT( - buyerNFTs[jss::result][jss::account_nfts].size() == - nftIDs.size()); - for (Json::Value const& ownedNFT : - buyerNFTs[jss::result][jss::account_nfts]) - { - uint256 ownedID; - BEAST_EXPECT(ownedID.parseHex( - ownedNFT[sfNFTokenID.jsonName].asString())); - auto const foundIter = - std::find(nftIDs.begin(), nftIDs.end(), ownedID); - - // Assuming we find the NFT, erase it so we know it's been - // found and can't be found again. - if (BEAST_EXPECT(foundIter != nftIDs.end())) - nftIDs.erase(foundIter); - } - - // All NFTs should now be accounted for, so nftIDs should be - // empty. - BEAST_EXPECT(nftIDs.empty()); - }; + // All NFTs should now be accounted for, so nftIDs should be + // empty. + BEAST_EXPECT(nftIDs.empty()); + }; // These seeds fill the last 17 entries of the initial page with // equivalent NFTs. The split should keep these together. @@ -628,8 +579,7 @@ class NFTokenDir_test : public beast::unit_test::suite accounts.reserve(seeds.size()); for (std::string_view seed : seeds) { - Account const& account = - accounts.emplace_back(Account::base58Seed, std::string(seed)); + Account const& account = accounts.emplace_back(Account::base58Seed, std::string(seed)); env.fund(XRP(10000), account); // Do not close the ledger inside the loop. If accounts are @@ -646,17 +596,13 @@ class NFTokenDir_test : public beast::unit_test::suite for (Account const& account : accounts) { // Mint the NFT. - uint256 const& nftID = nftIDs.emplace_back( - token::getNextID(env, account, 0, tfTransferable)); + uint256 const& nftID = nftIDs.emplace_back(token::getNextID(env, account, 0, tfTransferable)); env(token::mint(account, 0), txflags(tfTransferable)); env.close(); // Create an offer to give the NFT to buyer for free. - offers.emplace_back( - keylet::nftoffer(account, env.seq(account)).key); - env(token::createOffer(account, nftID, XRP(0)), - token::destination(buyer), - txflags((tfSellNFToken))); + offers.emplace_back(keylet::nftoffer(account, env.seq(account)).key); + env(token::createOffer(account, nftID, XRP(0)), token::destination(buyer), txflags((tfSellNFToken))); } env.close(); @@ -681,8 +627,7 @@ class NFTokenDir_test : public beast::unit_test::suite } // buyer accepts the last offer which causes a page overflow. - env(token::acceptSellOffer(buyer, offerForPageOverflow), - ter(tecNO_SUITABLE_NFTOKEN_PAGE)); + env(token::acceptSellOffer(buyer, offerForPageOverflow), ter(tecNO_SUITABLE_NFTOKEN_PAGE)); // Verify that all expected NFTs are owned by buyer and findable in // the ledger by having buyer create sell offers for all of their NFTs. @@ -691,8 +636,7 @@ class NFTokenDir_test : public beast::unit_test::suite for (uint256 const& nftID : nftIDs) { uint256 const offerID = keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftID, XRP(100)), - txflags(tfSellNFToken)); + env(token::createOffer(buyer, nftID, XRP(100)), txflags(tfSellNFToken)); env.close(); env(token::cancelOffer(buyer, {offerID})); @@ -706,16 +650,12 @@ class NFTokenDir_test : public beast::unit_test::suite return env.rpc("json", "account_nfts", to_string(params)); }(); - BEAST_EXPECT( - buyerNFTs[jss::result][jss::account_nfts].size() == nftIDs.size()); - for (Json::Value const& ownedNFT : - buyerNFTs[jss::result][jss::account_nfts]) + BEAST_EXPECT(buyerNFTs[jss::result][jss::account_nfts].size() == nftIDs.size()); + for (Json::Value const& ownedNFT : buyerNFTs[jss::result][jss::account_nfts]) { uint256 ownedID; - BEAST_EXPECT( - ownedID.parseHex(ownedNFT[sfNFTokenID.jsonName].asString())); - auto const foundIter = - std::find(nftIDs.begin(), nftIDs.end(), ownedID); + BEAST_EXPECT(ownedID.parseHex(ownedNFT[sfNFTokenID.jsonName].asString())); + auto const foundIter = std::find(nftIDs.begin(), nftIDs.end(), ownedID); // Assuming we find the NFT, erase it so we know it's been found // and can't be found again. @@ -799,8 +739,7 @@ class NFTokenDir_test : public beast::unit_test::suite accounts.reserve(seeds.size()); for (std::string_view seed : seeds) { - Account const& account = - accounts.emplace_back(Account::base58Seed, std::string(seed)); + Account const& account = accounts.emplace_back(Account::base58Seed, std::string(seed)); env.fund(XRP(10000), account); // Do not close the ledger inside the loop. If accounts are @@ -823,20 +762,16 @@ class NFTokenDir_test : public beast::unit_test::suite for (Account const& account : accounts) { // Mint the NFT. Tweak the taxon so zero is always stored. - std::uint32_t taxon = - toUInt32(nft::cipheredTaxon(i, nft::toTaxon(0))); + std::uint32_t taxon = toUInt32(nft::cipheredTaxon(i, nft::toTaxon(0))); - uint256 const& nftID = nftIDsByPage[i].emplace_back( - token::getNextID(env, account, taxon, tfTransferable)); + uint256 const& nftID = + nftIDsByPage[i].emplace_back(token::getNextID(env, account, taxon, tfTransferable)); env(token::mint(account, taxon), txflags(tfTransferable)); env.close(); // Create an offer to give the NFT to buyer for free. - offers[i].emplace_back( - keylet::nftoffer(account, env.seq(account)).key); - env(token::createOffer(account, nftID, XRP(0)), - token::destination(buyer), - txflags((tfSellNFToken))); + offers[i].emplace_back(keylet::nftoffer(account, env.seq(account)).key); + env(token::createOffer(account, nftID, XRP(0)), token::destination(buyer), txflags((tfSellNFToken))); } } env.close(); @@ -886,8 +821,7 @@ class NFTokenDir_test : public beast::unit_test::suite // the transaction succeeded. for (uint256 const& offer : overflowOffers) { - env(token::acceptSellOffer(buyer, offer), - ter(tecNO_SUITABLE_NFTOKEN_PAGE)); + env(token::acceptSellOffer(buyer, offer), ter(tecNO_SUITABLE_NFTOKEN_PAGE)); env.close(); } @@ -899,8 +833,7 @@ class NFTokenDir_test : public beast::unit_test::suite { for (uint256 const& nftID : vec) { - env(token::createOffer(buyer, nftID, XRP(100)), - txflags(tfSellNFToken)); + env(token::createOffer(buyer, nftID, XRP(100)), txflags(tfSellNFToken)); env.close(); } } @@ -918,8 +851,7 @@ class NFTokenDir_test : public beast::unit_test::suite if (!marker.empty()) params[jss::marker] = marker; - return env.rpc( - "json", "account_objects", to_string(params)); + return env.rpc("json", "account_objects", to_string(params)); }(); marker.clear(); @@ -974,8 +906,7 @@ class NFTokenDir_test : public beast::unit_test::suite return env.rpc("json", "account_objects", to_string(params)); }(); BEAST_EXPECT( - remainingOffers.isMember(jss::result) && - remainingOffers[jss::result].isMember(jss::account_objects) && + remainingOffers.isMember(jss::result) && remainingOffers[jss::result].isMember(jss::account_objects) && remainingOffers[jss::result][jss::account_objects].size() == 0); } @@ -1024,8 +955,7 @@ class NFTokenDir_test : public beast::unit_test::suite if (ownedNFT.isMember(sfNFTokenID.jsonName)) { uint256 ownedID; - BEAST_EXPECT(ownedID.parseHex( - ownedNFT[sfNFTokenID.jsonName].asString())); + BEAST_EXPECT(ownedID.parseHex(ownedNFT[sfNFTokenID.jsonName].asString())); auto const foundIter = allNftIDs.find(ownedID); // Assuming we find the NFT, erase it so we know it's been found diff --git a/src/test/app/NFToken_test.cpp b/src/test/app/NFToken_test.cpp index 59995a4078..1b9ce82d4a 100644 --- a/src/test/app/NFToken_test.cpp +++ b/src/test/app/NFToken_test.cpp @@ -57,10 +57,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite std::uint32_t lastClose(test::jtx::Env& env) { - return env.current() - ->header() - .parentCloseTime.time_since_epoch() - .count(); + return env.current()->header().parentCloseTime.time_since_epoch().count(); } void @@ -92,8 +89,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite BEAST_EXPECT(mintedCount(env, master) == 1); BEAST_EXPECT(burnedCount(env, master) == 1); - uint256 const nftId1{ - token::getNextID(env, env.master, 0u, tfTransferable)}; + uint256 const nftId1{token::getNextID(env, env.master, 0u, tfTransferable)}; env(token::mint(env.master, 0u), txflags(tfTransferable)); env.close(); BEAST_EXPECT(ownerCount(env, master) == 1); @@ -103,10 +99,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite Account const alice{"alice"}; env.fund(XRP(10000), alice); env.close(); - uint256 const aliceOfferIndex = - keylet::nftoffer(alice, env.seq(alice)).key; - env(token::createOffer(alice, nftId1, XRP(1000)), - token::owner(master)); + uint256 const aliceOfferIndex = keylet::nftoffer(alice, env.seq(alice)).key; + env(token::createOffer(alice, nftId1, XRP(1000)), token::owner(master)); env.close(); BEAST_EXPECT(ownerCount(env, master) == 1); @@ -171,28 +165,22 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // A lambda that checks alice's ownerCount, mintedCount, and // burnedCount all in one fell swoop. - auto checkAliceOwnerMintedBurned = [&env, this, &alice]( - std::uint32_t owners, - std::uint32_t minted, - std::uint32_t burned, - int line) { - auto oneCheck = - [line, this]( - char const* type, std::uint32_t found, std::uint32_t exp) { + auto checkAliceOwnerMintedBurned = + [&env, this, &alice](std::uint32_t owners, std::uint32_t minted, std::uint32_t burned, int line) { + auto oneCheck = [line, this](char const* type, std::uint32_t found, std::uint32_t exp) { if (found == exp) pass(); else { std::stringstream ss; - ss << "Wrong " << type << " count. Found: " << found - << "; Expected: " << exp; + ss << "Wrong " << type << " count. Found: " << found << "; Expected: " << exp; fail(ss.str(), __FILE__, line); } }; - oneCheck("owner", ownerCount(env, alice), owners); - oneCheck("minted", mintedCount(env, alice), minted); - oneCheck("burned", burnedCount(env, alice), burned); - }; + oneCheck("owner", ownerCount(env, alice), owners); + oneCheck("minted", mintedCount(env, alice), minted); + oneCheck("burned", burnedCount(env, alice), burned); + }; // alice still does not have enough XRP for the reserve of an NFT // page. @@ -255,8 +243,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite } // alice burns a non-existent NFT. - env(token::burn(alice, token::getID(env, alice, 197, 5)), - ter(tecNO_ENTRY)); + env(token::burn(alice, token::getID(env, alice, 197, 5)), ter(tecNO_ENTRY)); env.close(); checkAliceOwnerMintedBurned(0, 33, 33, __LINE__); @@ -265,8 +252,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // minter. env(token::setMinter(alice, minter)); env.close(); - BEAST_EXPECT( - env.le(alice)->getAccountID(sfNFTokenMinter) == minter.id()); + BEAST_EXPECT(env.le(alice)->getAccountID(sfNFTokenMinter) == minter.id()); // A lambda that checks minter's and alice's ownerCount, // mintedCount, and burnedCount all in one fell swoop. @@ -278,32 +264,22 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite std::uint32_t minterMinted, std::uint32_t minterBurned, int line) { - auto oneCheck = [this]( - char const* type, - std::uint32_t found, - std::uint32_t exp, - int line) { + auto oneCheck = [this](char const* type, std::uint32_t found, std::uint32_t exp, int line) { if (found == exp) pass(); else { std::stringstream ss; - ss << "Wrong " << type << " count. Found: " << found - << "; Expected: " << exp; + ss << "Wrong " << type << " count. Found: " << found << "; Expected: " << exp; fail(ss.str(), __FILE__, line); } }; oneCheck("alice owner", ownerCount(env, alice), aliceOwners, line); - oneCheck( - "alice minted", mintedCount(env, alice), aliceMinted, line); - oneCheck( - "alice burned", burnedCount(env, alice), aliceBurned, line); - oneCheck( - "minter owner", ownerCount(env, minter), minterOwners, line); - oneCheck( - "minter minted", mintedCount(env, minter), minterMinted, line); - oneCheck( - "minter burned", burnedCount(env, minter), minterBurned, line); + oneCheck("alice minted", mintedCount(env, alice), aliceMinted, line); + oneCheck("alice burned", burnedCount(env, alice), aliceBurned, line); + oneCheck("minter owner", ownerCount(env, minter), minterOwners, line); + oneCheck("minter minted", mintedCount(env, minter), minterMinted, line); + oneCheck("minter burned", burnedCount(env, minter), minterBurned, line); }; std::uint32_t nftSeq = 33; @@ -316,10 +292,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // minter still does not have enough XRP for the reserve of an NFT // page. Just for grins (and code coverage), minter mints NFTs that // include a URI. - env(token::mint(minter), - token::issuer(alice), - token::uri("uri"), - ter(tecINSUFFICIENT_RESERVE)); + env(token::mint(minter), token::issuer(alice), token::uri("uri"), ter(tecINSUFFICIENT_RESERVE)); env.close(); checkMintersOwnerMintedBurned(0, 33, nftSeq, 0, 0, 0, __LINE__); @@ -347,10 +320,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // That NFT page is full. Creating an additional NFT page requires // additional reserve. - env(token::mint(minter), - token::issuer(alice), - token::uri("uri"), - ter(tecINSUFFICIENT_RESERVE)); + env(token::mint(minter), token::issuer(alice), token::uri("uri"), ter(tecINSUFFICIENT_RESERVE)); env.close(); checkMintersOwnerMintedBurned(0, 65, nftSeq, 1, 0, 0, __LINE__); @@ -368,8 +338,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite { env(token::burn(minter, token::getID(env, alice, 0, nftSeq++))); env.close(); - checkMintersOwnerMintedBurned( - 0, 66, nftSeq, (65 - seq) ? 1 : 0, 0, 0, __LINE__); + checkMintersOwnerMintedBurned(0, 66, nftSeq, (65 - seq) ? 1 : 0, 0, 0, __LINE__); } // minter has one more NFT to burn. Should take her owner count to @@ -379,8 +348,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite checkMintersOwnerMintedBurned(0, 66, nftSeq, 0, 0, 0, __LINE__); // minter burns a non-existent NFT. - env(token::burn(minter, token::getID(env, alice, 2009, 3)), - ter(tecNO_ENTRY)); + env(token::burn(minter, token::getID(env, alice, 2009, 3)), ter(tecNO_ENTRY)); env.close(); checkMintersOwnerMintedBurned(0, 66, nftSeq, 0, 0, 0, __LINE__); } @@ -416,29 +384,28 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // Note that we're bypassing almost all of the ledger's safety // checks with this modify() call. If you call close() between // here and the end of the test all the effort will be lost. - env.app().openLedger().modify( - [&alice](OpenView& view, beast::Journal j) { - // Get the account root we want to hijack. - auto const sle = view.read(keylet::account(alice.id())); - if (!sle) - return false; // This would be really surprising! + env.app().openLedger().modify([&alice](OpenView& view, beast::Journal j) { + // Get the account root we want to hijack. + auto const sle = view.read(keylet::account(alice.id())); + if (!sle) + return false; // This would be really surprising! - // Just for sanity's sake we'll check that the current value - // of sfMintedNFTokens matches what we expect. - auto replacement = std::make_shared(*sle, sle->key()); - if (replacement->getFieldU32(sfMintedNFTokens) != 1) - return false; // Unexpected test conditions. + // Just for sanity's sake we'll check that the current value + // of sfMintedNFTokens matches what we expect. + auto replacement = std::make_shared(*sle, sle->key()); + if (replacement->getFieldU32(sfMintedNFTokens) != 1) + return false; // Unexpected test conditions. - // Sequence number is generated by sfFirstNFTokenSequence + - // sfMintedNFTokens. We can replace the two fields with any - // numbers as long as they add up to the largest valid number. - // In our case, sfFirstNFTokenSequence is set to the largest - // valid number, and sfMintedNFTokens is set to zero. - (*replacement)[sfFirstNFTokenSequence] = 0xFFFF'FFFE; - (*replacement)[sfMintedNFTokens] = 0x0000'0000; - view.rawReplace(replacement); - return true; - }); + // Sequence number is generated by sfFirstNFTokenSequence + + // sfMintedNFTokens. We can replace the two fields with any + // numbers as long as they add up to the largest valid number. + // In our case, sfFirstNFTokenSequence is set to the largest + // valid number, and sfMintedNFTokens is set to zero. + (*replacement)[sfFirstNFTokenSequence] = 0xFFFF'FFFE; + (*replacement)[sfMintedNFTokens] = 0x0000'0000; + view.rawReplace(replacement); + return true; + }); // See whether alice is at the boundary that causes an error. env(token::mint(alice, 0u), ter(tesSUCCESS)); @@ -474,18 +441,14 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // preflight // Set a negative fee. - env(token::mint(alice, 0u), - fee(STAmount(10ull, true)), - ter(temBAD_FEE)); + env(token::mint(alice, 0u), fee(STAmount(10ull, true)), ter(temBAD_FEE)); // Set an invalid flag. env(token::mint(alice, 0u), txflags(0x00008000), ter(temINVALID_FLAG)); // Can't set a transfer fee if the NFT does not have the tfTRANSFERABLE // flag set. - env(token::mint(alice, 0u), - token::xferFee(maxTransferFee), - ter(temMALFORMED)); + env(token::mint(alice, 0u), token::xferFee(maxTransferFee), ter(temMALFORMED)); // Set a bad transfer fee. env(token::mint(alice, 0u), @@ -500,25 +463,19 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env(token::mint(alice, 0u), token::uri(""), ter(temMALFORMED)); // Invalid URI: too long. - env(token::mint(alice, 0u), - token::uri(std::string(maxTokenURILength + 1, 'q')), - ter(temMALFORMED)); + env(token::mint(alice, 0u), token::uri(std::string(maxTokenURILength + 1, 'q')), ter(temMALFORMED)); //---------------------------------------------------------------------- // preclaim // Non-existent issuer. - env(token::mint(alice, 0u), - token::issuer(Account("demon")), - ter(tecNO_ISSUER)); + env(token::mint(alice, 0u), token::issuer(Account("demon")), ter(tecNO_ISSUER)); //---------------------------------------------------------------------- // doApply // Existent issuer, but not given minting permission - env(token::mint(minter, 0u), - token::issuer(alice), - ter(tecNO_PERMISSION)); + env(token::mint(minter, 0u), token::issuer(alice), ter(tecNO_PERMISSION)); } void @@ -543,8 +500,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env.close(); BEAST_EXPECT(ownerCount(env, alice) == 0); - uint256 const nftAlice0ID = - token::getNextID(env, alice, 0, tfTransferable); + uint256 const nftAlice0ID = token::getNextID(env, alice, 0, tfTransferable); env(token::mint(alice, 0u), txflags(tfTransferable)); env.close(); BEAST_EXPECT(ownerCount(env, alice) == 1); @@ -553,16 +509,12 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // preflight // Set a negative fee. - env(token::burn(alice, nftAlice0ID), - fee(STAmount(10ull, true)), - ter(temBAD_FEE)); + env(token::burn(alice, nftAlice0ID), fee(STAmount(10ull, true)), ter(temBAD_FEE)); env.close(); BEAST_EXPECT(ownerCount(env, alice) == 1); // Set an invalid flag. - env(token::burn(alice, nftAlice0ID), - txflags(0x00008000), - ter(temINVALID_FLAG)); + env(token::burn(alice, nftAlice0ID), txflags(0x00008000), ter(temINVALID_FLAG)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 0); @@ -570,8 +522,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // preclaim // Try to burn a token that doesn't exist. - env(token::burn(alice, token::getID(env, alice, 0, 1)), - ter(tecNO_ENTRY)); + env(token::burn(alice, token::getID(env, alice, 0, 1)), ter(tecNO_ENTRY)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 0); @@ -602,16 +553,12 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env.close(); BEAST_EXPECT(ownerCount(env, alice) == 0); - uint256 const nftAlice0ID = - token::getNextID(env, alice, 0, tfTransferable, 10); - env(token::mint(alice, 0u), - txflags(tfTransferable), - token::xferFee(10)); + uint256 const nftAlice0ID = token::getNextID(env, alice, 0, tfTransferable, 10); + env(token::mint(alice, 0u), txflags(tfTransferable), token::xferFee(10)); env.close(); BEAST_EXPECT(ownerCount(env, alice) == 1); - uint256 const nftXrpOnlyID = - token::getNextID(env, alice, 0, tfOnlyXRP | tfTransferable); + uint256 const nftXrpOnlyID = token::getNextID(env, alice, 0, tfOnlyXRP | tfTransferable); env(token::mint(alice, 0), txflags(tfOnlyXRP | tfTransferable)); env.close(); BEAST_EXPECT(ownerCount(env, alice) == 1); @@ -630,47 +577,35 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env.close(); // buyer tries to create an NFTokenOffer, but doesn't have the reserve. - env(token::createOffer(buyer, nftAlice0ID, XRP(1000)), - token::owner(alice), - ter(tecINSUFFICIENT_RESERVE)); + env(token::createOffer(buyer, nftAlice0ID, XRP(1000)), token::owner(alice), ter(tecINSUFFICIENT_RESERVE)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 0); // Set a negative fee. - env(token::createOffer(buyer, nftAlice0ID, XRP(1000)), - fee(STAmount(10ull, true)), - ter(temBAD_FEE)); + env(token::createOffer(buyer, nftAlice0ID, XRP(1000)), fee(STAmount(10ull, true)), ter(temBAD_FEE)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 0); // Set an invalid flag. - env(token::createOffer(buyer, nftAlice0ID, XRP(1000)), - txflags(0x00008000), - ter(temINVALID_FLAG)); + env(token::createOffer(buyer, nftAlice0ID, XRP(1000)), txflags(0x00008000), ter(temINVALID_FLAG)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 0); // Set an invalid amount. - env(token::createOffer(buyer, nftXrpOnlyID, buyer["USD"](1)), - ter(temBAD_AMOUNT)); - env(token::createOffer(buyer, nftAlice0ID, buyer["USD"](0)), - ter(temBAD_AMOUNT)); - env(token::createOffer(buyer, nftXrpOnlyID, drops(0)), - ter(temBAD_AMOUNT)); + env(token::createOffer(buyer, nftXrpOnlyID, buyer["USD"](1)), ter(temBAD_AMOUNT)); + env(token::createOffer(buyer, nftAlice0ID, buyer["USD"](0)), ter(temBAD_AMOUNT)); + env(token::createOffer(buyer, nftXrpOnlyID, drops(0)), ter(temBAD_AMOUNT)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 0); // Set a bad expiration. - env(token::createOffer(buyer, nftAlice0ID, buyer["USD"](1)), - token::expiration(0), - ter(temBAD_EXPIRATION)); + env(token::createOffer(buyer, nftAlice0ID, buyer["USD"](1)), token::expiration(0), ter(temBAD_EXPIRATION)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 0); // Invalid Owner field and tfSellToken flag relationships. // A buy offer must specify the owner. - env(token::createOffer(buyer, nftXrpOnlyID, XRP(1000)), - ter(temMALFORMED)); + env(token::createOffer(buyer, nftXrpOnlyID, XRP(1000)), ter(temMALFORMED)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 0); @@ -683,9 +618,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite BEAST_EXPECT(ownerCount(env, alice) == 1); // An owner may not offer to buy their own token. - env(token::createOffer(alice, nftXrpOnlyID, XRP(1000)), - token::owner(alice), - ter(temMALFORMED)); + env(token::createOffer(alice, nftXrpOnlyID, XRP(1000)), token::owner(alice), ter(temMALFORMED)); env.close(); BEAST_EXPECT(ownerCount(env, alice) == 1); @@ -717,25 +650,21 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite BEAST_EXPECT(ownerCount(env, buyer) == 0); // The nftID must be present in the ledger. - env(token::createOffer( - buyer, token::getID(env, alice, 0, 1), XRP(1000)), + env(token::createOffer(buyer, token::getID(env, alice, 0, 1), XRP(1000)), token::owner(alice), ter(tecNO_ENTRY)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 0); // The nftID must be present in the ledger of a sell offer too. - env(token::createOffer( - alice, token::getID(env, alice, 0, 1), XRP(1000)), + env(token::createOffer(alice, token::getID(env, alice, 0, 1), XRP(1000)), txflags(tfSellNFToken), ter(tecNO_ENTRY)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 0); // buyer must have the funds to pay for their offer. - env(token::createOffer(buyer, nftAlice0ID, gwAUD(1000)), - token::owner(alice), - ter(tecNO_LINE)); + env(token::createOffer(buyer, nftAlice0ID, gwAUD(1000)), token::owner(alice), ter(tecNO_LINE)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 0); @@ -745,9 +674,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env.close(); // Issuer (alice) must have a trust line for the offered funds. - env(token::createOffer(buyer, nftAlice0ID, gwAUD(1000)), - token::owner(alice), - ter(tecNO_LINE)); + env(token::createOffer(buyer, nftAlice0ID, gwAUD(1000)), token::owner(alice), ter(tecNO_LINE)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 1); @@ -757,9 +684,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // Issuer (alice) must have a trust line for the offered funds and // the trust line may not be frozen. - env(token::createOffer(buyer, nftAlice0ID, gwAUD(1000)), - token::owner(alice), - ter(tecFROZEN)); + env(token::createOffer(buyer, nftAlice0ID, gwAUD(1000)), token::owner(alice), ter(tecFROZEN)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 1); @@ -778,9 +703,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env(trust(gw, buyer["AUD"](999), tfSetFreeze)); env.close(); - env(token::createOffer(buyer, nftAlice0ID, gwAUD(1000)), - token::owner(alice), - ter(tecFROZEN)); + env(token::createOffer(buyer, nftAlice0ID, gwAUD(1000)), token::owner(alice), ter(tecFROZEN)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 1); @@ -790,9 +713,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env(trust(buyer, gwAUD(1000))); env.close(); - env(token::createOffer(buyer, nftAlice0ID, gwAUD(1000)), - token::owner(alice), - ter(tecUNFUNDED_OFFER)); + env(token::createOffer(buyer, nftAlice0ID, gwAUD(1000)), token::owner(alice), ter(tecUNFUNDED_OFFER)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 1); // the trust line. @@ -805,9 +726,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // However buyer doesn't have enough XRP to cover the reserve for // an NFT offer. - env(token::createOffer(buyer, nftAlice0ID, gwAUD(1000)), - token::owner(alice), - ter(tecINSUFFICIENT_RESERVE)); + env(token::createOffer(buyer, nftAlice0ID, gwAUD(1000)), token::owner(alice), ter(tecINSUFFICIENT_RESERVE)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 1); @@ -816,9 +735,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env(pay(env.master, buyer, XRP(50) + drops(baseFee * 12 - 1))); env.close(); - env(token::createOffer(buyer, nftAlice0ID, gwAUD(1000)), - token::owner(alice), - ter(tecINSUFFICIENT_RESERVE)); + env(token::createOffer(buyer, nftAlice0ID, gwAUD(1000)), token::owner(alice), ter(tecINSUFFICIENT_RESERVE)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 1); @@ -828,9 +745,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // We don't care whether the offer is fully funded until the offer is // accepted. Success at last! - env(token::createOffer(buyer, nftAlice0ID, gwAUD(1000)), - token::owner(alice), - ter(tesSUCCESS)); + env(token::createOffer(buyer, nftAlice0ID, gwAUD(1000)), token::owner(alice), ter(tesSUCCESS)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 2); } @@ -852,18 +767,14 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env.close(); BEAST_EXPECT(ownerCount(env, alice) == 0); - uint256 const nftAlice0ID = - token::getNextID(env, alice, 0, tfTransferable); + uint256 const nftAlice0ID = token::getNextID(env, alice, 0, tfTransferable); env(token::mint(alice, 0u), txflags(tfTransferable)); env.close(); BEAST_EXPECT(ownerCount(env, alice) == 1); // This is the offer we'll try to cancel. - uint256 const buyerOfferIndex = - keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftAlice0ID, XRP(1)), - token::owner(alice), - ter(tesSUCCESS)); + uint256 const buyerOfferIndex = keylet::nftoffer(buyer, env.seq(buyer)).key; + env(token::createOffer(buyer, nftAlice0ID, XRP(1)), token::owner(alice), ter(tesSUCCESS)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 1); @@ -871,16 +782,12 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // preflight // Set a negative fee. - env(token::cancelOffer(buyer, {buyerOfferIndex}), - fee(STAmount(10ull, true)), - ter(temBAD_FEE)); + env(token::cancelOffer(buyer, {buyerOfferIndex}), fee(STAmount(10ull, true)), ter(temBAD_FEE)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 1); // Set an invalid flag. - env(token::cancelOffer(buyer, {buyerOfferIndex}), - txflags(0x00008000), - ter(temINVALID_FLAG)); + env(token::cancelOffer(buyer, {buyerOfferIndex}), txflags(0x00008000), ter(temINVALID_FLAG)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 1); @@ -895,8 +802,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // List of tokens to delete is too long. { - std::vector offers( - maxTokenOfferCancelCount + 1, buyerOfferIndex); + std::vector offers(maxTokenOfferCancelCount + 1, buyerOfferIndex); env(token::cancelOffer(buyer, offers), ter(temMALFORMED)); env.close(); @@ -904,8 +810,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite } // Duplicate entries are not allowed in the list of offers to cancel. - env(token::cancelOffer(buyer, {buyerOfferIndex, buyerOfferIndex}), - ter(temMALFORMED)); + env(token::cancelOffer(buyer, {buyerOfferIndex, buyerOfferIndex}), ter(temMALFORMED)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 1); @@ -971,78 +876,79 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env.fund(XRP(1000), alice, buyer, gw); env.close(); BEAST_EXPECT(ownerCount(env, alice) == 0); + BEAST_EXPECT(ownerCount(env, buyer) == 0); - uint256 const nftAlice0ID = - token::getNextID(env, alice, 0, tfTransferable); + uint256 const nftAlice0ID = token::getNextID(env, alice, 0, tfTransferable); env(token::mint(alice, 0u), txflags(tfTransferable)); env.close(); - BEAST_EXPECT(ownerCount(env, alice) == 1); + uint8_t aliceCount = 1; + BEAST_EXPECT(ownerCount(env, alice) == aliceCount); - uint256 const nftXrpOnlyID = - token::getNextID(env, alice, 0, tfOnlyXRP | tfTransferable); + uint256 const nftXrpOnlyID = token::getNextID(env, alice, 0, tfOnlyXRP | tfTransferable); env(token::mint(alice, 0), txflags(tfOnlyXRP | tfTransferable)); env.close(); - BEAST_EXPECT(ownerCount(env, alice) == 1); + BEAST_EXPECT(ownerCount(env, alice) == aliceCount); uint256 nftNoXferID = token::getNextID(env, alice, 0); env(token::mint(alice, 0)); env.close(); - BEAST_EXPECT(ownerCount(env, alice) == 1); + BEAST_EXPECT(ownerCount(env, alice) == aliceCount); // alice creates sell offers for her nfts. - uint256 const plainOfferIndex = - keylet::nftoffer(alice, env.seq(alice)).key; - env(token::createOffer(alice, nftAlice0ID, XRP(10)), - txflags(tfSellNFToken)); + uint256 const plainOfferIndex = keylet::nftoffer(alice, env.seq(alice)).key; + env(token::createOffer(alice, nftAlice0ID, XRP(10)), txflags(tfSellNFToken)); env.close(); - BEAST_EXPECT(ownerCount(env, alice) == 2); + aliceCount++; + BEAST_EXPECT(ownerCount(env, alice) == aliceCount); - uint256 const audOfferIndex = - keylet::nftoffer(alice, env.seq(alice)).key; - env(token::createOffer(alice, nftAlice0ID, gwAUD(30)), - txflags(tfSellNFToken)); + uint256 const audOfferIndex = keylet::nftoffer(alice, env.seq(alice)).key; + env(token::createOffer(alice, nftAlice0ID, gwAUD(30)), txflags(tfSellNFToken)); env.close(); - BEAST_EXPECT(ownerCount(env, alice) == 3); + aliceCount++; + BEAST_EXPECT(ownerCount(env, alice) == aliceCount); - uint256 const xrpOnlyOfferIndex = - keylet::nftoffer(alice, env.seq(alice)).key; - env(token::createOffer(alice, nftXrpOnlyID, XRP(20)), - txflags(tfSellNFToken)); + uint256 const xrpOnlyOfferIndex = keylet::nftoffer(alice, env.seq(alice)).key; + env(token::createOffer(alice, nftXrpOnlyID, XRP(20)), txflags(tfSellNFToken)); env.close(); - BEAST_EXPECT(ownerCount(env, alice) == 4); + aliceCount++; + BEAST_EXPECT(ownerCount(env, alice) == aliceCount); - uint256 const noXferOfferIndex = - keylet::nftoffer(alice, env.seq(alice)).key; - env(token::createOffer(alice, nftNoXferID, XRP(30)), - txflags(tfSellNFToken)); + uint256 const noXferOfferIndex = keylet::nftoffer(alice, env.seq(alice)).key; + env(token::createOffer(alice, nftNoXferID, XRP(30)), txflags(tfSellNFToken)); env.close(); - BEAST_EXPECT(ownerCount(env, alice) == 5); + aliceCount++; + BEAST_EXPECT(ownerCount(env, alice) == aliceCount); // alice creates a sell offer that will expire soon. - uint256 const aliceExpOfferIndex = - keylet::nftoffer(alice, env.seq(alice)).key; + uint256 const aliceExpOfferIndex = keylet::nftoffer(alice, env.seq(alice)).key; env(token::createOffer(alice, nftNoXferID, XRP(40)), txflags(tfSellNFToken), token::expiration(lastClose(env) + 5)); env.close(); - BEAST_EXPECT(ownerCount(env, alice) == 6); + aliceCount++; + BEAST_EXPECT(ownerCount(env, alice) == aliceCount); + + // buyer creates a Buy offer that will expire soon. + uint256 const buyerExpOfferIndex = keylet::nftoffer(buyer, env.seq(buyer)).key; + env(token::createOffer(buyer, nftAlice0ID, XRP(40)), + token::owner(alice), + token::expiration(lastClose(env) + 5)); + env.close(); + uint8_t buyerCount = 1; + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); //---------------------------------------------------------------------- // preflight // Set a negative fee. - env(token::acceptSellOffer(buyer, noXferOfferIndex), - fee(STAmount(10ull, true)), - ter(temBAD_FEE)); + env(token::acceptSellOffer(buyer, noXferOfferIndex), fee(STAmount(10ull, true)), ter(temBAD_FEE)); env.close(); - BEAST_EXPECT(ownerCount(env, buyer) == 0); + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); // Set an invalid flag. - env(token::acceptSellOffer(buyer, noXferOfferIndex), - txflags(0x00008000), - ter(temINVALID_FLAG)); + env(token::acceptSellOffer(buyer, noXferOfferIndex), txflags(0x00008000), ter(temINVALID_FLAG)); env.close(); - BEAST_EXPECT(ownerCount(env, buyer) == 0); + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); // Supply nether an sfNFTokenBuyOffer nor an sfNFTokenSellOffer field. { @@ -1050,27 +956,25 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite jv.removeMember(sfNFTokenSellOffer.jsonName); env(jv, ter(temMALFORMED)); env.close(); - BEAST_EXPECT(ownerCount(env, buyer) == 0); + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); } // A buy offer may not contain a sfNFTokenBrokerFee field. { Json::Value jv = token::acceptBuyOffer(buyer, noXferOfferIndex); - jv[sfNFTokenBrokerFee.jsonName] = - STAmount(500000).getJson(JsonOptions::none); + jv[sfNFTokenBrokerFee.jsonName] = STAmount(500000).getJson(JsonOptions::none); env(jv, ter(temMALFORMED)); env.close(); - BEAST_EXPECT(ownerCount(env, buyer) == 0); + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); } // A sell offer may not contain a sfNFTokenBrokerFee field. { Json::Value jv = token::acceptSellOffer(buyer, noXferOfferIndex); - jv[sfNFTokenBrokerFee.jsonName] = - STAmount(500000).getJson(JsonOptions::none); + jv[sfNFTokenBrokerFee.jsonName] = STAmount(500000).getJson(JsonOptions::none); env(jv, ter(temMALFORMED)); env.close(); - BEAST_EXPECT(ownerCount(env, buyer) == 0); + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); } // A brokered offer may not contain a negative or zero brokerFee. @@ -1078,45 +982,56 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite token::brokerFee(gwAUD(0)), ter(temMALFORMED)); env.close(); - BEAST_EXPECT(ownerCount(env, buyer) == 0); + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); //---------------------------------------------------------------------- // preclaim // The buy offer must be non-zero. - env(token::acceptBuyOffer(buyer, beast::zero), - ter(tecOBJECT_NOT_FOUND)); + env(token::acceptBuyOffer(buyer, beast::zero), ter(tecOBJECT_NOT_FOUND)); env.close(); - BEAST_EXPECT(ownerCount(env, buyer) == 0); + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); // The buy offer must be present in the ledger. uint256 const missingOfferIndex = keylet::nftoffer(alice, 1).key; - env(token::acceptBuyOffer(buyer, missingOfferIndex), - ter(tecOBJECT_NOT_FOUND)); + env(token::acceptBuyOffer(buyer, missingOfferIndex), ter(tecOBJECT_NOT_FOUND)); env.close(); - BEAST_EXPECT(ownerCount(env, buyer) == 0); + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); // The buy offer must not have expired. - env(token::acceptBuyOffer(buyer, aliceExpOfferIndex), ter(tecEXPIRED)); + // NOTE: this is only a preclaim check with the + // fixExpiredNFTokenOfferRemoval amendment disabled. + env(token::acceptBuyOffer(alice, buyerExpOfferIndex), ter(tecEXPIRED)); env.close(); - BEAST_EXPECT(ownerCount(env, buyer) == 0); + if (features[fixExpiredNFTokenOfferRemoval]) + { + buyerCount--; + } + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); // The sell offer must be non-zero. - env(token::acceptSellOffer(buyer, beast::zero), - ter(tecOBJECT_NOT_FOUND)); + env(token::acceptSellOffer(buyer, beast::zero), ter(tecOBJECT_NOT_FOUND)); env.close(); - BEAST_EXPECT(ownerCount(env, buyer) == 0); + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); // The sell offer must be present in the ledger. - env(token::acceptSellOffer(buyer, missingOfferIndex), - ter(tecOBJECT_NOT_FOUND)); + env(token::acceptSellOffer(buyer, missingOfferIndex), ter(tecOBJECT_NOT_FOUND)); env.close(); - BEAST_EXPECT(ownerCount(env, buyer) == 0); + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); // The sell offer must not have expired. + // NOTE: this is only a preclaim check with the + // fixExpiredNFTokenOfferRemoval amendment disabled. env(token::acceptSellOffer(buyer, aliceExpOfferIndex), ter(tecEXPIRED)); env.close(); - BEAST_EXPECT(ownerCount(env, buyer) == 0); + // Alice's count is decremented by one when the expired offer is + // removed. + if (features[fixExpiredNFTokenOfferRemoval]) + { + aliceCount--; + } + BEAST_EXPECT(ownerCount(env, alice) == aliceCount); + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); //---------------------------------------------------------------------- // preclaim brokered @@ -1128,52 +1043,53 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env.close(); env(pay(gw, buyer, gwAUD(30))); env.close(); - BEAST_EXPECT(ownerCount(env, alice) == 7); - BEAST_EXPECT(ownerCount(env, buyer) == 1); + aliceCount++; + buyerCount++; + BEAST_EXPECT(ownerCount(env, alice) == aliceCount); + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); + + BEAST_EXPECT(ownerCount(env, alice) == aliceCount); + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); // We're about to exercise offer brokering, so we need // corresponding buy and sell offers. { // buyer creates a buy offer for one of alice's nfts. - uint256 const buyerOfferIndex = - keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftAlice0ID, gwAUD(29)), - token::owner(alice)); + uint256 const buyerOfferIndex = keylet::nftoffer(buyer, env.seq(buyer)).key; + env(token::createOffer(buyer, nftAlice0ID, gwAUD(29)), token::owner(alice)); env.close(); - BEAST_EXPECT(ownerCount(env, buyer) == 2); + buyerCount++; + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); // gw attempts to broker offers that are not for the same token. - env(token::brokerOffers(gw, buyerOfferIndex, xrpOnlyOfferIndex), - ter(tecNFTOKEN_BUY_SELL_MISMATCH)); + env(token::brokerOffers(gw, buyerOfferIndex, xrpOnlyOfferIndex), ter(tecNFTOKEN_BUY_SELL_MISMATCH)); env.close(); - BEAST_EXPECT(ownerCount(env, buyer) == 2); + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); // gw attempts to broker offers that are not for the same currency. - env(token::brokerOffers(gw, buyerOfferIndex, plainOfferIndex), - ter(tecNFTOKEN_BUY_SELL_MISMATCH)); + env(token::brokerOffers(gw, buyerOfferIndex, plainOfferIndex), ter(tecNFTOKEN_BUY_SELL_MISMATCH)); env.close(); - BEAST_EXPECT(ownerCount(env, buyer) == 2); + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); // In a brokered offer, the buyer must offer greater than or // equal to the selling price. - env(token::brokerOffers(gw, buyerOfferIndex, audOfferIndex), - ter(tecINSUFFICIENT_PAYMENT)); + env(token::brokerOffers(gw, buyerOfferIndex, audOfferIndex), ter(tecINSUFFICIENT_PAYMENT)); env.close(); - BEAST_EXPECT(ownerCount(env, buyer) == 2); + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); // Remove buyer's offer. env(token::cancelOffer(buyer, {buyerOfferIndex})); env.close(); - BEAST_EXPECT(ownerCount(env, buyer) == 1); + buyerCount--; + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); } { // buyer creates a buy offer for one of alice's nfts. - uint256 const buyerOfferIndex = - keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftAlice0ID, gwAUD(31)), - token::owner(alice)); + uint256 const buyerOfferIndex = keylet::nftoffer(buyer, env.seq(buyer)).key; + env(token::createOffer(buyer, nftAlice0ID, gwAUD(31)), token::owner(alice)); env.close(); - BEAST_EXPECT(ownerCount(env, buyer) == 2); + buyerCount++; + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); // Broker sets their fee in a denomination other than the one // used by the offers @@ -1181,14 +1097,14 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite token::brokerFee(XRP(40)), ter(tecNFTOKEN_BUY_SELL_MISMATCH)); env.close(); - BEAST_EXPECT(ownerCount(env, buyer) == 2); + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); // Broker fee way too big. env(token::brokerOffers(gw, buyerOfferIndex, audOfferIndex), token::brokerFee(gwAUD(31)), ter(tecINSUFFICIENT_PAYMENT)); env.close(); - BEAST_EXPECT(ownerCount(env, buyer) == 2); + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); // Broker fee is smaller, but still too big once the offer // seller's minimum is taken into account. @@ -1196,120 +1112,108 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite token::brokerFee(gwAUD(1.5)), ter(tecINSUFFICIENT_PAYMENT)); env.close(); - BEAST_EXPECT(ownerCount(env, buyer) == 2); + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); // Remove buyer's offer. env(token::cancelOffer(buyer, {buyerOfferIndex})); env.close(); - BEAST_EXPECT(ownerCount(env, buyer) == 1); + buyerCount--; + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); } //---------------------------------------------------------------------- // preclaim buy { // buyer creates a buy offer for one of alice's nfts. - uint256 const buyerOfferIndex = - keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftAlice0ID, gwAUD(30)), - token::owner(alice)); + uint256 const buyerOfferIndex = keylet::nftoffer(buyer, env.seq(buyer)).key; + env(token::createOffer(buyer, nftAlice0ID, gwAUD(30)), token::owner(alice)); env.close(); - BEAST_EXPECT(ownerCount(env, buyer) == 2); + buyerCount++; + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); // Don't accept a buy offer if the sell flag is set. - env(token::acceptBuyOffer(buyer, plainOfferIndex), - ter(tecNFTOKEN_OFFER_TYPE_MISMATCH)); + env(token::acceptBuyOffer(buyer, plainOfferIndex), ter(tecNFTOKEN_OFFER_TYPE_MISMATCH)); env.close(); - BEAST_EXPECT(ownerCount(env, alice) == 7); + BEAST_EXPECT(ownerCount(env, alice) == aliceCount); // An account can't accept its own offer. - env(token::acceptBuyOffer(buyer, buyerOfferIndex), - ter(tecCANT_ACCEPT_OWN_NFTOKEN_OFFER)); + env(token::acceptBuyOffer(buyer, buyerOfferIndex), ter(tecCANT_ACCEPT_OWN_NFTOKEN_OFFER)); env.close(); - BEAST_EXPECT(ownerCount(env, buyer) == 2); + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); // An offer acceptor must have enough funds to pay for the offer. env(pay(buyer, gw, gwAUD(30))); env.close(); BEAST_EXPECT(env.balance(buyer, gwAUD) == gwAUD(0)); - env(token::acceptBuyOffer(alice, buyerOfferIndex), - ter(tecINSUFFICIENT_FUNDS)); + env(token::acceptBuyOffer(alice, buyerOfferIndex), ter(tecINSUFFICIENT_FUNDS)); env.close(); - BEAST_EXPECT(ownerCount(env, buyer) == 2); + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); // alice gives her NFT to gw, so alice no longer owns nftAlice0. { - uint256 const offerIndex = - keylet::nftoffer(alice, env.seq(alice)).key; - env(token::createOffer(alice, nftAlice0ID, XRP(0)), - txflags(tfSellNFToken)); + uint256 const offerIndex = keylet::nftoffer(alice, env.seq(alice)).key; + env(token::createOffer(alice, nftAlice0ID, XRP(0)), txflags(tfSellNFToken)); env.close(); env(token::acceptSellOffer(gw, offerIndex)); env.close(); - BEAST_EXPECT(ownerCount(env, alice) == 7); + BEAST_EXPECT(ownerCount(env, alice) == aliceCount); } env(pay(gw, buyer, gwAUD(30))); env.close(); // alice can't accept a buy offer for an NFT she no longer owns. - env(token::acceptBuyOffer(alice, buyerOfferIndex), - ter(tecNO_PERMISSION)); + env(token::acceptBuyOffer(alice, buyerOfferIndex), ter(tecNO_PERMISSION)); env.close(); - BEAST_EXPECT(ownerCount(env, buyer) == 2); + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); // Remove buyer's offer. env(token::cancelOffer(buyer, {buyerOfferIndex})); env.close(); - BEAST_EXPECT(ownerCount(env, buyer) == 1); + buyerCount--; + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); } //---------------------------------------------------------------------- // preclaim sell { // buyer creates a buy offer for one of alice's nfts. - uint256 const buyerOfferIndex = - keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftXrpOnlyID, XRP(30)), - token::owner(alice)); + uint256 const buyerOfferIndex = keylet::nftoffer(buyer, env.seq(buyer)).key; + env(token::createOffer(buyer, nftXrpOnlyID, XRP(30)), token::owner(alice)); env.close(); - BEAST_EXPECT(ownerCount(env, buyer) == 2); + buyerCount++; + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); // Don't accept a sell offer without the sell flag set. - env(token::acceptSellOffer(alice, buyerOfferIndex), - ter(tecNFTOKEN_OFFER_TYPE_MISMATCH)); + env(token::acceptSellOffer(alice, buyerOfferIndex), ter(tecNFTOKEN_OFFER_TYPE_MISMATCH)); env.close(); - BEAST_EXPECT(ownerCount(env, alice) == 7); + BEAST_EXPECT(ownerCount(env, alice) == aliceCount); // An account can't accept its own offer. - env(token::acceptSellOffer(alice, plainOfferIndex), - ter(tecCANT_ACCEPT_OWN_NFTOKEN_OFFER)); + env(token::acceptSellOffer(alice, plainOfferIndex), ter(tecCANT_ACCEPT_OWN_NFTOKEN_OFFER)); env.close(); - BEAST_EXPECT(ownerCount(env, buyer) == 2); + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); // The seller must currently be in possession of the token they // are selling. alice gave nftAlice0ID to gw. - env(token::acceptSellOffer(buyer, plainOfferIndex), - ter(tecNO_PERMISSION)); + env(token::acceptSellOffer(buyer, plainOfferIndex), ter(tecNO_PERMISSION)); env.close(); - BEAST_EXPECT(ownerCount(env, buyer) == 2); + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); // gw gives nftAlice0ID back to alice. That allows us to check // buyer attempting to accept one of alice's offers with // insufficient funds. { - uint256 const offerIndex = - keylet::nftoffer(gw, env.seq(gw)).key; - env(token::createOffer(gw, nftAlice0ID, XRP(0)), - txflags(tfSellNFToken)); + uint256 const offerIndex = keylet::nftoffer(gw, env.seq(gw)).key; + env(token::createOffer(gw, nftAlice0ID, XRP(0)), txflags(tfSellNFToken)); env.close(); env(token::acceptSellOffer(alice, offerIndex)); env.close(); - BEAST_EXPECT(ownerCount(env, alice) == 7); + BEAST_EXPECT(ownerCount(env, alice) == aliceCount); } env(pay(buyer, gw, gwAUD(30))); env.close(); BEAST_EXPECT(env.balance(buyer, gwAUD) == gwAUD(0)); - env(token::acceptSellOffer(buyer, audOfferIndex), - ter(tecINSUFFICIENT_FUNDS)); + env(token::acceptSellOffer(buyer, audOfferIndex), ter(tecINSUFFICIENT_FUNDS)); env.close(); - BEAST_EXPECT(ownerCount(env, buyer) == 2); + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); } //---------------------------------------------------------------------- @@ -1345,16 +1249,13 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // 1. creates an alice nft // 2. minted by minter and // 3. transfers that nft to buyer. - auto nftToBuyer = [&env, &alice, &minter1, &buyer]( - std::uint32_t flags) { + auto nftToBuyer = [&env, &alice, &minter1, &buyer](std::uint32_t flags) { uint256 const nftID{token::getNextID(env, alice, 0u, flags)}; env(token::mint(minter1, 0u), token::issuer(alice), txflags(flags)); env.close(); - uint256 const offerIndex = - keylet::nftoffer(minter1, env.seq(minter1)).key; - env(token::createOffer(minter1, nftID, XRP(0)), - txflags(tfSellNFToken)); + uint256 const offerIndex = keylet::nftoffer(minter1, env.seq(minter1)).key; + env(token::createOffer(minter1, nftID, XRP(0)), txflags(tfSellNFToken)); env.close(); env(token::acceptSellOffer(buyer, offerIndex)); @@ -1366,17 +1267,11 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // An NFT without flagBurnable can only be burned by its owner. { uint256 const noBurnID = nftToBuyer(0); - env(token::burn(alice, noBurnID), - token::owner(buyer), - ter(tecNO_PERMISSION)); + env(token::burn(alice, noBurnID), token::owner(buyer), ter(tecNO_PERMISSION)); env.close(); - env(token::burn(minter1, noBurnID), - token::owner(buyer), - ter(tecNO_PERMISSION)); + env(token::burn(minter1, noBurnID), token::owner(buyer), ter(tecNO_PERMISSION)); env.close(); - env(token::burn(minter2, noBurnID), - token::owner(buyer), - ter(tecNO_PERMISSION)); + env(token::burn(minter2, noBurnID), token::owner(buyer), ter(tecNO_PERMISSION)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 1); @@ -1387,9 +1282,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // An NFT with flagBurnable can be burned by the issuer. { uint256 const burnableID = nftToBuyer(tfBurnable); - env(token::burn(minter2, burnableID), - token::owner(buyer), - ter(tecNO_PERMISSION)); + env(token::burn(minter2, burnableID), token::owner(buyer), ter(tecNO_PERMISSION)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 1); @@ -1424,9 +1317,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // minter1 is no longer alice's minter, so no longer has // permission to burn alice's nfts. - env(token::burn(minter1, burnableID), - token::owner(buyer), - ter(tecNO_PERMISSION)); + env(token::burn(minter1, burnableID), token::owner(buyer), ter(tecNO_PERMISSION)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 1); @@ -1461,24 +1352,19 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // Don't set flagOnlyXRP and offers can be made with IOUs. { - uint256 const nftIOUsOkayID{ - token::getNextID(env, alice, 0u, tfTransferable)}; + uint256 const nftIOUsOkayID{token::getNextID(env, alice, 0u, tfTransferable)}; env(token::mint(alice, 0u), txflags(tfTransferable)); env.close(); BEAST_EXPECT(ownerCount(env, alice) == 2); - uint256 const aliceOfferIndex = - keylet::nftoffer(alice, env.seq(alice)).key; - env(token::createOffer(alice, nftIOUsOkayID, gwAUD(50)), - txflags(tfSellNFToken)); + uint256 const aliceOfferIndex = keylet::nftoffer(alice, env.seq(alice)).key; + env(token::createOffer(alice, nftIOUsOkayID, gwAUD(50)), txflags(tfSellNFToken)); env.close(); BEAST_EXPECT(ownerCount(env, alice) == 3); BEAST_EXPECT(ownerCount(env, buyer) == 1); - uint256 const buyerOfferIndex = - keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftIOUsOkayID, gwAUD(50)), - token::owner(alice)); + uint256 const buyerOfferIndex = keylet::nftoffer(buyer, env.seq(buyer)).key; + env(token::createOffer(buyer, nftIOUsOkayID, gwAUD(50)), token::owner(alice)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 2); @@ -1497,35 +1383,28 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // Set flagOnlyXRP and offers using IOUs are rejected. { - uint256 const nftOnlyXRPID{ - token::getNextID(env, alice, 0u, tfOnlyXRP | tfTransferable)}; + uint256 const nftOnlyXrpID{token::getNextID(env, alice, 0u, tfOnlyXRP | tfTransferable)}; env(token::mint(alice, 0u), txflags(tfOnlyXRP | tfTransferable)); env.close(); BEAST_EXPECT(ownerCount(env, alice) == 2); - env(token::createOffer(alice, nftOnlyXRPID, gwAUD(50)), - txflags(tfSellNFToken), - ter(temBAD_AMOUNT)); + env(token::createOffer(alice, nftOnlyXrpID, gwAUD(50)), txflags(tfSellNFToken), ter(temBAD_AMOUNT)); env.close(); BEAST_EXPECT(ownerCount(env, alice) == 2); BEAST_EXPECT(ownerCount(env, buyer) == 1); - env(token::createOffer(buyer, nftOnlyXRPID, gwAUD(50)), - token::owner(alice), - ter(temBAD_AMOUNT)); + env(token::createOffer(buyer, nftOnlyXrpID, gwAUD(50)), token::owner(alice), ter(temBAD_AMOUNT)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 1); // However offers for XRP are okay. BEAST_EXPECT(ownerCount(env, alice) == 2); - env(token::createOffer(alice, nftOnlyXRPID, XRP(60)), - txflags(tfSellNFToken)); + env(token::createOffer(alice, nftOnlyXrpID, XRP(60)), txflags(tfSellNFToken)); env.close(); BEAST_EXPECT(ownerCount(env, alice) == 3); BEAST_EXPECT(ownerCount(env, buyer) == 1); - env(token::createOffer(buyer, nftOnlyXRPID, XRP(60)), - token::owner(alice)); + env(token::createOffer(buyer, nftOnlyXrpID, XRP(60)), token::owner(alice)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 2); } @@ -1551,8 +1430,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // presence (or absence) of the fixRemoveNFTokenAutoTrustLine // amendment. So we test both cases here. for (auto const& tweakedFeatures : - {features - fixRemoveNFTokenAutoTrustLine, - features | fixRemoveNFTokenAutoTrustLine}) + {features - fixRemoveNFTokenAutoTrustLine, features | fixRemoveNFTokenAutoTrustLine}) { Env env{*this, tweakedFeatures}; env.fund(XRP(1000), alice, becky, cheri, gw); @@ -1577,38 +1455,28 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // fee will not allow creating offers that use IOUs for payment. for (std::uint32_t xferFee : {0, 1}) { - uint256 const nftNoAutoTrustID{ - token::getNextID(env, alice, 0u, tfTransferable, xferFee)}; - env(token::mint(alice, 0u), - token::xferFee(xferFee), - txflags(tfTransferable)); + uint256 const nftNoAutoTrustID{token::getNextID(env, alice, 0u, tfTransferable, xferFee)}; + env(token::mint(alice, 0u), token::xferFee(xferFee), txflags(tfTransferable)); env.close(); // becky buys the nft for 1 drop. - uint256 const beckyBuyOfferIndex = - keylet::nftoffer(becky, env.seq(becky)).key; - env(token::createOffer(becky, nftNoAutoTrustID, drops(1)), - token::owner(alice)); + uint256 const beckyBuyOfferIndex = keylet::nftoffer(becky, env.seq(becky)).key; + env(token::createOffer(becky, nftNoAutoTrustID, drops(1)), token::owner(alice)); env.close(); env(token::acceptBuyOffer(alice, beckyBuyOfferIndex)); env.close(); // becky attempts to sell the nft for AUD. - TER const createOfferTER = - xferFee ? TER(tecNO_LINE) : TER(tesSUCCESS); - uint256 const beckyOfferIndex = - keylet::nftoffer(becky, env.seq(becky)).key; + TER const createOfferTER = xferFee ? TER(tecNO_LINE) : TER(tesSUCCESS); + uint256 const beckyOfferIndex = keylet::nftoffer(becky, env.seq(becky)).key; env(token::createOffer(becky, nftNoAutoTrustID, gwAUD(100)), txflags(tfSellNFToken), ter(createOfferTER)); env.close(); // cheri offers to buy the nft for CAD. - uint256 const cheriOfferIndex = - keylet::nftoffer(cheri, env.seq(cheri)).key; - env(token::createOffer(cheri, nftNoAutoTrustID, gwCAD(100)), - token::owner(becky), - ter(createOfferTER)); + uint256 const cheriOfferIndex = keylet::nftoffer(cheri, env.seq(cheri)).key; + env(token::createOffer(cheri, nftNoAutoTrustID, gwCAD(100)), token::owner(becky), ter(createOfferTER)); env.close(); // To keep things tidy, cancel the offers. @@ -1621,14 +1489,13 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite { std::uint16_t transferFee = 10000; // 10% - uint256 const nftAutoTrustID{token::getNextID( - env, alice, 0u, tfTransferable | tfTrustLine, transferFee)}; + uint256 const nftAutoTrustID{ + token::getNextID(env, alice, 0u, tfTransferable | tfTrustLine, transferFee)}; // If the fixRemoveNFTokenAutoTrustLine amendment is active // then this transaction fails. { - TER const mintTER = - tweakedFeatures[fixRemoveNFTokenAutoTrustLine] + TER const mintTER = tweakedFeatures[fixRemoveNFTokenAutoTrustLine] ? static_cast(temINVALID_FLAG) : static_cast(tesSUCCESS); @@ -1644,19 +1511,15 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite break; } // becky buys the nft for 1 drop. - uint256 const beckyBuyOfferIndex = - keylet::nftoffer(becky, env.seq(becky)).key; - env(token::createOffer(becky, nftAutoTrustID, drops(1)), - token::owner(alice)); + uint256 const beckyBuyOfferIndex = keylet::nftoffer(becky, env.seq(becky)).key; + env(token::createOffer(becky, nftAutoTrustID, drops(1)), token::owner(alice)); env.close(); env(token::acceptBuyOffer(alice, beckyBuyOfferIndex)); env.close(); // becky sells the nft for AUD. - uint256 const beckySellOfferIndex = - keylet::nftoffer(becky, env.seq(becky)).key; - env(token::createOffer(becky, nftAutoTrustID, gwAUD(100)), - txflags(tfSellNFToken)); + uint256 const beckySellOfferIndex = keylet::nftoffer(becky, env.seq(becky)).key; + env(token::createOffer(becky, nftAutoTrustID, gwAUD(100)), txflags(tfSellNFToken)); env.close(); env(token::acceptSellOffer(cheri, beckySellOfferIndex)); env.close(); @@ -1665,10 +1528,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite BEAST_EXPECT(env.balance(alice, gwAUD) == gwAUD(10)); // becky buys the nft back for CAD. - uint256 const beckyBuyBackOfferIndex = - keylet::nftoffer(becky, env.seq(becky)).key; - env(token::createOffer(becky, nftAutoTrustID, gwCAD(50)), - token::owner(cheri)); + uint256 const beckyBuyBackOfferIndex = keylet::nftoffer(becky, env.seq(becky)).key; + env(token::createOffer(becky, nftAutoTrustID, gwCAD(50)), token::owner(cheri)); env.close(); env(token::acceptBuyOffer(cheri, beckyBuyBackOfferIndex)); env.close(); @@ -1681,18 +1542,13 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // flagCreateTrustLines will work for preestablished trust lines. { std::uint16_t transferFee = 5000; // 5% - uint256 const nftNoAutoTrustID{token::getNextID( - env, alice, 0u, tfTransferable, transferFee)}; - env(token::mint(alice, 0u), - token::xferFee(transferFee), - txflags(tfTransferable)); + uint256 const nftNoAutoTrustID{token::getNextID(env, alice, 0u, tfTransferable, transferFee)}; + env(token::mint(alice, 0u), token::xferFee(transferFee), txflags(tfTransferable)); env.close(); // alice sells the nft using AUD. - uint256 const aliceSellOfferIndex = - keylet::nftoffer(alice, env.seq(alice)).key; - env(token::createOffer(alice, nftNoAutoTrustID, gwAUD(200)), - txflags(tfSellNFToken)); + uint256 const aliceSellOfferIndex = keylet::nftoffer(alice, env.seq(alice)).key; + env(token::createOffer(alice, nftNoAutoTrustID, gwAUD(200)), txflags(tfSellNFToken)); env.close(); env(token::acceptSellOffer(cheri, aliceSellOfferIndex)); env.close(); @@ -1703,14 +1559,10 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite BEAST_EXPECT(env.balance(alice, gwAUD) == gwAUD(210)); // cheri can't sell the NFT for EUR, but can for CAD. - env(token::createOffer(cheri, nftNoAutoTrustID, gwEUR(50)), - txflags(tfSellNFToken), - ter(tecNO_LINE)); + env(token::createOffer(cheri, nftNoAutoTrustID, gwEUR(50)), txflags(tfSellNFToken), ter(tecNO_LINE)); env.close(); - uint256 const cheriSellOfferIndex = - keylet::nftoffer(cheri, env.seq(cheri)).key; - env(token::createOffer(cheri, nftNoAutoTrustID, gwCAD(100)), - txflags(tfSellNFToken)); + uint256 const cheriSellOfferIndex = keylet::nftoffer(cheri, env.seq(cheri)).key; + env(token::createOffer(cheri, nftNoAutoTrustID, gwCAD(100)), txflags(tfSellNFToken)); env.close(); env(token::acceptSellOffer(becky, cheriSellOfferIndex)); env.close(); @@ -1743,8 +1595,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // First try an nft made by alice without flagTransferable set. { BEAST_EXPECT(ownerCount(env, alice) == 0); - uint256 const nftAliceNoTransferID{ - token::getNextID(env, alice, 0u)}; + uint256 const nftAliceNoTransferID{token::getNextID(env, alice, 0u)}; env(token::mint(alice, 0u), token::xferFee(0)); env.close(); BEAST_EXPECT(ownerCount(env, alice) == 1); @@ -1756,10 +1607,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite ter(tefNFTOKEN_IS_NOT_TRANSFERABLE)); // alice offers to sell the nft and becky accepts the offer. - uint256 const aliceSellOfferIndex = - keylet::nftoffer(alice, env.seq(alice)).key; - env(token::createOffer(alice, nftAliceNoTransferID, XRP(20)), - txflags(tfSellNFToken)); + uint256 const aliceSellOfferIndex = keylet::nftoffer(alice, env.seq(alice)).key; + env(token::createOffer(alice, nftAliceNoTransferID, XRP(20)), txflags(tfSellNFToken)); env.close(); env(token::acceptSellOffer(becky, aliceSellOfferIndex)); env.close(); @@ -1786,10 +1635,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // alice offers to buy the nft back from becky. becky accepts // the offer. - uint256 const aliceBuyOfferIndex = - keylet::nftoffer(alice, env.seq(alice)).key; - env(token::createOffer(alice, nftAliceNoTransferID, XRP(22)), - token::owner(becky)); + uint256 const aliceBuyOfferIndex = keylet::nftoffer(alice, env.seq(alice)).key; + env(token::createOffer(alice, nftAliceNoTransferID, XRP(22)), token::owner(becky)); env.close(); env(token::acceptBuyOffer(becky, aliceBuyOfferIndex)); env.close(); @@ -1808,8 +1655,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env.close(); BEAST_EXPECT(ownerCount(env, minter) == 0); - uint256 const nftMinterNoTransferID{ - token::getNextID(env, alice, 0u)}; + uint256 const nftMinterNoTransferID{token::getNextID(env, alice, 0u)}; env(token::mint(minter), token::issuer(alice)); env.close(); BEAST_EXPECT(ownerCount(env, minter) == 1); @@ -1845,10 +1691,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // minter successfully offers their nft for sale. BEAST_EXPECT(ownerCount(env, minter) == 1); - uint256 const minterSellOfferIndex = - keylet::nftoffer(minter, env.seq(minter)).key; - env(token::createOffer(minter, nftMinterNoTransferID, XRP(22)), - txflags(tfSellNFToken)); + uint256 const minterSellOfferIndex = keylet::nftoffer(minter, env.seq(minter)).key; + env(token::createOffer(minter, nftMinterNoTransferID, XRP(22)), txflags(tfSellNFToken)); env.close(); BEAST_EXPECT(ownerCount(env, minter) == 2); @@ -1882,10 +1726,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // alice can create an offer to buy the nft. BEAST_EXPECT(ownerCount(env, alice) == 0); - uint256 const aliceBuyOfferIndex = - keylet::nftoffer(alice, env.seq(alice)).key; - env(token::createOffer(alice, nftMinterNoTransferID, XRP(25)), - token::owner(becky)); + uint256 const aliceBuyOfferIndex = keylet::nftoffer(alice, env.seq(alice)).key; + env(token::createOffer(alice, nftMinterNoTransferID, XRP(25)), token::owner(becky)); env.close(); BEAST_EXPECT(ownerCount(env, alice) == 1); @@ -1899,10 +1741,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // Now minter can create an offer to buy the nft. BEAST_EXPECT(ownerCount(env, minter) == 0); - uint256 const minterBuyOfferIndex = - keylet::nftoffer(minter, env.seq(minter)).key; - env(token::createOffer(minter, nftMinterNoTransferID, XRP(26)), - token::owner(becky)); + uint256 const minterBuyOfferIndex = keylet::nftoffer(minter, env.seq(minter)).key; + env(token::createOffer(minter, nftMinterNoTransferID, XRP(26)), token::owner(becky)); env.close(); BEAST_EXPECT(ownerCount(env, minter) == 1); @@ -1934,24 +1774,19 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // by anybody. { BEAST_EXPECT(ownerCount(env, alice) == 0); - uint256 const nftAliceID{ - token::getNextID(env, alice, 0u, tfTransferable)}; + uint256 const nftAliceID{token::getNextID(env, alice, 0u, tfTransferable)}; env(token::mint(alice, 0u), txflags(tfTransferable)); env.close(); BEAST_EXPECT(ownerCount(env, alice) == 1); // Both alice and becky can make offers for alice's nft. - uint256 const aliceSellOfferIndex = - keylet::nftoffer(alice, env.seq(alice)).key; - env(token::createOffer(alice, nftAliceID, XRP(20)), - txflags(tfSellNFToken)); + uint256 const aliceSellOfferIndex = keylet::nftoffer(alice, env.seq(alice)).key; + env(token::createOffer(alice, nftAliceID, XRP(20)), txflags(tfSellNFToken)); env.close(); BEAST_EXPECT(ownerCount(env, alice) == 2); - uint256 const beckyBuyOfferIndex = - keylet::nftoffer(becky, env.seq(becky)).key; - env(token::createOffer(becky, nftAliceID, XRP(21)), - token::owner(alice)); + uint256 const beckyBuyOfferIndex = keylet::nftoffer(becky, env.seq(becky)).key; + env(token::createOffer(becky, nftAliceID, XRP(21)), token::owner(alice)); env.close(); BEAST_EXPECT(ownerCount(env, alice) == 2); @@ -1962,10 +1797,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite BEAST_EXPECT(ownerCount(env, becky) == 2); // becky offers to sell the nft. - uint256 const beckySellOfferIndex = - keylet::nftoffer(becky, env.seq(becky)).key; - env(token::createOffer(becky, nftAliceID, XRP(22)), - txflags(tfSellNFToken)); + uint256 const beckySellOfferIndex = keylet::nftoffer(becky, env.seq(becky)).key; + env(token::createOffer(becky, nftAliceID, XRP(22)), txflags(tfSellNFToken)); env.close(); BEAST_EXPECT(ownerCount(env, alice) == 0); BEAST_EXPECT(ownerCount(env, becky) == 3); @@ -1979,10 +1812,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite BEAST_EXPECT(ownerCount(env, minter) == 1); // minter offers to sell the nft. - uint256 const minterSellOfferIndex = - keylet::nftoffer(minter, env.seq(minter)).key; - env(token::createOffer(minter, nftAliceID, XRP(23)), - txflags(tfSellNFToken)); + uint256 const minterSellOfferIndex = keylet::nftoffer(minter, env.seq(minter)).key; + env(token::createOffer(minter, nftAliceID, XRP(23)), txflags(tfSellNFToken)); env.close(); BEAST_EXPECT(ownerCount(env, alice) == 0); BEAST_EXPECT(ownerCount(env, becky) == 1); @@ -2058,16 +1889,13 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite BEAST_EXPECT(ownerCount(env, carol) == 1); BEAST_EXPECT(ownerCount(env, minter) == 1); - uint256 const nftID = - token::getNextID(env, alice, 0u, tfTransferable); + uint256 const nftID = token::getNextID(env, alice, 0u, tfTransferable); env(token::mint(alice), txflags(tfTransferable)); env.close(); // Becky buys the nft for XAU(10). Check balances. - uint256 const beckyBuyOfferIndex = - keylet::nftoffer(becky, env.seq(becky)).key; - env(token::createOffer(becky, nftID, gwXAU(10)), - token::owner(alice)); + uint256 const beckyBuyOfferIndex = keylet::nftoffer(becky, env.seq(becky)).key; + env(token::createOffer(becky, nftID, gwXAU(10)), token::owner(alice)); env.close(); BEAST_EXPECT(env.balance(alice, gwXAU) == gwXAU(1000)); BEAST_EXPECT(env.balance(becky, gwXAU) == gwXAU(1000)); @@ -2078,10 +1906,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite BEAST_EXPECT(env.balance(becky, gwXAU) == gwXAU(990)); // becky sells nft to carol. alice's balance should not change. - uint256 const beckySellOfferIndex = - keylet::nftoffer(becky, env.seq(becky)).key; - env(token::createOffer(becky, nftID, gwXAU(10)), - txflags(tfSellNFToken)); + uint256 const beckySellOfferIndex = keylet::nftoffer(becky, env.seq(becky)).key; + env(token::createOffer(becky, nftID, gwXAU(10)), txflags(tfSellNFToken)); env.close(); env(token::acceptSellOffer(carol, beckySellOfferIndex)); env.close(); @@ -2090,10 +1916,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite BEAST_EXPECT(env.balance(carol, gwXAU) == gwXAU(990)); // minter buys nft from carol. alice's balance should not change. - uint256 const minterBuyOfferIndex = - keylet::nftoffer(minter, env.seq(minter)).key; - env(token::createOffer(minter, nftID, gwXAU(10)), - token::owner(carol)); + uint256 const minterBuyOfferIndex = keylet::nftoffer(minter, env.seq(minter)).key; + env(token::createOffer(minter, nftID, gwXAU(10)), token::owner(carol)); env.close(); env(token::acceptBuyOffer(carol, minterBuyOfferIndex)); env.close(); @@ -2104,10 +1928,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // minter sells the nft to alice. gwXAU balances should finish // where they started. - uint256 const minterSellOfferIndex = - keylet::nftoffer(minter, env.seq(minter)).key; - env(token::createOffer(minter, nftID, gwXAU(10)), - txflags(tfSellNFToken)); + uint256 const minterSellOfferIndex = keylet::nftoffer(minter, env.seq(minter)).key; + env(token::createOffer(minter, nftID, gwXAU(10)), txflags(tfSellNFToken)); env.close(); env(token::acceptSellOffer(alice, minterSellOfferIndex)); env.close(); @@ -2128,16 +1950,13 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // Set the smallest possible transfer fee. { // An nft with a transfer fee of 1 basis point. - uint256 const nftID = - token::getNextID(env, alice, 0u, tfTransferable, 1); + uint256 const nftID = token::getNextID(env, alice, 0u, tfTransferable, 1); env(token::mint(alice), txflags(tfTransferable), token::xferFee(1)); env.close(); // Becky buys the nft for XAU(10). Check balances. - uint256 const beckyBuyOfferIndex = - keylet::nftoffer(becky, env.seq(becky)).key; - env(token::createOffer(becky, nftID, gwXAU(10)), - token::owner(alice)); + uint256 const beckyBuyOfferIndex = keylet::nftoffer(becky, env.seq(becky)).key; + env(token::createOffer(becky, nftID, gwXAU(10)), token::owner(alice)); env.close(); BEAST_EXPECT(env.balance(alice, gwXAU) == gwXAU(1000)); BEAST_EXPECT(env.balance(becky, gwXAU) == gwXAU(1000)); @@ -2148,10 +1967,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite BEAST_EXPECT(env.balance(becky, gwXAU) == gwXAU(990)); // becky sells nft to carol. alice's balance goes up. - uint256 const beckySellOfferIndex = - keylet::nftoffer(becky, env.seq(becky)).key; - env(token::createOffer(becky, nftID, gwXAU(10)), - txflags(tfSellNFToken)); + uint256 const beckySellOfferIndex = keylet::nftoffer(becky, env.seq(becky)).key; + env(token::createOffer(becky, nftID, gwXAU(10)), txflags(tfSellNFToken)); env.close(); env(token::acceptSellOffer(carol, beckySellOfferIndex)); env.close(); @@ -2161,10 +1978,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite BEAST_EXPECT(env.balance(carol, gwXAU) == gwXAU(990)); // minter buys nft from carol. alice's balance goes up. - uint256 const minterBuyOfferIndex = - keylet::nftoffer(minter, env.seq(minter)).key; - env(token::createOffer(minter, nftID, gwXAU(10)), - token::owner(carol)); + uint256 const minterBuyOfferIndex = keylet::nftoffer(minter, env.seq(minter)).key; + env(token::createOffer(minter, nftID, gwXAU(10)), token::owner(carol)); env.close(); env(token::acceptBuyOffer(carol, minterBuyOfferIndex)); env.close(); @@ -2176,10 +1991,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // minter sells the nft to alice. Because alice is part of the // transaction no transfer fee is removed. - uint256 const minterSellOfferIndex = - keylet::nftoffer(minter, env.seq(minter)).key; - env(token::createOffer(minter, nftID, gwXAU(10)), - txflags(tfSellNFToken)); + uint256 const minterSellOfferIndex = keylet::nftoffer(minter, env.seq(minter)).key; + env(token::createOffer(minter, nftID, gwXAU(10)), txflags(tfSellNFToken)); env.close(); env(token::acceptSellOffer(alice, minterSellOfferIndex)); env.close(); @@ -2218,18 +2031,13 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env.close(); // Make an nft with a transfer fee of 50%. - uint256 const nftID = token::getNextID( - env, alice, 0u, tfTransferable, maxTransferFee); - env(token::mint(alice), - txflags(tfTransferable), - token::xferFee(maxTransferFee)); + uint256 const nftID = token::getNextID(env, alice, 0u, tfTransferable, maxTransferFee); + env(token::mint(alice), txflags(tfTransferable), token::xferFee(maxTransferFee)); env.close(); // Becky buys the nft for XAU(10). Check balances. - uint256 const beckyBuyOfferIndex = - keylet::nftoffer(becky, env.seq(becky)).key; - env(token::createOffer(becky, nftID, gwXAU(10)), - token::owner(alice)); + uint256 const beckyBuyOfferIndex = keylet::nftoffer(becky, env.seq(becky)).key; + env(token::createOffer(becky, nftID, gwXAU(10)), token::owner(alice)); env.close(); BEAST_EXPECT(env.balance(alice, gwXAU) == gwXAU(1000)); BEAST_EXPECT(env.balance(becky, gwXAU) == gwXAU(1000)); @@ -2240,10 +2048,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite BEAST_EXPECT(env.balance(becky, gwXAU) == gwXAU(990)); // becky sells nft to minter. alice's balance goes up. - uint256 const beckySellOfferIndex = - keylet::nftoffer(becky, env.seq(becky)).key; - env(token::createOffer(becky, nftID, gwXAU(100)), - txflags(tfSellNFToken)); + uint256 const beckySellOfferIndex = keylet::nftoffer(becky, env.seq(becky)).key; + env(token::createOffer(becky, nftID, gwXAU(100)), txflags(tfSellNFToken)); env.close(); env(token::acceptSellOffer(minter, beckySellOfferIndex)); env.close(); @@ -2253,10 +2059,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite BEAST_EXPECT(env.balance(minter, gwXAU) == gwXAU(900)); // carol buys nft from minter. alice's balance goes up. - uint256 const carolBuyOfferIndex = - keylet::nftoffer(carol, env.seq(carol)).key; - env(token::createOffer(carol, nftID, gwXAU(10)), - token::owner(minter)); + uint256 const carolBuyOfferIndex = keylet::nftoffer(carol, env.seq(carol)).key; + env(token::createOffer(carol, nftID, gwXAU(10)), token::owner(minter)); env.close(); env(token::acceptBuyOffer(minter, carolBuyOfferIndex)); env.close(); @@ -2268,10 +2072,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // carol sells the nft to alice. Because alice is part of the // transaction no transfer fee is removed. - uint256 const carolSellOfferIndex = - keylet::nftoffer(carol, env.seq(carol)).key; - env(token::createOffer(carol, nftID, gwXAU(10)), - txflags(tfSellNFToken)); + uint256 const carolSellOfferIndex = keylet::nftoffer(carol, env.seq(carol)).key; + env(token::createOffer(carol, nftID, gwXAU(10)), txflags(tfSellNFToken)); env.close(); env(token::acceptSellOffer(alice, carolSellOfferIndex)); env.close(); @@ -2309,8 +2111,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env.disableFeature(fixUniversalNumber); // An nft with a transfer fee of 1 basis point. - uint256 const nftID = - token::getNextID(env, alice, 0u, tfTransferable, 1); + uint256 const nftID = token::getNextID(env, alice, 0u, tfTransferable, 1); env(token::mint(alice), txflags(tfTransferable), token::xferFee(1)); env.close(); @@ -2318,8 +2119,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // alice there should be no transfer fee. STAmount aliceBalance = env.balance(alice); STAmount minterBalance = env.balance(minter); - uint256 const minterBuyOfferIndex = - keylet::nftoffer(minter, env.seq(minter)).key; + uint256 const minterBuyOfferIndex = keylet::nftoffer(minter, env.seq(minter)).key; env(token::createOffer(minter, nftID, XRP(1)), token::owner(alice)); env.close(); env(token::acceptBuyOffer(alice, minterBuyOfferIndex)); @@ -2333,8 +2133,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // alice does not get any transfer fee. auto pmt = NumberSwitchOver ? drops(50000) : drops(99999); STAmount carolBalance = env.balance(carol); - uint256 const minterSellOfferIndex = - keylet::nftoffer(minter, env.seq(minter)).key; + uint256 const minterSellOfferIndex = keylet::nftoffer(minter, env.seq(minter)).key; env(token::createOffer(minter, nftID, pmt), txflags(tfSellNFToken)); env.close(); env(token::acceptSellOffer(carol, minterSellOfferIndex)); @@ -2348,8 +2147,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // carol sells to becky. This is the smallest amount to pay for a // transfer that enables a transfer fee of 1 basis point. STAmount beckyBalance = env.balance(becky); - uint256 const beckyBuyOfferIndex = - keylet::nftoffer(becky, env.seq(becky)).key; + uint256 const beckyBuyOfferIndex = keylet::nftoffer(becky, env.seq(becky)).key; pmt = NumberSwitchOver ? drops(50001) : drops(100000); env(token::createOffer(becky, nftID, pmt), token::owner(carol)); env.close(); @@ -2369,8 +2167,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // of an IOU. { // An nft with a transfer fee of 1 basis point. - uint256 const nftID = - token::getNextID(env, alice, 0u, tfTransferable, 1); + uint256 const nftID = token::getNextID(env, alice, 0u, tfTransferable, 1); env(token::mint(alice), txflags(tfTransferable), token::xferFee(1)); env.close(); @@ -2382,25 +2179,21 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env(pay(becky, gw, env.balance(becky, gwXAU))); env.close(); - STAmount const startXAUBalance( - gwXAU.issue(), STAmount::cMinValue, STAmount::cMinOffset + 5); + STAmount const startXAUBalance(gwXAU.issue(), STAmount::cMinValue, STAmount::cMinOffset + 5); env(pay(gw, alice, startXAUBalance)); env(pay(gw, minter, startXAUBalance)); env(pay(gw, becky, startXAUBalance)); env.close(); // Here is the smallest expressible gwXAU amount. - STAmount tinyXAU( - gwXAU.issue(), STAmount::cMinValue, STAmount::cMinOffset); + STAmount tinyXAU(gwXAU.issue(), STAmount::cMinValue, STAmount::cMinOffset); // minter buys the nft for tinyXAU. Since the transfer involves // alice there should be no transfer fee. STAmount aliceBalance = env.balance(alice, gwXAU); STAmount minterBalance = env.balance(minter, gwXAU); - uint256 const minterBuyOfferIndex = - keylet::nftoffer(minter, env.seq(minter)).key; - env(token::createOffer(minter, nftID, tinyXAU), - token::owner(alice)); + uint256 const minterBuyOfferIndex = keylet::nftoffer(minter, env.seq(minter)).key; + env(token::createOffer(minter, nftID, tinyXAU), token::owner(alice)); env.close(); env(token::acceptBuyOffer(alice, minterBuyOfferIndex)); env.close(); @@ -2411,10 +2204,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // minter sells to carol. STAmount carolBalance = env.balance(carol, gwXAU); - uint256 const minterSellOfferIndex = - keylet::nftoffer(minter, env.seq(minter)).key; - env(token::createOffer(minter, nftID, tinyXAU), - txflags(tfSellNFToken)); + uint256 const minterSellOfferIndex = keylet::nftoffer(minter, env.seq(minter)).key; + env(token::createOffer(minter, nftID, tinyXAU), txflags(tfSellNFToken)); env.close(); env(token::acceptSellOffer(carol, minterSellOfferIndex)); env.close(); @@ -2428,14 +2219,11 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // carol sells to becky. This is the smallest gwXAU amount // to pay for a transfer that enables a transfer fee of 1. - STAmount const cheapNFT( - gwXAU.issue(), STAmount::cMinValue, STAmount::cMinOffset + 5); + STAmount const cheapNFT(gwXAU.issue(), STAmount::cMinValue, STAmount::cMinOffset + 5); STAmount beckyBalance = env.balance(becky, gwXAU); - uint256 const beckyBuyOfferIndex = - keylet::nftoffer(becky, env.seq(becky)).key; - env(token::createOffer(becky, nftID, cheapNFT), - token::owner(carol)); + uint256 const beckyBuyOfferIndex = keylet::nftoffer(becky, env.seq(becky)).key; + env(token::createOffer(becky, nftID, cheapNFT), token::owner(carol)); env.close(); env(token::acceptBuyOffer(carol, beckyBuyOfferIndex)); env.close(); @@ -2497,29 +2285,18 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite else { std::stringstream ss; - ss << "Taxon recovery failed from nftID " - << to_string(nftID) << ". Expected: " << taxon + ss << "Taxon recovery failed from nftID " << to_string(nftID) << ". Expected: " << taxon << "; got: " << gotTaxon; fail(ss.str()); } }; uint256 const nftAliceID = token::getID( - env, - alice, - taxon, - rand_int(), - rand_int(), - rand_int()); + env, alice, taxon, rand_int(), rand_int(), rand_int()); check(taxon, nftAliceID); uint256 const nftBeckyID = token::getID( - env, - becky, - taxon, - rand_int(), - rand_int(), - rand_int()); + env, becky, taxon, rand_int(), rand_int(), rand_int()); check(taxon, nftBeckyID); } } @@ -2568,8 +2345,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite std::string uri; std::uint32_t taxon; - Entry(std::string uri_, std::uint32_t taxon_) - : uri(std::move(uri_)), taxon(taxon_) + Entry(std::string uri_, std::uint32_t taxon_) : uri(std::move(uri_)), taxon(taxon_) { } }; @@ -2612,12 +2388,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite sortedNFTs.reserve(nfts.size()); for (std::size_t i = 0; i < nfts.size(); ++i) sortedNFTs.push_back(nfts[i]); - std::sort( - sortedNFTs.begin(), - sortedNFTs.end(), - [](Json::Value const& lhs, Json::Value const& rhs) { - return lhs[jss::nft_serial] < rhs[jss::nft_serial]; - }); + std::sort(sortedNFTs.begin(), sortedNFTs.end(), [](Json::Value const& lhs, Json::Value const& rhs) { + return lhs[jss::nft_serial] < rhs[jss::nft_serial]; + }); for (std::size_t i = 0; i < entries.size(); ++i) { @@ -2657,39 +2430,24 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env(token::setMinter(issuer, minter)); env.close(); - uint256 const nftokenID = - token::getNextID(env, issuer, 0, tfTransferable); - env(token::mint(minter, 0), - token::issuer(issuer), - txflags(tfTransferable)); + uint256 const nftokenID = token::getNextID(env, issuer, 0, tfTransferable); + env(token::mint(minter, 0), token::issuer(issuer), txflags(tfTransferable)); env.close(); // Test how adding a Destination field to an offer affects permissions // for canceling offers. { - uint256 const offerMinterToIssuer = - keylet::nftoffer(minter, env.seq(minter)).key; - env(token::createOffer(minter, nftokenID, drops(1)), - token::destination(issuer), - txflags(tfSellNFToken)); + uint256 const offerMinterToIssuer = keylet::nftoffer(minter, env.seq(minter)).key; + env(token::createOffer(minter, nftokenID, drops(1)), token::destination(issuer), txflags(tfSellNFToken)); - uint256 const offerMinterToBuyer = - keylet::nftoffer(minter, env.seq(minter)).key; - env(token::createOffer(minter, nftokenID, drops(1)), - token::destination(buyer), - txflags(tfSellNFToken)); + uint256 const offerMinterToBuyer = keylet::nftoffer(minter, env.seq(minter)).key; + env(token::createOffer(minter, nftokenID, drops(1)), token::destination(buyer), txflags(tfSellNFToken)); - uint256 const offerIssuerToMinter = - keylet::nftoffer(issuer, env.seq(issuer)).key; - env(token::createOffer(issuer, nftokenID, drops(1)), - token::owner(minter), - token::destination(minter)); + uint256 const offerIssuerToMinter = keylet::nftoffer(issuer, env.seq(issuer)).key; + env(token::createOffer(issuer, nftokenID, drops(1)), token::owner(minter), token::destination(minter)); - uint256 const offerIssuerToBuyer = - keylet::nftoffer(issuer, env.seq(issuer)).key; - env(token::createOffer(issuer, nftokenID, drops(1)), - token::owner(minter), - token::destination(buyer)); + uint256 const offerIssuerToBuyer = keylet::nftoffer(issuer, env.seq(issuer)).key; + env(token::createOffer(issuer, nftokenID, drops(1)), token::owner(minter), token::destination(buyer)); env.close(); BEAST_EXPECT(ownerCount(env, issuer) == 2); @@ -2703,14 +2461,10 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // Note that issuer does not have any special permissions regarding // offer cancellation. issuer cannot cancel an offer for an // NFToken they issued. - env(token::cancelOffer(issuer, {offerMinterToBuyer}), - ter(tecNO_PERMISSION)); - env(token::cancelOffer(buyer, {offerMinterToIssuer}), - ter(tecNO_PERMISSION)); - env(token::cancelOffer(buyer, {offerIssuerToMinter}), - ter(tecNO_PERMISSION)); - env(token::cancelOffer(minter, {offerIssuerToBuyer}), - ter(tecNO_PERMISSION)); + env(token::cancelOffer(issuer, {offerMinterToBuyer}), ter(tecNO_PERMISSION)); + env(token::cancelOffer(buyer, {offerMinterToIssuer}), ter(tecNO_PERMISSION)); + env(token::cancelOffer(buyer, {offerIssuerToMinter}), ter(tecNO_PERMISSION)); + env(token::cancelOffer(minter, {offerIssuerToBuyer}), ter(tecNO_PERMISSION)); env.close(); BEAST_EXPECT(ownerCount(env, issuer) == 2); BEAST_EXPECT(ownerCount(env, minter) == 3); @@ -2731,11 +2485,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // Test how adding a Destination field to a sell offer affects // accepting that offer. { - uint256 const offerMinterSellsToBuyer = - keylet::nftoffer(minter, env.seq(minter)).key; - env(token::createOffer(minter, nftokenID, drops(1)), - token::destination(buyer), - txflags(tfSellNFToken)); + uint256 const offerMinterSellsToBuyer = keylet::nftoffer(minter, env.seq(minter)).key; + env(token::createOffer(minter, nftokenID, drops(1)), token::destination(buyer), txflags(tfSellNFToken)); env.close(); BEAST_EXPECT(ownerCount(env, issuer) == 0); BEAST_EXPECT(ownerCount(env, minter) == 2); @@ -2743,8 +2494,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // issuer cannot accept a sell offer where they are not the // destination. - env(token::acceptSellOffer(issuer, offerMinterSellsToBuyer), - ter(tecNO_PERMISSION)); + env(token::acceptSellOffer(issuer, offerMinterSellsToBuyer), ter(tecNO_PERMISSION)); env.close(); BEAST_EXPECT(ownerCount(env, issuer) == 0); BEAST_EXPECT(ownerCount(env, minter) == 2); @@ -2761,11 +2511,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // Test how adding a Destination field to a buy offer affects // accepting that offer. { - uint256 const offerMinterBuysFromBuyer = - keylet::nftoffer(minter, env.seq(minter)).key; - env(token::createOffer(minter, nftokenID, drops(1)), - token::owner(buyer), - token::destination(buyer)); + uint256 const offerMinterBuysFromBuyer = keylet::nftoffer(minter, env.seq(minter)).key; + env(token::createOffer(minter, nftokenID, drops(1)), token::owner(buyer), token::destination(buyer)); env.close(); BEAST_EXPECT(ownerCount(env, issuer) == 0); BEAST_EXPECT(ownerCount(env, minter) == 1); @@ -2773,8 +2520,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // issuer cannot accept a buy offer where they are the // destination. - env(token::acceptBuyOffer(issuer, offerMinterBuysFromBuyer), - ter(tecNO_PERMISSION)); + env(token::acceptBuyOffer(issuer, offerMinterBuysFromBuyer), ter(tecNO_PERMISSION)); env.close(); BEAST_EXPECT(ownerCount(env, issuer) == 0); BEAST_EXPECT(ownerCount(env, minter) == 1); @@ -2790,18 +2536,14 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // If a destination other than the NFToken owner is set, that // destination must act as a broker. The NFToken owner may not // simply accept the offer. - uint256 const offerBuyerBuysFromMinter = - keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftokenID, drops(1)), - token::owner(minter), - token::destination(broker)); + uint256 const offerBuyerBuysFromMinter = keylet::nftoffer(buyer, env.seq(buyer)).key; + env(token::createOffer(buyer, nftokenID, drops(1)), token::owner(minter), token::destination(broker)); env.close(); BEAST_EXPECT(ownerCount(env, issuer) == 0); BEAST_EXPECT(ownerCount(env, minter) == 1); BEAST_EXPECT(ownerCount(env, buyer) == 1); - env(token::acceptBuyOffer(minter, offerBuyerBuysFromMinter), - ter(tecNO_PERMISSION)); + env(token::acceptBuyOffer(minter, offerBuyerBuysFromMinter), ter(tecNO_PERMISSION)); env.close(); // Clean up the unused offer. @@ -2815,16 +2557,11 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // Show that a sell offer's Destination can broker that sell offer // to another account. { - uint256 const offerMinterToBroker = - keylet::nftoffer(minter, env.seq(minter)).key; - env(token::createOffer(minter, nftokenID, drops(1)), - token::destination(broker), - txflags(tfSellNFToken)); + uint256 const offerMinterToBroker = keylet::nftoffer(minter, env.seq(minter)).key; + env(token::createOffer(minter, nftokenID, drops(1)), token::destination(broker), txflags(tfSellNFToken)); - uint256 const offerBuyerToMinter = - keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftokenID, drops(1)), - token::owner(minter)); + uint256 const offerBuyerToMinter = keylet::nftoffer(buyer, env.seq(buyer)).key; + env(token::createOffer(buyer, nftokenID, drops(1)), token::owner(minter)); env.close(); BEAST_EXPECT(ownerCount(env, issuer) == 0); @@ -2834,9 +2571,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite { // issuer cannot broker the offers, because they are not the // Destination. - env(token::brokerOffers( - issuer, offerBuyerToMinter, offerMinterToBroker), - ter(tecNO_PERMISSION)); + env(token::brokerOffers(issuer, offerBuyerToMinter, offerMinterToBroker), ter(tecNO_PERMISSION)); env.close(); BEAST_EXPECT(ownerCount(env, issuer) == 0); BEAST_EXPECT(ownerCount(env, minter) == 2); @@ -2845,8 +2580,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // Since broker is the sell offer's destination, they can broker // the two offers. - env(token::brokerOffers( - broker, offerBuyerToMinter, offerMinterToBroker)); + env(token::brokerOffers(broker, offerBuyerToMinter, offerMinterToBroker)); env.close(); BEAST_EXPECT(ownerCount(env, issuer) == 0); BEAST_EXPECT(ownerCount(env, minter) == 0); @@ -2857,21 +2591,14 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // Destination doesn't match, but can complete if the Destination // does match. { - uint256 const offerBuyerToMinter = - keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftokenID, drops(1)), - token::destination(minter), - txflags(tfSellNFToken)); + uint256 const offerBuyerToMinter = keylet::nftoffer(buyer, env.seq(buyer)).key; + env(token::createOffer(buyer, nftokenID, drops(1)), token::destination(minter), txflags(tfSellNFToken)); - uint256 const offerMinterToBuyer = - keylet::nftoffer(minter, env.seq(minter)).key; - env(token::createOffer(minter, nftokenID, drops(1)), - token::owner(buyer)); + uint256 const offerMinterToBuyer = keylet::nftoffer(minter, env.seq(minter)).key; + env(token::createOffer(minter, nftokenID, drops(1)), token::owner(buyer)); - uint256 const offerIssuerToBuyer = - keylet::nftoffer(issuer, env.seq(issuer)).key; - env(token::createOffer(issuer, nftokenID, drops(1)), - token::owner(buyer)); + uint256 const offerIssuerToBuyer = keylet::nftoffer(issuer, env.seq(issuer)).key; + env(token::createOffer(issuer, nftokenID, drops(1)), token::owner(buyer)); env.close(); BEAST_EXPECT(ownerCount(env, issuer) == 1); @@ -2881,18 +2608,14 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite { // Cannot broker offers when the sell destination is not the // buyer. - env(token::brokerOffers( - broker, offerIssuerToBuyer, offerBuyerToMinter), - ter(tecNO_PERMISSION)); + env(token::brokerOffers(broker, offerIssuerToBuyer, offerBuyerToMinter), ter(tecNO_PERMISSION)); env.close(); BEAST_EXPECT(ownerCount(env, issuer) == 1); BEAST_EXPECT(ownerCount(env, minter) == 1); BEAST_EXPECT(ownerCount(env, buyer) == 2); - env(token::brokerOffers( - broker, offerMinterToBuyer, offerBuyerToMinter), - ter(tecNO_PERMISSION)); + env(token::brokerOffers(broker, offerMinterToBuyer, offerBuyerToMinter), ter(tecNO_PERMISSION)); env.close(); // Buyer is successful with acceptOffer. @@ -2920,24 +2643,16 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // Show that if a buy and a sell offer both have the same destination, // then that destination can broker the offers. { - uint256 const offerMinterToBroker = - keylet::nftoffer(minter, env.seq(minter)).key; - env(token::createOffer(minter, nftokenID, drops(1)), - token::destination(broker), - txflags(tfSellNFToken)); + uint256 const offerMinterToBroker = keylet::nftoffer(minter, env.seq(minter)).key; + env(token::createOffer(minter, nftokenID, drops(1)), token::destination(broker), txflags(tfSellNFToken)); - uint256 const offerBuyerToBroker = - keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftokenID, drops(1)), - token::owner(minter), - token::destination(broker)); + uint256 const offerBuyerToBroker = keylet::nftoffer(buyer, env.seq(buyer)).key; + env(token::createOffer(buyer, nftokenID, drops(1)), token::owner(minter), token::destination(broker)); { // Cannot broker offers when the sell destination is not the // buyer or the broker. - env(token::brokerOffers( - issuer, offerBuyerToBroker, offerMinterToBroker), - ter(tecNO_PERMISSION)); + env(token::brokerOffers(issuer, offerBuyerToBroker, offerMinterToBroker), ter(tecNO_PERMISSION)); env.close(); BEAST_EXPECT(ownerCount(env, issuer) == 0); BEAST_EXPECT(ownerCount(env, minter) == 2); @@ -2945,8 +2660,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite } // Broker is successful if they are the destination of both offers. - env(token::brokerOffers( - broker, offerBuyerToBroker, offerMinterToBroker)); + env(token::brokerOffers(broker, offerBuyerToBroker, offerMinterToBroker)); env.close(); BEAST_EXPECT(ownerCount(env, issuer) == 0); BEAST_EXPECT(ownerCount(env, minter) == 0); @@ -2973,11 +2687,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env(token::setMinter(issuer, minter)); env.close(); - uint256 const nftokenID = - token::getNextID(env, issuer, 0, tfTransferable); - env(token::mint(minter, 0), - token::issuer(issuer), - txflags(tfTransferable)); + uint256 const nftokenID = token::getNextID(env, issuer, 0, tfTransferable); + env(token::mint(minter, 0), token::issuer(issuer), txflags(tfTransferable)); env.close(); // enable flag @@ -3002,12 +2713,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // create offer (allowed now) then cancel { - uint256 const offerIndex = - keylet::nftoffer(minter, env.seq(minter)).key; + uint256 const offerIndex = keylet::nftoffer(minter, env.seq(minter)).key; - env(token::createOffer(minter, nftokenID, drops(1)), - token::destination(buyer), - txflags(tfSellNFToken)); + env(token::createOffer(minter, nftokenID, drops(1)), token::destination(buyer), txflags(tfSellNFToken)); env.close(); env(token::cancelOffer(minter, {offerIndex})); @@ -3016,12 +2724,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // create offer, enable flag, then cancel { - uint256 const offerIndex = - keylet::nftoffer(minter, env.seq(minter)).key; + uint256 const offerIndex = keylet::nftoffer(minter, env.seq(minter)).key; - env(token::createOffer(minter, nftokenID, drops(1)), - token::destination(buyer), - txflags(tfSellNFToken)); + env(token::createOffer(minter, nftokenID, drops(1)), token::destination(buyer), txflags(tfSellNFToken)); env.close(); env(fset(buyer, asfDisallowIncomingNFTokenOffer)); @@ -3036,12 +2741,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // create offer then transfer { - uint256 const offerIndex = - keylet::nftoffer(minter, env.seq(minter)).key; + uint256 const offerIndex = keylet::nftoffer(minter, env.seq(minter)).key; - env(token::createOffer(minter, nftokenID, drops(1)), - token::destination(buyer), - txflags(tfSellNFToken)); + env(token::createOffer(minter, nftokenID, drops(1)), token::destination(buyer), txflags(tfSellNFToken)); env.close(); env(token::acceptSellOffer(buyer, offerIndex)); @@ -3056,17 +2758,13 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // a random offer to buy the token { - env(token::createOffer(alice, nftokenID, drops(1)), - token::owner(buyer), - ter(tecNO_PERMISSION)); + env(token::createOffer(alice, nftokenID, drops(1)), token::owner(buyer), ter(tecNO_PERMISSION)); env.close(); } // minter offer to buy the token { - env(token::createOffer(minter, nftokenID, drops(1)), - token::owner(buyer), - ter(tecNO_PERMISSION)); + env(token::createOffer(minter, nftokenID, drops(1)), token::owner(buyer), ter(tecNO_PERMISSION)); env.close(); } @@ -3076,17 +2774,12 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // enable flag env(fset(buyer, asfDisallowIncomingNFTokenOffer)); // a sell offer from the minter to the buyer should be rejected - env(token::mint(minter), - token::amount(drops(1)), - token::destination(buyer), - ter(tecNO_PERMISSION)); + env(token::mint(minter), token::amount(drops(1)), token::destination(buyer), ter(tecNO_PERMISSION)); env.close(); // disable flag env(fclear(buyer, asfDisallowIncomingNFTokenOffer)); - env(token::mint(minter), - token::amount(drops(1)), - token::destination(buyer)); + env(token::mint(minter), token::amount(drops(1)), token::destination(buyer)); env.close(); } } @@ -3112,53 +2805,43 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env(token::setMinter(issuer, minter)); env.close(); - uint256 const nftokenID0 = - token::getNextID(env, issuer, 0, tfTransferable); - env(token::mint(minter, 0), - token::issuer(issuer), - txflags(tfTransferable)); + uint256 const nftokenID0 = token::getNextID(env, issuer, 0, tfTransferable); + env(token::mint(minter, 0), token::issuer(issuer), txflags(tfTransferable)); env.close(); - uint256 const nftokenID1 = - token::getNextID(env, issuer, 0, tfTransferable); - env(token::mint(minter, 0), - token::issuer(issuer), - txflags(tfTransferable)); + uint256 const nftokenID1 = token::getNextID(env, issuer, 0, tfTransferable); + env(token::mint(minter, 0), token::issuer(issuer), txflags(tfTransferable)); env.close(); + uint8_t issuerCount, minterCount, buyerCount; // Test how adding an Expiration field to an offer affects permissions // for cancelling offers. { std::uint32_t const expiration = lastClose(env) + 25; - uint256 const offerMinterToIssuer = - keylet::nftoffer(minter, env.seq(minter)).key; + uint256 const offerMinterToIssuer = keylet::nftoffer(minter, env.seq(minter)).key; env(token::createOffer(minter, nftokenID0, drops(1)), token::destination(issuer), token::expiration(expiration), txflags(tfSellNFToken)); - uint256 const offerMinterToAnyone = - keylet::nftoffer(minter, env.seq(minter)).key; + uint256 const offerMinterToAnyone = keylet::nftoffer(minter, env.seq(minter)).key; env(token::createOffer(minter, nftokenID0, drops(1)), token::expiration(expiration), txflags(tfSellNFToken)); - uint256 const offerIssuerToMinter = - keylet::nftoffer(issuer, env.seq(issuer)).key; - env(token::createOffer(issuer, nftokenID0, drops(1)), - token::owner(minter), - token::expiration(expiration)); + uint256 const offerIssuerToMinter = keylet::nftoffer(issuer, env.seq(issuer)).key; + env(token::createOffer(issuer, nftokenID0, drops(1)), token::owner(minter), token::expiration(expiration)); - uint256 const offerBuyerToMinter = - keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftokenID0, drops(1)), - token::owner(minter), - token::expiration(expiration)); + uint256 const offerBuyerToMinter = keylet::nftoffer(buyer, env.seq(buyer)).key; + env(token::createOffer(buyer, nftokenID0, drops(1)), token::owner(minter), token::expiration(expiration)); env.close(); - BEAST_EXPECT(ownerCount(env, issuer) == 1); - BEAST_EXPECT(ownerCount(env, minter) == 3); - BEAST_EXPECT(ownerCount(env, buyer) == 1); + issuerCount = 1; + minterCount = 3; + buyerCount = 1; + BEAST_EXPECT(ownerCount(env, issuer) == issuerCount); + BEAST_EXPECT(ownerCount(env, minter) == minterCount); + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); // Test who gets to cancel the offers. Anyone outside of the // offer-owner/destination pair should not be able to cancel @@ -3166,38 +2849,40 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // // Note that these are tec responses, so these transactions will // not be retried by the ledger. - env(token::cancelOffer(issuer, {offerMinterToAnyone}), - ter(tecNO_PERMISSION)); - env(token::cancelOffer(buyer, {offerIssuerToMinter}), - ter(tecNO_PERMISSION)); + env(token::cancelOffer(issuer, {offerMinterToAnyone}), ter(tecNO_PERMISSION)); + env(token::cancelOffer(buyer, {offerIssuerToMinter}), ter(tecNO_PERMISSION)); env.close(); BEAST_EXPECT(lastClose(env) < expiration); - BEAST_EXPECT(ownerCount(env, issuer) == 1); - BEAST_EXPECT(ownerCount(env, minter) == 3); - BEAST_EXPECT(ownerCount(env, buyer) == 1); + BEAST_EXPECT(ownerCount(env, issuer) == issuerCount); + BEAST_EXPECT(ownerCount(env, minter) == minterCount); + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); // The offer creator can cancel their own unexpired offer. env(token::cancelOffer(minter, {offerMinterToAnyone})); + minterCount--; // The destination of a sell offer can cancel the NFT owner's // unexpired offer. env(token::cancelOffer(issuer, {offerMinterToIssuer})); + minterCount--; // Close enough ledgers to get past the expiration. while (lastClose(env) < expiration) env.close(); - BEAST_EXPECT(ownerCount(env, issuer) == 1); - BEAST_EXPECT(ownerCount(env, minter) == 1); - BEAST_EXPECT(ownerCount(env, buyer) == 1); + BEAST_EXPECT(ownerCount(env, issuer) == issuerCount); + BEAST_EXPECT(ownerCount(env, minter) == minterCount); + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); // Anyone can cancel expired offers. env(token::cancelOffer(issuer, {offerBuyerToMinter})); + buyerCount--; env(token::cancelOffer(buyer, {offerIssuerToMinter})); + issuerCount--; env.close(); - BEAST_EXPECT(ownerCount(env, issuer) == 0); - BEAST_EXPECT(ownerCount(env, minter) == 1); - BEAST_EXPECT(ownerCount(env, buyer) == 0); + BEAST_EXPECT(ownerCount(env, issuer) == issuerCount); + BEAST_EXPECT(ownerCount(env, minter) == minterCount); + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); } // Show that: // 1. An unexpired sell offer with an expiration can be accepted. @@ -3206,64 +2891,86 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite { std::uint32_t const expiration = lastClose(env) + 25; - uint256 const offer0 = - keylet::nftoffer(minter, env.seq(minter)).key; + uint256 const offer0 = keylet::nftoffer(minter, env.seq(minter)).key; env(token::createOffer(minter, nftokenID0, drops(1)), token::expiration(expiration), txflags(tfSellNFToken)); + minterCount++; - uint256 const offer1 = - keylet::nftoffer(minter, env.seq(minter)).key; + uint256 const offer1 = keylet::nftoffer(minter, env.seq(minter)).key; env(token::createOffer(minter, nftokenID1, drops(1)), token::expiration(expiration), txflags(tfSellNFToken)); + minterCount++; env.close(); BEAST_EXPECT(lastClose(env) < expiration); - BEAST_EXPECT(ownerCount(env, issuer) == 0); - BEAST_EXPECT(ownerCount(env, minter) == 3); - BEAST_EXPECT(ownerCount(env, buyer) == 0); + BEAST_EXPECT(ownerCount(env, issuer) == issuerCount); + BEAST_EXPECT(ownerCount(env, minter) == minterCount); + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); // Anyone can accept an unexpired sell offer. env(token::acceptSellOffer(buyer, offer0)); + minterCount--; + buyerCount++; // Close enough ledgers to get past the expiration. while (lastClose(env) < expiration) env.close(); - BEAST_EXPECT(ownerCount(env, issuer) == 0); - BEAST_EXPECT(ownerCount(env, minter) == 2); - BEAST_EXPECT(ownerCount(env, buyer) == 1); + BEAST_EXPECT(ownerCount(env, issuer) == issuerCount); + BEAST_EXPECT(ownerCount(env, minter) == minterCount); + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); // No one can accept an expired sell offer. env(token::acceptSellOffer(buyer, offer1), ter(tecEXPIRED)); - env(token::acceptSellOffer(issuer, offer1), ter(tecEXPIRED)); + + // With fixExpiredNFTokenOfferRemoval amendment, the first accept + // attempt deletes the expired offer. Without the amendment, + // the offer remains and we can try to accept it again. + if (features[fixExpiredNFTokenOfferRemoval]) + { + // After amendment: offer was deleted by first accept attempt + minterCount--; + env(token::acceptSellOffer(issuer, offer1), ter(tecOBJECT_NOT_FOUND)); + } + else + { + // Before amendment: offer still exists, second accept also + // fails + env(token::acceptSellOffer(issuer, offer1), ter(tecEXPIRED)); + } env.close(); - // The expired sell offer is still in the ledger. - BEAST_EXPECT(ownerCount(env, issuer) == 0); - BEAST_EXPECT(ownerCount(env, minter) == 2); - BEAST_EXPECT(ownerCount(env, buyer) == 1); + // Check if the expired sell offer behavior matches amendment status + BEAST_EXPECT(ownerCount(env, issuer) == issuerCount); + BEAST_EXPECT(ownerCount(env, minter) == minterCount); + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); - // Anyone can cancel the expired sell offer. - env(token::cancelOffer(issuer, {offer1})); - env.close(); - BEAST_EXPECT(ownerCount(env, issuer) == 0); - BEAST_EXPECT(ownerCount(env, minter) == 1); - BEAST_EXPECT(ownerCount(env, buyer) == 1); + if (!features[fixExpiredNFTokenOfferRemoval]) + { + // Before amendment: expired offer still exists and needs to be + // cancelled + env(token::cancelOffer(issuer, {offer1})); + env.close(); + minterCount--; + } + // Ensure that owner counts are correct with and without the + // amendment + BEAST_EXPECT(ownerCount(env, issuer) == 0 && issuerCount == 0); + BEAST_EXPECT(ownerCount(env, minter) == 1 && minterCount == 1); + BEAST_EXPECT(ownerCount(env, buyer) == 1 && buyerCount == 1); // Transfer nftokenID0 back to minter so we start the next test in // a simple place. - uint256 const offerSellBack = - keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftokenID0, XRP(0)), - txflags(tfSellNFToken), - token::destination(minter)); + uint256 const offerSellBack = keylet::nftoffer(buyer, env.seq(buyer)).key; + env(token::createOffer(buyer, nftokenID0, XRP(0)), txflags(tfSellNFToken), token::destination(minter)); env.close(); env(token::acceptSellOffer(minter, offerSellBack)); + buyerCount--; env.close(); - BEAST_EXPECT(ownerCount(env, issuer) == 0); - BEAST_EXPECT(ownerCount(env, minter) == 1); - BEAST_EXPECT(ownerCount(env, buyer) == 0); + BEAST_EXPECT(ownerCount(env, issuer) == issuerCount); + BEAST_EXPECT(ownerCount(env, minter) == minterCount); + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); } // Show that: // 1. An unexpired buy offer with an expiration can be accepted. @@ -3273,19 +2980,17 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite std::uint32_t const expiration = lastClose(env) + 25; uint256 const offer0 = keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftokenID0, drops(1)), - token::owner(minter), - token::expiration(expiration)); + env(token::createOffer(buyer, nftokenID0, drops(1)), token::owner(minter), token::expiration(expiration)); + buyerCount++; uint256 const offer1 = keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftokenID1, drops(1)), - token::owner(minter), - token::expiration(expiration)); + env(token::createOffer(buyer, nftokenID1, drops(1)), token::owner(minter), token::expiration(expiration)); + buyerCount++; env.close(); BEAST_EXPECT(lastClose(env) < expiration); - BEAST_EXPECT(ownerCount(env, issuer) == 0); - BEAST_EXPECT(ownerCount(env, minter) == 1); - BEAST_EXPECT(ownerCount(env, buyer) == 2); + BEAST_EXPECT(ownerCount(env, issuer) == issuerCount); + BEAST_EXPECT(ownerCount(env, minter) == minterCount); + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); // An unexpired buy offer can be accepted. env(token::acceptBuyOffer(minter, offer0)); @@ -3294,40 +2999,60 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite while (lastClose(env) < expiration) env.close(); - BEAST_EXPECT(ownerCount(env, issuer) == 0); - BEAST_EXPECT(ownerCount(env, minter) == 1); - BEAST_EXPECT(ownerCount(env, buyer) == 2); + BEAST_EXPECT(ownerCount(env, issuer) == issuerCount); + BEAST_EXPECT(ownerCount(env, minter) == minterCount); + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); // An expired buy offer cannot be accepted. env(token::acceptBuyOffer(minter, offer1), ter(tecEXPIRED)); - env(token::acceptBuyOffer(issuer, offer1), ter(tecEXPIRED)); + + // With fixExpiredNFTokenOfferRemoval amendment, the first accept + // attempt deletes the expired offer. Without the amendment, + // the offer remains and we can try to accept it again. + if (features[fixExpiredNFTokenOfferRemoval]) + { + // After amendment: offer was deleted by first accept attempt + buyerCount--; + env(token::acceptBuyOffer(issuer, offer1), ter(tecOBJECT_NOT_FOUND)); + } + else + { + // Before amendment: offer still exists, second accept also + // fails + env(token::acceptBuyOffer(issuer, offer1), ter(tecEXPIRED)); + } env.close(); - // The expired buy offer is still in the ledger. - BEAST_EXPECT(ownerCount(env, issuer) == 0); - BEAST_EXPECT(ownerCount(env, minter) == 1); - BEAST_EXPECT(ownerCount(env, buyer) == 2); + // Check if the expired buy offer behavior matches amendment status + BEAST_EXPECT(ownerCount(env, issuer) == issuerCount); + BEAST_EXPECT(ownerCount(env, minter) == minterCount); + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); - // Anyone can cancel the expired buy offer. - env(token::cancelOffer(issuer, {offer1})); - env.close(); - BEAST_EXPECT(ownerCount(env, issuer) == 0); - BEAST_EXPECT(ownerCount(env, minter) == 1); - BEAST_EXPECT(ownerCount(env, buyer) == 1); + if (!features[fixExpiredNFTokenOfferRemoval]) + { + // Before amendment: expired offer still exists and can be + // cancelled + env(token::cancelOffer(issuer, {offer1})); + env.close(); + buyerCount--; + } + // Ensure that owner counts are the same with and without the + // amendment + BEAST_EXPECT(ownerCount(env, issuer) == 0 && issuerCount == 0); + BEAST_EXPECT(ownerCount(env, minter) == 1 && minterCount == 1); + BEAST_EXPECT(ownerCount(env, buyer) == 1 && buyerCount == 1); // Transfer nftokenID0 back to minter so we start the next test in // a simple place. - uint256 const offerSellBack = - keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftokenID0, XRP(0)), - txflags(tfSellNFToken), - token::destination(minter)); + uint256 const offerSellBack = keylet::nftoffer(buyer, env.seq(buyer)).key; + env(token::createOffer(buyer, nftokenID0, XRP(0)), txflags(tfSellNFToken), token::destination(minter)); env.close(); env(token::acceptSellOffer(minter, offerSellBack)); env.close(); - BEAST_EXPECT(ownerCount(env, issuer) == 0); - BEAST_EXPECT(ownerCount(env, minter) == 1); - BEAST_EXPECT(ownerCount(env, buyer) == 0); + buyerCount--; + BEAST_EXPECT(ownerCount(env, issuer) == issuerCount); + BEAST_EXPECT(ownerCount(env, minter) == minterCount); + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); } // Show that in brokered mode: // 1. An unexpired sell offer with an expiration can be accepted. @@ -3336,75 +3061,90 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite { std::uint32_t const expiration = lastClose(env) + 25; - uint256 const sellOffer0 = - keylet::nftoffer(minter, env.seq(minter)).key; + uint256 const sellOffer0 = keylet::nftoffer(minter, env.seq(minter)).key; env(token::createOffer(minter, nftokenID0, drops(1)), token::expiration(expiration), txflags(tfSellNFToken)); + minterCount++; - uint256 const sellOffer1 = - keylet::nftoffer(minter, env.seq(minter)).key; + uint256 const sellOffer1 = keylet::nftoffer(minter, env.seq(minter)).key; env(token::createOffer(minter, nftokenID1, drops(1)), token::expiration(expiration), txflags(tfSellNFToken)); + minterCount++; - uint256 const buyOffer0 = - keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftokenID0, drops(1)), - token::owner(minter)); + uint256 const buyOffer0 = keylet::nftoffer(buyer, env.seq(buyer)).key; + env(token::createOffer(buyer, nftokenID0, drops(1)), token::owner(minter)); + buyerCount++; - uint256 const buyOffer1 = - keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftokenID1, drops(1)), - token::owner(minter)); + uint256 const buyOffer1 = keylet::nftoffer(buyer, env.seq(buyer)).key; + env(token::createOffer(buyer, nftokenID1, drops(1)), token::owner(minter)); + buyerCount++; env.close(); BEAST_EXPECT(lastClose(env) < expiration); - BEAST_EXPECT(ownerCount(env, issuer) == 0); - BEAST_EXPECT(ownerCount(env, minter) == 3); - BEAST_EXPECT(ownerCount(env, buyer) == 2); + BEAST_EXPECT(ownerCount(env, issuer) == issuerCount); + BEAST_EXPECT(ownerCount(env, minter) == minterCount); + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); // An unexpired offer can be brokered. env(token::brokerOffers(issuer, buyOffer0, sellOffer0)); + minterCount--; // Close enough ledgers to get past the expiration. while (lastClose(env) < expiration) env.close(); - BEAST_EXPECT(ownerCount(env, issuer) == 0); - BEAST_EXPECT(ownerCount(env, minter) == 2); - BEAST_EXPECT(ownerCount(env, buyer) == 2); + BEAST_EXPECT(ownerCount(env, issuer) == issuerCount); + BEAST_EXPECT(ownerCount(env, minter) == minterCount); + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); // If the sell offer is expired it cannot be brokered. - env(token::brokerOffers(issuer, buyOffer1, sellOffer1), - ter(tecEXPIRED)); + env(token::brokerOffers(issuer, buyOffer1, sellOffer1), ter(tecEXPIRED)); env.close(); - // The expired sell offer is still in the ledger. - BEAST_EXPECT(ownerCount(env, issuer) == 0); - BEAST_EXPECT(ownerCount(env, minter) == 2); - BEAST_EXPECT(ownerCount(env, buyer) == 2); + if (features[fixExpiredNFTokenOfferRemoval]) + { + // With amendment: expired offers are deleted + minterCount--; + } - // Anyone can cancel the expired sell offer. - env(token::cancelOffer(buyer, {buyOffer1, sellOffer1})); + BEAST_EXPECT(ownerCount(env, issuer) == issuerCount); + BEAST_EXPECT(ownerCount(env, minter) == minterCount); + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); + + if (features[fixExpiredNFTokenOfferRemoval]) + { + // The buy offer was deleted, so no need to cancel it + // The sell offer still exists, so we can cancel it + env(token::cancelOffer(buyer, {buyOffer1})); + buyerCount--; + } + else + { + // Anyone can cancel the expired offers + env(token::cancelOffer(buyer, {buyOffer1, sellOffer1})); + minterCount--; + buyerCount--; + } env.close(); - BEAST_EXPECT(ownerCount(env, issuer) == 0); - BEAST_EXPECT(ownerCount(env, minter) == 1); - BEAST_EXPECT(ownerCount(env, buyer) == 1); + // Ensure that owner counts are the same with and without the + // amendment + BEAST_EXPECT(ownerCount(env, issuer) == 0 && issuerCount == 0); + BEAST_EXPECT(ownerCount(env, minter) == 1 && minterCount == 1); + BEAST_EXPECT(ownerCount(env, buyer) == 1 && buyerCount == 1); // Transfer nftokenID0 back to minter so we start the next test in // a simple place. - uint256 const offerSellBack = - keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftokenID0, XRP(0)), - txflags(tfSellNFToken), - token::destination(minter)); + uint256 const offerSellBack = keylet::nftoffer(buyer, env.seq(buyer)).key; + env(token::createOffer(buyer, nftokenID0, XRP(0)), txflags(tfSellNFToken), token::destination(minter)); env.close(); env(token::acceptSellOffer(minter, offerSellBack)); env.close(); - BEAST_EXPECT(ownerCount(env, issuer) == 0); - BEAST_EXPECT(ownerCount(env, minter) == 1); - BEAST_EXPECT(ownerCount(env, buyer) == 0); + buyerCount--; + BEAST_EXPECT(ownerCount(env, issuer) == issuerCount); + BEAST_EXPECT(ownerCount(env, minter) == minterCount); + BEAST_EXPECT(ownerCount(env, buyer) == buyerCount); } // Show that in brokered mode: // 1. An unexpired buy offer with an expiration can be accepted. @@ -3413,27 +3153,17 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite { std::uint32_t const expiration = lastClose(env) + 25; - uint256 const sellOffer0 = - keylet::nftoffer(minter, env.seq(minter)).key; - env(token::createOffer(minter, nftokenID0, drops(1)), - txflags(tfSellNFToken)); + uint256 const sellOffer0 = keylet::nftoffer(minter, env.seq(minter)).key; + env(token::createOffer(minter, nftokenID0, drops(1)), txflags(tfSellNFToken)); - uint256 const sellOffer1 = - keylet::nftoffer(minter, env.seq(minter)).key; - env(token::createOffer(minter, nftokenID1, drops(1)), - txflags(tfSellNFToken)); + uint256 const sellOffer1 = keylet::nftoffer(minter, env.seq(minter)).key; + env(token::createOffer(minter, nftokenID1, drops(1)), txflags(tfSellNFToken)); - uint256 const buyOffer0 = - keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftokenID0, drops(1)), - token::expiration(expiration), - token::owner(minter)); + uint256 const buyOffer0 = keylet::nftoffer(buyer, env.seq(buyer)).key; + env(token::createOffer(buyer, nftokenID0, drops(1)), token::expiration(expiration), token::owner(minter)); - uint256 const buyOffer1 = - keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftokenID1, drops(1)), - token::expiration(expiration), - token::owner(minter)); + uint256 const buyOffer1 = keylet::nftoffer(buyer, env.seq(buyer)).key; + env(token::createOffer(buyer, nftokenID1, drops(1)), token::expiration(expiration), token::owner(minter)); env.close(); BEAST_EXPECT(lastClose(env) < expiration); @@ -3452,18 +3182,28 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite BEAST_EXPECT(ownerCount(env, minter) == 2); BEAST_EXPECT(ownerCount(env, buyer) == 2); - // If the buy offer is expired it cannot be brokered. - env(token::brokerOffers(issuer, buyOffer1, sellOffer1), - ter(tecEXPIRED)); + env(token::brokerOffers(issuer, buyOffer1, sellOffer1), ter(tecEXPIRED)); env.close(); - // The expired buy offer is still in the ledger. BEAST_EXPECT(ownerCount(env, issuer) == 0); - BEAST_EXPECT(ownerCount(env, minter) == 2); - BEAST_EXPECT(ownerCount(env, buyer) == 2); - - // Anyone can cancel the expired buy offer. - env(token::cancelOffer(minter, {buyOffer1, sellOffer1})); + if (features[fixExpiredNFTokenOfferRemoval]) + { + // After amendment: expired offers were deleted during broker + // attempt + BEAST_EXPECT(ownerCount(env, minter) == 2); + BEAST_EXPECT(ownerCount(env, buyer) == 1); + // The buy offer was deleted, so no need to cancel it + // The sell offer still exists, so we can cancel it + env(token::cancelOffer(minter, {sellOffer1})); + } + else + { + // Before amendment: expired offers still exist in ledger + BEAST_EXPECT(ownerCount(env, minter) == 2); + BEAST_EXPECT(ownerCount(env, buyer) == 2); + // Anyone can cancel the expired offers + env(token::cancelOffer(minter, {buyOffer1, sellOffer1})); + } env.close(); BEAST_EXPECT(ownerCount(env, issuer) == 0); BEAST_EXPECT(ownerCount(env, minter) == 1); @@ -3471,11 +3211,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // Transfer nftokenID0 back to minter so we start the next test in // a simple place. - uint256 const offerSellBack = - keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftokenID0, XRP(0)), - txflags(tfSellNFToken), - token::destination(minter)); + uint256 const offerSellBack = keylet::nftoffer(buyer, env.seq(buyer)).key; + env(token::createOffer(buyer, nftokenID0, XRP(0)), txflags(tfSellNFToken), token::destination(minter)); env.close(); env(token::acceptSellOffer(minter, offerSellBack)); env.close(); @@ -3491,29 +3228,21 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite { std::uint32_t const expiration = lastClose(env) + 25; - uint256 const sellOffer0 = - keylet::nftoffer(minter, env.seq(minter)).key; + uint256 const sellOffer0 = keylet::nftoffer(minter, env.seq(minter)).key; env(token::createOffer(minter, nftokenID0, drops(1)), token::expiration(expiration), txflags(tfSellNFToken)); - uint256 const sellOffer1 = - keylet::nftoffer(minter, env.seq(minter)).key; + uint256 const sellOffer1 = keylet::nftoffer(minter, env.seq(minter)).key; env(token::createOffer(minter, nftokenID1, drops(1)), token::expiration(expiration), txflags(tfSellNFToken)); - uint256 const buyOffer0 = - keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftokenID0, drops(1)), - token::expiration(expiration), - token::owner(minter)); + uint256 const buyOffer0 = keylet::nftoffer(buyer, env.seq(buyer)).key; + env(token::createOffer(buyer, nftokenID0, drops(1)), token::expiration(expiration), token::owner(minter)); - uint256 const buyOffer1 = - keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftokenID1, drops(1)), - token::expiration(expiration), - token::owner(minter)); + uint256 const buyOffer1 = keylet::nftoffer(buyer, env.seq(buyer)).key; + env(token::createOffer(buyer, nftokenID1, drops(1)), token::expiration(expiration), token::owner(minter)); env.close(); BEAST_EXPECT(lastClose(env) < expiration); @@ -3532,18 +3261,19 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite BEAST_EXPECT(ownerCount(env, minter) == 2); BEAST_EXPECT(ownerCount(env, buyer) == 2); - // If the offers are expired they cannot be brokered. - env(token::brokerOffers(issuer, buyOffer1, sellOffer1), - ter(tecEXPIRED)); + env(token::brokerOffers(issuer, buyOffer1, sellOffer1), ter(tecEXPIRED)); env.close(); // The expired offers are still in the ledger. BEAST_EXPECT(ownerCount(env, issuer) == 0); - BEAST_EXPECT(ownerCount(env, minter) == 2); - BEAST_EXPECT(ownerCount(env, buyer) == 2); - - // Anyone can cancel the expired offers. - env(token::cancelOffer(issuer, {buyOffer1, sellOffer1})); + if (!features[fixExpiredNFTokenOfferRemoval]) + { + // Before amendment: expired offers still exist in ledger + BEAST_EXPECT(ownerCount(env, minter) == 2); + BEAST_EXPECT(ownerCount(env, buyer) == 2); + // Anyone can cancel the expired offers + env(token::cancelOffer(issuer, {buyOffer1, sellOffer1})); + } env.close(); BEAST_EXPECT(ownerCount(env, issuer) == 0); BEAST_EXPECT(ownerCount(env, minter) == 1); @@ -3551,11 +3281,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // Transfer nftokenID0 back to minter so we start the next test in // a simple place. - uint256 const offerSellBack = - keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftokenID0, XRP(0)), - txflags(tfSellNFToken), - token::destination(minter)); + uint256 const offerSellBack = keylet::nftoffer(buyer, env.seq(buyer)).key; + env(token::createOffer(buyer, nftokenID0, XRP(0)), txflags(tfSellNFToken), token::destination(minter)); env.close(); env(token::acceptSellOffer(minter, offerSellBack)); env.close(); @@ -3585,14 +3312,12 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env(token::setMinter(alice, minter)); env.close(); - uint256 const nftokenID = - token::getNextID(env, alice, 0, tfTransferable); + uint256 const nftokenID = token::getNextID(env, alice, 0, tfTransferable); env(token::mint(alice, 0), txflags(tfTransferable)); env.close(); // Anyone can cancel an expired offer. - uint256 const expiredOfferIndex = - keylet::nftoffer(alice, env.seq(alice)).key; + uint256 const expiredOfferIndex = keylet::nftoffer(alice, env.seq(alice)).key; env(token::createOffer(alice, nftokenID, XRP(1000)), txflags(tfSellNFToken), @@ -3601,8 +3326,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // The offer has not expired yet, so becky can't cancel it now. BEAST_EXPECT(ownerCount(env, alice) == 2); - env(token::cancelOffer(becky, {expiredOfferIndex}), - ter(tecNO_PERMISSION)); + env(token::cancelOffer(becky, {expiredOfferIndex}), ter(tecNO_PERMISSION)); env.close(); // Close a couple of ledgers and advance the time. Then becky @@ -3615,18 +3339,14 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // Create a couple of offers with a destination. Those offers // should be cancellable by the creator and the destination. - uint256 const dest1OfferIndex = - keylet::nftoffer(alice, env.seq(alice)).key; + uint256 const dest1OfferIndex = keylet::nftoffer(alice, env.seq(alice)).key; - env(token::createOffer(alice, nftokenID, XRP(1000)), - token::destination(becky), - txflags(tfSellNFToken)); + env(token::createOffer(alice, nftokenID, XRP(1000)), token::destination(becky), txflags(tfSellNFToken)); env.close(); BEAST_EXPECT(ownerCount(env, alice) == 2); // Minter can't cancel that offer, but becky (the destination) can. - env(token::cancelOffer(minter, {dest1OfferIndex}), - ter(tecNO_PERMISSION)); + env(token::cancelOffer(minter, {dest1OfferIndex}), ter(tecNO_PERMISSION)); env.close(); BEAST_EXPECT(ownerCount(env, alice) == 2); @@ -3635,12 +3355,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite BEAST_EXPECT(ownerCount(env, alice) == 1); // alice can cancel her own offer, even if becky is the destination. - uint256 const dest2OfferIndex = - keylet::nftoffer(alice, env.seq(alice)).key; + uint256 const dest2OfferIndex = keylet::nftoffer(alice, env.seq(alice)).key; - env(token::createOffer(alice, nftokenID, XRP(1000)), - token::destination(becky), - txflags(tfSellNFToken)); + env(token::createOffer(alice, nftokenID, XRP(1000)), token::destination(becky), txflags(tfSellNFToken)); env.close(); BEAST_EXPECT(ownerCount(env, alice) == 2); @@ -3651,26 +3368,19 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // The issuer has no special permissions regarding offer cancellation. // Minter creates a token with alice as issuer. alice cannot cancel // minter's offer. - uint256 const mintersNFTokenID = - token::getNextID(env, alice, 0, tfTransferable); - env(token::mint(minter, 0), - token::issuer(alice), - txflags(tfTransferable)); + uint256 const mintersNFTokenID = token::getNextID(env, alice, 0, tfTransferable); + env(token::mint(minter, 0), token::issuer(alice), txflags(tfTransferable)); env.close(); - uint256 const minterOfferIndex = - keylet::nftoffer(minter, env.seq(minter)).key; + uint256 const minterOfferIndex = keylet::nftoffer(minter, env.seq(minter)).key; - env(token::createOffer(minter, mintersNFTokenID, XRP(1000)), - txflags(tfSellNFToken)); + env(token::createOffer(minter, mintersNFTokenID, XRP(1000)), txflags(tfSellNFToken)); env.close(); BEAST_EXPECT(ownerCount(env, minter) == 2); // Nobody other than minter should be able to cancel minter's offer. - env(token::cancelOffer(alice, {minterOfferIndex}), - ter(tecNO_PERMISSION)); - env(token::cancelOffer(becky, {minterOfferIndex}), - ter(tecNO_PERMISSION)); + env(token::cancelOffer(alice, {minterOfferIndex}), ter(tecNO_PERMISSION)); + env(token::cancelOffer(becky, {minterOfferIndex}), ter(tecNO_PERMISSION)); env.close(); BEAST_EXPECT(ownerCount(env, minter) == 2); @@ -3712,20 +3422,15 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite for (uint32_t i = 0; i < maxTokenOfferCancelCount + 1; ++i) { Account const nftAcct(std::string("nftAcct") + std::to_string(i)); - Account const offerAcct( - std::string("offerAcct") + std::to_string(i)); + Account const offerAcct(std::string("offerAcct") + std::to_string(i)); env.fund(XRP(1000), nftAcct, offerAcct); env.close(); - uint256 const nftokenID = - token::getNextID(env, nftAcct, 0, tfTransferable); - env(token::mint(nftAcct, 0), - token::uri(uri), - txflags(tfTransferable)); + uint256 const nftokenID = token::getNextID(env, nftAcct, 0, tfTransferable); + env(token::mint(nftAcct, 0), token::uri(uri), txflags(tfTransferable)); env.close(); - offerIndexes.push_back( - keylet::nftoffer(offerAcct, env.seq(offerAcct)).key); + offerIndexes.push_back(keylet::nftoffer(offerAcct, env.seq(offerAcct)).key); env(token::createOffer(offerAcct, nftokenID, drops(1)), token::owner(nftAcct), token::expiration(lastClose(env) + 5)); @@ -3756,16 +3461,12 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // But alice adds a sell offer to the list... { - uint256 const nftokenID = - token::getNextID(env, alice, 0, tfTransferable); - env(token::mint(alice, 0), - token::uri(uri), - txflags(tfTransferable)); + uint256 const nftokenID = token::getNextID(env, alice, 0, tfTransferable); + env(token::mint(alice, 0), token::uri(uri), txflags(tfTransferable)); env.close(); offerIndexes.push_back(keylet::nftoffer(alice, env.seq(alice)).key); - env(token::createOffer(alice, nftokenID, drops(1)), - txflags(tfSellNFToken)); + env(token::createOffer(alice, nftokenID, drops(1)), txflags(tfSellNFToken)); env.close(); // alice's owner count should now to 2 for the nft and the offer. @@ -3837,20 +3538,13 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // Lambda to check owner count of all accounts is one. auto checkOwnerCountIsOne = - [this, &env]( - std::initializer_list> - accounts, - int line) { + [this, &env](std::initializer_list> accounts, int line) { for (Account const& acct : accounts) { - if (std::uint32_t ownerCount = - test::jtx::ownerCount(env, acct); - ownerCount != 1) + if (std::uint32_t ownerCount = test::jtx::ownerCount(env, acct); ownerCount != 1) { std::stringstream ss; - ss << "Account " << acct.human() - << " expected ownerCount == 1. Got " - << ownerCount; + ss << "Account " << acct.human() << " expected ownerCount == 1. Got " << ownerCount; fail(ss.str(), __FILE__, line); } } @@ -3858,12 +3552,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // Lambda that mints an NFT and returns the nftID. auto mintNFT = [&env, &issuer, &minter](std::uint16_t xferFee = 0) { - uint256 const nftID = - token::getNextID(env, issuer, 0, tfTransferable, xferFee); - env(token::mint(minter, 0), - token::issuer(issuer), - token::xferFee(xferFee), - txflags(tfTransferable)); + uint256 const nftID = token::getNextID(env, issuer, 0, tfTransferable, xferFee); + env(token::mint(minter, 0), token::issuer(issuer), token::xferFee(xferFee), txflags(tfTransferable)); env.close(); return nftID; }; @@ -3879,18 +3569,14 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite uint256 const nftID = mintNFT(); // minter creates their offer. - uint256 const minterOfferIndex = - keylet::nftoffer(minter, env.seq(minter)).key; - env(token::createOffer(minter, nftID, XRP(0)), - txflags(tfSellNFToken)); + uint256 const minterOfferIndex = keylet::nftoffer(minter, env.seq(minter)).key; + env(token::createOffer(minter, nftID, XRP(0)), txflags(tfSellNFToken)); env.close(); // buyer creates their offer. Note: a buy offer can never // offer zero. - uint256 const buyOfferIndex = - keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftID, XRP(1)), - token::owner(minter)); + uint256 const buyOfferIndex = keylet::nftoffer(buyer, env.seq(buyer)).key; + env(token::createOffer(buyer, nftID, XRP(1)), token::owner(minter)); env.close(); auto const minterBalance = env.balance(minter); @@ -3899,8 +3585,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite auto const issuerBalance = env.balance(issuer); // Broker charges no brokerFee. - env(token::brokerOffers( - broker, buyOfferIndex, minterOfferIndex)); + env(token::brokerOffers(broker, buyOfferIndex, minterOfferIndex)); env.close(); // Note that minter's XRP balance goes up even though they @@ -3926,23 +3611,18 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite uint256 const nftID = mintNFT(); // minter creates their offer. - uint256 const minterOfferIndex = - keylet::nftoffer(minter, env.seq(minter)).key; - env(token::createOffer(minter, nftID, XRP(0)), - txflags(tfSellNFToken)); + uint256 const minterOfferIndex = keylet::nftoffer(minter, env.seq(minter)).key; + env(token::createOffer(minter, nftID, XRP(0)), txflags(tfSellNFToken)); env.close(); // buyer creates their offer. Note: a buy offer can never // offer zero. - uint256 const buyOfferIndex = - keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftID, XRP(1)), - token::owner(minter)); + uint256 const buyOfferIndex = keylet::nftoffer(buyer, env.seq(buyer)).key; + env(token::createOffer(buyer, nftID, XRP(1)), token::owner(minter)); env.close(); // Broker attempts to charge a 1.1 XRP brokerFee and fails. - env(token::brokerOffers( - broker, buyOfferIndex, minterOfferIndex), + env(token::brokerOffers(broker, buyOfferIndex, minterOfferIndex), token::brokerFee(XRP(1.1)), ter(tecINSUFFICIENT_PAYMENT)); env.close(); @@ -3953,17 +3633,14 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite auto const issuerBalance = env.balance(issuer); // Broker charges a 0.5 XRP brokerFee. - env(token::brokerOffers( - broker, buyOfferIndex, minterOfferIndex), - token::brokerFee(XRP(0.5))); + env(token::brokerOffers(broker, buyOfferIndex, minterOfferIndex), token::brokerFee(XRP(0.5))); env.close(); // Note that minter's XRP balance goes up even though they // requested XRP(0). BEAST_EXPECT(env.balance(minter) == minterBalance + XRP(0.5)); BEAST_EXPECT(env.balance(buyer) == buyerBalance - XRP(1)); - BEAST_EXPECT( - env.balance(broker) == brokerBalance + XRP(0.5) - baseFee); + BEAST_EXPECT(env.balance(broker) == brokerBalance + XRP(0.5) - baseFee); BEAST_EXPECT(env.balance(issuer) == issuerBalance); // Burn the NFT so the next test starts with a clean state. @@ -3982,18 +3659,14 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite uint256 const nftID = mintNFT(maxTransferFee); // minter creates their offer. - uint256 const minterOfferIndex = - keylet::nftoffer(minter, env.seq(minter)).key; - env(token::createOffer(minter, nftID, XRP(0)), - txflags(tfSellNFToken)); + uint256 const minterOfferIndex = keylet::nftoffer(minter, env.seq(minter)).key; + env(token::createOffer(minter, nftID, XRP(0)), txflags(tfSellNFToken)); env.close(); // buyer creates their offer. Note: a buy offer can never // offer zero. - uint256 const buyOfferIndex = - keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftID, XRP(1)), - token::owner(minter)); + uint256 const buyOfferIndex = keylet::nftoffer(buyer, env.seq(buyer)).key; + env(token::createOffer(buyer, nftID, XRP(1)), token::owner(minter)); env.close(); auto const minterBalance = env.balance(minter); @@ -4002,8 +3675,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite auto const issuerBalance = env.balance(issuer); // Broker charges no brokerFee. - env(token::brokerOffers( - broker, buyOfferIndex, minterOfferIndex)); + env(token::brokerOffers(broker, buyOfferIndex, minterOfferIndex)); env.close(); // Note that minter's XRP balance goes up even though they @@ -4029,18 +3701,14 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite uint256 const nftID = mintNFT(maxTransferFee); // minter creates their offer. - uint256 const minterOfferIndex = - keylet::nftoffer(minter, env.seq(minter)).key; - env(token::createOffer(minter, nftID, XRP(0)), - txflags(tfSellNFToken)); + uint256 const minterOfferIndex = keylet::nftoffer(minter, env.seq(minter)).key; + env(token::createOffer(minter, nftID, XRP(0)), txflags(tfSellNFToken)); env.close(); // buyer creates their offer. Note: a buy offer can never // offer zero. - uint256 const buyOfferIndex = - keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftID, XRP(1)), - token::owner(minter)); + uint256 const buyOfferIndex = keylet::nftoffer(buyer, env.seq(buyer)).key; + env(token::createOffer(buyer, nftID, XRP(1)), token::owner(minter)); env.close(); auto const minterBalance = env.balance(minter); @@ -4049,9 +3717,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite auto const issuerBalance = env.balance(issuer); // Broker charges a 0.75 XRP brokerFee. - env(token::brokerOffers( - broker, buyOfferIndex, minterOfferIndex), - token::brokerFee(XRP(0.75))); + env(token::brokerOffers(broker, buyOfferIndex, minterOfferIndex), token::brokerFee(XRP(0.75))); env.close(); // Note that, with a 50% transfer fee, issuer gets 1/2 of what's @@ -4059,8 +3725,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // remainder after both broker and minter take their cuts BEAST_EXPECT(env.balance(minter) == minterBalance + XRP(0.125)); BEAST_EXPECT(env.balance(buyer) == buyerBalance - XRP(1)); - BEAST_EXPECT( - env.balance(broker) == brokerBalance + XRP(0.75) - baseFee); + BEAST_EXPECT(env.balance(broker) == brokerBalance + XRP(0.75) - baseFee); BEAST_EXPECT(env.balance(issuer) == issuerBalance + XRP(0.125)); // Burn the NFT so the next test starts with a clean state. @@ -4072,10 +3737,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // gwXAU(amount). auto setXAUBalance = [this, &gw, &gwXAU, &env]( - std::initializer_list> - accounts, - int amount, - int line) { + std::initializer_list> accounts, int amount, int line) { for (Account const& acct : accounts) { auto const xauAmt = gwXAU(amount); @@ -4093,8 +3755,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite if (env.balance(acct, gwXAU) != xauAmt) { std::stringstream ss; - ss << "Unable to set " << acct.human() - << " account balance to gwXAU(" << amount << ")"; + ss << "Unable to set " << acct.human() << " account balance to gwXAU(" << amount << ")"; this->fail(ss.str(), __FILE__, line); } } @@ -4109,25 +3770,19 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite uint256 const nftID = mintNFT(); // minter creates their offer. - uint256 const minterOfferIndex = - keylet::nftoffer(minter, env.seq(minter)).key; - env(token::createOffer(minter, nftID, gwXAU(1000)), - txflags(tfSellNFToken)); + uint256 const minterOfferIndex = keylet::nftoffer(minter, env.seq(minter)).key; + env(token::createOffer(minter, nftID, gwXAU(1000)), txflags(tfSellNFToken)); env.close(); { // buyer creates an offer for more XAU than they currently // own. - uint256 const buyOfferIndex = - keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftID, gwXAU(1001)), - token::owner(minter)); + uint256 const buyOfferIndex = keylet::nftoffer(buyer, env.seq(buyer)).key; + env(token::createOffer(buyer, nftID, gwXAU(1001)), token::owner(minter)); env.close(); // broker attempts to broker the offers but cannot. - env(token::brokerOffers( - broker, buyOfferIndex, minterOfferIndex), - ter(tecINSUFFICIENT_FUNDS)); + env(token::brokerOffers(broker, buyOfferIndex, minterOfferIndex), ter(tecINSUFFICIENT_FUNDS)); env.close(); // Cancel buyer's bad offer so the next test starts in a @@ -4138,16 +3793,12 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite { // buyer creates an offer for less that what minter is // asking. - uint256 const buyOfferIndex = - keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftID, gwXAU(999)), - token::owner(minter)); + uint256 const buyOfferIndex = keylet::nftoffer(buyer, env.seq(buyer)).key; + env(token::createOffer(buyer, nftID, gwXAU(999)), token::owner(minter)); env.close(); // broker attempts to broker the offers but cannot. - env(token::brokerOffers( - broker, buyOfferIndex, minterOfferIndex), - ter(tecINSUFFICIENT_PAYMENT)); + env(token::brokerOffers(broker, buyOfferIndex, minterOfferIndex), ter(tecINSUFFICIENT_PAYMENT)); env.close(); // Cancel buyer's bad offer so the next test starts in a @@ -4157,22 +3808,18 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite } // buyer creates a large enough offer. - uint256 const buyOfferIndex = - keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftID, gwXAU(1000)), - token::owner(minter)); + uint256 const buyOfferIndex = keylet::nftoffer(buyer, env.seq(buyer)).key; + env(token::createOffer(buyer, nftID, gwXAU(1000)), token::owner(minter)); env.close(); // Broker attempts to charge a brokerFee but cannot. - env(token::brokerOffers( - broker, buyOfferIndex, minterOfferIndex), + env(token::brokerOffers(broker, buyOfferIndex, minterOfferIndex), token::brokerFee(gwXAU(0.1)), ter(tecINSUFFICIENT_PAYMENT)); env.close(); // broker charges no brokerFee and succeeds. - env(token::brokerOffers( - broker, buyOfferIndex, minterOfferIndex)); + env(token::brokerOffers(broker, buyOfferIndex, minterOfferIndex)); env.close(); BEAST_EXPECT(ownerCount(env, issuer) == 1); @@ -4198,24 +3845,18 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite uint256 const nftID = mintNFT(maxTransferFee); // minter creates their offer. - uint256 const minterOfferIndex = - keylet::nftoffer(minter, env.seq(minter)).key; - env(token::createOffer(minter, nftID, gwXAU(900)), - txflags(tfSellNFToken)); + uint256 const minterOfferIndex = keylet::nftoffer(minter, env.seq(minter)).key; + env(token::createOffer(minter, nftID, gwXAU(900)), txflags(tfSellNFToken)); env.close(); { // buyer creates an offer for more XAU than they currently // own. - uint256 const buyOfferIndex = - keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftID, gwXAU(1001)), - token::owner(minter)); + uint256 const buyOfferIndex = keylet::nftoffer(buyer, env.seq(buyer)).key; + env(token::createOffer(buyer, nftID, gwXAU(1001)), token::owner(minter)); env.close(); // broker attempts to broker the offers but cannot. - env(token::brokerOffers( - broker, buyOfferIndex, minterOfferIndex), - ter(tecINSUFFICIENT_FUNDS)); + env(token::brokerOffers(broker, buyOfferIndex, minterOfferIndex), ter(tecINSUFFICIENT_FUNDS)); env.close(); // Cancel buyer's bad offer so the next test starts in a @@ -4226,16 +3867,12 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite { // buyer creates an offer for less that what minter is // asking. - uint256 const buyOfferIndex = - keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftID, gwXAU(899)), - token::owner(minter)); + uint256 const buyOfferIndex = keylet::nftoffer(buyer, env.seq(buyer)).key; + env(token::createOffer(buyer, nftID, gwXAU(899)), token::owner(minter)); env.close(); // broker attempts to broker the offers but cannot. - env(token::brokerOffers( - broker, buyOfferIndex, minterOfferIndex), - ter(tecINSUFFICIENT_PAYMENT)); + env(token::brokerOffers(broker, buyOfferIndex, minterOfferIndex), ter(tecINSUFFICIENT_PAYMENT)); env.close(); // Cancel buyer's bad offer so the next test starts in a @@ -4244,25 +3881,20 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env.close(); } // buyer creates a large enough offer. - uint256 const buyOfferIndex = - keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftID, gwXAU(1000)), - token::owner(minter)); + uint256 const buyOfferIndex = keylet::nftoffer(buyer, env.seq(buyer)).key; + env(token::createOffer(buyer, nftID, gwXAU(1000)), token::owner(minter)); env.close(); // Broker attempts to charge a brokerFee larger than the // difference between the two offers but cannot. - env(token::brokerOffers( - broker, buyOfferIndex, minterOfferIndex), + env(token::brokerOffers(broker, buyOfferIndex, minterOfferIndex), token::brokerFee(gwXAU(101)), ter(tecINSUFFICIENT_PAYMENT)); env.close(); // broker charges the full difference between the two offers and // succeeds. - env(token::brokerOffers( - broker, buyOfferIndex, minterOfferIndex), - token::brokerFee(gwXAU(100))); + env(token::brokerOffers(broker, buyOfferIndex, minterOfferIndex), token::brokerFee(gwXAU(100))); env.close(); BEAST_EXPECT(ownerCount(env, issuer) == 1); @@ -4288,25 +3920,19 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite uint256 const nftID = mintNFT(maxTransferFee / 2); // 25% // minter creates their offer. - uint256 const minterOfferIndex = - keylet::nftoffer(minter, env.seq(minter)).key; - env(token::createOffer(minter, nftID, gwXAU(900)), - txflags(tfSellNFToken)); + uint256 const minterOfferIndex = keylet::nftoffer(minter, env.seq(minter)).key; + env(token::createOffer(minter, nftID, gwXAU(900)), txflags(tfSellNFToken)); env.close(); // buyer creates a large enough offer. - uint256 const buyOfferIndex = - keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftID, gwXAU(1000)), - token::owner(minter)); + uint256 const buyOfferIndex = keylet::nftoffer(buyer, env.seq(buyer)).key; + env(token::createOffer(buyer, nftID, gwXAU(1000)), token::owner(minter)); env.close(); // broker charges half difference between the two offers and // succeeds. 25% of the remaining difference goes to issuer. // The rest goes to minter. - env(token::brokerOffers( - broker, buyOfferIndex, minterOfferIndex), - token::brokerFee(gwXAU(50))); + env(token::brokerOffers(broker, buyOfferIndex, minterOfferIndex), token::brokerFee(gwXAU(50))); env.close(); BEAST_EXPECT(ownerCount(env, issuer) == 1); @@ -4330,22 +3956,16 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite uint256 const nftID = mintNFT(maxTransferFee / 2); // 25% // minter creates their offer. - uint256 const minterOfferIndex = - keylet::nftoffer(minter, env.seq(minter)).key; - env(token::createOffer(minter, nftID, gwXAU(900)), - txflags(tfSellNFToken)); + uint256 const minterOfferIndex = keylet::nftoffer(minter, env.seq(minter)).key; + env(token::createOffer(minter, nftID, gwXAU(900)), txflags(tfSellNFToken)); env.close(); // buyer creates a large enough offer. - uint256 const buyOfferIndex = - keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftID, gwXAU(1000)), - token::owner(minter)); + uint256 const buyOfferIndex = keylet::nftoffer(buyer, env.seq(buyer)).key; + env(token::createOffer(buyer, nftID, gwXAU(1000)), token::owner(minter)); env.close(); - env(token::brokerOffers( - broker, buyOfferIndex, minterOfferIndex), - token::brokerFee(gwXAU(50))); + env(token::brokerOffers(broker, buyOfferIndex, minterOfferIndex), token::brokerFee(gwXAU(50))); env.close(); BEAST_EXPECT(ownerCount(env, issuer) == 1); BEAST_EXPECT(ownerCount(env, minter) == 1); @@ -4390,11 +4010,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite BEAST_EXPECT(nftCount(env, buyer2) == 0); // Both buyer1 and buyer2 create buy offers for nftId. - uint256 const buyer1OfferIndex = - keylet::nftoffer(buyer1, env.seq(buyer1)).key; + uint256 const buyer1OfferIndex = keylet::nftoffer(buyer1, env.seq(buyer1)).key; env(token::createOffer(buyer1, nftId, XRP(100)), token::owner(issuer)); - uint256 const buyer2OfferIndex = - keylet::nftoffer(buyer2, env.seq(buyer2)).key; + uint256 const buyer2OfferIndex = keylet::nftoffer(buyer2, env.seq(buyer2)).key; env(token::createOffer(buyer2, nftId, XRP(100)), token::owner(issuer)); env.close(); @@ -4404,11 +4022,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // returned, so we skip the marker stuff. Json::Value params; params[jss::nft_id] = to_string(nftId); - Json::Value buyOffers = - env.rpc("json", "nft_buy_offers", to_string(params)); + Json::Value buyOffers = env.rpc("json", "nft_buy_offers", to_string(params)); - if (buyOffers.isMember(jss::result) && - buyOffers[jss::result].isMember(jss::offers)) + if (buyOffers.isMember(jss::result) && buyOffers[jss::result].isMember(jss::offers)) return buyOffers[jss::result][jss::offers].size(); return 0; @@ -4477,9 +4093,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // NFTokenMint BEAST_EXPECT(ownerCount(env, issuer) == 10); uint256 const nftId{token::getNextID(env, issuer, 0u, tfTransferable)}; - env(token::mint(issuer, 0u), - txflags(tfTransferable), - ticket::use(issuerTicketSeq++)); + env(token::mint(issuer, 0u), txflags(tfTransferable), ticket::use(issuerTicketSeq++)); env.close(); BEAST_EXPECT(ownerCount(env, issuer) == 10); BEAST_EXPECT(ticketCount(env, issuer) == 9); @@ -4487,32 +4101,26 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // NFTokenCreateOffer BEAST_EXPECT(ownerCount(env, buyer) == 10); uint256 const offerIndex0 = keylet::nftoffer(buyer, buyerTicketSeq).key; - env(token::createOffer(buyer, nftId, XRP(1)), - token::owner(issuer), - ticket::use(buyerTicketSeq++)); + env(token::createOffer(buyer, nftId, XRP(1)), token::owner(issuer), ticket::use(buyerTicketSeq++)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 10); BEAST_EXPECT(ticketCount(env, buyer) == 9); // NFTokenCancelOffer - env(token::cancelOffer(buyer, {offerIndex0}), - ticket::use(buyerTicketSeq++)); + env(token::cancelOffer(buyer, {offerIndex0}), ticket::use(buyerTicketSeq++)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 8); BEAST_EXPECT(ticketCount(env, buyer) == 8); // NFTokenCreateOffer. buyer tries again. uint256 const offerIndex1 = keylet::nftoffer(buyer, buyerTicketSeq).key; - env(token::createOffer(buyer, nftId, XRP(2)), - token::owner(issuer), - ticket::use(buyerTicketSeq++)); + env(token::createOffer(buyer, nftId, XRP(2)), token::owner(issuer), ticket::use(buyerTicketSeq++)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 8); BEAST_EXPECT(ticketCount(env, buyer) == 7); // NFTokenAcceptOffer. issuer accepts buyer's offer. - env(token::acceptBuyOffer(issuer, offerIndex1), - ticket::use(issuerTicketSeq++)); + env(token::acceptBuyOffer(issuer, offerIndex1), ticket::use(issuerTicketSeq++)); env.close(); BEAST_EXPECT(ownerCount(env, issuer) == 8); BEAST_EXPECT(ownerCount(env, buyer) == 8); @@ -4561,9 +4169,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env.close(); uint256 const nftId{token::getNextID(env, issuer, 0u, tfTransferable)}; - env(token::mint(minter, 0u), - token::issuer(issuer), - txflags(tfTransferable)); + env(token::mint(minter, 0u), token::issuer(issuer), txflags(tfTransferable)); env.close(); // At the moment issuer and minter cannot delete themselves. @@ -4582,8 +4188,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env(token::createOffer(becky, nftId, XRP(2)), token::owner(minter)); env.close(); - uint256 const carlaOfferIndex = - keylet::nftoffer(carla, env.seq(carla)).key; + uint256 const carlaOfferIndex = keylet::nftoffer(carla, env.seq(carla)).key; env(token::createOffer(carla, nftId, XRP(3)), token::owner(minter)); env.close(); @@ -4652,11 +4257,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env.close(); // A lambda that validates nft_XXX_offers query responses. - auto checkOffers = [this, &env, &nftID]( - char const* request, - int expectCount, - int expectMarkerCount, - int line) { + auto checkOffers = [this, &env, &nftID](char const* request, int expectCount, int expectMarkerCount, int line) { int markerCount = 0; Json::Value allOffers(Json::arrayValue); std::string marker; @@ -4676,21 +4277,12 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // If there are no offers for the NFT we get an error if (expectCount == 0) { - if (expect( - nftOffers.isMember(jss::result), - "expected \"result\"", - __FILE__, - line)) + if (expect(nftOffers.isMember(jss::result), "expected \"result\"", __FILE__, line)) { - if (expect( - nftOffers[jss::result].isMember(jss::error), - "expected \"error\"", - __FILE__, - line)) + if (expect(nftOffers[jss::result].isMember(jss::error), "expected \"error\"", __FILE__, line)) { expect( - nftOffers[jss::result][jss::error].asString() == - "objectNotFound", + nftOffers[jss::result][jss::error].asString() == "objectNotFound", "expected \"objectNotFound\"", __FILE__, line); @@ -4700,11 +4292,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite } marker.clear(); - if (expect( - nftOffers.isMember(jss::result), - "expected \"result\"", - __FILE__, - line)) + if (expect(nftOffers.isMember(jss::result), "expected \"result\"", __FILE__, line)) { Json::Value& result = nftOffers[jss::result]; @@ -4714,11 +4302,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite marker = result[jss::marker].asString(); } - if (expect( - result.isMember(jss::offers), - "expected \"offers\"", - __FILE__, - line)) + if (expect(result.isMember(jss::offers), "expected \"offers\"", __FILE__, line)) { Json::Value& someOffers = result[jss::offers]; for (std::size_t i = 0; i < someOffers.size(); ++i) @@ -4728,16 +4312,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite } while (!marker.empty()); // Verify the contents of allOffers makes sense. - expect( - allOffers.size() == expectCount, - "Unexpected returned offer count", - __FILE__, - line); - expect( - markerCount == expectMarkerCount, - "Unexpected marker count", - __FILE__, - line); + expect(allOffers.size() == expectCount, "Unexpected returned offer count", __FILE__, line); + expect(markerCount == expectMarkerCount, "Unexpected marker count", __FILE__, line); std::optional globalFlags; std::set offerIndexes; std::set amounts; @@ -4747,11 +4323,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite if (!globalFlags) globalFlags = offer[jss::flags].asInt(); - expect( - *globalFlags == offer[jss::flags].asInt(), - "Inconsistent flags returned", - __FILE__, - line); + expect(*globalFlags == offer[jss::flags].asInt(), "Inconsistent flags returned", __FILE__, line); // The test conditions should produce unique indexes and // amounts for all offers. @@ -4759,16 +4331,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite amounts.insert(offer[jss::amount].asString()); } - expect( - offerIndexes.size() == expectCount, - "Duplicate indexes returned?", - __FILE__, - line); - expect( - amounts.size() == expectCount, - "Duplicate amounts returned?", - __FILE__, - line); + expect(offerIndexes.size() == expectCount, "Duplicate indexes returned?", __FILE__, line); + expect(amounts.size() == expectCount, "Duplicate amounts returned?", __FILE__, line); }; // There are no sell offers. @@ -4776,20 +4340,18 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // A lambda that generates sell offers. STAmount sellPrice = XRP(0); - auto makeSellOffers = - [&env, &issuer, &nftID, &sellPrice](STAmount const& limit) { - // Save a little test time by not closing too often. - int offerCount = 0; - while (sellPrice < limit) - { - sellPrice += XRP(1); - env(token::createOffer(issuer, nftID, sellPrice), - txflags(tfSellNFToken)); - if (++offerCount % 10 == 0) - env.close(); - } - env.close(); - }; + auto makeSellOffers = [&env, &issuer, &nftID, &sellPrice](STAmount const& limit) { + // Save a little test time by not closing too often. + int offerCount = 0; + while (sellPrice < limit) + { + sellPrice += XRP(1); + env(token::createOffer(issuer, nftID, sellPrice), txflags(tfSellNFToken)); + if (++offerCount % 10 == 0) + env.close(); + } + env.close(); + }; // There is one sell offer. makeSellOffers(XRP(1)); @@ -4816,20 +4378,18 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // A lambda that generates buy offers. STAmount buyPrice = XRP(0); - auto makeBuyOffers = - [&env, &buyer, &issuer, &nftID, &buyPrice](STAmount const& limit) { - // Save a little test time by not closing too often. - int offerCount = 0; - while (buyPrice < limit) - { - buyPrice += XRP(1); - env(token::createOffer(buyer, nftID, buyPrice), - token::owner(issuer)); - if (++offerCount % 10 == 0) - env.close(); - } - env.close(); - }; + auto makeBuyOffers = [&env, &buyer, &issuer, &nftID, &buyPrice](STAmount const& limit) { + // Save a little test time by not closing too often. + int offerCount = 0; + while (buyPrice < limit) + { + buyPrice += XRP(1); + env(token::createOffer(buyer, nftID, buyPrice), token::owner(issuer)); + if (++offerCount % 10 == 0) + env.close(); + } + env.close(); + }; // There is one buy offer; makeBuyOffers(XRP(1)); @@ -4879,46 +4439,32 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env.close(); // Create an NFT that we'll make XRP offers for. - uint256 const nftID0{ - token::getNextID(env, issuer, 0u, tfTransferable)}; + uint256 const nftID0{token::getNextID(env, issuer, 0u, tfTransferable)}; env(token::mint(issuer, 0), txflags(tfTransferable)); env.close(); // Create an NFT that we'll make IOU offers for. - uint256 const nftID1{ - token::getNextID(env, issuer, 1u, tfTransferable)}; + uint256 const nftID1{token::getNextID(env, issuer, 1u, tfTransferable)}; env(token::mint(issuer, 1), txflags(tfTransferable)); env.close(); TER const offerCreateTER = temBAD_AMOUNT; // Make offers with negative amounts for the NFTs - uint256 const sellNegXrpOfferIndex = - keylet::nftoffer(issuer, env.seq(issuer)).key; - env(token::createOffer(issuer, nftID0, XRP(-2)), - txflags(tfSellNFToken), - ter(offerCreateTER)); + uint256 const sellNegXrpOfferIndex = keylet::nftoffer(issuer, env.seq(issuer)).key; + env(token::createOffer(issuer, nftID0, XRP(-2)), txflags(tfSellNFToken), ter(offerCreateTER)); env.close(); - uint256 const sellNegIouOfferIndex = - keylet::nftoffer(issuer, env.seq(issuer)).key; - env(token::createOffer(issuer, nftID1, gwXAU(-2)), - txflags(tfSellNFToken), - ter(offerCreateTER)); + uint256 const sellNegIouOfferIndex = keylet::nftoffer(issuer, env.seq(issuer)).key; + env(token::createOffer(issuer, nftID1, gwXAU(-2)), txflags(tfSellNFToken), ter(offerCreateTER)); env.close(); - uint256 const buyNegXrpOfferIndex = - keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftID0, XRP(-1)), - token::owner(issuer), - ter(offerCreateTER)); + uint256 const buyNegXrpOfferIndex = keylet::nftoffer(buyer, env.seq(buyer)).key; + env(token::createOffer(buyer, nftID0, XRP(-1)), token::owner(issuer), ter(offerCreateTER)); env.close(); - uint256 const buyNegIouOfferIndex = - keylet::nftoffer(buyer, env.seq(buyer)).key; - env(token::createOffer(buyer, nftID1, gwXAU(-1)), - token::owner(issuer), - ter(offerCreateTER)); + uint256 const buyNegIouOfferIndex = keylet::nftoffer(buyer, env.seq(buyer)).key; + env(token::createOffer(buyer, nftID1, gwXAU(-1)), token::owner(issuer), ter(offerCreateTER)); env.close(); { @@ -4926,32 +4472,24 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite TER const offerAcceptTER = tecOBJECT_NOT_FOUND; // Sell offers. - env(token::acceptSellOffer(buyer, sellNegXrpOfferIndex), - ter(offerAcceptTER)); + env(token::acceptSellOffer(buyer, sellNegXrpOfferIndex), ter(offerAcceptTER)); env.close(); - env(token::acceptSellOffer(buyer, sellNegIouOfferIndex), - ter(offerAcceptTER)); + env(token::acceptSellOffer(buyer, sellNegIouOfferIndex), ter(offerAcceptTER)); env.close(); // Buy offers. - env(token::acceptBuyOffer(issuer, buyNegXrpOfferIndex), - ter(offerAcceptTER)); + env(token::acceptBuyOffer(issuer, buyNegXrpOfferIndex), ter(offerAcceptTER)); env.close(); - env(token::acceptBuyOffer(issuer, buyNegIouOfferIndex), - ter(offerAcceptTER)); + env(token::acceptBuyOffer(issuer, buyNegIouOfferIndex), ter(offerAcceptTER)); env.close(); } { TER const offerAcceptTER = tecOBJECT_NOT_FOUND; // Brokered offers. - env(token::brokerOffers( - gw, buyNegXrpOfferIndex, sellNegXrpOfferIndex), - ter(offerAcceptTER)); + env(token::brokerOffers(gw, buyNegXrpOfferIndex, sellNegXrpOfferIndex), ter(offerAcceptTER)); env.close(); - env(token::brokerOffers( - gw, buyNegIouOfferIndex, sellNegIouOfferIndex), - ter(offerAcceptTER)); + env(token::brokerOffers(gw, buyNegIouOfferIndex, sellNegIouOfferIndex), ter(offerAcceptTER)); env.close(); } } @@ -4963,8 +4501,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env.fund(XRP(1000000), issuer, buyer); // Create an NFT that we'll make offers for. - uint256 const nftID{ - token::getNextID(env, issuer, 0u, tfTransferable)}; + uint256 const nftID{token::getNextID(env, issuer, 0u, tfTransferable)}; env(token::mint(issuer, 0), txflags(tfTransferable)); env.close(); @@ -5010,15 +4547,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env(rate(gw, 1.02)); env.close(); - auto expectInitialState = [this, - &env, - &buyer, - &minter, - &secondarySeller, - &broker, - &gw, - &gwXAU, - &gwXPB]() { + auto expectInitialState = [this, &env, &buyer, &minter, &secondarySeller, &broker, &gw, &gwXAU, &gwXPB]() { // Buyer should have XAU 1000, XPB 0 // Minter should have XAU 0, XPB 0 // Secondary seller should have XAU 0, XPB 0 @@ -5035,107 +4564,80 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite BEAST_EXPECT(env.balance(gw, buyer["XPB"]) == gwXPB(0)); BEAST_EXPECT(env.balance(gw, minter["XAU"]) == gwXAU(0)); BEAST_EXPECT(env.balance(gw, minter["XPB"]) == gwXPB(0)); - BEAST_EXPECT( - env.balance(gw, secondarySeller["XAU"]) == gwXAU(0)); - BEAST_EXPECT( - env.balance(gw, secondarySeller["XPB"]) == gwXPB(0)); + BEAST_EXPECT(env.balance(gw, secondarySeller["XAU"]) == gwXAU(0)); + BEAST_EXPECT(env.balance(gw, secondarySeller["XPB"]) == gwXPB(0)); BEAST_EXPECT(env.balance(gw, broker["XAU"]) == gwXAU(-5000)); BEAST_EXPECT(env.balance(gw, broker["XPB"]) == gwXPB(0)); }; - auto reinitializeTrustLineBalances = [&expectInitialState, - &env, - &buyer, - &minter, - &secondarySeller, - &broker, - &gw, - &gwXAU, - &gwXPB]() { - if (auto const difference = - gwXAU(1000) - env.balance(buyer, gwXAU); - difference > gwXAU(0)) - env(pay(gw, buyer, difference)); - if (env.balance(buyer, gwXPB) > gwXPB(0)) - env(pay(buyer, gw, env.balance(buyer, gwXPB))); - if (env.balance(minter, gwXAU) > gwXAU(0)) - env(pay(minter, gw, env.balance(minter, gwXAU))); - if (env.balance(minter, gwXPB) > gwXPB(0)) - env(pay(minter, gw, env.balance(minter, gwXPB))); - if (env.balance(secondarySeller, gwXAU) > gwXAU(0)) - env( - pay(secondarySeller, - gw, - env.balance(secondarySeller, gwXAU))); - if (env.balance(secondarySeller, gwXPB) > gwXPB(0)) - env( - pay(secondarySeller, - gw, - env.balance(secondarySeller, gwXPB))); - auto brokerDiff = gwXAU(5000) - env.balance(broker, gwXAU); - if (brokerDiff > gwXAU(0)) - env(pay(gw, broker, brokerDiff)); - else if (brokerDiff < gwXAU(0)) - { - brokerDiff.negate(); - env(pay(broker, gw, brokerDiff)); - } - if (env.balance(broker, gwXPB) > gwXPB(0)) - env(pay(broker, gw, env.balance(broker, gwXPB))); - env.close(); - expectInitialState(); - }; + auto reinitializeTrustLineBalances = + [&expectInitialState, &env, &buyer, &minter, &secondarySeller, &broker, &gw, &gwXAU, &gwXPB]() { + if (auto const difference = gwXAU(1000) - env.balance(buyer, gwXAU); difference > gwXAU(0)) + env(pay(gw, buyer, difference)); + if (env.balance(buyer, gwXPB) > gwXPB(0)) + env(pay(buyer, gw, env.balance(buyer, gwXPB))); + if (env.balance(minter, gwXAU) > gwXAU(0)) + env(pay(minter, gw, env.balance(minter, gwXAU))); + if (env.balance(minter, gwXPB) > gwXPB(0)) + env(pay(minter, gw, env.balance(minter, gwXPB))); + if (env.balance(secondarySeller, gwXAU) > gwXAU(0)) + env(pay(secondarySeller, gw, env.balance(secondarySeller, gwXAU))); + if (env.balance(secondarySeller, gwXPB) > gwXPB(0)) + env(pay(secondarySeller, gw, env.balance(secondarySeller, gwXPB))); + auto brokerDiff = gwXAU(5000) - env.balance(broker, gwXAU); + if (brokerDiff > gwXAU(0)) + env(pay(gw, broker, brokerDiff)); + else if (brokerDiff < gwXAU(0)) + { + brokerDiff.negate(); + env(pay(broker, gw, brokerDiff)); + } + if (env.balance(broker, gwXPB) > gwXPB(0)) + env(pay(broker, gw, env.balance(broker, gwXPB))); + env.close(); + expectInitialState(); + }; auto mintNFT = [&env](Account const& minter, int transferFee = 0) { - uint256 const nftID = token::getNextID( - env, minter, 0, tfTransferable, transferFee); - env(token::mint(minter), - token::xferFee(transferFee), - txflags(tfTransferable)); + uint256 const nftID = token::getNextID(env, minter, 0, tfTransferable, transferFee); + env(token::mint(minter), token::xferFee(transferFee), txflags(tfTransferable)); env.close(); return nftID; }; - auto createBuyOffer = - [&env]( - Account const& offerer, - Account const& owner, - uint256 const& nftID, - STAmount const& amount, - std::optional const terCode = {}) { - uint256 const offerID = - keylet::nftoffer(offerer, env.seq(offerer)).key; - env(token::createOffer(offerer, nftID, amount), - token::owner(owner), - terCode ? ter(*terCode) - : ter(static_cast(tesSUCCESS))); - env.close(); - return offerID; - }; + auto createBuyOffer = [&env]( + Account const& offerer, + Account const& owner, + uint256 const& nftID, + STAmount const& amount, + std::optional const terCode = {}) { + uint256 const offerID = keylet::nftoffer(offerer, env.seq(offerer)).key; + env(token::createOffer(offerer, nftID, amount), + token::owner(owner), + terCode ? ter(*terCode) : ter(static_cast(tesSUCCESS))); + env.close(); + return offerID; + }; - auto createSellOffer = - [&env]( - Account const& offerer, - uint256 const& nftID, - STAmount const& amount, - std::optional const terCode = {}) { - uint256 const offerID = - keylet::nftoffer(offerer, env.seq(offerer)).key; - env(token::createOffer(offerer, nftID, amount), - txflags(tfSellNFToken), - terCode ? ter(*terCode) - : ter(static_cast(tesSUCCESS))); - env.close(); - return offerID; - }; + auto createSellOffer = [&env]( + Account const& offerer, + uint256 const& nftID, + STAmount const& amount, + std::optional const terCode = {}) { + uint256 const offerID = keylet::nftoffer(offerer, env.seq(offerer)).key; + env(token::createOffer(offerer, nftID, amount), + txflags(tfSellNFToken), + terCode ? ter(*terCode) : ter(static_cast(tesSUCCESS))); + env.close(); + return offerID; + }; { // Buyer attempts to send 100% of their balance of an IOU // (sellside) reinitializeTrustLineBalances(); auto const nftID = mintNFT(minter); - auto const offerID = - createSellOffer(minter, nftID, gwXAU(1000)); + auto const offerID = createSellOffer(minter, nftID, gwXAU(1000)); TER const sellTER = tecINSUFFICIENT_FUNDS; env(token::acceptSellOffer(buyer, offerID), ter(sellTER)); env.close(); @@ -5147,8 +4649,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // (buyside) reinitializeTrustLineBalances(); auto const nftID = mintNFT(minter); - auto const offerID = - createBuyOffer(buyer, minter, nftID, gwXAU(1000)); + auto const offerID = createBuyOffer(buyer, minter, nftID, gwXAU(1000)); TER const sellTER = tecINSUFFICIENT_FUNDS; env(token::acceptBuyOffer(minter, offerID), ter(sellTER)); env.close(); @@ -5174,8 +4675,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // fee would be greater than the buyer's balance (buyside) reinitializeTrustLineBalances(); auto const nftID = mintNFT(minter); - auto const offerID = - createBuyOffer(buyer, minter, nftID, gwXAU(995)); + auto const offerID = createBuyOffer(buyer, minter, nftID, gwXAU(995)); TER const sellTER = tecINSUFFICIENT_FUNDS; env(token::acceptBuyOffer(minter, offerID), ter(sellTER)); env.close(); @@ -5205,8 +4705,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // (buyside) reinitializeTrustLineBalances(); auto const nftID = mintNFT(minter); - auto const offerID = - createBuyOffer(buyer, minter, nftID, gwXAU(900)); + auto const offerID = createBuyOffer(buyer, minter, nftID, gwXAU(900)); env(token::acceptBuyOffer(minter, offerID)); env.close(); @@ -5227,8 +4726,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env.close(); auto const nftID = mintNFT(minter); - auto const offerID = - createSellOffer(minter, nftID, gwXAU(1000)); + auto const offerID = createSellOffer(minter, nftID, gwXAU(1000)); env(token::acceptSellOffer(buyer, offerID)); env.close(); @@ -5249,8 +4747,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env.close(); auto const nftID = mintNFT(minter); - auto const offerID = - createBuyOffer(buyer, minter, nftID, gwXAU(1000)); + auto const offerID = createBuyOffer(buyer, minter, nftID, gwXAU(1000)); env(token::acceptBuyOffer(minter, offerID)); env.close(); @@ -5265,8 +4762,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite reinitializeTrustLineBalances(); auto const nftID = mintNFT(minter); - auto const offerID = - createSellOffer(minter, nftID, gwXAU(1000)); + auto const offerID = createSellOffer(minter, nftID, gwXAU(1000)); TER const sellTER = tesSUCCESS; env(token::acceptSellOffer(gw, offerID), ter(sellTER)); env.close(); @@ -5281,8 +4777,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite auto const nftID = mintNFT(minter); TER const offerTER = tesSUCCESS; - auto const offerID = - createBuyOffer(gw, minter, nftID, gwXAU(1000), {offerTER}); + auto const offerID = createBuyOffer(gw, minter, nftID, gwXAU(1000), {offerTER}); TER const sellTER = tesSUCCESS; env(token::acceptBuyOffer(minter, offerID), ter(sellTER)); env.close(); @@ -5295,8 +4790,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // than minter trusts (sellside) reinitializeTrustLineBalances(); auto const nftID = mintNFT(minter); - auto const offerID = - createSellOffer(minter, nftID, gwXAU(5000)); + auto const offerID = createSellOffer(minter, nftID, gwXAU(5000)); TER const sellTER = tesSUCCESS; env(token::acceptSellOffer(gw, offerID), ter(sellTER)); env.close(); @@ -5311,8 +4805,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite auto const nftID = mintNFT(minter); TER const offerTER = tesSUCCESS; - auto const offerID = - createBuyOffer(gw, minter, nftID, gwXAU(5000), {offerTER}); + auto const offerID = createBuyOffer(gw, minter, nftID, gwXAU(5000), {offerTER}); TER const sellTER = tesSUCCESS; env(token::acceptBuyOffer(minter, offerID), ter(sellTER)); env.close(); @@ -5340,8 +4833,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite reinitializeTrustLineBalances(); auto const nftID = mintNFT(gw); - auto const offerID = - createBuyOffer(buyer, gw, nftID, gwXAU(1000)); + auto const offerID = createBuyOffer(buyer, gw, nftID, gwXAU(1000)); env(token::acceptBuyOffer(gw, offerID)); env.close(); @@ -5355,8 +4847,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite reinitializeTrustLineBalances(); auto const nftID = mintNFT(gw); auto const offerID = createSellOffer(gw, nftID, gwXAU(2000)); - env(token::acceptSellOffer(buyer, offerID), - ter(static_cast(tecINSUFFICIENT_FUNDS))); + env(token::acceptSellOffer(buyer, offerID), ter(static_cast(tecINSUFFICIENT_FUNDS))); env.close(); expectInitialState(); } @@ -5366,10 +4857,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // (buyside) reinitializeTrustLineBalances(); auto const nftID = mintNFT(gw); - auto const offerID = - createBuyOffer(buyer, gw, nftID, gwXAU(2000)); - env(token::acceptBuyOffer(gw, offerID), - ter(static_cast(tecINSUFFICIENT_FUNDS))); + auto const offerID = createBuyOffer(buyer, gw, nftID, gwXAU(2000)); + env(token::acceptBuyOffer(gw, offerID), ter(static_cast(tecINSUFFICIENT_FUNDS))); env.close(); expectInitialState(); } @@ -5379,8 +4868,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite reinitializeTrustLineBalances(); auto const nftID = mintNFT(minter); auto const offerID = createSellOffer(minter, nftID, gwXPB(10)); - env(token::acceptSellOffer(buyer, offerID), - ter(static_cast(tecINSUFFICIENT_FUNDS))); + env(token::acceptSellOffer(buyer, offerID), ter(static_cast(tecINSUFFICIENT_FUNDS))); env.close(); expectInitialState(); } @@ -5389,14 +4877,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // have no trust line for and buyer has none of (buyside). reinitializeTrustLineBalances(); auto const nftID = mintNFT(minter); - auto const offerID = createBuyOffer( - buyer, - minter, - nftID, - gwXPB(10), - {static_cast(tecUNFUNDED_OFFER)}); - env(token::acceptBuyOffer(minter, offerID), - ter(static_cast(tecOBJECT_NOT_FOUND))); + auto const offerID = + createBuyOffer(buyer, minter, nftID, gwXPB(10), {static_cast(tecUNFUNDED_OFFER)}); + env(token::acceptBuyOffer(minter, offerID), ter(static_cast(tecOBJECT_NOT_FOUND))); env.close(); expectInitialState(); } @@ -5427,8 +4910,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env.close(); auto const nftID = mintNFT(minter); - auto const offerID = - createBuyOffer(buyer, minter, nftID, gwXPB(10)); + auto const offerID = createBuyOffer(buyer, minter, nftID, gwXPB(10)); env(token::acceptBuyOffer(minter, offerID)); env.close(); @@ -5445,14 +4927,12 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // secondarySeller has to sell it because transfer fees only // happen on secondary sales auto const nftID = mintNFT(minter, 3000); // 3% - auto const primaryOfferID = - createSellOffer(minter, nftID, XRP(0)); + auto const primaryOfferID = createSellOffer(minter, nftID, XRP(0)); env(token::acceptSellOffer(secondarySeller, primaryOfferID)); env.close(); // now we can do a secondary sale - auto const offerID = - createSellOffer(secondarySeller, nftID, gwXAU(1000)); + auto const offerID = createSellOffer(secondarySeller, nftID, gwXAU(1000)); TER const sellTER = tecINSUFFICIENT_FUNDS; env(token::acceptSellOffer(buyer, offerID), ter(sellTER)); env.close(); @@ -5467,17 +4947,14 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // secondarySeller has to sell it because transfer fees only // happen on secondary sales auto const nftID = mintNFT(minter, 3000); // 3% - auto const primaryOfferID = - createSellOffer(minter, nftID, XRP(0)); + auto const primaryOfferID = createSellOffer(minter, nftID, XRP(0)); env(token::acceptSellOffer(secondarySeller, primaryOfferID)); env.close(); // now we can do a secondary sale - auto const offerID = - createBuyOffer(buyer, secondarySeller, nftID, gwXAU(1000)); + auto const offerID = createBuyOffer(buyer, secondarySeller, nftID, gwXAU(1000)); TER const sellTER = tecINSUFFICIENT_FUNDS; - env(token::acceptBuyOffer(secondarySeller, offerID), - ter(sellTER)); + env(token::acceptBuyOffer(secondarySeller, offerID), ter(sellTER)); env.close(); expectInitialState(); @@ -5490,14 +4967,12 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // secondarySeller has to sell it because transfer fees only // happen on secondary sales auto const nftID = mintNFT(minter, 3000); // 3% - auto const primaryOfferID = - createSellOffer(minter, nftID, XRP(0)); + auto const primaryOfferID = createSellOffer(minter, nftID, XRP(0)); env(token::acceptSellOffer(secondarySeller, primaryOfferID)); env.close(); // now we can do a secondary sale - auto const offerID = - createSellOffer(secondarySeller, nftID, gwXAU(900)); + auto const offerID = createSellOffer(secondarySeller, nftID, gwXAU(900)); env(token::acceptSellOffer(buyer, offerID)); env.close(); @@ -5505,8 +4980,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite BEAST_EXPECT(env.balance(secondarySeller, gwXAU) == gwXAU(873)); BEAST_EXPECT(env.balance(buyer, gwXAU) == gwXAU(82)); BEAST_EXPECT(env.balance(gw, minter["XAU"]) == gwXAU(-27)); - BEAST_EXPECT( - env.balance(gw, secondarySeller["XAU"]) == gwXAU(-873)); + BEAST_EXPECT(env.balance(gw, secondarySeller["XAU"]) == gwXAU(-873)); BEAST_EXPECT(env.balance(gw, buyer["XAU"]) == gwXAU(-82)); } { @@ -5517,14 +4991,12 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // secondarySeller has to sell it because transfer fees only // happen on secondary sales auto const nftID = mintNFT(minter, 3000); // 3% - auto const primaryOfferID = - createSellOffer(minter, nftID, XRP(0)); + auto const primaryOfferID = createSellOffer(minter, nftID, XRP(0)); env(token::acceptSellOffer(secondarySeller, primaryOfferID)); env.close(); // now we can do a secondary sale - auto const offerID = - createBuyOffer(buyer, secondarySeller, nftID, gwXAU(900)); + auto const offerID = createBuyOffer(buyer, secondarySeller, nftID, gwXAU(900)); env(token::acceptBuyOffer(secondarySeller, offerID)); env.close(); @@ -5535,8 +5007,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // pays 900 plus 2% transfer fee on XAU - 918 BEAST_EXPECT(env.balance(buyer, gwXAU) == gwXAU(82)); BEAST_EXPECT(env.balance(gw, minter["XAU"]) == gwXAU(-27)); - BEAST_EXPECT( - env.balance(gw, secondarySeller["XAU"]) == gwXAU(-873)); + BEAST_EXPECT(env.balance(gw, secondarySeller["XAU"]) == gwXAU(-873)); BEAST_EXPECT(env.balance(gw, buyer["XAU"]) == gwXAU(-82)); } { @@ -5558,12 +5029,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite reinitializeTrustLineBalances(); auto const nftID = mintNFT(minter); - auto const sellOffer = - createSellOffer(minter, nftID, gwXAU(300)); - auto const buyOffer = - createBuyOffer(buyer, minter, nftID, gwXAU(500)); - env(token::brokerOffers(broker, buyOffer, sellOffer), - token::brokerFee(gwXAU(100))); + auto const sellOffer = createSellOffer(minter, nftID, gwXAU(300)); + auto const buyOffer = createBuyOffer(buyer, minter, nftID, gwXAU(500)); + env(token::brokerOffers(broker, buyOffer, sellOffer), token::brokerFee(gwXAU(100))); env.close(); BEAST_EXPECT(env.balance(minter, gwXAU) == gwXAU(400)); @@ -5594,18 +5062,14 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // secondarySeller has to sell it because transfer fees only // happen on secondary sales auto const nftID = mintNFT(minter, 3000); // 3% - auto const primaryOfferID = - createSellOffer(minter, nftID, XRP(0)); + auto const primaryOfferID = createSellOffer(minter, nftID, XRP(0)); env(token::acceptSellOffer(secondarySeller, primaryOfferID)); env.close(); // now we can do a secondary sale - auto const sellOffer = - createSellOffer(secondarySeller, nftID, gwXAU(300)); - auto const buyOffer = - createBuyOffer(buyer, secondarySeller, nftID, gwXAU(500)); - env(token::brokerOffers(broker, buyOffer, sellOffer), - token::brokerFee(gwXAU(100))); + auto const sellOffer = createSellOffer(secondarySeller, nftID, gwXAU(300)); + auto const buyOffer = createBuyOffer(buyer, secondarySeller, nftID, gwXAU(500)); + env(token::brokerOffers(broker, buyOffer, sellOffer), token::brokerFee(gwXAU(100))); env.close(); BEAST_EXPECT(env.balance(minter, gwXAU) == gwXAU(12)); @@ -5614,8 +5078,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite BEAST_EXPECT(env.balance(broker, gwXAU) == gwXAU(5100)); BEAST_EXPECT(env.balance(gw, minter["XAU"]) == gwXAU(-12)); BEAST_EXPECT(env.balance(gw, buyer["XAU"]) == gwXAU(-490)); - BEAST_EXPECT( - env.balance(gw, secondarySeller["XAU"]) == gwXAU(-388)); + BEAST_EXPECT(env.balance(gw, secondarySeller["XAU"]) == gwXAU(-388)); BEAST_EXPECT(env.balance(gw, broker["XAU"]) == gwXAU(-5100)); } } @@ -5670,15 +5133,11 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // Bob creates a buy offer for 5 XRP. Alice creates a sell offer // for 0 XRP. - uint256 const bobBuyOfferIndex = - keylet::nftoffer(bob, env.seq(bob)).key; + uint256 const bobBuyOfferIndex = keylet::nftoffer(bob, env.seq(bob)).key; env(token::createOffer(bob, nftId, XRP(5)), token::owner(alice)); - uint256 const aliceSellOfferIndex = - keylet::nftoffer(alice, env.seq(alice)).key; - env(token::createOffer(alice, nftId, XRP(0)), - token::destination(bob), - txflags(tfSellNFToken)); + uint256 const aliceSellOfferIndex = keylet::nftoffer(alice, env.seq(alice)).key; + env(token::createOffer(alice, nftId, XRP(0)), token::destination(bob), txflags(tfSellNFToken)); env.close(); // bob accepts alice's offer but forgets to remove the old buy offer. @@ -5689,16 +5148,15 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite BEAST_EXPECT(env.le(keylet::nftoffer(bobBuyOfferIndex))); // Bob creates a sell offer for the gift NFT from alice. - uint256 const bobSellOfferIndex = - keylet::nftoffer(bob, env.seq(bob)).key; + uint256 const bobSellOfferIndex = keylet::nftoffer(bob, env.seq(bob)).key; env(token::createOffer(bob, nftId, XRP(4)), txflags(tfSellNFToken)); env.close(); // bob now has a buy offer and a sell offer on the books. A broker // spots this and swoops in to make a profit. BEAST_EXPECT(nftCount(env, bob) == 1); - auto const bobsPriorBalance = env.balance(bob); - auto const brokersPriorBalance = env.balance(broker); + auto const bobPriorBalance = env.balance(bob); + auto const brokerPriorBalance = env.balance(broker); env(token::brokerOffers(broker, bobBuyOfferIndex, bobSellOfferIndex), token::brokerFee(XRP(1)), ter(tecCANT_ACCEPT_OWN_NFTOKEN_OFFER)); @@ -5707,8 +5165,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // A tec result was returned, so no state should change other // than the broker burning their transaction fee. BEAST_EXPECT(nftCount(env, bob) == 1); - BEAST_EXPECT(env.balance(bob) == bobsPriorBalance); - BEAST_EXPECT(env.balance(broker) == brokersPriorBalance - baseFee); + BEAST_EXPECT(env.balance(bob) == bobPriorBalance); + BEAST_EXPECT(env.balance(broker) == brokerPriorBalance - baseFee); } void @@ -5740,8 +5198,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite auto incLgrSeqForFixNftRemint = [&](Env& env, Account const& acct) { int delta = 0; auto const deletableLgrSeq = - (*env.le(acct))[~sfFirstNFTokenSequence].value_or(0) + - (*env.le(acct))[sfMintedNFTokens] + 255; + (*env.le(acct))[~sfFirstNFTokenSequence].value_or(0) + (*env.le(acct))[sfMintedNFTokens] + 255; if (deletableLgrSeq > openLedgerSeq(env)) delta = deletableLgrSeq - openLedgerSeq(env); @@ -5898,9 +5355,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // The new NFT minted will not have the same ID // as any of the NFTs authorized minter minted - BEAST_EXPECT( - std::find(nftIDs.begin(), nftIDs.end(), remintNFTokenID) == - nftIDs.end()); + BEAST_EXPECT(std::find(nftIDs.begin(), nftIDs.end(), remintNFTokenID) == nftIDs.end()); } // When an account mints and burns a batch of NFTokens using tickets, @@ -5936,8 +5391,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // alice burns 50 NFTs using tickets for (auto const nftokenID : nftIDs) { - env(token::burn(alice, nftokenID), - ticket::use(aliceTicketSeq++)); + env(token::burn(alice, nftokenID), ticket::use(aliceTicketSeq++)); } env.close(); @@ -6000,9 +5454,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // The new NFT minted will not have the same ID // as any of the NFTs authorized minter minted using tickets - BEAST_EXPECT( - std::find(nftIDs.begin(), nftIDs.end(), remintNFTokenID) == - nftIDs.end()); + BEAST_EXPECT(std::find(nftIDs.begin(), nftIDs.end(), remintNFTokenID) == nftIDs.end()); } // When an authorized minter mints and burns a batch of NFTokens using // tickets, issuer's account needs to wait a longer time before it can @@ -6036,9 +5488,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite { uint256 const nftokenID = token::getNextID(env, alice, 0u); nftIDs.push_back(nftokenID); - env(token::mint(minter), - token::issuer(alice), - ticket::use(minterTicketSeq++)); + env(token::mint(minter), token::issuer(alice), ticket::use(minterTicketSeq++)); } env.close(); @@ -6107,9 +5557,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // The new NFT minted will not have the same ID // as one of NFTs authorized minter minted using tickets - BEAST_EXPECT( - std::find(nftIDs.begin(), nftIDs.end(), remintNFTokenID) == - nftIDs.end()); + BEAST_EXPECT(std::find(nftIDs.begin(), nftIDs.end(), remintNFTokenID) == nftIDs.end()); } void @@ -6128,19 +5576,13 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env.fund(XRP(10000), alice, buyer); env.close(); - env(token::mint(alice), - token::amount(XRP(10000)), - ter(temDISABLED)); + env(token::mint(alice), token::amount(XRP(10000)), ter(temDISABLED)); env.close(); - env(token::mint(alice), - token::destination("buyer"), - ter(temDISABLED)); + env(token::mint(alice), token::destination("buyer"), ter(temDISABLED)); env.close(); - env(token::mint(alice), - token::expiration(lastClose(env) + 25), - ter(temDISABLED)); + env(token::mint(alice), token::expiration(lastClose(env) + 25), ter(temDISABLED)); env.close(); return; @@ -6163,16 +5605,12 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite { // Destination field specified but Amount field not specified - env(token::mint(alice), - token::destination(buyer), - ter(temMALFORMED)); + env(token::mint(alice), token::destination(buyer), ter(temMALFORMED)); env.close(); BEAST_EXPECT(ownerCount(env, alice) == 0); // Expiration field specified but Amount field not specified - env(token::mint(alice), - token::expiration(lastClose(env) + 25), - ter(temMALFORMED)); + env(token::mint(alice), token::expiration(lastClose(env) + 25), ter(temMALFORMED)); env.close(); BEAST_EXPECT(ownerCount(env, buyer) == 0); } @@ -6180,50 +5618,33 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite { // The destination may not be the account submitting the // transaction. - env(token::mint(alice), - token::amount(XRP(1000)), - token::destination(alice), - ter(temMALFORMED)); + env(token::mint(alice), token::amount(XRP(1000)), token::destination(alice), ter(temMALFORMED)); env.close(); BEAST_EXPECT(ownerCount(env, alice) == 0); // The destination must be an account already established in the // ledger. - env(token::mint(alice), - token::amount(XRP(1000)), - token::destination(Account("demon")), - ter(tecNO_DST)); + env(token::mint(alice), token::amount(XRP(1000)), token::destination(Account("demon")), ter(tecNO_DST)); env.close(); BEAST_EXPECT(ownerCount(env, alice) == 0); } { // Set a bad expiration. - env(token::mint(alice), - token::amount(XRP(1000)), - token::expiration(0), - ter(temBAD_EXPIRATION)); + env(token::mint(alice), token::amount(XRP(1000)), token::expiration(0), ter(temBAD_EXPIRATION)); env.close(); BEAST_EXPECT(ownerCount(env, alice) == 0); // The new NFTokenOffer may not have passed its expiration time. - env(token::mint(alice), - token::amount(XRP(1000)), - token::expiration(lastClose(env)), - ter(tecEXPIRED)); + env(token::mint(alice), token::amount(XRP(1000)), token::expiration(lastClose(env)), ter(tecEXPIRED)); env.close(); BEAST_EXPECT(ownerCount(env, alice) == 0); } { // Set an invalid amount. - env(token::mint(alice), - token::amount(buyer["USD"](1)), - txflags(tfOnlyXRP), - ter(temBAD_AMOUNT)); - env(token::mint(alice), - token::amount(buyer["USD"](0)), - ter(temBAD_AMOUNT)); + env(token::mint(alice), token::amount(buyer["USD"](1)), txflags(tfOnlyXRP), ter(temBAD_AMOUNT)); + env(token::mint(alice), token::amount(buyer["USD"](0)), ter(temBAD_AMOUNT)); env.close(); BEAST_EXPECT(ownerCount(env, alice) == 0); @@ -6239,10 +5660,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // If the IOU issuer and the NFToken issuer are the same, // then that issuer does not need a trust line to accept their // fee. - env(token::mint(gw), - token::amount(gwAUD(1000)), - txflags(tfTransferable), - token::xferFee(10)); + env(token::mint(gw), token::amount(gwAUD(1000)), txflags(tfTransferable), token::xferFee(10)); env.close(); // Give alice the needed trust line, but freeze it. @@ -6260,9 +5678,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite BEAST_EXPECT(ownerCount(env, alice) == 0); // Seller (alice) must have a trust line may not be frozen. - env(token::mint(alice), - token::amount(gwAUD(1000)), - ter(tecFROZEN)); + env(token::mint(alice), token::amount(gwAUD(1000)), ter(tecFROZEN)); env.close(); BEAST_EXPECT(ownerCount(env, alice) == 0); @@ -6280,9 +5696,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env.close(); // doesn't have reserve for 2 objects (NFTokenPage, Offer) - env(token::mint(bob), - token::amount(XRP(0)), - ter(tecINSUFFICIENT_RESERVE)); + env(token::mint(bob), token::amount(XRP(0)), ter(tecINSUFFICIENT_RESERVE)); env.close(); // have reserve for NFTokenPage, Offer @@ -6294,9 +5708,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // doesn't have reserve for Offer env(pay(env.master, bob, drops(baseFee))); env.close(); - env(token::mint(bob), - token::amount(XRP(0)), - ter(tecINSUFFICIENT_RESERVE)); + env(token::mint(bob), token::amount(XRP(0)), ter(tecINSUFFICIENT_RESERVE)); env.close(); // have reserve for Offer @@ -6335,8 +5747,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite token::amount(XRP(10)), token::destination(buyer), token::expiration(lastClose(env) + 25)); - uint256 const offerAliceSellsToBuyer = - keylet::nftoffer(alice, env.seq(alice)).key; + uint256 const offerAliceSellsToBuyer = keylet::nftoffer(alice, env.seq(alice)).key; env(token::cancelOffer(alice, {offerAliceSellsToBuyer})); env.close(); @@ -6345,8 +5756,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite token::amount(XRP(10)), token::destination(alice), token::expiration(lastClose(env) + 25)); - uint256 const offerBuyerSellsToAlice = - keylet::nftoffer(buyer, env.seq(buyer)).key; + uint256 const offerBuyerSellsToAlice = keylet::nftoffer(buyer, env.seq(buyer)).key; env(token::cancelOffer(alice, {offerBuyerSellsToAlice})); env.close(); @@ -6356,9 +5766,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // Minter will have offer not issuer BEAST_EXPECT(ownerCount(env, minter) == 0); BEAST_EXPECT(ownerCount(env, issuer) == 0); - env(token::mint(minter), - token::issuer(issuer), - token::amount(drops(1))); + env(token::mint(minter), token::issuer(issuer), token::amount(drops(1))); env.close(); BEAST_EXPECT(ownerCount(env, minter) == 2); BEAST_EXPECT(ownerCount(env, issuer) == 0); @@ -6407,12 +5815,10 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // transaction auto verifyNFTokenID = [&](uint256 const& actualNftID) { // Get the hash for the most recent transaction. - std::string const txHash{ - env.tx()->getJson(JsonOptions::none)[jss::hash].asString()}; + std::string const txHash{env.tx()->getJson(JsonOptions::none)[jss::hash].asString()}; env.close(); - Json::Value const meta = - env.rpc("tx", txHash)[jss::result][jss::meta]; + Json::Value const meta = env.rpc("tx", txHash)[jss::result][jss::meta]; // Expect nftokens_id field if (!BEAST_EXPECT(meta.isMember(jss::nftoken_id))) @@ -6427,55 +5833,50 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // Verify `nftoken_ids` value equals to the NFTokenIDs that were // changed in the most recent NFTokenCancelOffer transaction - auto verifyNFTokenIDsInCancelOffer = - [&](std::vector actualNftIDs) { - // Get the hash for the most recent transaction. - std::string const txHash{ - env.tx()->getJson(JsonOptions::none)[jss::hash].asString()}; + auto verifyNFTokenIDsInCancelOffer = [&](std::vector actualNftIDs) { + // Get the hash for the most recent transaction. + std::string const txHash{env.tx()->getJson(JsonOptions::none)[jss::hash].asString()}; - env.close(); - Json::Value const meta = - env.rpc("tx", txHash)[jss::result][jss::meta]; + env.close(); + Json::Value const meta = env.rpc("tx", txHash)[jss::result][jss::meta]; - // Expect nftokens_ids field and verify the values - if (!BEAST_EXPECT(meta.isMember(jss::nftoken_ids))) - return; + // Expect nftokens_ids field and verify the values + if (!BEAST_EXPECT(meta.isMember(jss::nftoken_ids))) + return; - // Convert NFT IDs from Json::Value to uint256 - std::vector metaIDs; - std::transform( - meta[jss::nftoken_ids].begin(), - meta[jss::nftoken_ids].end(), - std::back_inserter(metaIDs), - [this](Json::Value id) { - uint256 nftID; - BEAST_EXPECT(nftID.parseHex(id.asString())); - return nftID; - }); + // Convert NFT IDs from Json::Value to uint256 + std::vector metaIDs; + std::transform( + meta[jss::nftoken_ids].begin(), + meta[jss::nftoken_ids].end(), + std::back_inserter(metaIDs), + [this](Json::Value id) { + uint256 nftID; + BEAST_EXPECT(nftID.parseHex(id.asString())); + return nftID; + }); - // Sort both array to prepare for comparison - std::sort(metaIDs.begin(), metaIDs.end()); - std::sort(actualNftIDs.begin(), actualNftIDs.end()); + // Sort both array to prepare for comparison + std::sort(metaIDs.begin(), metaIDs.end()); + std::sort(actualNftIDs.begin(), actualNftIDs.end()); - // Make sure the expect number of NFTs is correct - BEAST_EXPECT(metaIDs.size() == actualNftIDs.size()); + // Make sure the expect number of NFTs is correct + BEAST_EXPECT(metaIDs.size() == actualNftIDs.size()); - // Check the value of NFT ID in the meta with the - // actual values - for (size_t i = 0; i < metaIDs.size(); ++i) - BEAST_EXPECT(metaIDs[i] == actualNftIDs[i]); - }; + // Check the value of NFT ID in the meta with the + // actual values + for (size_t i = 0; i < metaIDs.size(); ++i) + BEAST_EXPECT(metaIDs[i] == actualNftIDs[i]); + }; // Verify `offer_id` value equals to the offerID that was // changed in the most recent NFTokenCreateOffer tx auto verifyNFTokenOfferID = [&](uint256 const& offerID) { // Get the hash for the most recent transaction. - std::string const txHash{ - env.tx()->getJson(JsonOptions::none)[jss::hash].asString()}; + std::string const txHash{env.tx()->getJson(JsonOptions::none)[jss::hash].asString()}; env.close(); - Json::Value const meta = - env.rpc("tx", txHash)[jss::result][jss::meta]; + Json::Value const meta = env.rpc("tx", txHash)[jss::result][jss::meta]; // Expect offer_id field and verify the value if (!BEAST_EXPECT(meta.isMember(jss::offer_id))) @@ -6490,14 +5891,12 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite { // Alice mints 2 NFTs // Verify the NFTokenIDs are correct in the NFTokenMint tx meta - uint256 const nftId1{ - token::getNextID(env, alice, 0u, tfTransferable)}; + uint256 const nftId1{token::getNextID(env, alice, 0u, tfTransferable)}; env(token::mint(alice, 0u), txflags(tfTransferable)); env.close(); verifyNFTokenID(nftId1); - uint256 const nftId2{ - token::getNextID(env, alice, 0u, tfTransferable)}; + uint256 const nftId2{token::getNextID(env, alice, 0u, tfTransferable)}; env(token::mint(alice, 0u), txflags(tfTransferable)); env.close(); verifyNFTokenID(nftId2); @@ -6505,32 +5904,26 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // Alice creates one sell offer for each NFT // Verify the offer indexes are correct in the NFTokenCreateOffer tx // meta - uint256 const aliceOfferIndex1 = - keylet::nftoffer(alice, env.seq(alice)).key; - env(token::createOffer(alice, nftId1, drops(1)), - txflags(tfSellNFToken)); + uint256 const aliceOfferIndex1 = keylet::nftoffer(alice, env.seq(alice)).key; + env(token::createOffer(alice, nftId1, drops(1)), txflags(tfSellNFToken)); env.close(); verifyNFTokenOfferID(aliceOfferIndex1); - uint256 const aliceOfferIndex2 = - keylet::nftoffer(alice, env.seq(alice)).key; - env(token::createOffer(alice, nftId2, drops(1)), - txflags(tfSellNFToken)); + uint256 const aliceOfferIndex2 = keylet::nftoffer(alice, env.seq(alice)).key; + env(token::createOffer(alice, nftId2, drops(1)), txflags(tfSellNFToken)); env.close(); verifyNFTokenOfferID(aliceOfferIndex2); // Alice cancels two offers she created // Verify the NFTokenIDs are correct in the NFTokenCancelOffer tx // meta - env(token::cancelOffer( - alice, {aliceOfferIndex1, aliceOfferIndex2})); + env(token::cancelOffer(alice, {aliceOfferIndex1, aliceOfferIndex2})); env.close(); verifyNFTokenIDsInCancelOffer({nftId1, nftId2}); // Bobs creates a buy offer for nftId1 // Verify the offer id is correct in the NFTokenCreateOffer tx meta - auto const bobBuyOfferIndex = - keylet::nftoffer(bob, env.seq(bob)).key; + auto const bobBuyOfferIndex = keylet::nftoffer(bob, env.seq(bob)).key; env(token::createOffer(bob, nftId1, drops(1)), token::owner(alice)); env.close(); verifyNFTokenOfferID(bobBuyOfferIndex); @@ -6545,31 +5938,25 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // Check `nftoken_ids` in brokered mode { // Alice mints a NFT - uint256 const nftId{ - token::getNextID(env, alice, 0u, tfTransferable)}; + uint256 const nftId{token::getNextID(env, alice, 0u, tfTransferable)}; env(token::mint(alice, 0u), txflags(tfTransferable)); env.close(); verifyNFTokenID(nftId); // Alice creates sell offer and set broker as destination - uint256 const offerAliceToBroker = - keylet::nftoffer(alice, env.seq(alice)).key; - env(token::createOffer(alice, nftId, drops(1)), - token::destination(broker), - txflags(tfSellNFToken)); + uint256 const offerAliceToBroker = keylet::nftoffer(alice, env.seq(alice)).key; + env(token::createOffer(alice, nftId, drops(1)), token::destination(broker), txflags(tfSellNFToken)); env.close(); verifyNFTokenOfferID(offerAliceToBroker); // Bob creates buy offer - uint256 const offerBobToBroker = - keylet::nftoffer(bob, env.seq(bob)).key; + uint256 const offerBobToBroker = keylet::nftoffer(bob, env.seq(bob)).key; env(token::createOffer(bob, nftId, drops(1)), token::owner(alice)); env.close(); verifyNFTokenOfferID(offerBobToBroker); // Check NFTokenID meta for NFTokenAcceptOffer in brokered mode - env(token::brokerOffers( - broker, offerBobToBroker, offerAliceToBroker)); + env(token::brokerOffers(broker, offerBobToBroker, offerAliceToBroker)); env.close(); verifyNFTokenID(nftId); } @@ -6578,39 +5965,32 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // multiple offers are cancelled for the same NFT { // Alice mints a NFT - uint256 const nftId{ - token::getNextID(env, alice, 0u, tfTransferable)}; + uint256 const nftId{token::getNextID(env, alice, 0u, tfTransferable)}; env(token::mint(alice, 0u), txflags(tfTransferable)); env.close(); verifyNFTokenID(nftId); // Alice creates 2 sell offers for the same NFT - uint256 const aliceOfferIndex1 = - keylet::nftoffer(alice, env.seq(alice)).key; - env(token::createOffer(alice, nftId, drops(1)), - txflags(tfSellNFToken)); + uint256 const aliceOfferIndex1 = keylet::nftoffer(alice, env.seq(alice)).key; + env(token::createOffer(alice, nftId, drops(1)), txflags(tfSellNFToken)); env.close(); verifyNFTokenOfferID(aliceOfferIndex1); - uint256 const aliceOfferIndex2 = - keylet::nftoffer(alice, env.seq(alice)).key; - env(token::createOffer(alice, nftId, drops(1)), - txflags(tfSellNFToken)); + uint256 const aliceOfferIndex2 = keylet::nftoffer(alice, env.seq(alice)).key; + env(token::createOffer(alice, nftId, drops(1)), txflags(tfSellNFToken)); env.close(); verifyNFTokenOfferID(aliceOfferIndex2); // Make sure the metadata only has 1 nft id, since both offers are // for the same nft - env(token::cancelOffer( - alice, {aliceOfferIndex1, aliceOfferIndex2})); + env(token::cancelOffer(alice, {aliceOfferIndex1, aliceOfferIndex2})); env.close(); verifyNFTokenIDsInCancelOffer({nftId}); } if (features[featureNFTokenMintOffer]) { - uint256 const aliceMintWithOfferIndex1 = - keylet::nftoffer(alice, env.seq(alice)).key; + uint256 const aliceMintWithOfferIndex1 = keylet::nftoffer(alice, env.seq(alice)).key; env(token::mint(alice), token::amount(XRP(0))); env.close(); verifyNFTokenOfferID(aliceMintWithOfferIndex1); @@ -6625,18 +6005,15 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite using namespace test::jtx; // Lambda that mints an NFT and then creates a sell offer - auto mintAndCreateSellOffer = [](test::jtx::Env& env, - test::jtx::Account const& acct, - STAmount const amt) -> uint256 { + auto mintAndCreateSellOffer = + [](test::jtx::Env& env, test::jtx::Account const& acct, STAmount const amt) -> uint256 { // acct mints a NFT - uint256 const nftId{ - token::getNextID(env, acct, 0u, tfTransferable)}; + uint256 const nftId{token::getNextID(env, acct, 0u, tfTransferable)}; env(token::mint(acct, 0u), txflags(tfTransferable)); env.close(); // acct makes an sell offer - uint256 const sellOfferIndex = - keylet::nftoffer(acct, env.seq(acct)).key; + uint256 const sellOfferIndex = keylet::nftoffer(acct, env.seq(acct)).key; env(token::createOffer(acct, nftId, amt), txflags(tfSellNFToken)); env.close(); @@ -6663,8 +6040,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env.close(); // alice mints an NFT and create a sell offer for 0 XRP - auto const sellOfferIndex = - mintAndCreateSellOffer(env, alice, XRP(0)); + auto const sellOfferIndex = mintAndCreateSellOffer(env, alice, XRP(0)); // Bob owns no object BEAST_EXPECT(ownerCount(env, bob) == 0); @@ -6693,8 +6069,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite { // Bob is not able to accept the offer with only the account // reserve (200,000,000 drops) - env(token::acceptSellOffer(bob, sellOfferIndex), - ter(tecINSUFFICIENT_RESERVE)); + env(token::acceptSellOffer(bob, sellOfferIndex), ter(tecINSUFFICIENT_RESERVE)); env.close(); // after prev transaction, Bob owns `200M - base fee` drops due @@ -6710,8 +6085,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // However, this transaction will still fail because the reserve // requirement is `base fee` drops higher - env(token::acceptSellOffer(bob, sellOfferIndex), - ter(tecINSUFFICIENT_RESERVE)); + env(token::acceptSellOffer(bob, sellOfferIndex), ter(tecINSUFFICIENT_RESERVE)); env.close(); // Send bob `base fee * 2` drops @@ -6749,8 +6123,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite for (size_t i = 0; i < 200; i++) { // alice mints an NFT and creates a sell offer for 0 XRP - auto const sellOfferIndex = - mintAndCreateSellOffer(env, alice, XRP(0)); + auto const sellOfferIndex = mintAndCreateSellOffer(env, alice, XRP(0)); // Bob is able to accept the offer env(token::acceptSellOffer(bob, sellOfferIndex)); @@ -6760,13 +6133,11 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite else { // alice mints the first NFT and creates a sell offer for 0 XRP - auto const sellOfferIndex1 = - mintAndCreateSellOffer(env, alice, XRP(0)); + auto const sellOfferIndex1 = mintAndCreateSellOffer(env, alice, XRP(0)); // Bob cannot accept this offer because he doesn't have the // reserve for the NFT - env(token::acceptSellOffer(bob, sellOfferIndex1), - ter(tecINSUFFICIENT_RESERVE)); + env(token::acceptSellOffer(bob, sellOfferIndex1), ter(tecINSUFFICIENT_RESERVE)); env.close(); // Give bob enough reserve @@ -6786,8 +6157,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite for (size_t i = 0; i < 31; i++) { // alice mints an NFT and creates a sell offer for 0 XRP - auto const sellOfferIndex = - mintAndCreateSellOffer(env, alice, XRP(0)); + auto const sellOfferIndex = mintAndCreateSellOffer(env, alice, XRP(0)); // Bob can accept the offer because the new NFT is stored in // an existing NFTokenPage so no new reserve is required @@ -6799,13 +6169,11 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // alice now mints the 33rd NFT and creates an sell offer for 0 // XRP - auto const sellOfferIndex33 = - mintAndCreateSellOffer(env, alice, XRP(0)); + auto const sellOfferIndex33 = mintAndCreateSellOffer(env, alice, XRP(0)); // Bob fails to accept this NFT because he does not have enough // reserve for a new NFTokenPage - env(token::acceptSellOffer(bob, sellOfferIndex33), - ter(tecINSUFFICIENT_RESERVE)); + env(token::acceptSellOffer(bob, sellOfferIndex33), ter(tecINSUFFICIENT_RESERVE)); env.close(); // Send bob incremental reserve @@ -6845,8 +6213,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env.close(); // Alice mints a NFT - uint256 const nftId{ - token::getNextID(env, alice, 0u, tfTransferable)}; + uint256 const nftId{token::getNextID(env, alice, 0u, tfTransferable)}; env(token::mint(alice, 0u), txflags(tfTransferable)); env.close(); @@ -6858,8 +6225,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // accepting the buy offer fails because bob's balance is `base fee` // drops lower than the required amount, since the previous tx burnt // drops for tx fee. - env(token::acceptBuyOffer(alice, buyOfferIndex), - ter(tecINSUFFICIENT_FUNDS)); + env(token::acceptBuyOffer(alice, buyOfferIndex), ter(tecINSUFFICIENT_FUNDS)); env.close(); // send Bob `base fee` drops @@ -6895,22 +6261,17 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env.close(); // Alice mints a NFT - uint256 const nftId{ - token::getNextID(env, alice, 0u, tfTransferable)}; + uint256 const nftId{token::getNextID(env, alice, 0u, tfTransferable)}; env(token::mint(alice, 0u), txflags(tfTransferable)); env.close(); // Alice creates sell offer and set broker as destination - uint256 const offerAliceToBroker = - keylet::nftoffer(alice, env.seq(alice)).key; - env(token::createOffer(alice, nftId, XRP(1)), - token::destination(broker), - txflags(tfSellNFToken)); + uint256 const offerAliceToBroker = keylet::nftoffer(alice, env.seq(alice)).key; + env(token::createOffer(alice, nftId, XRP(1)), token::destination(broker), txflags(tfSellNFToken)); env.close(); // Bob creates buy offer - uint256 const offerBobToBroker = - keylet::nftoffer(bob, env.seq(bob)).key; + uint256 const offerBobToBroker = keylet::nftoffer(bob, env.seq(bob)).key; env(token::createOffer(bob, nftId, XRP(1)), token::owner(alice)); env.close(); @@ -6918,9 +6279,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // Returns insufficient funds, because bob burnt tx fee when he // created his buy offer, which makes his spendable balance to be // less than the required amount. - env(token::brokerOffers( - broker, offerBobToBroker, offerAliceToBroker), - ter(tecINSUFFICIENT_FUNDS)); + env(token::brokerOffers(broker, offerBobToBroker, offerAliceToBroker), ter(tecINSUFFICIENT_FUNDS)); env.close(); // send Bob `base fee` drops @@ -6928,8 +6287,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env.close(); // broker offers. - env(token::brokerOffers( - broker, offerBobToBroker, offerAliceToBroker)); + env(token::brokerOffers(broker, offerBobToBroker, offerAliceToBroker)); env.close(); } } @@ -6974,11 +6332,9 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // // In both cases we remove the fixRemoveNFTokenAutoTrustLine amendment. // Otherwise we can't create NFTokens with tfTrustLine enabled. - FeatureBitset const localFeatures = - features - fixRemoveNFTokenAutoTrustLine; + FeatureBitset const localFeatures = features - fixRemoveNFTokenAutoTrustLine; for (FeatureBitset feats : - {localFeatures - fixEnforceNFTokenTrustline, - localFeatures | fixEnforceNFTokenTrustline}) + {localFeatures - fixEnforceNFTokenTrustline, localFeatures | fixEnforceNFTokenTrustline}) { Env env{*this, feats}; env.fund(XRP(1000), issuer, becky, cheri, gw); @@ -6993,31 +6349,21 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // issuer creates two NFTs: one with and one without AutoTrustLine. std::uint16_t xferFee = 5000; // 5% - uint256 const nftAutoTrustID{token::getNextID( - env, issuer, 0u, tfTransferable | tfTrustLine, xferFee)}; - env(token::mint(issuer, 0u), - token::xferFee(xferFee), - txflags(tfTransferable | tfTrustLine)); + uint256 const nftAutoTrustID{token::getNextID(env, issuer, 0u, tfTransferable | tfTrustLine, xferFee)}; + env(token::mint(issuer, 0u), token::xferFee(xferFee), txflags(tfTransferable | tfTrustLine)); env.close(); - uint256 const nftNoAutoTrustID{ - token::getNextID(env, issuer, 0u, tfTransferable, xferFee)}; - env(token::mint(issuer, 0u), - token::xferFee(xferFee), - txflags(tfTransferable)); + uint256 const nftNoAutoTrustID{token::getNextID(env, issuer, 0u, tfTransferable, xferFee)}; + env(token::mint(issuer, 0u), token::xferFee(xferFee), txflags(tfTransferable)); env.close(); // becky buys the nfts for 1 drop each. { - uint256 const beckyBuyOfferIndex1 = - keylet::nftoffer(becky, env.seq(becky)).key; - env(token::createOffer(becky, nftAutoTrustID, drops(1)), - token::owner(issuer)); + uint256 const beckyBuyOfferIndex1 = keylet::nftoffer(becky, env.seq(becky)).key; + env(token::createOffer(becky, nftAutoTrustID, drops(1)), token::owner(issuer)); - uint256 const beckyBuyOfferIndex2 = - keylet::nftoffer(becky, env.seq(becky)).key; - env(token::createOffer(becky, nftNoAutoTrustID, drops(1)), - token::owner(issuer)); + uint256 const beckyBuyOfferIndex2 = keylet::nftoffer(becky, env.seq(becky)).key; + env(token::createOffer(becky, nftNoAutoTrustID, drops(1)), token::owner(issuer)); env.close(); env(token::acceptBuyOffer(issuer, beckyBuyOfferIndex1)); @@ -7026,17 +6372,13 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite } // becky creates offers to sell the nfts for AUD. - uint256 const beckyAutoTrustOfferIndex = - keylet::nftoffer(becky, env.seq(becky)).key; - env(token::createOffer(becky, nftAutoTrustID, gwAUD(100)), - txflags(tfSellNFToken)); + uint256 const beckyAutoTrustOfferIndex = keylet::nftoffer(becky, env.seq(becky)).key; + env(token::createOffer(becky, nftAutoTrustID, gwAUD(100)), txflags(tfSellNFToken)); env.close(); // Creating an offer for the NFToken without tfTrustLine fails // because issuer does not have a trust line for AUD. - env(token::createOffer(becky, nftNoAutoTrustID, gwAUD(100)), - txflags(tfSellNFToken), - ter(tecNO_LINE)); + env(token::createOffer(becky, nftNoAutoTrustID, gwAUD(100)), txflags(tfSellNFToken), ter(tecNO_LINE)); env.close(); // issuer creates a trust line. Now the offer create for the @@ -7046,10 +6388,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env.close(); BEAST_EXPECT(ownerCount(env, issuer) == 1); - uint256 const beckyNoAutoTrustOfferIndex = - keylet::nftoffer(becky, env.seq(becky)).key; - env(token::createOffer(becky, nftNoAutoTrustID, gwAUD(100)), - txflags(tfSellNFToken)); + uint256 const beckyNoAutoTrustOfferIndex = keylet::nftoffer(becky, env.seq(becky)).key; + env(token::createOffer(becky, nftNoAutoTrustID, gwAUD(100)), txflags(tfSellNFToken)); env.close(); // Now that the offers are in place, issuer removes the trustline. @@ -7079,8 +6419,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // With fixEnforceNFTokenTrustline cheri can't accept the // offer because issuer could not get their transfer fee // without the appropriate trustline. - env(token::acceptSellOffer(cheri, beckyNoAutoTrustOfferIndex), - ter(tecNO_LINE)); + env(token::acceptSellOffer(cheri, beckyNoAutoTrustOfferIndex), ter(tecNO_LINE)); env.close(); // But if issuer re-establishes the trustline then the offer @@ -7145,8 +6484,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // // We remove the fixRemoveNFTokenAutoTrustLine amendment. Otherwise // we can't create NFTokens with tfTrustLine enabled. - FeatureBitset const localFeatures = - features - fixRemoveNFTokenAutoTrustLine; + FeatureBitset const localFeatures = features - fixRemoveNFTokenAutoTrustLine; Env env{*this, localFeatures}; env.fund(XRP(1000), issuer, becky, cheri); @@ -7161,31 +6499,21 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // issuer creates two NFTs: one with and one without AutoTrustLine. std::uint16_t xferFee = 5000; // 5% - uint256 const nftAutoTrustID{token::getNextID( - env, issuer, 0u, tfTransferable | tfTrustLine, xferFee)}; - env(token::mint(issuer, 0u), - token::xferFee(xferFee), - txflags(tfTransferable | tfTrustLine)); + uint256 const nftAutoTrustID{token::getNextID(env, issuer, 0u, tfTransferable | tfTrustLine, xferFee)}; + env(token::mint(issuer, 0u), token::xferFee(xferFee), txflags(tfTransferable | tfTrustLine)); env.close(); - uint256 const nftNoAutoTrustID{ - token::getNextID(env, issuer, 0u, tfTransferable, xferFee)}; - env(token::mint(issuer, 0u), - token::xferFee(xferFee), - txflags(tfTransferable)); + uint256 const nftNoAutoTrustID{token::getNextID(env, issuer, 0u, tfTransferable, xferFee)}; + env(token::mint(issuer, 0u), token::xferFee(xferFee), txflags(tfTransferable)); env.close(); // becky buys the nfts for 1 drop each. { - uint256 const beckyBuyOfferIndex1 = - keylet::nftoffer(becky, env.seq(becky)).key; - env(token::createOffer(becky, nftAutoTrustID, drops(1)), - token::owner(issuer)); + uint256 const beckyBuyOfferIndex1 = keylet::nftoffer(becky, env.seq(becky)).key; + env(token::createOffer(becky, nftAutoTrustID, drops(1)), token::owner(issuer)); - uint256 const beckyBuyOfferIndex2 = - keylet::nftoffer(becky, env.seq(becky)).key; - env(token::createOffer(becky, nftNoAutoTrustID, drops(1)), - token::owner(issuer)); + uint256 const beckyBuyOfferIndex2 = keylet::nftoffer(becky, env.seq(becky)).key; + env(token::createOffer(becky, nftNoAutoTrustID, drops(1)), token::owner(issuer)); env.close(); env(token::acceptBuyOffer(issuer, beckyBuyOfferIndex1)); @@ -7200,9 +6528,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // Without featureNFTokenMintOffer becky simply can't // create an offer for a non-tfTrustLine NFToken that would // pay the transfer fee in issuer's own IOU. - env(token::createOffer(becky, nftNoAutoTrustID, isISU(100)), - txflags(tfSellNFToken), - ter(tecNO_LINE)); + env(token::createOffer(becky, nftNoAutoTrustID, isISU(100)), txflags(tfSellNFToken), ter(tecNO_LINE)); env.close(); // And issuer can't create a trust line to themselves. @@ -7211,10 +6537,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // However if the NFToken has the tfTrustLine flag set, // then becky can create the offer. - uint256 const beckyAutoTrustOfferIndex = - keylet::nftoffer(becky, env.seq(becky)).key; - env(token::createOffer(becky, nftAutoTrustID, isISU(100)), - txflags(tfSellNFToken)); + uint256 const beckyAutoTrustOfferIndex = keylet::nftoffer(becky, env.seq(becky)).key; + env(token::createOffer(becky, nftAutoTrustID, isISU(100)), txflags(tfSellNFToken)); env.close(); // And cheri can accept the offer. @@ -7230,15 +6554,11 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite { // With featureNFTokenMintOffer things go better. // becky creates offers to sell the nfts for ISU. - uint256 const beckyNoAutoTrustOfferIndex = - keylet::nftoffer(becky, env.seq(becky)).key; - env(token::createOffer(becky, nftNoAutoTrustID, isISU(100)), - txflags(tfSellNFToken)); + uint256 const beckyNoAutoTrustOfferIndex = keylet::nftoffer(becky, env.seq(becky)).key; + env(token::createOffer(becky, nftNoAutoTrustID, isISU(100)), txflags(tfSellNFToken)); env.close(); - uint256 const beckyAutoTrustOfferIndex = - keylet::nftoffer(becky, env.seq(becky)).key; - env(token::createOffer(becky, nftAutoTrustID, isISU(100)), - txflags(tfSellNFToken)); + uint256 const beckyAutoTrustOfferIndex = keylet::nftoffer(becky, env.seq(becky)).key; + env(token::createOffer(becky, nftAutoTrustID, isISU(100)), txflags(tfSellNFToken)); env.close(); // cheri accepts becky's offers. Behavior is uniform: @@ -7281,8 +6601,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env.fund(XRP(10000), issuer); env.close(); - auto const expectedTer = - modifyEnabled ? TER{tesSUCCESS} : TER{temINVALID_FLAG}; + auto const expectedTer = modifyEnabled ? TER{tesSUCCESS} : TER{temINVALID_FLAG}; env(token::mint(issuer, 0u), txflags(tfMutable), ter(expectedTer)); env.close(); } @@ -7322,32 +6641,22 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env.close(); // Set a negative fee. Exercises invalid preflight1. - env(token::modify(issuer, nftId), - fee(STAmount(10ull, true)), - ter(temBAD_FEE)); + env(token::modify(issuer, nftId), fee(STAmount(10ull, true)), ter(temBAD_FEE)); env.close(); // Invalid Flags - env(token::modify(issuer, nftId), - txflags(0x00000001), - ter(temINVALID_FLAG)); + env(token::modify(issuer, nftId), txflags(0x00000001), ter(temINVALID_FLAG)); // Invalid Owner - env(token::modify(issuer, nftId), - token::owner(issuer), - ter(temMALFORMED)); + env(token::modify(issuer, nftId), token::owner(issuer), ter(temMALFORMED)); env.close(); // Invalid URI length = 0 - env(token::modify(issuer, nftId), - token::uri(""), - ter(temMALFORMED)); + env(token::modify(issuer, nftId), token::uri(""), ter(temMALFORMED)); env.close(); // Invalid URI length > 256 - env(token::modify(issuer, nftId), - token::uri(std::string(maxTokenURILength + 1, 'q')), - ter(temMALFORMED)); + env(token::modify(issuer, nftId), token::uri(std::string(maxTokenURILength + 1, 'q')), ter(temMALFORMED)); env.close(); } { @@ -7357,8 +6666,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite { // NFToken not exists - uint256 const nftIDNotExists{ - token::getNextID(env, issuer, 0u, tfMutable)}; + uint256 const nftIDNotExists{token::getNextID(env, issuer, 0u, tfMutable)}; env.close(); env(token::modify(issuer, nftIDNotExists), ter(tecNO_ENTRY)); @@ -7366,33 +6674,26 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite } { // Invalid NFToken flag - uint256 const nftIDNotModifiable{ - token::getNextID(env, issuer, 0u)}; + uint256 const nftIDNotModifiable{token::getNextID(env, issuer, 0u)}; env(token::mint(issuer, 0u)); env.close(); - env(token::modify(issuer, nftIDNotModifiable), - ter(tecNO_PERMISSION)); + env(token::modify(issuer, nftIDNotModifiable), ter(tecNO_PERMISSION)); env.close(); } { // Unauthorized account - uint256 const nftId{ - token::getNextID(env, issuer, 0u, tfMutable)}; + uint256 const nftId{token::getNextID(env, issuer, 0u, tfMutable)}; env(token::mint(issuer, 0u), txflags(tfMutable)); env.close(); - env(token::modify(bob, nftId), - token::owner(issuer), - ter(tecNO_PERMISSION)); + env(token::modify(bob, nftId), token::owner(issuer), ter(tecNO_PERMISSION)); env.close(); env(token::setMinter(issuer, alice)); env.close(); - env(token::modify(bob, nftId), - token::owner(issuer), - ter(tecNO_PERMISSION)); + env(token::modify(bob, nftId), token::owner(issuer), ter(tecNO_PERMISSION)); env.close(); } } @@ -7419,16 +6720,12 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite Json::Value params; params[jss::account] = acct.human(); params[jss::type] = "state"; - auto response = - env.rpc("json", "account_nfts", to_string(params)); + auto response = env.rpc("json", "account_nfts", to_string(params)); return response[jss::result][jss::account_nfts]; }; // lambda that checks for the expected URI value of an NFToken - auto checkURI = [&accountNFTs, this]( - Account const& acct, - char const* uri, - int line) { + auto checkURI = [&accountNFTs, this](Account const& acct, char const* uri, int line) { auto const nfts = accountNFTs(acct); if (nfts.size() == 1) pass(); @@ -7447,8 +6744,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite else { std::ostringstream text; - text << "checkURI: unexpected URI present on line " - << line; + text << "checkURI: unexpected URI present on line " << line; fail(text.str(), __FILE__, line); } return; @@ -7459,8 +6755,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite else { std::ostringstream text; - text << "checkURI: unexpected URI contents on line " - << line; + text << "checkURI: unexpected URI contents on line " << line; fail(text.str(), __FILE__, line); } }; @@ -7488,10 +6783,8 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite checkURI(issuer, "uri", __LINE__); // Account != Owner - uint256 const offerID = - keylet::nftoffer(issuer, env.seq(issuer)).key; - env(token::createOffer(issuer, nftId, XRP(0)), - txflags(tfSellNFToken)); + uint256 const offerID = keylet::nftoffer(issuer, env.seq(issuer)).key; + env(token::createOffer(issuer, nftId, XRP(0)), txflags(tfSellNFToken)); env.close(); env(token::acceptSellOffer(alice, offerID)); env.close(); @@ -7500,17 +6793,13 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite checkURI(alice, "uri", __LINE__); // Modify by owner fails. - env(token::modify(alice, nftId), - token::uri("new_uri"), - ter(tecNO_PERMISSION)); + env(token::modify(alice, nftId), token::uri("new_uri"), ter(tecNO_PERMISSION)); env.close(); BEAST_EXPECT(ownerCount(env, issuer) == 0); BEAST_EXPECT(ownerCount(env, alice) == 1); checkURI(alice, "uri", __LINE__); - env(token::modify(issuer, nftId), - token::owner(alice), - token::uri("new_uri")); + env(token::modify(issuer, nftId), token::owner(alice), token::uri("new_uri")); env.close(); BEAST_EXPECT(ownerCount(env, issuer) == 0); BEAST_EXPECT(ownerCount(env, alice) == 1); @@ -7520,18 +6809,14 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env.close(); checkURI(alice, nullptr, __LINE__); - env(token::modify(issuer, nftId), - token::owner(alice), - token::uri("uri")); + env(token::modify(issuer, nftId), token::owner(alice), token::uri("uri")); env.close(); checkURI(alice, "uri", __LINE__); // Modify by authorized minter env(token::setMinter(issuer, bob)); env.close(); - env(token::modify(bob, nftId), - token::owner(alice), - token::uri("new_uri")); + env(token::modify(bob, nftId), token::owner(alice), token::uri("new_uri")); env.close(); checkURI(alice, "new_uri", __LINE__); @@ -7539,9 +6824,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env.close(); checkURI(alice, nullptr, __LINE__); - env(token::modify(bob, nftId), - token::owner(alice), - token::uri("uri")); + env(token::modify(bob, nftId), token::owner(alice), token::uri("uri")); env.close(); checkURI(alice, "uri", __LINE__); } @@ -7595,8 +6878,8 @@ public: run() override { testWithFeats( - allFeatures - fixNFTokenReserve - featureNFTokenMintOffer - - featureDynamicNFT); + allFeatures - fixNFTokenReserve - featureNFTokenMintOffer - featureDynamicNFT - + fixExpiredNFTokenOfferRemoval); } }; @@ -7605,9 +6888,7 @@ class NFTokenDisallowIncoming_test : public NFTokenBaseUtil_test void run() override { - testWithFeats( - allFeatures - fixNFTokenReserve - featureNFTokenMintOffer - - featureDynamicNFT); + testWithFeats(allFeatures - fixNFTokenReserve - featureNFTokenMintOffer - featureDynamicNFT); } }; @@ -7616,8 +6897,7 @@ class NFTokenWOMintOffer_test : public NFTokenBaseUtil_test void run() override { - testWithFeats( - allFeatures - featureNFTokenMintOffer - featureDynamicNFT); + testWithFeats(allFeatures - featureNFTokenMintOffer - featureDynamicNFT); } }; @@ -7630,6 +6910,15 @@ class NFTokenWOModify_test : public NFTokenBaseUtil_test } }; +class NFTokenWOExpiredOfferRemoval_test : public NFTokenBaseUtil_test +{ + void + run() override + { + testWithFeats(allFeatures - fixExpiredNFTokenOfferRemoval); + } +}; + class NFTokenAllFeatures_test : public NFTokenBaseUtil_test { void diff --git a/src/test/app/NetworkID_test.cpp b/src/test/app/NetworkID_test.cpp index d924710cb3..5fddc8f641 100644 --- a/src/test/app/NetworkID_test.cpp +++ b/src/test/app/NetworkID_test.cpp @@ -37,9 +37,7 @@ public: auto const alice = Account{"alice"}; - auto const runTx = [&](test::jtx::Env& env, - Json::Value const& jv, - TER expectedOutcome) { + auto const runTx = [&](test::jtx::Env& env, Json::Value const& jv, TER expectedOutcome) { env.memoize(env.master); env.memoize(alice); @@ -117,10 +115,7 @@ public: Serializer s; jt.stx->add(s); BEAST_EXPECT( - env.rpc( - "submit", - strHex(s.slice()))[jss::result][jss::engine_result] == - "telREQUIRES_NETWORK_ID"); + env.rpc("submit", strHex(s.slice()))[jss::result][jss::engine_result] == "telREQUIRES_NETWORK_ID"); env.close(); } diff --git a/src/test/app/NetworkOPs_test.cpp b/src/test/app/NetworkOPs_test.cpp index 582f9a8084..a4bdae9101 100644 --- a/src/test/app/NetworkOPs_test.cpp +++ b/src/test/app/NetworkOPs_test.cpp @@ -2,7 +2,7 @@ #include #include -#include +#include namespace xrpl { namespace test { @@ -28,30 +28,23 @@ public: { using namespace jtx; auto const alice = Account{"alice"}; - Env env{ - *this, - envconfig(), - std::make_unique(&logs), - beast::severities::kAll}; + Env env{*this, envconfig(), std::make_unique(&logs), beast::severities::kAll}; env.memoize(env.master); env.memoize(alice); auto const jtx = env.jt(ticket::create(alice, 1), seq(1), fee(10)); auto transactionId = jtx.stx->getTransactionID(); - env.app().getHashRouter().setFlags( - transactionId, HashRouterFlags::HELD); + env.app().getHashRouter().setFlags(transactionId, HashRouterFlags::HELD); env(jtx, json(jss::Sequence, 1), ter(terNO_ACCOUNT)); - env.app().getHashRouter().setFlags( - transactionId, HashRouterFlags::BAD); + env.app().getHashRouter().setFlags(transactionId, HashRouterFlags::BAD); env.close(); } - BEAST_EXPECT( - logs.find("No transaction to process!") != std::string::npos); + BEAST_EXPECT(logs.find("No transaction to process!") != std::string::npos); } }; diff --git a/src/test/app/Offer_test.cpp b/src/test/app/Offer_test.cpp index f1d68ece1e..4847b7edb0 100644 --- a/src/test/app/Offer_test.cpp +++ b/src/test/app/Offer_test.cpp @@ -20,30 +20,20 @@ class OfferBaseUtil_test : public beast::unit_test::suite std::uint32_t lastClose(jtx::Env& env) { - return env.current() - ->header() - .parentCloseTime.time_since_epoch() - .count(); + return env.current()->header().parentCloseTime.time_since_epoch().count(); } static auto - ledgerEntryOffer( - jtx::Env& env, - jtx::Account const& acct, - std::uint32_t offer_seq) + ledgerEntryOffer(jtx::Env& env, jtx::Account const& acct, std::uint32_t offer_seq) { Json::Value jvParams; jvParams[jss::offer][jss::account] = acct.human(); jvParams[jss::offer][jss::seq] = offer_seq; - return env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; + return env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; } static auto - getBookOffers( - jtx::Env& env, - Issue const& taker_pays, - Issue const& taker_gets) + getBookOffers(jtx::Env& env, Issue const& taker_pays, Issue const& taker_gets) { Json::Value jvbp; jvbp[jss::ledger_index] = "current"; @@ -105,15 +95,10 @@ public: PathSet paths(Path(XRP, USD), Path(USD)); - env(pay(alice, bob, USD(100)), - json(paths.json()), - sendmax(BTC(1000)), - txflags(tfPartialPayment)); + env(pay(alice, bob, USD(100)), json(paths.json()), sendmax(BTC(1000)), txflags(tfPartialPayment)); env.require(balance(bob, USD(100))); - BEAST_EXPECT( - !isOffer(env, carol, BTC(1), USD(100)) && - isOffer(env, carol, BTC(49), XRP(49))); + BEAST_EXPECT(!isOffer(env, carol, BTC(1), USD(100)) && isOffer(env, carol, BTC(49), XRP(49))); } void @@ -146,26 +131,18 @@ public: // cancel the offer above and replace it with a new offer auto const offer2Seq = env.seq(alice); - env(offer(alice, XRP(300), USD(100)), - json(jss::OfferSequence, offer1Seq), - require(offers(alice, 1))); + env(offer(alice, XRP(300), USD(100)), json(jss::OfferSequence, offer1Seq), require(offers(alice, 1))); env.close(); - BEAST_EXPECT( - isOffer(env, alice, XRP(300), USD(100)) && - !isOffer(env, alice, XRP(500), USD(100))); + BEAST_EXPECT(isOffer(env, alice, XRP(300), USD(100)) && !isOffer(env, alice, XRP(500), USD(100))); // Test canceling non-existent offer. // auto const offer3Seq = env.seq (alice); - env(offer(alice, XRP(400), USD(200)), - json(jss::OfferSequence, offer1Seq), - require(offers(alice, 2))); + env(offer(alice, XRP(400), USD(200)), json(jss::OfferSequence, offer1Seq), require(offers(alice, 2))); env.close(); - BEAST_EXPECT( - isOffer(env, alice, XRP(300), USD(100)) && - isOffer(env, alice, XRP(400), USD(200))); + BEAST_EXPECT(isOffer(env, alice, XRP(300), USD(100)) && isOffer(env, alice, XRP(400), USD(200))); // Test cancellation now with OfferCancel tx auto const offer4Seq = env.seq(alice); @@ -289,10 +266,7 @@ public: // stAmountCalcSwitchover2 was inactive.) env(offer(erin, drops(2), USD(1))); - env(pay(alice, bob, USD(1)), - path(~USD), - sendmax(XRP(102)), - txflags(tfNoRippleDirect | tfPartialPayment)); + env(pay(alice, bob, USD(1)), path(~USD), sendmax(XRP(102)), txflags(tfNoRippleDirect | tfPartialPayment)); env.require(offers(carol, 0), offers(dan, 1)); @@ -347,22 +321,15 @@ public: env(offer(alice, USD(1), aliceTakerGets)); env.close(); - env.require( - offers(carol, 0), - balance( - carol, - initialCarolUSD)); // offer is removed but not taken + env.require(offers(carol, 0), balance(carol, + initialCarolUSD)); // offer is removed but not taken if (crossBothOffers) { - env.require( - offers(alice, 0), - balance(alice, USD(1))); // alice's offer is crossed + env.require(offers(alice, 0), balance(alice, USD(1))); // alice's offer is crossed } else { - env.require( - offers(alice, 1), - balance(alice, USD(0))); // alice's offer is not crossed + env.require(offers(alice, 1), balance(alice, USD(0))); // alice's offer is not crossed } } @@ -386,26 +353,18 @@ public: env.close(); env.require(offers(bob, 1), offers(carol, 1)); - std::uint32_t const flags = partialPayment - ? (tfNoRippleDirect | tfPartialPayment) - : tfNoRippleDirect; + std::uint32_t const flags = partialPayment ? (tfNoRippleDirect | tfPartialPayment) : tfNoRippleDirect; - TER const expectedTer = - partialPayment ? TER{tesSUCCESS} : TER{tecPATH_PARTIAL}; + TER const expectedTer = partialPayment ? TER{tesSUCCESS} : TER{tecPATH_PARTIAL}; - env(pay(alice, bob, USD(5)), - path(~USD), - sendmax(XRP(1)), - txflags(flags), - ter(expectedTer)); + env(pay(alice, bob, USD(5)), path(~USD), sendmax(XRP(1)), txflags(flags), ter(expectedTer)); env.close(); if (expectedTer == tesSUCCESS) { env.require(offers(carol, 0)); - env.require(balance( - carol, - initialCarolUSD)); // offer is removed but not taken + env.require(balance(carol, + initialCarolUSD)); // offer is removed but not taken } else { @@ -475,22 +434,15 @@ public: env(offer(alice, USD(1), aliceTakerGets)); env.close(); - env.require( - offers(carol, 0), - balance( - carol, - initialCarolUSD)); // offer is removed but not taken + env.require(offers(carol, 0), balance(carol, + initialCarolUSD)); // offer is removed but not taken if (crossBothOffers) { - env.require( - offers(alice, 0), - balance(alice, USD(1))); // alice's offer is crossed + env.require(offers(alice, 0), balance(alice, USD(1))); // alice's offer is crossed } else { - env.require( - offers(alice, 1), - balance(alice, USD(0))); // alice's offer is not crossed + env.require(offers(alice, 1), balance(alice, USD(0))); // alice's offer is not crossed } } @@ -517,26 +469,18 @@ public: env.close(); env.require(offers(bob, 1), offers(carol, 1)); - std::uint32_t const flags = partialPayment - ? (tfNoRippleDirect | tfPartialPayment) - : tfNoRippleDirect; + std::uint32_t const flags = partialPayment ? (tfNoRippleDirect | tfPartialPayment) : tfNoRippleDirect; - TER const expectedTer = - partialPayment ? TER{tesSUCCESS} : TER{tecPATH_PARTIAL}; + TER const expectedTer = partialPayment ? TER{tesSUCCESS} : TER{tecPATH_PARTIAL}; - env(pay(alice, bob, USD(5)), - path(~USD), - sendmax(EUR(10)), - txflags(flags), - ter(expectedTer)); + env(pay(alice, bob, USD(5)), path(~USD), sendmax(EUR(10)), txflags(flags), ter(expectedTer)); env.close(); if (expectedTer == tesSUCCESS) { env.require(offers(carol, 0)); - env.require(balance( - carol, - initialCarolUSD)); // offer is removed but not taken + env.require(balance(carol, + initialCarolUSD)); // offer is removed but not taken } else { @@ -612,10 +556,7 @@ public: env(offer(dan, XRP(50), USD1(50))); - env(pay(alice, carol, USD2(50)), - path(~USD1, bob), - sendmax(XRP(50)), - txflags(tfNoRippleDirect)); + env(pay(alice, carol, USD2(50)), path(~USD1, bob), sendmax(XRP(50)), txflags(tfNoRippleDirect)); env.require(balance(alice, xrpMinusFee(env, 10000 - 50))); env.require(balance(bob, USD1(100))); @@ -737,13 +678,10 @@ public: offersOnAccount(jtx::Env& env, jtx::Account account) { std::vector> result; - forEachItem( - *env.current(), - account, - [&result](std::shared_ptr const& sle) { - if (sle->getType() == ltOFFER) - result.push_back(sle); - }); + forEachItem(*env.current(), account, [&result](std::shared_ptr const& sle) { + if (sle->getType() == ltOFFER) + result.push_back(sle); + }); return result; } @@ -772,9 +710,7 @@ public: env.close(); // bob creates an offer that expires before the next ledger close. - env(offer(bob, USD(500), XRP(500)), - json(sfExpiration.fieldName, lastClose(env) + 1), - ter(tesSUCCESS)); + env(offer(bob, USD(500), XRP(500)), json(sfExpiration.fieldName, lastClose(env) + 1), ter(tesSUCCESS)); // The offer expires (it's not removed yet). env.close(); @@ -791,9 +727,7 @@ public: // Order that can't be filled but will remove bob's expired offer: { TER const killedCode{TER{tecKILLED}}; - env(offer(alice, XRP(1000), USD(1000)), - txflags(tfFillOrKill), - ter(killedCode)); + env(offer(alice, XRP(1000), USD(1000)), txflags(tfFillOrKill), ter(killedCode)); } env.require( balance(alice, startBalance - (f * 2)), @@ -806,9 +740,7 @@ public: offers(bob, 1)); // Order that can be filled - env(offer(alice, XRP(500), USD(500)), - txflags(tfFillOrKill), - ter(tesSUCCESS)); + env(offer(alice, XRP(500), USD(500)), txflags(tfFillOrKill), ter(tesSUCCESS)); env.require( balance(alice, startBalance - (f * 3) + XRP(500)), @@ -837,22 +769,15 @@ public: // No cross: { TER const expectedCode = tecKILLED; - env(offer(alice, XRP(1000), USD(1000)), - txflags(tfImmediateOrCancel), - ter(expectedCode)); + env(offer(alice, XRP(1000), USD(1000)), txflags(tfImmediateOrCancel), ter(expectedCode)); } env.require( - balance(alice, startBalance - f - f), - balance(alice, USD(1000)), - owners(alice, 1), - offers(alice, 0)); + balance(alice, startBalance - f - f), balance(alice, USD(1000)), owners(alice, 1), offers(alice, 0)); // Partially cross: env(offer(bob, USD(50), XRP(50)), ter(tesSUCCESS)); - env(offer(alice, XRP(1000), USD(1000)), - txflags(tfImmediateOrCancel), - ter(tesSUCCESS)); + env(offer(alice, XRP(1000), USD(1000)), txflags(tfImmediateOrCancel), ter(tesSUCCESS)); env.require( balance(alice, startBalance - f - f - f + XRP(50)), @@ -866,9 +791,7 @@ public: // Fully cross: env(offer(bob, USD(50), XRP(50)), ter(tesSUCCESS)); - env(offer(alice, XRP(50), USD(50)), - txflags(tfImmediateOrCancel), - ter(tesSUCCESS)); + env(offer(alice, XRP(50), USD(50)), txflags(tfImmediateOrCancel), ter(tesSUCCESS)); env.require( balance(alice, startBalance - f - f - f - f + XRP(100)), @@ -990,18 +913,12 @@ public: env.close(); // Order that has invalid flags - env(offer(alice, USD(1000), XRP(1000)), - txflags(tfImmediateOrCancel + 1), - ter(temINVALID_FLAG)); - env.require( - balance(alice, startBalance), owners(alice, 0), offers(alice, 0)); + env(offer(alice, USD(1000), XRP(1000)), txflags(tfImmediateOrCancel + 1), ter(temINVALID_FLAG)); + env.require(balance(alice, startBalance), owners(alice, 0), offers(alice, 0)); // Order with incompatible flags - env(offer(alice, USD(1000), XRP(1000)), - txflags(tfImmediateOrCancel | tfFillOrKill), - ter(temINVALID_FLAG)); - env.require( - balance(alice, startBalance), owners(alice, 0), offers(alice, 0)); + env(offer(alice, USD(1000), XRP(1000)), txflags(tfImmediateOrCancel | tfFillOrKill), ter(temINVALID_FLAG)); + env.require(balance(alice, startBalance), owners(alice, 0), offers(alice, 0)); // Sell and buy the same asset { @@ -1035,9 +952,7 @@ public: // Offer with a bad offer sequence { - env(offer(alice, USD(1000), XRP(1000)), - json(jss::OfferSequence, std::uint32_t(0)), - ter(temBAD_SEQUENCE)); + env(offer(alice, USD(1000), XRP(1000)), json(jss::OfferSequence, std::uint32_t(0)), ter(temBAD_SEQUENCE)); env.require(owners(alice, 1), offers(alice, 0)); } @@ -1076,40 +991,22 @@ public: env(trust(alice, usdOffer), ter(tesSUCCESS)); env(pay(gw, alice, usdOffer), ter(tesSUCCESS)); env.close(); - env.require( - balance(alice, startBalance - f), - balance(alice, usdOffer), - offers(alice, 0), - owners(alice, 1)); + env.require(balance(alice, startBalance - f), balance(alice, usdOffer), offers(alice, 0), owners(alice, 1)); - env(offer(alice, xrpOffer, usdOffer), - json(sfExpiration.fieldName, lastClose(env)), - ter(tecEXPIRED)); + env(offer(alice, xrpOffer, usdOffer), json(sfExpiration.fieldName, lastClose(env)), ter(tecEXPIRED)); - env.require( - balance(alice, startBalance - f - f), - balance(alice, usdOffer), - offers(alice, 0), - owners(alice, 1)); + env.require(balance(alice, startBalance - f - f), balance(alice, usdOffer), offers(alice, 0), owners(alice, 1)); env.close(); // Add an offer that expires before the next ledger close - env(offer(alice, xrpOffer, usdOffer), - json(sfExpiration.fieldName, lastClose(env) + 1), - ter(tesSUCCESS)); + env(offer(alice, xrpOffer, usdOffer), json(sfExpiration.fieldName, lastClose(env) + 1), ter(tesSUCCESS)); env.require( - balance(alice, startBalance - f - f - f), - balance(alice, usdOffer), - offers(alice, 1), - owners(alice, 2)); + balance(alice, startBalance - f - f - f), balance(alice, usdOffer), offers(alice, 1), owners(alice, 2)); // The offer expires (it's not removed yet) env.close(); env.require( - balance(alice, startBalance - f - f - f), - balance(alice, usdOffer), - offers(alice, 1), - owners(alice, 2)); + balance(alice, startBalance - f - f - f), balance(alice, usdOffer), offers(alice, 1), owners(alice, 2)); // Add offer - the expired offer is removed env(offer(bob, usdOffer, xrpOffer), ter(tesSUCCESS)); @@ -1165,8 +1062,7 @@ public: env.fund(reserve(env, 0) + f + XRP(1), "carol"); env.close(); env(offer("carol", usdOffer, xrpOffer), ter(tecINSUF_RESERVE_OFFER)); - env.require( - balance("carol", reserve(env, 0) + XRP(1)), owners("carol", 0)); + env.require(balance("carol", reserve(env, 0) + XRP(1)), owners("carol", 0)); // Account has enough for the reserve plus one // offer, and the fee. @@ -1180,16 +1076,13 @@ public: env.fund(reserve(env, 1) + f + xrpOffer, "eve"); env.close(); env(offer("eve", usdOffer, xrpOffer), ter(tesSUCCESS)); - env.require( - balance("eve", reserve(env, 1) + xrpOffer), owners("eve", 1)); + env.require(balance("eve", reserve(env, 1) + xrpOffer), owners("eve", 1)); } void testSelfCross(bool use_partner, FeatureBitset features) { - testcase( - std::string("Self-crossing") + - (use_partner ? ", with partner account" : "")); + testcase(std::string("Self-crossing") + (use_partner ? ", with partner account" : "")); using namespace jtx; @@ -1305,8 +1198,7 @@ public: // This is one of the few tests where fixReducedOffersV2 changes the // results. So test both with and without fixReducedOffersV2. - for (FeatureBitset localFeatures : - {features - fixReducedOffersV2, features | fixReducedOffersV2}) + for (FeatureBitset localFeatures : {features - fixReducedOffersV2, features | fixReducedOffersV2}) { Env env{*this, localFeatures}; @@ -1321,8 +1213,7 @@ public: auto const gw_initial_balance = drops(1149999730); auto const alice_initial_balance = drops(499946999680); auto const bob_initial_balance = drops(10199999920); - auto const small_amount = - STAmount{bob["USD"].issue(), UINT64_C(2710505431213761), -33}; + auto const small_amount = STAmount{bob["USD"].issue(), UINT64_C(2710505431213761), -33}; env.fund(gw_initial_balance, gw); env.fund(alice_initial_balance, alice); @@ -1348,13 +1239,10 @@ public: // verify balances auto jrr = ledgerEntryState(env, alice, gw, "USD"); - BEAST_EXPECT( - jrr[jss::node][sfBalance.fieldName][jss::value] == "50"); + BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "50"); jrr = ledgerEntryState(env, bob, gw, "USD"); - BEAST_EXPECT( - jrr[jss::node][sfBalance.fieldName][jss::value] == - "-2710505431213761e-33"); + BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-2710505431213761e-33"); // create crossing offer std::uint32_t const bobOfferSeq = env.seq(bob); @@ -1366,12 +1254,9 @@ public: // offer does not cross alice's offer and goes straight into // the ledger. jrr = ledgerEntryState(env, bob, gw, "USD"); - BEAST_EXPECT( - jrr[jss::node][sfBalance.fieldName][jss::value] == - "-2710505431213761e-33"); + BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-2710505431213761e-33"); - Json::Value const bobOffer = - ledgerEntryOffer(env, bob, bobOfferSeq)[jss::node]; + Json::Value const bobOffer = ledgerEntryOffer(env, bob, bobOfferSeq)[jss::node]; BEAST_EXPECT(bobOffer[sfTakerGets.jsonName][jss::value] == "1"); BEAST_EXPECT(bobOffer[sfTakerPays.jsonName] == "2000000000"); return; @@ -1387,29 +1272,22 @@ public: auto const crossingDelta = drops(1); jrr = ledgerEntryState(env, alice, gw, "USD"); - BEAST_EXPECT( - jrr[jss::node][sfBalance.fieldName][jss::value] == "50"); + BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "50"); BEAST_EXPECT( env.balance(alice, xrpIssue()) == - alice_initial_balance - env.current()->fees().base * 3 - - crossingDelta); + alice_initial_balance - env.current()->fees().base * 3 - crossingDelta); jrr = ledgerEntryState(env, bob, gw, "USD"); + BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "0"); BEAST_EXPECT( - jrr[jss::node][sfBalance.fieldName][jss::value] == "0"); - BEAST_EXPECT( - env.balance(bob, xrpIssue()) == - bob_initial_balance - env.current()->fees().base * 2 + - crossingDelta); + env.balance(bob, xrpIssue()) == bob_initial_balance - env.current()->fees().base * 2 + crossingDelta); } } void testOfferCrossWithXRP(bool reverse_order, FeatureBitset features) { - testcase( - std::string("Offer Crossing with XRP, ") + - (reverse_order ? "Reverse" : "Normal") + " order"); + testcase(std::string("Offer Crossing with XRP, ") + (reverse_order ? "Reverse" : "Normal") + " order"); using namespace jtx; @@ -1445,18 +1323,14 @@ public: jrr = ledgerEntryRoot(env, bob); BEAST_EXPECT( jrr[jss::node][sfBalance.fieldName] == - to_string((XRP(10000) - XRP(reverse_order ? 4000 : 3000) - - env.current()->fees().base * 2) - .xrp())); + to_string((XRP(10000) - XRP(reverse_order ? 4000 : 3000) - env.current()->fees().base * 2).xrp())); jrr = ledgerEntryState(env, alice, gw, "USD"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-499"); jrr = ledgerEntryRoot(env, alice); BEAST_EXPECT( jrr[jss::node][sfBalance.fieldName] == - to_string((XRP(10000) + XRP(reverse_order ? 4000 : 3000) - - env.current()->fees().base * 2) - .xrp())); + to_string((XRP(10000) + XRP(reverse_order ? 4000 : 3000) - env.current()->fees().base * 2).xrp())); } void @@ -1488,16 +1362,14 @@ public: jrr = ledgerEntryRoot(env, bob); BEAST_EXPECT( jrr[jss::node][sfBalance.fieldName] == - to_string((XRP(100000) - XRP(3000) - env.current()->fees().base * 1) - .xrp())); + to_string((XRP(100000) - XRP(3000) - env.current()->fees().base * 1).xrp())); jrr = ledgerEntryState(env, alice, gw, "USD"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-499"); jrr = ledgerEntryRoot(env, alice); BEAST_EXPECT( jrr[jss::node][sfBalance.fieldName] == - to_string((XRP(100000) + XRP(3000) - env.current()->fees().base * 2) - .xrp())); + to_string((XRP(100000) + XRP(3000) - env.current()->fees().base * 2).xrp())); } void @@ -1541,11 +1413,9 @@ public: env(offer_cancel(env.master, nextOfferSeq)); - env(offer_cancel(env.master, env.seq(env.master)), - ter(temBAD_SEQUENCE)); + env(offer_cancel(env.master, env.seq(env.master)), ter(temBAD_SEQUENCE)); - env(offer_cancel(env.master, env.seq(env.master) + 1), - ter(temBAD_SEQUENCE)); + env(offer_cancel(env.master, env.seq(env.master) + 1), ter(temBAD_SEQUENCE)); env.close(); } @@ -1579,11 +1449,8 @@ public: env.require(owners(alice, 1), owners(bob, 2)); auto jro = ledgerEntryOffer(env, bob, bobOfferSeq); - BEAST_EXPECT( - jro[jss::node][jss::TakerGets] == XRP(500).value().getText()); - BEAST_EXPECT( - jro[jss::node][jss::TakerPays] == - USD(100).value().getJson(JsonOptions::none)); + BEAST_EXPECT(jro[jss::node][jss::TakerGets] == XRP(500).value().getText()); + BEAST_EXPECT(jro[jss::node][jss::TakerPays] == USD(100).value().getJson(JsonOptions::none)); env(pay(alice, alice, XRP(500)), sendmax(USD(100))); @@ -1592,8 +1459,7 @@ public: jrr = ledgerEntryRoot(env, alice); BEAST_EXPECT( jrr[jss::node][sfBalance.fieldName] == - to_string((XRP(10000) + XRP(500) - env.current()->fees().base * 2) - .xrp())); + to_string((XRP(10000) + XRP(500) - env.current()->fees().base * 2).xrp())); jrr = ledgerEntryState(env, bob, gw, "USD"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-100"); @@ -1625,8 +1491,7 @@ public: env(trust(carol, bob["EUR"](1000))); auto const bobOfferSeq = env.seq(bob); - env(offer(bob, alice["USD"](50), carol["EUR"](200)), - ter(tecUNFUNDED_OFFER)); + env(offer(bob, alice["USD"](50), carol["EUR"](200)), ter(tecUNFUNDED_OFFER)); env(offer(alice, carol["EUR"](200), alice["USD"](50))); @@ -1663,11 +1528,8 @@ public: // The previous payment reduced the remaining offer amount by 200 XRP auto jro = ledgerEntryOffer(env, bob, bobOfferSeq); - BEAST_EXPECT( - jro[jss::node][jss::TakerGets] == XRP(300).value().getText()); - BEAST_EXPECT( - jro[jss::node][jss::TakerPays] == - USD(60).value().getJson(JsonOptions::none)); + BEAST_EXPECT(jro[jss::node][jss::TakerGets] == XRP(300).value().getText()); + BEAST_EXPECT(jro[jss::node][jss::TakerPays] == USD(60).value().getJson(JsonOptions::none)); // the balance between alice and gw is 160 USD..200 less the 40 taken // by the offer @@ -1677,8 +1539,7 @@ public: jrr = ledgerEntryRoot(env, alice); BEAST_EXPECT( jrr[jss::node][sfBalance.fieldName] == - to_string((XRP(10000) + XRP(200) - env.current()->fees().base * 2) - .xrp())); + to_string((XRP(10000) + XRP(200) - env.current()->fees().base * 2).xrp())); // bob got 40 USD from partial consumption of the offer jrr = ledgerEntryState(env, bob, gw, "USD"); @@ -1686,15 +1547,11 @@ public: // Alice converts USD to XRP which should fail // due to PartialPayment. - env(pay(alice, alice, XRP(600)), - sendmax(USD(100)), - ter(tecPATH_PARTIAL)); + env(pay(alice, alice, XRP(600)), sendmax(USD(100)), ter(tecPATH_PARTIAL)); // Alice converts USD to XRP, should succeed because // we permit partial payment - env(pay(alice, alice, XRP(600)), - sendmax(USD(100)), - txflags(tfPartialPayment)); + env(pay(alice, alice, XRP(600)), sendmax(USD(100)), txflags(tfPartialPayment)); // Verify the offer was consumed jro = ledgerEntryOffer(env, bob, bobOfferSeq); @@ -1710,9 +1567,7 @@ public: jrr = ledgerEntryRoot(env, alice); BEAST_EXPECT( jrr[jss::node][sfBalance.fieldName] == - to_string((XRP(10000) + XRP(200) + XRP(300) - - env.current()->fees().base * 4) - .xrp())); + to_string((XRP(10000) + XRP(200) + XRP(300) - env.current()->fees().base * 4).xrp())); // bob now has 100 USD - 40 from the first payment and 60 from the // second (partial) payment @@ -1755,11 +1610,8 @@ public: BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-475"); auto jro = ledgerEntryOffer(env, carol, carolOfferSeq); - BEAST_EXPECT( - jro[jss::node][jss::TakerGets] == - USD(25).value().getJson(JsonOptions::none)); - BEAST_EXPECT( - jro[jss::node][jss::TakerPays] == XRP(250).value().getText()); + BEAST_EXPECT(jro[jss::node][jss::TakerGets] == USD(25).value().getJson(JsonOptions::none)); + BEAST_EXPECT(jro[jss::node][jss::TakerPays] == XRP(250).value().getText()); } void @@ -1799,15 +1651,11 @@ public: jrr = ledgerEntryRoot(env, bob); BEAST_EXPECT( jrr[jss::node][sfBalance.fieldName] == - std::to_string( - XRP(10000).value().mantissa() + XRP(250).value().mantissa())); + std::to_string(XRP(10000).value().mantissa() + XRP(250).value().mantissa())); auto jro = ledgerEntryOffer(env, carol, carolOfferSeq); - BEAST_EXPECT( - jro[jss::node][jss::TakerGets] == XRP(250).value().getText()); - BEAST_EXPECT( - jro[jss::node][jss::TakerPays] == - USD(25).value().getJson(JsonOptions::none)); + BEAST_EXPECT(jro[jss::node][jss::TakerGets] == XRP(250).value().getText()); + BEAST_EXPECT(jro[jss::node][jss::TakerPays] == USD(25).value().getJson(JsonOptions::none)); } void @@ -1862,18 +1710,12 @@ public: BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-370"); auto jro = ledgerEntryOffer(env, carol, carolOfferSeq); - BEAST_EXPECT( - jro[jss::node][jss::TakerGets] == XRP(200).value().getText()); - BEAST_EXPECT( - jro[jss::node][jss::TakerPays] == - USD(20).value().getJson(JsonOptions::none)); + BEAST_EXPECT(jro[jss::node][jss::TakerGets] == XRP(200).value().getText()); + BEAST_EXPECT(jro[jss::node][jss::TakerPays] == USD(20).value().getJson(JsonOptions::none)); jro = ledgerEntryOffer(env, dan, danOfferSeq); - BEAST_EXPECT( - jro[jss::node][jss::TakerGets] == - gw2["EUR"](20).value().getJson(JsonOptions::none)); - BEAST_EXPECT( - jro[jss::node][jss::TakerPays] == XRP(200).value().getText()); + BEAST_EXPECT(jro[jss::node][jss::TakerGets] == gw2["EUR"](20).value().getJson(JsonOptions::none)); + BEAST_EXPECT(jro[jss::node][jss::TakerPays] == XRP(200).value().getText()); } void @@ -1967,9 +1809,7 @@ public: // fees: // 1 for each trust limit == 3 (alice < mtgox/amazon/bitstamp) + // 1 for payment == 4 - auto const starting_xrp = XRP(100) + - env.current()->fees().accountReserve(3) + - env.current()->fees().base * 4; + auto const starting_xrp = XRP(100) + env.current()->fees().accountReserve(3) + env.current()->fees().base * 4; env.fund(starting_xrp, gw1, gw2, gw3, alice, bob); env.close(); @@ -1991,8 +1831,7 @@ public: BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "100"); jrr = ledgerEntryRoot(env, alice); BEAST_EXPECT( - jrr[jss::node][sfBalance.fieldName] == - STAmount(env.current()->fees().accountReserve(3)).getText()); + jrr[jss::node][sfBalance.fieldName] == STAmount(env.current()->fees().accountReserve(3)).getText()); jrr = ledgerEntryState(env, bob, gw1, "USD"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-400"); @@ -2036,20 +1875,17 @@ public: env(offer(bob, XRP(100), USD(0.1))); auto jrr = ledgerEntryState(env, alice, gw, "USD"); - BEAST_EXPECT( - jrr[jss::node][sfBalance.fieldName][jss::value] == - "49.96666666666667"); + BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "49.96666666666667"); jrr = ledgerEntryState(env, bob, gw, "USD"); - Json::Value const bobsUSD = - jrr[jss::node][sfBalance.fieldName][jss::value]; + Json::Value const bobUSD = jrr[jss::node][sfBalance.fieldName][jss::value]; if (!NumberSwitchOver) { - BEAST_EXPECT(bobsUSD == "-0.966500000033334"); + BEAST_EXPECT(bobUSD == "-0.966500000033334"); } else { - BEAST_EXPECT(bobsUSD == "-0.9665000000333333"); + BEAST_EXPECT(bobUSD == "-0.9665000000333333"); } } } @@ -2068,9 +1904,7 @@ public: auto const bob = Account{"bob"}; auto const USD = gw["USD"]; - auto const starting_xrp = XRP(100) + - env.current()->fees().accountReserve(1) + - env.current()->fees().base * 2; + auto const starting_xrp = XRP(100) + env.current()->fees().accountReserve(1) + env.current()->fees().base * 2; env.fund(starting_xrp, gw, alice, bob); env.close(); @@ -2090,8 +1924,7 @@ public: BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-100"); jrr = ledgerEntryRoot(env, alice); BEAST_EXPECT( - jrr[jss::node][sfBalance.fieldName] == - STAmount(env.current()->fees().accountReserve(1)).getText()); + jrr[jss::node][sfBalance.fieldName] == STAmount(env.current()->fees().accountReserve(1)).getText()); jrr = ledgerEntryState(env, bob, gw, "USD"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-400"); @@ -2111,9 +1944,7 @@ public: auto const bob = Account{"bob"}; auto const USD = gw["USD"]; - auto const starting_xrp = XRP(100) + - env.current()->fees().accountReserve(1) + - env.current()->fees().base * 2; + auto const starting_xrp = XRP(100) + env.current()->fees().accountReserve(1) + env.current()->fees().base * 2; env.fund(starting_xrp, gw, alice, bob); env.close(); @@ -2135,8 +1966,7 @@ public: BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-200"); jrr = ledgerEntryRoot(env, alice); BEAST_EXPECT( - jrr[jss::node][sfBalance.fieldName] == - STAmount(env.current()->fees().accountReserve(1)).getText()); + jrr[jss::node][sfBalance.fieldName] == STAmount(env.current()->fees().accountReserve(1)).getText()); jrr = ledgerEntryState(env, bob, gw, "USD"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "-300"); @@ -2157,9 +1987,7 @@ public: auto const XTS = gw["XTS"]; auto const XXX = gw["XXX"]; - auto const starting_xrp = XRP(100.1) + - env.current()->fees().accountReserve(1) + - env.current()->fees().base * 2; + auto const starting_xrp = XRP(100.1) + env.current()->fees().accountReserve(1) + env.current()->fees().base * 2; env.fund(starting_xrp, gw, alice, bob); env.close(); @@ -2184,22 +2012,16 @@ public: payment[jss::id] = env.seq(bob); payment[jss::build_path] = true; payment[jss::tx_json] = pay(bob, bob, bob["XXX"](1)); - payment[jss::tx_json][jss::Sequence] = - env.current() - ->read(keylet::account(bob.id())) - ->getFieldU32(sfSequence); + payment[jss::tx_json][jss::Sequence] = env.current()->read(keylet::account(bob.id()))->getFieldU32(sfSequence); payment[jss::tx_json][jss::Fee] = to_string(env.current()->fees().base); - payment[jss::tx_json][jss::SendMax] = - bob["XTS"](1.5).value().getJson(JsonOptions::none); + payment[jss::tx_json][jss::SendMax] = bob["XTS"](1.5).value().getJson(JsonOptions::none); auto jrr = wsc->invoke("submit", payment); BEAST_EXPECT(jrr[jss::status] == "success"); BEAST_EXPECT(jrr[jss::result][jss::engine_result] == "tesSUCCESS"); if (wsc->version() == 2) { - BEAST_EXPECT( - jrr.isMember(jss::jsonrpc) && jrr[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jrr.isMember(jss::ripplerpc) && jrr[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jrr.isMember(jss::jsonrpc) && jrr[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jrr.isMember(jss::ripplerpc) && jrr[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jrr.isMember(jss::id) && jrr[jss::id] == 5); } @@ -2221,13 +2043,9 @@ public: // a trust line defined). If the trustline is not defaulted then the tests // will not pass. void - verifyDefaultTrustline( - jtx::Env& env, - jtx::Account const& account, - jtx::PrettyAmount const& expectBalance) + verifyDefaultTrustline(jtx::Env& env, jtx::Account const& account, jtx::PrettyAmount const& expectBalance) { - auto const sleTrust = - env.le(keylet::line(account.id(), expectBalance.value().issue())); + auto const sleTrust = env.le(keylet::line(account.id(), expectBalance.value().issue())); BEAST_EXPECT(sleTrust); if (sleTrust) { @@ -2370,8 +2188,7 @@ public: std::uint32_t const acctOfferSeq = env.seq(acct) - 1; BEAST_EXPECT(env.balance(acct, USD.issue()) == t.balanceUsd); - BEAST_EXPECT( - env.balance(acct, xrpIssue()) == t.fundXrp - t.spentXrp); + BEAST_EXPECT(env.balance(acct, xrpIssue()) == t.fundXrp - t.spentXrp); env.require(offers(acct, t.offers)); env.require(owners(acct, t.owners)); @@ -2396,8 +2213,7 @@ public: else { // Verify that no trustline was created. - auto const sleTrust = - env.le(keylet::line(acct, USD.issue())); + auto const sleTrust = env.le(keylet::line(acct, USD.issue())); BEAST_EXPECT(!sleTrust); } } @@ -2449,8 +2265,8 @@ public: // The scenario: // o alice has USD but wants XRP. // o bob has XRP but wants USD. - auto const alicesXRP = env.balance(alice); - auto const bobsXRP = env.balance(bob); + auto const aliceXRP = env.balance(alice); + auto const bobXRP = env.balance(bob); env(offer(alice, xrpOffer, usdOffer)); env.close(); @@ -2460,8 +2276,8 @@ public: env.require( balance(alice, USD(0)), balance(bob, usdOffer), - balance(alice, alicesXRP + xrpOffer - fee), - balance(bob, bobsXRP - xrpOffer - fee), + balance(alice, aliceXRP + xrpOffer - fee), + balance(bob, bobXRP - xrpOffer - fee), offers(alice, 0), offers(bob, 0)); @@ -2477,13 +2293,13 @@ public: env.require(offers(alice, 0)); verifyDefaultTrustline(env, bob, USD(1)); { - auto const bobsOffers = offersOnAccount(env, bob); - BEAST_EXPECT(bobsOffers.size() == 1); - auto const& bobsOffer = *(bobsOffers.front()); + auto const bobOffers = offersOnAccount(env, bob); + BEAST_EXPECT(bobOffers.size() == 1); + auto const& bobOffer = *(bobOffers.front()); - BEAST_EXPECT(bobsOffer[sfLedgerEntryType] == ltOFFER); - BEAST_EXPECT(bobsOffer[sfTakerGets] == USD(1)); - BEAST_EXPECT(bobsOffer[sfTakerPays] == XRP(1)); + BEAST_EXPECT(bobOffer[sfLedgerEntryType] == ltOFFER); + BEAST_EXPECT(bobOffer[sfTakerGets] == USD(1)); + BEAST_EXPECT(bobOffer[sfTakerPays] == XRP(1)); } } @@ -2534,11 +2350,7 @@ public: env(offer(bob, usdOffer, eurOffer)); env.close(); - env.require( - balance(alice, eurOffer), - balance(bob, usdOffer), - offers(alice, 0), - offers(bob, 0)); + env.require(balance(alice, eurOffer), balance(bob, usdOffer), offers(alice, 0), offers(bob, 0)); // Alice's offer crossing created a default EUR trustline and // Bob's offer crossing created a default USD trustline: @@ -2563,13 +2375,13 @@ public: env.require(balance(bob, EUR(999))); { - auto bobsOffers = offersOnAccount(env, bob); - if (BEAST_EXPECT(bobsOffers.size() == 1)) + auto bobOffers = offersOnAccount(env, bob); + if (BEAST_EXPECT(bobOffers.size() == 1)) { - auto const& bobsOffer = *(bobsOffers.front()); + auto const& bobOffer = *(bobOffers.front()); - BEAST_EXPECT(bobsOffer[sfTakerGets] == USD(1)); - BEAST_EXPECT(bobsOffer[sfTakerPays] == EUR(1)); + BEAST_EXPECT(bobOffer[sfTakerGets] == USD(1)); + BEAST_EXPECT(bobOffer[sfTakerPays] == EUR(1)); } } @@ -2658,22 +2470,22 @@ public: verifyDefaultTrustline(env, bob, EUR(400)); verifyDefaultTrustline(env, carol, USD(400)); { - auto const alicesOffers = offersOnAccount(env, alice); - BEAST_EXPECT(alicesOffers.size() == 1); - auto const& alicesOffer = *(alicesOffers.front()); + auto const aliceOffers = offersOnAccount(env, alice); + BEAST_EXPECT(aliceOffers.size() == 1); + auto const& aliceOffer = *(aliceOffers.front()); - BEAST_EXPECT(alicesOffer[sfLedgerEntryType] == ltOFFER); - BEAST_EXPECT(alicesOffer[sfTakerGets] == USD(600)); - BEAST_EXPECT(alicesOffer[sfTakerPays] == XRP(600)); + BEAST_EXPECT(aliceOffer[sfLedgerEntryType] == ltOFFER); + BEAST_EXPECT(aliceOffer[sfTakerGets] == USD(600)); + BEAST_EXPECT(aliceOffer[sfTakerPays] == XRP(600)); } { - auto const bobsOffers = offersOnAccount(env, bob); - BEAST_EXPECT(bobsOffers.size() == 1); - auto const& bobsOffer = *(bobsOffers.front()); + auto const bobOffers = offersOnAccount(env, bob); + BEAST_EXPECT(bobOffers.size() == 1); + auto const& bobOffer = *(bobOffers.front()); - BEAST_EXPECT(bobsOffer[sfLedgerEntryType] == ltOFFER); - BEAST_EXPECT(bobsOffer[sfTakerGets] == XRP(600)); - BEAST_EXPECT(bobsOffer[sfTakerPays] == EUR(600)); + BEAST_EXPECT(bobOffer[sfLedgerEntryType] == ltOFFER); + BEAST_EXPECT(bobOffer[sfTakerGets] == XRP(600)); + BEAST_EXPECT(bobOffer[sfTakerPays] == EUR(600)); } // carol makes an offer that exactly consumes alice and bob's offers. @@ -2691,15 +2503,15 @@ public: verifyDefaultTrustline(env, carol, USD(1000)); // In pre-flow code alice's offer is left empty in the ledger. - auto const alicesOffers = offersOnAccount(env, alice); - if (alicesOffers.size() != 0) + auto const aliceOffers = offersOnAccount(env, alice); + if (aliceOffers.size() != 0) { - BEAST_EXPECT(alicesOffers.size() == 1); - auto const& alicesOffer = *(alicesOffers.front()); + BEAST_EXPECT(aliceOffers.size() == 1); + auto const& aliceOffer = *(aliceOffers.front()); - BEAST_EXPECT(alicesOffer[sfLedgerEntryType] == ltOFFER); - BEAST_EXPECT(alicesOffer[sfTakerGets] == USD(0)); - BEAST_EXPECT(alicesOffer[sfTakerPays] == XRP(0)); + BEAST_EXPECT(aliceOffer[sfLedgerEntryType] == ltOFFER); + BEAST_EXPECT(aliceOffer[sfTakerGets] == USD(0)); + BEAST_EXPECT(aliceOffer[sfTakerPays] == XRP(0)); } } @@ -2865,8 +2677,7 @@ public: // Check results BEAST_EXPECT(env.balance(acct, USD.issue()) == t.finalUsd); - BEAST_EXPECT( - env.balance(acct, xrpIssue()) == t.fundXrp - t.spentXrp); + BEAST_EXPECT(env.balance(acct, xrpIssue()) == t.fundXrp - t.spentXrp); env.require(offers(acct, t.offers)); env.require(owners(acct, t.owners)); @@ -2923,8 +2734,7 @@ public: env.close(); { // alice submits a tfSell | tfFillOrKill offer that does not cross. - env(offer(alice, USD(21), XRP(2100), tfSell | tfFillOrKill), - ter(killedCode)); + env(offer(alice, USD(21), XRP(2100), tfSell | tfFillOrKill), ter(killedCode)); env.close(); env.require(balance(alice, USD(none))); env.require(offers(alice, 0)); @@ -2957,8 +2767,7 @@ public: // all of the offer is consumed. // We're using bob's left-over offer for XRP(500), USD(5) - env(offer(alice, USD(1), XRP(501), tfSell | tfFillOrKill), - ter(killedCode)); + env(offer(alice, USD(1), XRP(501), tfSell | tfFillOrKill), ter(killedCode)); env.close(); env.require(balance(alice, USD(35))); env.require(offers(alice, 0)); @@ -3870,16 +3679,16 @@ public: // Place alice's tiny offer in the book first. Let's see what happens // when a reasonable offer crosses it. - STAmount const alicesCnyOffer{ + STAmount const aliceCnyOffer{ CNY.issue(), std::uint64_t(4926000000000000), -23}; - env(offer(alice, alicesCnyOffer, drops(1), tfPassive)); + env(offer(alice, aliceCnyOffer, drops(1), tfPassive)); env.close(); // bob places an ordinary offer - STAmount const bobsCnyStartBalance{ + STAmount const bobCnyStartBalance{ CNY.issue(), std::uint64_t(3767479960090235), -15}; - env(pay(gw, bob, bobsCnyStartBalance)); + env(pay(gw, bob, bobCnyStartBalance)); env.close(); env(offer( @@ -3888,9 +3697,9 @@ public: STAmount{CNY.issue(), std::uint64_t(1000000000000000), -20})); env.close(); - env.require(balance(alice, alicesCnyOffer)); + env.require(balance(alice, aliceCnyOffer)); env.require(balance(alice, startXrpBalance - fee - drops(1))); - env.require(balance(bob, bobsCnyStartBalance - alicesCnyOffer)); + env.require(balance(bob, bobCnyStartBalance - aliceCnyOffer)); env.require(balance(bob, startXrpBalance - (fee * 2) + drops(1))); } @@ -4026,12 +3835,9 @@ public: auto actorOffers = offersOnAccount(env, actor.acct); auto const offerCount = std::distance( actorOffers.begin(), - std::remove_if( - actorOffers.begin(), - actorOffers.end(), - [](std::shared_ptr& offer) { - return (*offer)[sfTakerGets].signum() == 0; - })); + std::remove_if(actorOffers.begin(), actorOffers.end(), [](std::shared_ptr& offer) { + return (*offer)[sfTakerGets].signum() == 0; + })); BEAST_EXPECT(offerCount == actor.offers); env.require(balance(actor.acct, actor.xrp)); @@ -4175,12 +3981,9 @@ public: auto actorOffers = offersOnAccount(env, actor.acct); auto const offerCount = std::distance( actorOffers.begin(), - std::remove_if( - actorOffers.begin(), - actorOffers.end(), - [](std::shared_ptr& offer) { - return (*offer)[sfTakerGets].signum() == 0; - })); + std::remove_if(actorOffers.begin(), actorOffers.end(), [](std::shared_ptr& offer) { + return (*offer)[sfTakerGets].signum() == 0; + })); BEAST_EXPECT(offerCount == actor.offers); env.require(balance(actor.acct, actor.xrp)); @@ -4430,12 +4233,10 @@ public: // MM places offers float const rate = 0.9f; // 0.9 USD = 1 EUR - env(offer(mm, EUR(4000000 * rate), USD(4000000)), - json(jss::Flags, tfSell)); + env(offer(mm, EUR(4000000 * rate), USD(4000000)), json(jss::Flags, tfSell)); float const reverseRate = 1.0f / rate * 1.00101f; - env(offer(mm, USD(4000000 * reverseRate), EUR(4000000)), - json(jss::Flags, tfSell)); + env(offer(mm, USD(4000000 * reverseRate), EUR(4000000)), json(jss::Flags, tfSell)); env.close(); // There should be a path available from hot US to cold EUR @@ -4447,13 +4248,10 @@ public: jvParams[jss::destination_amount][jss::value] = 10; jvParams[jss::source_account] = hotUS.human(); - Json::Value const jrr{env.rpc( - "json", "ripple_path_find", to_string(jvParams))[jss::result]}; + Json::Value const jrr{env.rpc("json", "ripple_path_find", to_string(jvParams))[jss::result]}; BEAST_EXPECT(jrr[jss::status] == "success"); - BEAST_EXPECT( - jrr[jss::alternatives].isArray() && - jrr[jss::alternatives].size() > 0); + BEAST_EXPECT(jrr[jss::alternatives].isArray() && jrr[jss::alternatives].size() > 0); } // Send the payment using the found path. env(pay(hotUS, coldEU, EUR(10)), sendmax(USD(11.1223326))); @@ -4531,10 +4329,8 @@ public: testcase("Deleted offer issuer"); - auto trustLineExists = [](jtx::Env const& env, - jtx::Account const& src, - jtx::Account const& dst, - Currency const& cur) -> bool { + auto trustLineExists = + [](jtx::Env const& env, jtx::Account const& src, jtx::Account const& dst, Currency const& cur) -> bool { return bool(env.le(keylet::line(src, dst, cur))); }; @@ -4574,8 +4370,7 @@ public: { // The ledger sequence needs to far enough ahead of the account // sequence before the account can be deleted. - int const delta = - [&env, &gw, openLedgerSeq = env.current()->seq()]() -> int { + int const delta = [&env, &gw, openLedgerSeq = env.current()->seq()]() -> int { std::uint32_t const gwSeq{env.seq(gw)}; if (gwSeq + 255 > openLedgerSeq) return gwSeq - openLedgerSeq + 255; @@ -4586,8 +4381,7 @@ public: env.close(); // Account deletion has a high fee. Account for that. - env(acctdelete(gw, alice), - fee(drops(env.current()->fees().increment))); + env(acctdelete(gw, alice), fee(drops(env.current()->fees().increment))); env.close(); // Verify that gw's account root is gone from the ledger. @@ -4700,40 +4494,31 @@ public: env(offer(alice, XTS(30), XXX(10)), json(jss::Flags, tfSell)); std::map> offers; - forEachItem( - *env.current(), alice, [&](std::shared_ptr const& sle) { - if (sle->getType() == ltOFFER) - offers.emplace( - (*sle)[sfSequence], - std::make_pair( - (*sle)[sfTakerPays], (*sle)[sfTakerGets])); - }); + forEachItem(*env.current(), alice, [&](std::shared_ptr const& sle) { + if (sle->getType() == ltOFFER) + offers.emplace((*sle)[sfSequence], std::make_pair((*sle)[sfTakerPays], (*sle)[sfTakerGets])); + }); // first offer auto it = offers.begin(); BEAST_EXPECT(it != offers.end()); - BEAST_EXPECT( - it->second.first == XTS(10) && it->second.second < XXX(30) && - it->second.second > XXX(29.9994)); + BEAST_EXPECT(it->second.first == XTS(10) && it->second.second < XXX(30) && it->second.second > XXX(29.9994)); // second offer ++it; BEAST_EXPECT(it != offers.end()); - BEAST_EXPECT( - it->second.first == XTS(30) && it->second.second == XXX(10)); + BEAST_EXPECT(it->second.first == XTS(30) && it->second.second == XXX(10)); // third offer ++it; BEAST_EXPECT(it != offers.end()); - BEAST_EXPECT( - it->second.first == XTS(10.0002) && it->second.second == XXX(30)); + BEAST_EXPECT(it->second.first == XTS(10.0002) && it->second.second == XXX(30)); // fourth offer // exact TakerPays is XTS(1/.033333) ++it; BEAST_EXPECT(it != offers.end()); - BEAST_EXPECT( - it->second.first == XTS(30) && it->second.second == XXX(10)); + BEAST_EXPECT(it->second.first == XTS(30) && it->second.second == XXX(10)); BEAST_EXPECT(++it == offers.end()); } @@ -4742,13 +4527,11 @@ public: static std::vector> sortedOffersOnAccount(jtx::Env& env, jtx::Account const& acct) { - std::vector> offers{ - offersOnAccount(env, acct)}; + std::vector> offers{offersOnAccount(env, acct)}; std::sort( offers.begin(), offers.end(), - [](std::shared_ptr const& rhs, - std::shared_ptr const& lhs) { + [](std::shared_ptr const& rhs, std::shared_ptr const& lhs) { return (*rhs)[sfSequence] < (*lhs)[sfSequence]; }); return offers; @@ -5038,15 +4821,12 @@ public: // tfFillOrKill, TakerPays must be filled { - TER const err = - features[fixFillOrKill] ? TER(tesSUCCESS) : tecKILLED; + TER const err = features[fixFillOrKill] ? TER(tesSUCCESS) : tecKILLED; env(offer(maker, XRP(100), USD(100))); env.close(); - env(offer(taker, USD(100), XRP(101)), - txflags(tfFillOrKill), - ter(err)); + env(offer(taker, USD(100), XRP(101)), txflags(tfFillOrKill), ter(err)); env.close(); makerXRPBalance -= txfee(env, 1); @@ -5063,9 +4843,7 @@ public: env(offer(maker, USD(100), XRP(100))); env.close(); - env(offer(taker, XRP(100), USD(101)), - txflags(tfFillOrKill), - ter(err)); + env(offer(taker, XRP(100), USD(101)), txflags(tfFillOrKill), ter(err)); env.close(); makerXRPBalance -= txfee(env, 1); @@ -5082,9 +4860,7 @@ public: env(offer(maker, USD(100), EUR(100))); env.close(); - env(offer(taker, EUR(100), USD(101)), - txflags(tfFillOrKill), - ter(err)); + env(offer(taker, EUR(100), USD(101)), txflags(tfFillOrKill), ter(err)); env.close(); makerXRPBalance -= txfee(env, 1); @@ -5104,8 +4880,7 @@ public: env(offer(maker, XRP(101), USD(101))); env.close(); - env(offer(taker, USD(100), XRP(101)), - txflags(tfFillOrKill | tfSell)); + env(offer(taker, USD(100), XRP(101)), txflags(tfFillOrKill | tfSell)); env.close(); makerUSDBalance -= USD(101); @@ -5117,8 +4892,7 @@ public: env(offer(maker, USD(101), XRP(101))); env.close(); - env(offer(taker, XRP(100), USD(101)), - txflags(tfFillOrKill | tfSell)); + env(offer(taker, XRP(100), USD(101)), txflags(tfFillOrKill | tfSell)); env.close(); makerUSDBalance += USD(101); @@ -5130,8 +4904,7 @@ public: env(offer(maker, USD(101), EUR(101))); env.close(); - env(offer(taker, EUR(100), USD(101)), - txflags(tfFillOrKill | tfSell)); + env(offer(taker, EUR(100), USD(101)), txflags(tfFillOrKill | tfSell)); env.close(); makerUSDBalance += USD(101); @@ -5149,9 +4922,7 @@ public: env(offer(maker, XRP(100), USD(100))); env.close(); - env(offer(taker, USD(100), XRP(99)), - txflags(flags), - ter(tecKILLED)); + env(offer(taker, USD(100), XRP(99)), txflags(flags), ter(tecKILLED)); env.close(); makerXRPBalance -= txfee(env, 1); @@ -5161,9 +4932,7 @@ public: env(offer(maker, USD(100), XRP(100))); env.close(); - env(offer(taker, XRP(100), USD(99)), - txflags(flags), - ter(tecKILLED)); + env(offer(taker, XRP(100), USD(99)), txflags(flags), ter(tecKILLED)); env.close(); makerXRPBalance -= txfee(env, 1); @@ -5173,9 +4942,7 @@ public: env(offer(maker, USD(100), EUR(100))); env.close(); - env(offer(taker, EUR(100), USD(99)), - txflags(flags), - ter(tecKILLED)); + env(offer(taker, EUR(100), USD(99)), txflags(flags), ter(tecKILLED)); env.close(); makerXRPBalance -= txfee(env, 1); @@ -5184,12 +4951,9 @@ public: } BEAST_EXPECT( - env.balance(maker, USD) == makerUSDBalance && - env.balance(taker, USD) == takerUSDBalance && - env.balance(maker, EUR) == makerEURBalance && - env.balance(taker, EUR) == takerEURBalance && - env.balance(maker, XRP) == makerXRPBalance && - env.balance(taker, XRP) == takerXRPBalance); + env.balance(maker, USD) == makerUSDBalance && env.balance(taker, USD) == takerUSDBalance && + env.balance(maker, EUR) == makerEURBalance && env.balance(taker, EUR) == takerEURBalance && + env.balance(maker, XRP) == makerXRPBalance && env.balance(taker, XRP) == takerXRPBalance); } void diff --git a/src/test/app/Oracle_test.cpp b/src/test/app/Oracle_test.cpp index 6708f56275..66a8969164 100644 --- a/src/test/app/Oracle_test.cpp +++ b/src/test/app/Oracle_test.cpp @@ -44,14 +44,8 @@ private: // Insufficient reserve if the data series extends to greater than 5 { Env env(*this); - env.fund( - env.current()->fees().accountReserve(1) + - env.current()->fees().base * 2, - owner); - Oracle oracle( - env, - {.owner = owner, - .fee = static_cast(env.current()->fees().base.drops())}); + env.fund(env.current()->fees().accountReserve(1) + env.current()->fees().base * 2, owner); + Oracle oracle(env, {.owner = owner, .fee = static_cast(env.current()->fees().base.drops())}); BEAST_EXPECT(oracle.exists()); oracle.set(UpdateArg{ .series = @@ -68,40 +62,31 @@ private: { Env env(*this); - auto const baseFee = - static_cast(env.current()->fees().base.drops()); + auto const baseFee = static_cast(env.current()->fees().base.drops()); env.fund(XRP(1'000), owner); Oracle oracle(env, {.owner = owner, .fee = baseFee}, false); // Invalid flag - oracle.set(CreateArg{ - .flags = tfSellNFToken, - .fee = baseFee, - .err = ter(temINVALID_FLAG)}); + oracle.set(CreateArg{.flags = tfSellNFToken, .fee = baseFee, .err = ter(temINVALID_FLAG)}); // Duplicate token pair oracle.set(CreateArg{ - .series = {{"XRP", "USD", 740, 1}, {"XRP", "USD", 750, 1}}, - .fee = baseFee, - .err = ter(temMALFORMED)}); + .series = {{"XRP", "USD", 740, 1}, {"XRP", "USD", 750, 1}}, .fee = baseFee, .err = ter(temMALFORMED)}); // Price is not included oracle.set(CreateArg{ - .series = - {{"XRP", "USD", 740, 1}, {"XRP", "EUR", std::nullopt, 1}}, + .series = {{"XRP", "USD", 740, 1}, {"XRP", "EUR", std::nullopt, 1}}, .fee = baseFee, .err = ter(temMALFORMED)}); // Token pair is in update and delete oracle.set(CreateArg{ - .series = - {{"XRP", "USD", 740, 1}, {"XRP", "USD", std::nullopt, 1}}, + .series = {{"XRP", "USD", 740, 1}, {"XRP", "USD", std::nullopt, 1}}, .fee = baseFee, .err = ter(temMALFORMED)}); // Token pair is in add and delete oracle.set(CreateArg{ - .series = - {{"XRP", "EUR", 740, 1}, {"XRP", "EUR", std::nullopt, 1}}, + .series = {{"XRP", "EUR", 740, 1}, {"XRP", "EUR", std::nullopt, 1}}, .fee = baseFee, .err = ter(temMALFORMED)}); @@ -121,23 +106,16 @@ private: {"XRP", "U11", 740, 1}}, .fee = baseFee, .err = ter(temARRAY_TOO_LARGE)}); - oracle.set(CreateArg{ - .series = {}, .fee = baseFee, .err = ter(temARRAY_EMPTY)}); + oracle.set(CreateArg{.series = {}, .fee = baseFee, .err = ter(temARRAY_EMPTY)}); } // Array of token pair exceeds 10 after update { Env env{*this}; - auto const baseFee = - static_cast(env.current()->fees().base.drops()); + auto const baseFee = static_cast(env.current()->fees().base.drops()); env.fund(XRP(1'000), owner); - Oracle oracle( - env, - CreateArg{ - .owner = owner, - .series = {{{"XRP", "USD", 740, 1}}}, - .fee = baseFee}); + Oracle oracle(env, CreateArg{.owner = owner, .series = {{{"XRP", "USD", 740, 1}}}, .fee = baseFee}); oracle.set(UpdateArg{ .series = { @@ -158,17 +136,13 @@ private: { Env env(*this); - auto const baseFee = - static_cast(env.current()->fees().base.drops()); + auto const baseFee = static_cast(env.current()->fees().base.drops()); env.fund(XRP(1'000), owner); Oracle oracle(env, {.owner = owner, .fee = baseFee}, false); // Asset class or provider not included on create oracle.set(CreateArg{ - .assetClass = std::nullopt, - .provider = "provider", - .fee = baseFee, - .err = ter(temMALFORMED)}); + .assetClass = std::nullopt, .provider = "provider", .fee = baseFee, .err = ter(temMALFORMED)}); oracle.set(CreateArg{ .assetClass = "currency", .provider = std::nullopt, @@ -178,14 +152,10 @@ private: // Asset class or provider are included on update // and don't match the current values - oracle.set(CreateArg{ - .fee = static_cast(env.current()->fees().base.drops())}); + oracle.set(CreateArg{.fee = static_cast(env.current()->fees().base.drops())}); BEAST_EXPECT(oracle.exists()); oracle.set(UpdateArg{ - .series = {{"XRP", "USD", 740, 1}}, - .provider = "provider1", - .fee = baseFee, - .err = ter(temMALFORMED)}); + .series = {{"XRP", "USD", 740, 1}}, .provider = "provider1", .fee = baseFee, .err = ter(temMALFORMED)}); oracle.set(UpdateArg{ .series = {{"XRP", "USD", 740, 1}}, .assetClass = "currency1", @@ -195,68 +165,49 @@ private: { Env env(*this); - auto const baseFee = - static_cast(env.current()->fees().base.drops()); + auto const baseFee = static_cast(env.current()->fees().base.drops()); env.fund(XRP(1'000), owner); Oracle oracle(env, {.owner = owner, .fee = baseFee}, false); // Fields too long // Asset class std::string assetClass(17, '0'); - oracle.set(CreateArg{ - .assetClass = assetClass, - .fee = baseFee, - .err = ter(temMALFORMED)}); + oracle.set(CreateArg{.assetClass = assetClass, .fee = baseFee, .err = ter(temMALFORMED)}); // provider std::string const large(257, '0'); - oracle.set(CreateArg{ - .provider = large, .fee = baseFee, .err = ter(temMALFORMED)}); + oracle.set(CreateArg{.provider = large, .fee = baseFee, .err = ter(temMALFORMED)}); // URI - oracle.set(CreateArg{ - .uri = large, .fee = baseFee, .err = ter(temMALFORMED)}); + oracle.set(CreateArg{.uri = large, .fee = baseFee, .err = ter(temMALFORMED)}); // Empty field // Asset class - oracle.set(CreateArg{ - .assetClass = "", .fee = baseFee, .err = ter(temMALFORMED)}); + oracle.set(CreateArg{.assetClass = "", .fee = baseFee, .err = ter(temMALFORMED)}); // provider - oracle.set(CreateArg{ - .provider = "", .fee = baseFee, .err = ter(temMALFORMED)}); + oracle.set(CreateArg{.provider = "", .fee = baseFee, .err = ter(temMALFORMED)}); // URI - oracle.set( - CreateArg{.uri = "", .fee = baseFee, .err = ter(temMALFORMED)}); + oracle.set(CreateArg{.uri = "", .fee = baseFee, .err = ter(temMALFORMED)}); } { // Different owner creates a new object and fails because // of missing fields currency/provider Env env(*this); - auto const baseFee = - static_cast(env.current()->fees().base.drops()); + auto const baseFee = static_cast(env.current()->fees().base.drops()); Account const some("some"); env.fund(XRP(1'000), owner); env.fund(XRP(1'000), some); Oracle oracle(env, {.owner = owner, .fee = baseFee}); BEAST_EXPECT(oracle.exists()); - oracle.set(UpdateArg{ - .owner = some, - .series = {{"XRP", "USD", 740, 1}}, - .fee = baseFee, - .err = ter(temMALFORMED)}); + oracle.set( + UpdateArg{.owner = some, .series = {{"XRP", "USD", 740, 1}}, .fee = baseFee, .err = ter(temMALFORMED)}); } { // Invalid update time using namespace std::chrono; Env env(*this); - auto const baseFee = - static_cast(env.current()->fees().base.drops()); + auto const baseFee = static_cast(env.current()->fees().base.drops()); auto closeTime = [&]() { - return duration_cast( - env.current() - ->header() - .closeTime.time_since_epoch() - - 10'000s) - .count(); + return duration_cast(env.current()->header().closeTime.time_since_epoch() - 10'000s).count(); }; env.fund(XRP(1'000), owner); Oracle oracle(env, {.owner = owner, .fee = baseFee}); @@ -274,10 +225,8 @@ private: .lastUpdateTime = static_cast(closeTime() + 311), .fee = baseFee, .err = ter(tecINVALID_UPDATE_TIME)}); - oracle.set( - UpdateArg{.series = {{"XRP", "USD", 740, 1}}, .fee = baseFee}); - BEAST_EXPECT(oracle.expectLastUpdateTime( - static_cast(testStartTime.count() + 450))); + oracle.set(UpdateArg{.series = {{"XRP", "USD", 740, 1}}, .fee = baseFee}); + BEAST_EXPECT(oracle.expectLastUpdateTime(static_cast(testStartTime.count() + 450))); // Less than the previous lastUpdateTime oracle.set(UpdateArg{ .series = {{"XRP", "USD", 740, 1}}, @@ -295,8 +244,7 @@ private: { // delete token pair that doesn't exist Env env(*this); - auto const baseFee = - static_cast(env.current()->fees().base.drops()); + auto const baseFee = static_cast(env.current()->fees().base.drops()); env.fund(XRP(1'000), owner); Oracle oracle(env, {.owner = owner, .fee = baseFee}); BEAST_EXPECT(oracle.exists()); @@ -306,30 +254,22 @@ private: .err = ter(tecTOKEN_PAIR_NOT_FOUND)}); // delete all token pairs oracle.set(UpdateArg{ - .series = {{"XRP", "USD", std::nullopt, std::nullopt}}, - .fee = baseFee, - .err = ter(tecARRAY_EMPTY)}); + .series = {{"XRP", "USD", std::nullopt, std::nullopt}}, .fee = baseFee, .err = ter(tecARRAY_EMPTY)}); } { // same BaseAsset and QuoteAsset Env env(*this); - auto const baseFee = - static_cast(env.current()->fees().base.drops()); + auto const baseFee = static_cast(env.current()->fees().base.drops()); env.fund(XRP(1'000), owner); Oracle oracle( - env, - {.owner = owner, - .series = {{"USD", "USD", 740, 1}}, - .fee = baseFee, - .err = ter(temMALFORMED)}); + env, {.owner = owner, .series = {{"USD", "USD", 740, 1}}, .fee = baseFee, .err = ter(temMALFORMED)}); } { // Scale is greater than maxPriceScale Env env(*this); - auto const baseFee = - static_cast(env.current()->fees().base.drops()); + auto const baseFee = static_cast(env.current()->fees().base.drops()); env.fund(XRP(1'000), owner); Oracle oracle( env, @@ -342,14 +282,11 @@ private: { // Updating token pair to add and delete Env env(*this); - auto const baseFee = - static_cast(env.current()->fees().base.drops()); + auto const baseFee = static_cast(env.current()->fees().base.drops()); env.fund(XRP(1'000), owner); Oracle oracle(env, {.owner = owner, .fee = baseFee}); oracle.set(UpdateArg{ - .series = - {{"XRP", "EUR", std::nullopt, std::nullopt}, - {"XRP", "EUR", 740, 1}}, + .series = {{"XRP", "EUR", std::nullopt, std::nullopt}, {"XRP", "EUR", 740, 1}}, .fee = baseFee, .err = ter(temMALFORMED)}); // Delete token pair that doesn't exist in this oracle @@ -369,14 +306,9 @@ private: // Bad fee Env env(*this); env.fund(XRP(1'000), owner); - Oracle oracle( - env, {.owner = owner, .fee = -1, .err = ter(temBAD_FEE)}); - Oracle oracle1( - env, - {.owner = owner, - .fee = static_cast(env.current()->fees().base.drops())}); - oracle.set( - UpdateArg{.owner = owner, .fee = -1, .err = ter(temBAD_FEE)}); + Oracle oracle(env, {.owner = owner, .fee = -1, .err = ter(temBAD_FEE)}); + Oracle oracle1(env, {.owner = owner, .fee = static_cast(env.current()->fees().base.drops())}); + oracle.set(UpdateArg{.owner = owner, .fee = -1, .err = ter(temBAD_FEE)}); } } @@ -388,21 +320,17 @@ private: Account const owner("owner"); auto test = [&](Env& env, DataSeries const& series, std::uint16_t adj) { - auto const baseFee = - static_cast(env.current()->fees().base.drops()); + auto const baseFee = static_cast(env.current()->fees().base.drops()); env.fund(XRP(1'000), owner); auto const count = ownerCount(env, owner); - Oracle oracle( - env, {.owner = owner, .series = series, .fee = baseFee}); + Oracle oracle(env, {.owner = owner, .series = series, .fee = baseFee}); BEAST_EXPECT(oracle.exists()); BEAST_EXPECT(ownerCount(env, owner) == (count + adj)); auto const entry = oracle.ledgerEntry(); BEAST_EXPECT(entry[jss::node][jss::Owner] == owner.human()); if (features[fixIncludeKeyletFields]) { - BEAST_EXPECT( - entry[jss::node][jss::OracleDocumentID] == - oracle.documentID()); + BEAST_EXPECT(entry[jss::node][jss::OracleDocumentID] == oracle.documentID()); } else { @@ -434,17 +362,13 @@ private: { // Different owner creates a new object Env env(*this, features); - auto const baseFee = - static_cast(env.current()->fees().base.drops()); + auto const baseFee = static_cast(env.current()->fees().base.drops()); Account const some("some"); env.fund(XRP(1'000), owner); env.fund(XRP(1'000), some); Oracle oracle(env, {.owner = owner, .fee = baseFee}); BEAST_EXPECT(oracle.exists()); - oracle.set(CreateArg{ - .owner = some, - .series = {{"912810RR9", "USD", 740, 1}}, - .fee = baseFee}); + oracle.set(CreateArg{.owner = some, .series = {{"912810RR9", "USD", 740, 1}}, .fee = baseFee}); BEAST_EXPECT(Oracle::exists(env, some, oracle.documentID())); } } @@ -456,8 +380,7 @@ private: using namespace jtx; Env env(*this); - auto const baseFee = - static_cast(env.current()->fees().base.drops()); + auto const baseFee = static_cast(env.current()->fees().base.drops()); Account const owner("owner"); env.fund(XRP(1'000), owner); Oracle oracle(env, {.owner = owner, .fee = baseFee}); @@ -467,28 +390,19 @@ private: // Invalid account Account const bad("bad"); env.memoize(bad); - oracle.remove( - {.owner = bad, - .seq = seq(1), - .fee = baseFee, - .err = ter(terNO_ACCOUNT)}); + oracle.remove({.owner = bad, .seq = seq(1), .fee = baseFee, .err = ter(terNO_ACCOUNT)}); } // Invalid DocumentID - oracle.remove( - {.documentID = 2, .fee = baseFee, .err = ter(tecNO_ENTRY)}); + oracle.remove({.documentID = 2, .fee = baseFee, .err = ter(tecNO_ENTRY)}); // Invalid owner Account const invalid("invalid"); env.fund(XRP(1'000), invalid); - oracle.remove( - {.owner = invalid, .fee = baseFee, .err = ter(tecNO_ENTRY)}); + oracle.remove({.owner = invalid, .fee = baseFee, .err = ter(tecNO_ENTRY)}); // Invalid flags - oracle.remove( - {.flags = tfSellNFToken, - .fee = baseFee, - .err = ter(temINVALID_FLAG)}); + oracle.remove({.flags = tfSellNFToken, .fee = baseFee, .err = ter(temINVALID_FLAG)}); // Bad fee oracle.remove({.fee = -1, .err = ter(temBAD_FEE)}); @@ -502,11 +416,9 @@ private: Account const owner("owner"); auto test = [&](Env& env, DataSeries const& series, std::uint16_t adj) { - auto const baseFee = - static_cast(env.current()->fees().base.drops()); + auto const baseFee = static_cast(env.current()->fees().base.drops()); env.fund(XRP(1'000), owner); - Oracle oracle( - env, {.owner = owner, .series = series, .fee = baseFee}); + Oracle oracle(env, {.owner = owner, .series = series, .fee = baseFee}); auto const count = ownerCount(env, owner); BEAST_EXPECT(oracle.exists()); oracle.remove({.fee = baseFee}); @@ -539,24 +451,14 @@ private: { // deleting the account deletes the oracles Env env(*this); - auto const baseFee = - static_cast(env.current()->fees().base.drops()); + auto const baseFee = static_cast(env.current()->fees().base.drops()); auto const alice = Account("alice"); auto const acctDelFee{drops(env.current()->fees().increment)}; env.fund(XRP(1'000), owner); env.fund(XRP(1'000), alice); - Oracle oracle( - env, - {.owner = owner, - .series = {{"XRP", "USD", 740, 1}}, - .fee = baseFee}); - Oracle oracle1( - env, - {.owner = owner, - .documentID = 2, - .series = {{"XRP", "EUR", 740, 1}}, - .fee = baseFee}); + Oracle oracle(env, {.owner = owner, .series = {{"XRP", "USD", 740, 1}}, .fee = baseFee}); + Oracle oracle1(env, {.owner = owner, .documentID = 2, .series = {{"XRP", "EUR", 740, 1}}, .fee = baseFee}); BEAST_EXPECT(ownerCount(env, owner) == 2); BEAST_EXPECT(oracle.exists()); BEAST_EXPECT(oracle1.exists()); @@ -575,8 +477,7 @@ private: jvParams[field] = value; jvParams[jss::binary] = false; jvParams[jss::type] = jss::oracle; - Json::Value jrr = - env.rpc("json", "ledger_data", to_string(jvParams)); + Json::Value jrr = env.rpc("json", "ledger_data", to_string(jvParams)); BEAST_EXPECT(jrr[jss::result][jss::state].size() == 2); }; verifyLedgerData(jss::ledger_index, index); @@ -593,16 +494,14 @@ private: { Env env(*this); - auto const baseFee = - static_cast(env.current()->fees().base.drops()); + auto const baseFee = static_cast(env.current()->fees().base.drops()); env.fund(XRP(1'000), owner); auto count = ownerCount(env, owner); Oracle oracle(env, {.owner = owner, .fee = baseFee}); BEAST_EXPECT(oracle.exists()); // update existing pair - oracle.set( - UpdateArg{.series = {{"XRP", "USD", 740, 2}}, .fee = baseFee}); + oracle.set(UpdateArg{.series = {{"XRP", "USD", 740, 2}}, .fee = baseFee}); BEAST_EXPECT(oracle.expectPrice({{"XRP", "USD", 740, 2}})); // owner count is increased by 1 since the oracle object is added // with one token pair @@ -610,19 +509,14 @@ private: BEAST_EXPECT(ownerCount(env, owner) == count); // add new pairs, not-included pair is reset - oracle.set( - UpdateArg{.series = {{"XRP", "EUR", 700, 2}}, .fee = baseFee}); - BEAST_EXPECT(oracle.expectPrice( - {{"XRP", "USD", 0, 0}, {"XRP", "EUR", 700, 2}})); + oracle.set(UpdateArg{.series = {{"XRP", "EUR", 700, 2}}, .fee = baseFee}); + BEAST_EXPECT(oracle.expectPrice({{"XRP", "USD", 0, 0}, {"XRP", "EUR", 700, 2}})); // owner count is not changed since the number of pairs is 2 BEAST_EXPECT(ownerCount(env, owner) == count); // update both pairs - oracle.set(UpdateArg{ - .series = {{"XRP", "USD", 741, 2}, {"XRP", "EUR", 710, 2}}, - .fee = baseFee}); - BEAST_EXPECT(oracle.expectPrice( - {{"XRP", "USD", 741, 2}, {"XRP", "EUR", 710, 2}})); + oracle.set(UpdateArg{.series = {{"XRP", "USD", 741, 2}, {"XRP", "EUR", 710, 2}}, .fee = baseFee}); + BEAST_EXPECT(oracle.expectPrice({{"XRP", "USD", 741, 2}, {"XRP", "EUR", 710, 2}})); // owner count is not changed since the number of pairs is 2 BEAST_EXPECT(ownerCount(env, owner) == count); @@ -640,9 +534,7 @@ private: BEAST_EXPECT(ownerCount(env, owner) == count); // update two pairs and delete four - oracle.set(UpdateArg{ - .series = {{"BTC", "USD", std::nullopt, std::nullopt}}, - .fee = baseFee}); + oracle.set(UpdateArg{.series = {{"BTC", "USD", std::nullopt, std::nullopt}}, .fee = baseFee}); oracle.set(UpdateArg{ .series = {{"XRP", "USD", 742, 2}, @@ -651,8 +543,7 @@ private: {"YAN", "EUR", std::nullopt, std::nullopt}, {"CAN", "EUR", std::nullopt, std::nullopt}}, .fee = baseFee}); - BEAST_EXPECT(oracle.expectPrice( - {{"XRP", "USD", 742, 2}, {"XRP", "EUR", 711, 2}})); + BEAST_EXPECT(oracle.expectPrice({{"XRP", "USD", 742, 2}, {"XRP", "EUR", 711, 2}})); // owner count is decreased by 1 since the number of pairs is 2 count -= 1; BEAST_EXPECT(ownerCount(env, owner) == count); @@ -661,57 +552,37 @@ private: // Min reserve to create and update { Env env(*this); - auto const baseFee = - static_cast(env.current()->fees().base.drops()); - env.fund( - env.current()->fees().accountReserve(1) + - env.current()->fees().base * 2, - owner); + auto const baseFee = static_cast(env.current()->fees().base.drops()); + env.fund(env.current()->fees().accountReserve(1) + env.current()->fees().base * 2, owner); Oracle oracle(env, {.owner = owner, .fee = baseFee}); - oracle.set( - UpdateArg{.series = {{"XRP", "USD", 742, 2}}, .fee = baseFee}); + oracle.set(UpdateArg{.series = {{"XRP", "USD", 742, 2}}, .fee = baseFee}); } for (bool const withFixOrder : {false, true}) { // Should be same order as creation - Env env( - *this, - withFixOrder ? testable_amendments() - : testable_amendments() - fixPriceOracleOrder); - auto const baseFee = - static_cast(env.current()->fees().base.drops()); + Env env(*this, withFixOrder ? testable_amendments() : testable_amendments() - fixPriceOracleOrder); + auto const baseFee = static_cast(env.current()->fees().base.drops()); auto test = [&](Env& env, DataSeries const& series) { env.fund(XRP(1'000), owner); - Oracle oracle( - env, {.owner = owner, .series = series, .fee = baseFee}); + Oracle oracle(env, {.owner = owner, .series = series, .fee = baseFee}); BEAST_EXPECT(oracle.exists()); auto sle = env.le(keylet::oracle(owner, oracle.documentID())); - BEAST_EXPECT( - sle->getFieldArray(sfPriceDataSeries).size() == - series.size()); + BEAST_EXPECT(sle->getFieldArray(sfPriceDataSeries).size() == series.size()); auto const beforeQuoteAssetName1 = - sle->getFieldArray(sfPriceDataSeries)[0] - .getFieldCurrency(sfQuoteAsset) - .getText(); + sle->getFieldArray(sfPriceDataSeries)[0].getFieldCurrency(sfQuoteAsset).getText(); auto const beforeQuoteAssetName2 = - sle->getFieldArray(sfPriceDataSeries)[1] - .getFieldCurrency(sfQuoteAsset) - .getText(); + sle->getFieldArray(sfPriceDataSeries)[1].getFieldCurrency(sfQuoteAsset).getText(); oracle.set(UpdateArg{.series = series, .fee = baseFee}); sle = env.le(keylet::oracle(owner, oracle.documentID())); auto const afterQuoteAssetName1 = - sle->getFieldArray(sfPriceDataSeries)[0] - .getFieldCurrency(sfQuoteAsset) - .getText(); + sle->getFieldArray(sfPriceDataSeries)[0].getFieldCurrency(sfQuoteAsset).getText(); auto const afterQuoteAssetName2 = - sle->getFieldArray(sfPriceDataSeries)[1] - .getFieldCurrency(sfQuoteAsset) - .getText(); + sle->getFieldArray(sfPriceDataSeries)[1].getFieldCurrency(sfQuoteAsset).getText(); if (env.current()->rules().enabled(fixPriceOracleOrder)) { @@ -736,8 +607,7 @@ private: Oracle::setFee(100'000); Env env(*this); - auto const baseFee = - static_cast(env.current()->fees().base.drops()); + auto const baseFee = static_cast(env.current()->fees().base.drops()); Account const alice{"alice", KeyType::secp256k1}; Account const bogie{"bogie", KeyType::secp256k1}; @@ -761,32 +631,18 @@ private: // Create // Force close (true) and time advancement because the close time // is no longer 0. - Oracle oracle( - env, - CreateArg{.owner = alice, .fee = baseFee, .close = true}, - false); - oracle.set(CreateArg{ - .msig = msig(becky), .fee = baseFee, .err = ter(tefBAD_QUORUM)}); - oracle.set(CreateArg{ - .msig = msig(zelda), .fee = baseFee, .err = ter(tefBAD_SIGNATURE)}); + Oracle oracle(env, CreateArg{.owner = alice, .fee = baseFee, .close = true}, false); + oracle.set(CreateArg{.msig = msig(becky), .fee = baseFee, .err = ter(tefBAD_QUORUM)}); + oracle.set(CreateArg{.msig = msig(zelda), .fee = baseFee, .err = ter(tefBAD_SIGNATURE)}); oracle.set(CreateArg{.msig = msig(becky, bogie), .fee = baseFee}); BEAST_EXPECT(oracle.exists()); // Update oracle.set(UpdateArg{ - .series = {{"XRP", "USD", 740, 1}}, - .msig = msig(becky), - .fee = baseFee, - .err = ter(tefBAD_QUORUM)}); + .series = {{"XRP", "USD", 740, 1}}, .msig = msig(becky), .fee = baseFee, .err = ter(tefBAD_QUORUM)}); oracle.set(UpdateArg{ - .series = {{"XRP", "USD", 740, 1}}, - .msig = msig(zelda), - .fee = baseFee, - .err = ter(tefBAD_SIGNATURE)}); - oracle.set(UpdateArg{ - .series = {{"XRP", "USD", 741, 1}}, - .msig = msig(becky, bogie), - .fee = baseFee}); + .series = {{"XRP", "USD", 740, 1}}, .msig = msig(zelda), .fee = baseFee, .err = ter(tefBAD_SIGNATURE)}); + oracle.set(UpdateArg{.series = {{"XRP", "USD", 741, 1}}, .msig = msig(becky, bogie), .fee = baseFee}); BEAST_EXPECT(oracle.expectPrice({{"XRP", "USD", 741, 1}})); // remove the signer list env(signers(alice, jtx::none), sig(alie)); @@ -802,24 +658,14 @@ private: .fee = baseFee, .err = ter(tefBAD_SIGNATURE)}); // updated list succeeds - oracle.set(UpdateArg{ - .series = {{"XRP", "USD", 7412, 2}}, - .msig = msig(zelda, bob), - .fee = baseFee}); + oracle.set(UpdateArg{.series = {{"XRP", "USD", 7412, 2}}, .msig = msig(zelda, bob), .fee = baseFee}); BEAST_EXPECT(oracle.expectPrice({{"XRP", "USD", 7412, 2}})); - oracle.set(UpdateArg{ - .series = {{"XRP", "USD", 74245, 3}}, - .msig = msig(ed), - .fee = baseFee}); + oracle.set(UpdateArg{.series = {{"XRP", "USD", 74245, 3}}, .msig = msig(ed), .fee = baseFee}); BEAST_EXPECT(oracle.expectPrice({{"XRP", "USD", 74245, 3}})); // Remove - oracle.remove( - {.msig = msig(bob), .fee = baseFee, .err = ter(tefBAD_QUORUM)}); - oracle.remove( - {.msig = msig(becky), - .fee = baseFee, - .err = ter(tefBAD_SIGNATURE)}); + oracle.remove({.msig = msig(bob), .fee = baseFee, .err = ter(tefBAD_QUORUM)}); + oracle.remove({.msig = msig(becky), .fee = baseFee, .err = ter(tefBAD_SIGNATURE)}); oracle.remove({.msig = msig(ed), .fee = baseFee}); BEAST_EXPECT(!oracle.exists()); } @@ -833,13 +679,11 @@ private: auto const features = testable_amendments() - featurePriceOracle; Account const owner("owner"); Env env(*this, features); - auto const baseFee = - static_cast(env.current()->fees().base.drops()); + auto const baseFee = static_cast(env.current()->fees().base.drops()); env.fund(XRP(1'000), owner); { - Oracle oracle( - env, {.owner = owner, .fee = baseFee, .err = ter(temDISABLED)}); + Oracle oracle(env, {.owner = owner, .fee = baseFee, .err = ter(temDISABLED)}); } { diff --git a/src/test/app/OversizeMeta_test.cpp b/src/test/app/OversizeMeta_test.cpp index 2eb300b095..d5e2948f5b 100644 --- a/src/test/app/OversizeMeta_test.cpp +++ b/src/test/app/OversizeMeta_test.cpp @@ -160,8 +160,7 @@ public: void run() override { - auto const result = - bfind(100, 9000, [&](std::size_t n) { return oversize(n); }); + auto const result = bfind(100, 9000, [&](std::size_t n) { return oversize(n); }); log << "Min oversize offers = " << result << '\n'; } }; diff --git a/src/test/app/Path_test.cpp b/src/test/app/Path_test.cpp index 8a80ecd6d8..c019c2b8a3 100644 --- a/src/test/app/Path_test.cpp +++ b/src/test/app/Path_test.cpp @@ -140,8 +140,7 @@ public: params[jss::command] = "ripple_path_find"; params[jss::source_account] = toBase58(src); params[jss::destination_account] = toBase58(dst); - params[jss::destination_amount] = - saDstAmount.getJson(JsonOptions::none); + params[jss::destination_amount] = saDstAmount.getJson(JsonOptions::none); if (saSendMax) params[jss::send_max] = saSendMax->getJson(JsonOptions::none); if (saSrcCurrency) @@ -156,13 +155,12 @@ public: Json::Value result; gate g; - app.getJobQueue().postCoro( - jtCLIENT, "RPC-Client", [&](auto const& coro) { - context.params = std::move(params); - context.coro = coro; - RPC::doCommand(context, result); - g.signal(); - }); + app.getJobQueue().postCoro(jtCLIENT, "RPC-Client", [&](auto const& coro) { + context.params = std::move(params); + context.coro = coro; + RPC::doCommand(context, result); + g.signal(); + }); using namespace std::chrono_literals; BEAST_EXPECT(g.wait_for(5s)); @@ -180,8 +178,7 @@ public: std::optional const& saSrcCurrency = std::nullopt, std::optional const& domain = std::nullopt) { - Json::Value result = find_paths_request( - env, src, dst, saDstAmount, saSendMax, saSrcCurrency, domain); + Json::Value result = find_paths_request(env, src, dst, saDstAmount, saSendMax, saSrcCurrency, domain); BEAST_EXPECT(!result.isMember(jss::error)); STAmount da; @@ -201,8 +198,7 @@ public: sa = amountFromJson(sfGeneric, path[jss::source_amount]); if (path.isMember(jss::destination_amount)) - da = amountFromJson( - sfGeneric, path[jss::destination_amount]); + da = amountFromJson(sfGeneric, path[jss::destination_amount]); if (path.isMember(jss::paths_computed)) { @@ -250,53 +246,45 @@ public: Json::Value result; gate g; // Test RPC::Tuning::max_src_cur source currencies. - app.getJobQueue().postCoro( - jtCLIENT, "RPC-Client", [&](auto const& coro) { - context.params = rpf( - Account("alice"), Account("bob"), RPC::Tuning::max_src_cur); - context.coro = coro; - RPC::doCommand(context, result); - g.signal(); - }); + app.getJobQueue().postCoro(jtCLIENT, "RPC-Client", [&](auto const& coro) { + context.params = rpf(Account("alice"), Account("bob"), RPC::Tuning::max_src_cur); + context.coro = coro; + RPC::doCommand(context, result); + g.signal(); + }); BEAST_EXPECT(g.wait_for(5s)); BEAST_EXPECT(!result.isMember(jss::error)); // Test more than RPC::Tuning::max_src_cur source currencies. - app.getJobQueue().postCoro( - jtCLIENT, "RPC-Client", [&](auto const& coro) { - context.params = - rpf(Account("alice"), - Account("bob"), - RPC::Tuning::max_src_cur + 1); - context.coro = coro; - RPC::doCommand(context, result); - g.signal(); - }); + app.getJobQueue().postCoro(jtCLIENT, "RPC-Client", [&](auto const& coro) { + context.params = rpf(Account("alice"), Account("bob"), RPC::Tuning::max_src_cur + 1); + context.coro = coro; + RPC::doCommand(context, result); + g.signal(); + }); BEAST_EXPECT(g.wait_for(5s)); BEAST_EXPECT(result.isMember(jss::error)); // Test RPC::Tuning::max_auto_src_cur source currencies. for (auto i = 0; i < (RPC::Tuning::max_auto_src_cur - 1); ++i) env.trust(Account("alice")[std::to_string(i + 100)](100), "bob"); - app.getJobQueue().postCoro( - jtCLIENT, "RPC-Client", [&](auto const& coro) { - context.params = rpf(Account("alice"), Account("bob"), 0); - context.coro = coro; - RPC::doCommand(context, result); - g.signal(); - }); + app.getJobQueue().postCoro(jtCLIENT, "RPC-Client", [&](auto const& coro) { + context.params = rpf(Account("alice"), Account("bob"), 0); + context.coro = coro; + RPC::doCommand(context, result); + g.signal(); + }); BEAST_EXPECT(g.wait_for(5s)); BEAST_EXPECT(!result.isMember(jss::error)); // Test more than RPC::Tuning::max_auto_src_cur source currencies. env.trust(Account("alice")["AUD"](100), "bob"); - app.getJobQueue().postCoro( - jtCLIENT, "RPC-Client", [&](auto const& coro) { - context.params = rpf(Account("alice"), Account("bob"), 0); - context.coro = coro; - RPC::doCommand(context, result); - g.signal(); - }); + app.getJobQueue().postCoro(jtCLIENT, "RPC-Client", [&](auto const& coro) { + context.params = rpf(Account("alice"), Account("bob"), 0); + context.coro = coro; + RPC::doCommand(context, result); + g.signal(); + }); BEAST_EXPECT(g.wait_for(5s)); BEAST_EXPECT(result.isMember(jss::error)); } @@ -310,8 +298,7 @@ public: env.fund(XRP(10000), "alice", "bob"); env.close(); - auto const result = - find_paths(env, "alice", "bob", Account("bob")["USD"](5)); + auto const result = find_paths(env, "alice", "bob", Account("bob")["USD"](5)); BEAST_EXPECT(std::get<0>(result).empty()); } @@ -327,8 +314,7 @@ public: STPathSet st; STAmount sa; - std::tie(st, sa, std::ignore) = - find_paths(env, "alice", "bob", Account("bob")["USD"](5)); + std::tie(st, sa, std::ignore) = find_paths(env, "alice", "bob", Account("bob")["USD"](5)); BEAST_EXPECT(st.empty()); BEAST_EXPECT(equal(sa, Account("alice")["USD"](5))); } @@ -356,9 +342,7 @@ public: void path_find(bool const domainEnabled) { - testcase( - std::string("path find") + (domainEnabled ? " w/ " : " w/o ") + - "domain"); + testcase(std::string("path find") + (domainEnabled ? " w/ " : " w/o ") + "domain"); using namespace jtx; Env env = pathTestEnv(); auto const gw = Account("gateway"); @@ -376,14 +360,8 @@ public: STPathSet st; STAmount sa; - std::tie(st, sa, std::ignore) = find_paths( - env, - "alice", - "bob", - Account("bob")["USD"](5), - std::nullopt, - std::nullopt, - domainID); + std::tie(st, sa, std::ignore) = + find_paths(env, "alice", "bob", Account("bob")["USD"](5), std::nullopt, std::nullopt, domainID); BEAST_EXPECT(same(st, stpath("gateway"))); BEAST_EXPECT(equal(sa, Account("alice")["USD"](5))); } @@ -392,9 +370,7 @@ public: xrp_to_xrp(bool const domainEnabled) { using namespace jtx; - testcase( - std::string("XRP to XRP") + (domainEnabled ? " w/ " : " w/o ") + - "domain"); + testcase(std::string("XRP to XRP") + (domainEnabled ? " w/ " : " w/o ") + "domain"); Env env = pathTestEnv(); env.fund(XRP(10000), "alice", "bob"); env.close(); @@ -403,17 +379,14 @@ public: if (domainEnabled) domainID = setupDomain(env, {"alice", "bob"}); - auto const result = find_paths( - env, "alice", "bob", XRP(5), std::nullopt, std::nullopt, domainID); + auto const result = find_paths(env, "alice", "bob", XRP(5), std::nullopt, std::nullopt, domainID); BEAST_EXPECT(std::get<0>(result).empty()); } void path_find_consume_all(bool const domainEnabled) { - testcase( - std::string("path find consume all") + - (domainEnabled ? " w/ " : " w/o ") + "domain"); + testcase(std::string("path find consume all") + (domainEnabled ? " w/ " : " w/o ") + "domain"); using namespace jtx; { @@ -428,20 +401,13 @@ public: std::optional domainID; if (domainEnabled) - domainID = setupDomain( - env, {"alice", "bob", "carol", "dan", "edward"}); + domainID = setupDomain(env, {"alice", "bob", "carol", "dan", "edward"}); STPathSet st; STAmount sa; STAmount da; - std::tie(st, sa, da) = find_paths( - env, - "alice", - "edward", - Account("edward")["USD"](-1), - std::nullopt, - std::nullopt, - domainID); + std::tie(st, sa, da) = + find_paths(env, "alice", "edward", Account("edward")["USD"](-1), std::nullopt, std::nullopt, domainID); BEAST_EXPECT(same(st, stpath("dan"), stpath("bob", "carol"))); BEAST_EXPECT(equal(sa, Account("alice")["USD"](110))); BEAST_EXPECT(equal(da, Account("edward")["USD"](110))); @@ -461,8 +427,7 @@ public: std::optional domainID; if (domainEnabled) { - domainID = - setupDomain(env, {"alice", "bob", "carol", "gateway"}); + domainID = setupDomain(env, {"alice", "bob", "carol", "gateway"}); env(offer("carol", XRP(100), USD(100)), domain(*domainID)); } else @@ -514,9 +479,7 @@ public: void alternative_path_consume_both(bool const domainEnabled) { - testcase( - std::string("alternative path consume both") + - (domainEnabled ? " w/ " : " w/o ") + "domain"); + testcase(std::string("alternative path consume both") + (domainEnabled ? " w/ " : " w/o ") + "domain"); using namespace jtx; Env env = pathTestEnv(); auto const gw = Account("gateway"); @@ -533,20 +496,16 @@ public: std::optional domainID; if (domainEnabled) { - domainID = - setupDomain(env, {"alice", "bob", "gateway", "gateway2"}); + domainID = setupDomain(env, {"alice", "bob", "gateway", "gateway2"}); env(pay(gw, "alice", USD(70)), domain(*domainID)); env(pay(gw2, "alice", gw2_USD(70)), domain(*domainID)); - env(pay("alice", "bob", Account("bob")["USD"](140)), - paths(Account("alice")["USD"]), - domain(*domainID)); + env(pay("alice", "bob", Account("bob")["USD"](140)), paths(Account("alice")["USD"]), domain(*domainID)); } else { env(pay(gw, "alice", USD(70))); env(pay(gw2, "alice", gw2_USD(70))); - env(pay("alice", "bob", Account("bob")["USD"](140)), - paths(Account("alice")["USD"])); + env(pay("alice", "bob", Account("bob")["USD"](140)), paths(Account("alice")["USD"])); } env.require(balance("alice", USD(0))); @@ -563,8 +522,7 @@ public: alternative_paths_consume_best_transfer(bool const domainEnabled) { testcase( - std::string("alternative paths consume best transfer") + - (domainEnabled ? " w/ " : " w/o ") + "domain"); + std::string("alternative paths consume best transfer") + (domainEnabled ? " w/ " : " w/o ") + "domain"); using namespace jtx; Env env = pathTestEnv(); auto const gw = Account("gateway"); @@ -582,8 +540,7 @@ public: std::optional domainID; if (domainEnabled) { - domainID = - setupDomain(env, {"alice", "bob", "gateway", "gateway2"}); + domainID = setupDomain(env, {"alice", "bob", "gateway", "gateway2"}); env(pay(gw, "alice", USD(70)), domain(*domainID)); env(pay(gw2, "alice", gw2_USD(70)), domain(*domainID)); env(pay("alice", "bob", USD(70)), domain(*domainID)); @@ -637,12 +594,10 @@ public: } void - alternative_paths_limit_returned_paths_to_best_quality( - bool const domainEnabled) + alternative_paths_limit_returned_paths_to_best_quality(bool const domainEnabled) { testcase( - std::string( - "alternative paths - limit returned paths to best quality") + + std::string("alternative paths - limit returned paths to best quality") + (domainEnabled ? " w/ " : " w/o ") + "domain"); using namespace jtx; Env env = pathTestEnv(); @@ -670,35 +625,21 @@ public: std::optional domainID; if (domainEnabled) { - domainID = - setupDomain(env, {"alice", "bob", "carol", "dan", gw, gw2}); + domainID = setupDomain(env, {"alice", "bob", "carol", "dan", gw, gw2}); } STPathSet st; STAmount sa; - std::tie(st, sa, std::ignore) = find_paths( - env, - "alice", - "bob", - Account("bob")["USD"](5), - std::nullopt, - std::nullopt, - domainID); - BEAST_EXPECT(same( - st, - stpath("gateway"), - stpath("gateway2"), - stpath("dan"), - stpath("carol"))); + std::tie(st, sa, std::ignore) = + find_paths(env, "alice", "bob", Account("bob")["USD"](5), std::nullopt, std::nullopt, domainID); + BEAST_EXPECT(same(st, stpath("gateway"), stpath("gateway2"), stpath("dan"), stpath("carol"))); BEAST_EXPECT(equal(sa, Account("alice")["USD"](5))); } void issues_path_negative_issue(bool const domainEnabled) { - testcase( - std::string("path negative: Issue #5") + - (domainEnabled ? " w/ " : " w/o ") + "domain"); + testcase(std::string("path negative: Issue #5") + (domainEnabled ? " w/ " : " w/o ") + "domain"); using namespace jtx; Env env = pathTestEnv(); env.fund(XRP(10000), "alice", "bob", "carol", "dan"); @@ -717,27 +658,13 @@ public: domainID = setupDomain(env, {"alice", "bob", "carol", "dan"}); } - auto result = find_paths( - env, - "alice", - "bob", - Account("bob")["USD"](25), - std::nullopt, - std::nullopt, - domainID); + auto result = find_paths(env, "alice", "bob", Account("bob")["USD"](25), std::nullopt, std::nullopt, domainID); BEAST_EXPECT(std::get<0>(result).empty()); env(pay("alice", "bob", Account("alice")["USD"](25)), ter(tecPATH_DRY)); env.close(); - result = find_paths( - env, - "alice", - "bob", - Account("alice")["USD"](25), - std::nullopt, - std::nullopt, - domainID); + result = find_paths(env, "alice", "bob", Account("alice")["USD"](25), std::nullopt, std::nullopt, domainID); BEAST_EXPECT(std::get<0>(result).empty()); env.require(balance("alice", Account("bob")["USD"](0))); @@ -767,8 +694,7 @@ public: env.trust(Account("dan")["USD"](20), "bob"); env.trust(Account("alice")["USD"](20), "carol"); env.trust(Account("carol")["USD"](20), "dan"); - env(pay("alice", "bob", Account("bob")["USD"](55)), - paths(Account("alice")["USD"])); + env(pay("alice", "bob", Account("bob")["USD"](55)), paths(Account("alice")["USD"])); env.require(balance("bob", Account("alice")["USD"](40))); env.require(balance("bob", Account("dan")["USD"](15))); } @@ -788,8 +714,7 @@ public: env.trust(Account("dan")["USD"](100), "bob"); env.trust(Account("alice")["USD"](25), "carol"); env.trust(Account("carol")["USD"](75), "dan"); - env(pay("alice", "bob", Account("bob")["USD"](50)), - paths(Account("alice")["USD"])); + env(pay("alice", "bob", Account("bob")["USD"](50)), paths(Account("alice")["USD"])); env.require(balance("alice", Account("edward")["USD"](-25))); env.require(balance("alice", Account("carol")["USD"](-25))); env.require(balance("bob", Account("edward")["USD"](25))); @@ -806,9 +731,7 @@ public: void via_offers_via_gateway(bool const domainEnabled) { - testcase( - std::string("via gateway") + (domainEnabled ? " w/ " : " w/o ") + - "domain"); + testcase(std::string("via gateway") + (domainEnabled ? " w/ " : " w/o ") + "domain"); using namespace jtx; Env env = pathTestEnv(); auto const gw = Account("gateway"); @@ -828,10 +751,7 @@ public: domainID = setupDomain(env, {"alice", "bob", "carol", gw}); env(offer("carol", XRP(50), AUD(50)), domain(*domainID)); env.close(); - env(pay("alice", "bob", AUD(10)), - sendmax(XRP(100)), - paths(XRP), - domain(*domainID)); + env(pay("alice", "bob", AUD(10)), sendmax(XRP(100)), paths(XRP), domain(*domainID)); env.close(); } else @@ -845,14 +765,8 @@ public: env.require(balance("bob", AUD(10))); env.require(balance("carol", AUD(39))); - auto const result = find_paths( - env, - "alice", - "bob", - Account("bob")["USD"](25), - std::nullopt, - std::nullopt, - domainID); + auto const result = + find_paths(env, "alice", "bob", Account("bob")["USD"](25), std::nullopt, std::nullopt, domainID); BEAST_EXPECT(std::get<0>(result).empty()); } @@ -869,8 +783,7 @@ public: STPathSet st; STAmount sa; - std::tie(st, sa, std::ignore) = - find_paths(env, "alice", "carol", Account("carol")["USD"](5)); + std::tie(st, sa, std::ignore) = find_paths(env, "alice", "carol", Account("carol")["USD"](5)); BEAST_EXPECT(same(st, stpath("bob"))); BEAST_EXPECT(equal(sa, Account("alice")["USD"](5))); } @@ -915,9 +828,7 @@ public: jv); auto const jv_l = - env.le(keylet::line( - Account("bob").id(), Account("alice")["USD"].issue())) - ->getJson(JsonOptions::none); + env.le(keylet::line(Account("bob").id(), Account("alice")["USD"].issue()))->getJson(JsonOptions::none); for (auto it = jv.begin(); it != jv.end(); ++it) BEAST_EXPECT(*it == jv_l[it.memberName()]); } @@ -959,18 +870,13 @@ public: jv); auto const jv_l = - env.le(keylet::line( - Account("bob").id(), Account("alice")["USD"].issue())) - ->getJson(JsonOptions::none); + env.le(keylet::line(Account("bob").id(), Account("alice")["USD"].issue()))->getJson(JsonOptions::none); for (auto it = jv.begin(); it != jv.end(); ++it) BEAST_EXPECT(*it == jv_l[it.memberName()]); env.trust(Account("bob")["USD"](0), "alice"); env.trust(Account("alice")["USD"](0), "bob"); - BEAST_EXPECT( - env.le(keylet::line( - Account("bob").id(), Account("alice")["USD"].issue())) == - nullptr); + BEAST_EXPECT(env.le(keylet::line(Account("bob").id(), Account("alice")["USD"].issue())) == nullptr); } void @@ -1014,25 +920,18 @@ public: jv); auto const jv_l = - env.le(keylet::line( - Account("alice").id(), Account("bob")["USD"].issue())) - ->getJson(JsonOptions::none); + env.le(keylet::line(Account("alice").id(), Account("bob")["USD"].issue()))->getJson(JsonOptions::none); for (auto it = jv.begin(); it != jv.end(); ++it) BEAST_EXPECT(*it == jv_l[it.memberName()]); env(pay("alice", "bob", Account("alice")["USD"](50))); - BEAST_EXPECT( - env.le(keylet::line( - Account("alice").id(), Account("bob")["USD"].issue())) == - nullptr); + BEAST_EXPECT(env.le(keylet::line(Account("alice").id(), Account("bob")["USD"].issue())) == nullptr); } void path_find_01(bool const domainEnabled) { - testcase( - std::string("Path Find: XRP -> XRP and XRP -> IOU") + - (domainEnabled ? " w/ " : " w/o ") + "domain"); + testcase(std::string("Path Find: XRP -> XRP and XRP -> IOU") + (domainEnabled ? " w/ " : " w/o ") + "domain"); using namespace jtx; Env env = pathTestEnv(); Account A1{"A1"}; @@ -1084,8 +983,7 @@ public: { auto const& send_amt = XRP(10); - std::tie(st, sa, da) = find_paths( - env, A1, A2, send_amt, std::nullopt, xrpCurrency(), domainID); + std::tie(st, sa, da) = find_paths(env, A1, A2, send_amt, std::nullopt, xrpCurrency(), domainID); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(st.empty()); } @@ -1094,22 +992,14 @@ public: // no path should exist for this since dest account // does not exist. auto const& send_amt = XRP(200); - std::tie(st, sa, da) = find_paths( - env, - A1, - Account{"A0"}, - send_amt, - std::nullopt, - xrpCurrency(), - domainID); + std::tie(st, sa, da) = find_paths(env, A1, Account{"A0"}, send_amt, std::nullopt, xrpCurrency(), domainID); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(st.empty()); } { auto const& send_amt = G3["ABC"](10); - std::tie(st, sa, da) = find_paths( - env, A2, G3, send_amt, std::nullopt, xrpCurrency(), domainID); + std::tie(st, sa, da) = find_paths(env, A2, G3, send_amt, std::nullopt, xrpCurrency(), domainID); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, XRP(100))); BEAST_EXPECT(same(st, stpath(IPE(G3["ABC"])))); @@ -1117,8 +1007,7 @@ public: { auto const& send_amt = A2["ABC"](1); - std::tie(st, sa, da) = find_paths( - env, A1, A2, send_amt, std::nullopt, xrpCurrency(), domainID); + std::tie(st, sa, da) = find_paths(env, A1, A2, send_amt, std::nullopt, xrpCurrency(), domainID); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, XRP(10))); BEAST_EXPECT(same(st, stpath(IPE(G3["ABC"]), G3))); @@ -1126,8 +1015,7 @@ public: { auto const& send_amt = A3["ABC"](1); - std::tie(st, sa, da) = find_paths( - env, A1, A3, send_amt, std::nullopt, xrpCurrency(), domainID); + std::tie(st, sa, da) = find_paths(env, A1, A3, send_amt, std::nullopt, xrpCurrency(), domainID); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, XRP(10))); BEAST_EXPECT(same(st, stpath(IPE(G3["ABC"]), G3, A2))); @@ -1137,9 +1025,7 @@ public: void path_find_02(bool const domainEnabled) { - testcase( - std::string("Path Find: non-XRP -> XRP") + - (domainEnabled ? " w/ " : " w/o ") + "domain"); + testcase(std::string("Path Find: non-XRP -> XRP") + (domainEnabled ? " w/ " : " w/o ") + "domain"); using namespace jtx; Env env = pathTestEnv(); Account A1{"A1"}; @@ -1176,14 +1062,7 @@ public: auto const& send_amt = XRP(10); { - std::tie(st, sa, da) = find_paths( - env, - A1, - A2, - send_amt, - std::nullopt, - A2["ABC"].currency, - domainID); + std::tie(st, sa, da) = find_paths(env, A1, A2, send_amt, std::nullopt, A2["ABC"].currency, domainID); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, A1["ABC"](1))); BEAST_EXPECT(same(st, stpath(G3, IPE(xrpIssue())))); @@ -1193,8 +1072,7 @@ public: // paths if (domainEnabled) { - std::tie(st, sa, da) = find_paths( - env, A1, A2, send_amt, std::nullopt, A2["ABC"].currency); + std::tie(st, sa, da) = find_paths(env, A1, A2, send_amt, std::nullopt, A2["ABC"].currency); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(st.empty()); } @@ -1204,8 +1082,7 @@ public: path_find_04(bool const domainEnabled) { testcase( - std::string( - "Path Find: Bitstamp and SnapSwap, liquidity with no offers") + + std::string("Path Find: Bitstamp and SnapSwap, liquidity with no offers") + (domainEnabled ? " w/ " : " w/o ") + "domain"); using namespace jtx; Env env = pathTestEnv(); @@ -1243,14 +1120,7 @@ public: { auto const& send_amt = A2["HKD"](10); - std::tie(st, sa, da) = find_paths( - env, - A1, - A2, - send_amt, - std::nullopt, - A2["HKD"].currency, - domainID); + std::tie(st, sa, da) = find_paths(env, A1, A2, send_amt, std::nullopt, A2["HKD"].currency, domainID); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, A1["HKD"](10))); BEAST_EXPECT(same(st, stpath(G1BS, M1, G2SW))); @@ -1258,14 +1128,7 @@ public: { auto const& send_amt = A1["HKD"](10); - std::tie(st, sa, da) = find_paths( - env, - A2, - A1, - send_amt, - std::nullopt, - A1["HKD"].currency, - domainID); + std::tie(st, sa, da) = find_paths(env, A2, A1, send_amt, std::nullopt, A1["HKD"].currency, domainID); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, A2["HKD"](10))); BEAST_EXPECT(same(st, stpath(G2SW, M1, G1BS))); @@ -1273,14 +1136,7 @@ public: { auto const& send_amt = A2["HKD"](10); - std::tie(st, sa, da) = find_paths( - env, - G1BS, - A2, - send_amt, - std::nullopt, - A1["HKD"].currency, - domainID); + std::tie(st, sa, da) = find_paths(env, G1BS, A2, send_amt, std::nullopt, A1["HKD"].currency, domainID); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, G1BS["HKD"](10))); BEAST_EXPECT(same(st, stpath(M1, G2SW))); @@ -1288,14 +1144,7 @@ public: { auto const& send_amt = M1["HKD"](10); - std::tie(st, sa, da) = find_paths( - env, - M1, - G1BS, - send_amt, - std::nullopt, - A1["HKD"].currency, - domainID); + std::tie(st, sa, da) = find_paths(env, M1, G1BS, send_amt, std::nullopt, A1["HKD"].currency, domainID); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, M1["HKD"](10))); BEAST_EXPECT(st.empty()); @@ -1303,14 +1152,7 @@ public: { auto const& send_amt = A1["HKD"](10); - std::tie(st, sa, da) = find_paths( - env, - G2SW, - A1, - send_amt, - std::nullopt, - A1["HKD"].currency, - domainID); + std::tie(st, sa, da) = find_paths(env, G2SW, A1, send_amt, std::nullopt, A1["HKD"].currency, domainID); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, G2SW["HKD"](10))); BEAST_EXPECT(same(st, stpath(M1, G1BS))); @@ -1321,8 +1163,8 @@ public: path_find_05(bool const domainEnabled) { testcase( - std::string("Path Find: non-XRP -> non-XRP, same currency") + - (domainEnabled ? " w/ " : " w/o ") + "domain"); + std::string("Path Find: non-XRP -> non-XRP, same currency") + (domainEnabled ? " w/ " : " w/o ") + + "domain"); using namespace jtx; Env env = pathTestEnv(); Account A1{"A1"}; @@ -1362,8 +1204,7 @@ public: std::optional domainID; if (domainEnabled) { - domainID = - setupDomain(env, {A1, A2, A3, A4, G1, G2, G3, G4, M1, M2}); + domainID = setupDomain(env, {A1, A2, A3, A4, G1, G2, G3, G4, M1, M2}); env(offer(M1, G1["HKD"](1000), G2["HKD"](1000)), domain(*domainID)); env(offer(M2, XRP(10000), G2["HKD"](1000)), domain(*domainID)); env(offer(M2, G1["HKD"](1000), XRP(10000)), domain(*domainID)); @@ -1382,14 +1223,7 @@ public: // A) Borrow or repay -- // Source -> Destination (repay source issuer) auto const& send_amt = G1["HKD"](10); - std::tie(st, sa, da) = find_paths( - env, - A1, - G1, - send_amt, - std::nullopt, - G1["HKD"].currency, - domainID); + std::tie(st, sa, da) = find_paths(env, A1, G1, send_amt, std::nullopt, G1["HKD"].currency, domainID); BEAST_EXPECT(st.empty()); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, A1["HKD"](10))); @@ -1399,14 +1233,7 @@ public: // A2) Borrow or repay -- // Source -> Destination (repay destination issuer) auto const& send_amt = A1["HKD"](10); - std::tie(st, sa, da) = find_paths( - env, - A1, - G1, - send_amt, - std::nullopt, - G1["HKD"].currency, - domainID); + std::tie(st, sa, da) = find_paths(env, A1, G1, send_amt, std::nullopt, G1["HKD"].currency, domainID); BEAST_EXPECT(st.empty()); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, A1["HKD"](10))); @@ -1416,14 +1243,7 @@ public: // B) Common gateway -- // Source -> AC -> Destination auto const& send_amt = A3["HKD"](10); - std::tie(st, sa, da) = find_paths( - env, - A1, - A3, - send_amt, - std::nullopt, - G1["HKD"].currency, - domainID); + std::tie(st, sa, da) = find_paths(env, A1, A3, send_amt, std::nullopt, G1["HKD"].currency, domainID); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, A1["HKD"](10))); BEAST_EXPECT(same(st, stpath(G1))); @@ -1433,36 +1253,18 @@ public: // C) Gateway to gateway -- // Source -> OB -> Destination auto const& send_amt = G2["HKD"](10); - std::tie(st, sa, da) = find_paths( - env, - G1, - G2, - send_amt, - std::nullopt, - G1["HKD"].currency, - domainID); + std::tie(st, sa, da) = find_paths(env, G1, G2, send_amt, std::nullopt, G1["HKD"].currency, domainID); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, G1["HKD"](10))); - BEAST_EXPECT(same( - st, - stpath(IPE(G2["HKD"])), - stpath(M1), - stpath(M2), - stpath(IPE(xrpIssue()), IPE(G2["HKD"])))); + BEAST_EXPECT( + same(st, stpath(IPE(G2["HKD"])), stpath(M1), stpath(M2), stpath(IPE(xrpIssue()), IPE(G2["HKD"])))); } { // D) User to unlinked gateway via order book -- // Source -> AC -> OB -> Destination auto const& send_amt = G2["HKD"](10); - std::tie(st, sa, da) = find_paths( - env, - A1, - G2, - send_amt, - std::nullopt, - G1["HKD"].currency, - domainID); + std::tie(st, sa, da) = find_paths(env, A1, G2, send_amt, std::nullopt, G1["HKD"].currency, domainID); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, A1["HKD"](10))); BEAST_EXPECT(same( @@ -1478,14 +1280,7 @@ public: // Source -> AC -> OB to XRP -> OB from XRP -> AC -> // Destination auto const& send_amt = A2["HKD"](10); - std::tie(st, sa, da) = find_paths( - env, - A1, - A2, - send_amt, - std::nullopt, - G1["HKD"].currency, - domainID); + std::tie(st, sa, da) = find_paths(env, A1, A2, send_amt, std::nullopt, G1["HKD"].currency, domainID); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, A1["HKD"](10))); BEAST_EXPECT(same( @@ -1501,8 +1296,8 @@ public: path_find_06(bool const domainEnabled) { testcase( - std::string("Path Find: non-XRP -> non-XRP, same currency)") + - (domainEnabled ? " w/ " : " w/o ") + "domain"); + std::string("Path Find: non-XRP -> non-XRP, same currency)") + (domainEnabled ? " w/ " : " w/o ") + + "domain"); using namespace jtx; Env env = pathTestEnv(); Account A1{"A1"}; @@ -1545,8 +1340,7 @@ public: auto const& send_amt = A2["HKD"](10); STPathSet st; STAmount sa, da; - std::tie(st, sa, da) = find_paths( - env, G1, A2, send_amt, std::nullopt, G1["HKD"].currency, domainID); + std::tie(st, sa, da) = find_paths(env, G1, A2, send_amt, std::nullopt, G1["HKD"].currency, domainID); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, G1["HKD"](10))); BEAST_EXPECT(same(st, stpath(M1, G2), stpath(IPE(G2["HKD"]), G2))); @@ -1555,9 +1349,7 @@ public: void receive_max(bool const domainEnabled) { - testcase( - std::string("Receive max") + (domainEnabled ? " w/ " : " w/o ") + - "domain"); + testcase(std::string("Receive max") + (domainEnabled ? " w/ " : " w/o ") + "domain"); using namespace jtx; auto const alice = Account("alice"); @@ -1588,22 +1380,14 @@ public: env.close(); } - auto [st, sa, da] = find_paths( - env, - alice, - bob, - USD(-1), - XRP(100).value(), - std::nullopt, - domainID); + auto [st, sa, da] = find_paths(env, alice, bob, USD(-1), XRP(100).value(), std::nullopt, domainID); BEAST_EXPECT(sa == XRP(10)); BEAST_EXPECT(equal(da, USD(10))); if (BEAST_EXPECT(st.size() == 1 && st[0].size() == 1)) { auto const& pathElem = st[0][0]; BEAST_EXPECT( - pathElem.isOffer() && pathElem.getIssuerID() == gw.id() && - pathElem.getCurrency() == USD.currency); + pathElem.isOffer() && pathElem.getIssuerID() == gw.id() && pathElem.getCurrency() == USD.currency); } } { @@ -1629,22 +1413,14 @@ public: env.close(); } - auto [st, sa, da] = find_paths( - env, - alice, - bob, - drops(-1), - USD(100).value(), - std::nullopt, - domainID); + auto [st, sa, da] = find_paths(env, alice, bob, drops(-1), USD(100).value(), std::nullopt, domainID); BEAST_EXPECT(sa == USD(10)); BEAST_EXPECT(equal(da, XRP(10))); if (BEAST_EXPECT(st.size() == 1 && st[0].size() == 1)) { auto const& pathElem = st[0][0]; BEAST_EXPECT( - pathElem.isOffer() && - pathElem.getIssuerID() == xrpAccount() && + pathElem.isOffer() && pathElem.getIssuerID() == xrpAccount() && pathElem.getCurrency() == xrpCurrency()); } } @@ -1662,10 +1438,7 @@ public: auto const bob = Account("bob"); auto const george = Account("george"); auto const USD = george["USD"]; - auto test = [&](std::string casename, - bool aliceRipple, - bool bobRipple, - bool expectPath) { + auto test = [&](std::string casename, bool aliceRipple, bool bobRipple, bool expectPath) { testcase(casename); Env env = pathTestEnv(); @@ -1673,26 +1446,15 @@ public: env.close(); // Set the same flags at both ends of the trustline, even though // only george's matter. - env(trust( - alice, - USD(100), - aliceRipple ? tfClearNoRipple : tfSetNoRipple)); - env(trust( - george, - alice["USD"](100), - aliceRipple ? tfClearNoRipple : tfSetNoRipple)); - env(trust( - bob, USD(100), bobRipple ? tfClearNoRipple : tfSetNoRipple)); - env(trust( - george, - bob["USD"](100), - bobRipple ? tfClearNoRipple : tfSetNoRipple)); + env(trust(alice, USD(100), aliceRipple ? tfClearNoRipple : tfSetNoRipple)); + env(trust(george, alice["USD"](100), aliceRipple ? tfClearNoRipple : tfSetNoRipple)); + env(trust(bob, USD(100), bobRipple ? tfClearNoRipple : tfSetNoRipple)); + env(trust(george, bob["USD"](100), bobRipple ? tfClearNoRipple : tfSetNoRipple)); env.close(); env(pay(george, alice, USD(70))); env.close(); - auto [st, sa, da] = - find_paths(env, "alice", "bob", Account("bob")["USD"](5)); + auto [st, sa, da] = find_paths(env, "alice", "bob", Account("bob")["USD"](5)); BEAST_EXPECT(equal(da, bob["USD"](5))); if (expectPath) @@ -1758,8 +1520,7 @@ public: env(pay(G2, M2, G2["HKD"](5000))); env.close(); - std::optional domainID = - setupDomain(env, {A1, A2, A3, A4, G1, G2, G3, G4, M1, M2}); + std::optional domainID = setupDomain(env, {A1, A2, A3, A4, G1, G2, G3, G4, M1, M2}); BEAST_EXPECT(domainID); func(env, M1, M2, G1, G2, *domainID); @@ -1772,13 +1533,7 @@ public: // Source -> Destination (repay source issuer) auto const& send_amt = G1["HKD"](10); std::tie(st, sa, da) = find_paths( - env, - A1, - G1, - send_amt, - std::nullopt, - G1["HKD"].currency, - domainEnabled ? domainID : std::nullopt); + env, A1, G1, send_amt, std::nullopt, G1["HKD"].currency, domainEnabled ? domainID : std::nullopt); BEAST_EXPECT(st.empty()); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, A1["HKD"](10))); @@ -1789,13 +1544,7 @@ public: // Source -> Destination (repay destination issuer) auto const& send_amt = A1["HKD"](10); std::tie(st, sa, da) = find_paths( - env, - A1, - G1, - send_amt, - std::nullopt, - G1["HKD"].currency, - domainEnabled ? domainID : std::nullopt); + env, A1, G1, send_amt, std::nullopt, G1["HKD"].currency, domainEnabled ? domainID : std::nullopt); BEAST_EXPECT(st.empty()); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, A1["HKD"](10))); @@ -1806,13 +1555,7 @@ public: // Source -> AC -> Destination auto const& send_amt = A3["HKD"](10); std::tie(st, sa, da) = find_paths( - env, - A1, - A3, - send_amt, - std::nullopt, - G1["HKD"].currency, - domainEnabled ? domainID : std::nullopt); + env, A1, A3, send_amt, std::nullopt, G1["HKD"].currency, domainEnabled ? domainID : std::nullopt); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, A1["HKD"](10))); BEAST_EXPECT(same(st, stpath(G1))); @@ -1823,21 +1566,11 @@ public: // Source -> OB -> Destination auto const& send_amt = G2["HKD"](10); std::tie(st, sa, da) = find_paths( - env, - G1, - G2, - send_amt, - std::nullopt, - G1["HKD"].currency, - domainEnabled ? domainID : std::nullopt); + env, G1, G2, send_amt, std::nullopt, G1["HKD"].currency, domainEnabled ? domainID : std::nullopt); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, G1["HKD"](10))); - BEAST_EXPECT(same( - st, - stpath(IPE(G2["HKD"])), - stpath(M1), - stpath(M2), - stpath(IPE(xrpIssue()), IPE(G2["HKD"])))); + BEAST_EXPECT( + same(st, stpath(IPE(G2["HKD"])), stpath(M1), stpath(M2), stpath(IPE(xrpIssue()), IPE(G2["HKD"])))); } { @@ -1845,13 +1578,7 @@ public: // Source -> AC -> OB -> Destination auto const& send_amt = G2["HKD"](10); std::tie(st, sa, da) = find_paths( - env, - A1, - G2, - send_amt, - std::nullopt, - G1["HKD"].currency, - domainEnabled ? domainID : std::nullopt); + env, A1, G2, send_amt, std::nullopt, G1["HKD"].currency, domainEnabled ? domainID : std::nullopt); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, A1["HKD"](10))); BEAST_EXPECT(same( @@ -1868,13 +1595,7 @@ public: // Destination auto const& send_amt = A2["HKD"](10); std::tie(st, sa, da) = find_paths( - env, - A1, - A2, - send_amt, - std::nullopt, - G1["HKD"].currency, - domainEnabled ? domainID : std::nullopt); + env, A1, A2, send_amt, std::nullopt, G1["HKD"].currency, domainEnabled ? domainID : std::nullopt); BEAST_EXPECT(equal(da, send_amt)); BEAST_EXPECT(equal(sa, A1["HKD"](10))); BEAST_EXPECT(same( @@ -1890,77 +1611,34 @@ public: // offers to make sure that hybrid offers work in pathfinding for open // order book { - testPathfind([](Env& env, - Account M1, - Account M2, - Account G1, - Account G2, - uint256 domainID) { - env(offer(M1, G1["HKD"](1000), G2["HKD"](1000)), - domain(domainID), - txflags(tfHybrid)); + testPathfind([](Env& env, Account M1, Account M2, Account G1, Account G2, uint256 domainID) { + env(offer(M1, G1["HKD"](1000), G2["HKD"](1000)), domain(domainID), txflags(tfHybrid)); env(offer(M2, XRP(10000), G2["HKD"](1000))); env(offer(M2, G1["HKD"](1000), XRP(10000))); }); - testPathfind([](Env& env, - Account M1, - Account M2, - Account G1, - Account G2, - uint256 domainID) { - env(offer(M1, G1["HKD"](1000), G2["HKD"](1000)), - domain(domainID), - txflags(tfHybrid)); - env(offer(M2, XRP(10000), G2["HKD"](1000)), - domain(domainID), - txflags(tfHybrid)); + testPathfind([](Env& env, Account M1, Account M2, Account G1, Account G2, uint256 domainID) { + env(offer(M1, G1["HKD"](1000), G2["HKD"](1000)), domain(domainID), txflags(tfHybrid)); + env(offer(M2, XRP(10000), G2["HKD"](1000)), domain(domainID), txflags(tfHybrid)); env(offer(M2, G1["HKD"](1000), XRP(10000))); }); - testPathfind([](Env& env, - Account M1, - Account M2, - Account G1, - Account G2, - uint256 domainID) { - env(offer(M1, G1["HKD"](1000), G2["HKD"](1000)), - domain(domainID), - txflags(tfHybrid)); - env(offer(M2, XRP(10000), G2["HKD"](1000)), - domain(domainID), - txflags(tfHybrid)); - env(offer(M2, G1["HKD"](1000), XRP(10000)), - domain(domainID), - txflags(tfHybrid)); + testPathfind([](Env& env, Account M1, Account M2, Account G1, Account G2, uint256 domainID) { + env(offer(M1, G1["HKD"](1000), G2["HKD"](1000)), domain(domainID), txflags(tfHybrid)); + env(offer(M2, XRP(10000), G2["HKD"](1000)), domain(domainID), txflags(tfHybrid)); + env(offer(M2, G1["HKD"](1000), XRP(10000)), domain(domainID), txflags(tfHybrid)); }); - testPathfind([](Env& env, - Account M1, - Account M2, - Account G1, - Account G2, - uint256 domainID) { + testPathfind([](Env& env, Account M1, Account M2, Account G1, Account G2, uint256 domainID) { env(offer(M1, G1["HKD"](1000), G2["HKD"](1000))); env(offer(M2, XRP(10000), G2["HKD"](1000))); - env(offer(M2, G1["HKD"](1000), XRP(10000)), - domain(domainID), - txflags(tfHybrid)); + env(offer(M2, G1["HKD"](1000), XRP(10000)), domain(domainID), txflags(tfHybrid)); }); - testPathfind([](Env& env, - Account M1, - Account M2, - Account G1, - Account G2, - uint256 domainID) { + testPathfind([](Env& env, Account M1, Account M2, Account G1, Account G2, uint256 domainID) { env(offer(M1, G1["HKD"](1000), G2["HKD"](1000))); - env(offer(M2, XRP(10000), G2["HKD"](1000)), - domain(domainID), - txflags(tfHybrid)); - env(offer(M2, G1["HKD"](1000), XRP(10000)), - domain(domainID), - txflags(tfHybrid)); + env(offer(M2, XRP(10000), G2["HKD"](1000)), domain(domainID), txflags(tfHybrid)); + env(offer(M2, G1["HKD"](1000), XRP(10000)), domain(domainID), txflags(tfHybrid)); }); } @@ -1969,72 +1647,34 @@ public: // order book { testPathfind( - [](Env& env, - Account M1, - Account M2, - Account G1, - Account G2, - uint256 domainID) { - env(offer(M1, G1["HKD"](1000), G2["HKD"](1000)), - domain(domainID), - txflags(tfHybrid)); - env(offer(M2, XRP(10000), G2["HKD"](1000)), - domain(domainID)); - env(offer(M2, G1["HKD"](1000), XRP(10000)), - domain(domainID)); + [](Env& env, Account M1, Account M2, Account G1, Account G2, uint256 domainID) { + env(offer(M1, G1["HKD"](1000), G2["HKD"](1000)), domain(domainID), txflags(tfHybrid)); + env(offer(M2, XRP(10000), G2["HKD"](1000)), domain(domainID)); + env(offer(M2, G1["HKD"](1000), XRP(10000)), domain(domainID)); }, true); testPathfind( - [](Env& env, - Account M1, - Account M2, - Account G1, - Account G2, - uint256 domainID) { - env(offer(M1, G1["HKD"](1000), G2["HKD"](1000)), - domain(domainID), - txflags(tfHybrid)); - env(offer(M2, XRP(10000), G2["HKD"](1000)), - domain(domainID), - txflags(tfHybrid)); - env(offer(M2, G1["HKD"](1000), XRP(10000)), - domain(domainID)); + [](Env& env, Account M1, Account M2, Account G1, Account G2, uint256 domainID) { + env(offer(M1, G1["HKD"](1000), G2["HKD"](1000)), domain(domainID), txflags(tfHybrid)); + env(offer(M2, XRP(10000), G2["HKD"](1000)), domain(domainID), txflags(tfHybrid)); + env(offer(M2, G1["HKD"](1000), XRP(10000)), domain(domainID)); }, true); testPathfind( - [](Env& env, - Account M1, - Account M2, - Account G1, - Account G2, - uint256 domainID) { - env(offer(M1, G1["HKD"](1000), G2["HKD"](1000)), - domain(domainID)); - env(offer(M2, XRP(10000), G2["HKD"](1000)), - domain(domainID)); - env(offer(M2, G1["HKD"](1000), XRP(10000)), - domain(domainID), - txflags(tfHybrid)); + [](Env& env, Account M1, Account M2, Account G1, Account G2, uint256 domainID) { + env(offer(M1, G1["HKD"](1000), G2["HKD"](1000)), domain(domainID)); + env(offer(M2, XRP(10000), G2["HKD"](1000)), domain(domainID)); + env(offer(M2, G1["HKD"](1000), XRP(10000)), domain(domainID), txflags(tfHybrid)); }, true); testPathfind( - [](Env& env, - Account M1, - Account M2, - Account G1, - Account G2, - uint256 domainID) { - env(offer(M1, G1["HKD"](1000), G2["HKD"](1000)), - domain(domainID)); - env(offer(M2, XRP(10000), G2["HKD"](1000)), - domain(domainID), - txflags(tfHybrid)); - env(offer(M2, G1["HKD"](1000), XRP(10000)), - domain(domainID), - txflags(tfHybrid)); + [](Env& env, Account M1, Account M2, Account G1, Account G2, uint256 domainID) { + env(offer(M1, G1["HKD"](1000), G2["HKD"](1000)), domain(domainID)); + env(offer(M2, XRP(10000), G2["HKD"](1000)), domain(domainID), txflags(tfHybrid)); + env(offer(M2, G1["HKD"](1000), XRP(10000)), domain(domainID), txflags(tfHybrid)); }, true); } @@ -2047,8 +1687,7 @@ public: using namespace jtx; Env env = pathTestEnv(); PermissionedDEX permDex(env); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = - permDex; + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = permDex; AMM amm(env, alice, XRP(10), USD(50)); STPathSet st; @@ -2057,13 +1696,11 @@ public: auto const& send_amt = XRP(1); // doing pathfind with domain won't include amm - std::tie(st, sa, da) = find_paths( - env, bob, carol, send_amt, std::nullopt, USD.currency, domainID); + std::tie(st, sa, da) = find_paths(env, bob, carol, send_amt, std::nullopt, USD.currency, domainID); BEAST_EXPECT(st.empty()); // a non-domain pathfind returns amm in the path - std::tie(st, sa, da) = - find_paths(env, bob, carol, send_amt, std::nullopt, USD.currency); + std::tie(st, sa, da) = find_paths(env, bob, carol, send_amt, std::nullopt, USD.currency); BEAST_EXPECT(same(st, stpath(gw, IPE(xrpIssue())))); } @@ -2089,8 +1726,7 @@ public: path_find_consume_all(domainEnabled); alternative_path_consume_both(domainEnabled); alternative_paths_consume_best_transfer(domainEnabled); - alternative_paths_limit_returned_paths_to_best_quality( - domainEnabled); + alternative_paths_limit_returned_paths_to_best_quality(domainEnabled); issues_path_negative_issue(domainEnabled); via_offers_via_gateway(domainEnabled); xrp_to_xrp(domainEnabled); diff --git a/src/test/app/PayChan_test.cpp b/src/test/app/PayChan_test.cpp index ed8c3c507e..019dd42ca1 100644 --- a/src/test/app/PayChan_test.cpp +++ b/src/test/app/PayChan_test.cpp @@ -15,10 +15,7 @@ using namespace jtx::paychan; struct PayChan_test : public beast::unit_test::suite { static std::pair> - channelKeyAndSle( - ReadView const& view, - jtx::Account const& account, - jtx::Account const& dst) + channelKeyAndSle(ReadView const& view, jtx::Account const& account, jtx::Account const& dst) { auto const sle = view.read(keylet::account(account)); if (!sle) @@ -28,11 +25,7 @@ struct PayChan_test : public beast::unit_test::suite } static Buffer - signClaimAuth( - PublicKey const& pk, - SecretKey const& sk, - uint256 const& channel, - STAmount const& authAmt) + signClaimAuth(PublicKey const& pk, SecretKey const& sk, uint256 const& channel, STAmount const& authAmt) { Serializer msg; serializePayChanAuthorization(msg, channel, authAmt.xrp()); @@ -91,27 +84,19 @@ struct PayChan_test : public beast::unit_test::suite { // bad amounts (non-xrp, negative amounts) - env(create(alice, bob, USDA(1000), settleDelay, pk), - ter(temBAD_AMOUNT)); + env(create(alice, bob, USDA(1000), settleDelay, pk), ter(temBAD_AMOUNT)); env(fund(alice, chan, USDA(1000)), ter(temBAD_AMOUNT)); - env(create(alice, bob, XRP(-1000), settleDelay, pk), - ter(temBAD_AMOUNT)); + env(create(alice, bob, XRP(-1000), settleDelay, pk), ter(temBAD_AMOUNT)); env(fund(alice, chan, XRP(-1000)), ter(temBAD_AMOUNT)); } // invalid account - env(create(alice, "noAccount", XRP(1000), settleDelay, pk), - ter(tecNO_DST)); + env(create(alice, "noAccount", XRP(1000), settleDelay, pk), ter(tecNO_DST)); // can't create channel to the same account - env(create(alice, alice, XRP(1000), settleDelay, pk), - ter(temDST_IS_SRC)); + env(create(alice, alice, XRP(1000), settleDelay, pk), ter(temDST_IS_SRC)); // invalid channel - env(fund( - alice, - channel(alice, "noAccount", env.seq(alice) - 1), - XRP(1000)), - ter(tecNO_ENTRY)); + env(fund(alice, channel(alice, "noAccount", env.seq(alice) - 1), XRP(1000)), ter(tecNO_ENTRY)); // not enough funds env(create(alice, bob, XRP(10000), settleDelay, pk), ter(tecUNFUNDED)); @@ -155,8 +140,7 @@ struct PayChan_test : public beast::unit_test::suite auto const reqBal = chanBal + delta; auto const authAmt = reqBal + XRP(100); assert(reqBal <= chanAmt); - auto const sig = - signClaimAuth(alice.pk(), alice.sk(), chan, authAmt); + auto const sig = signClaimAuth(alice.pk(), alice.sk(), chan, authAmt); env(claim(bob, chan, reqBal, authAmt, Slice(sig), alice.pk())); BEAST_EXPECT(channelBalance(*env.current(), chan) == reqBal); BEAST_EXPECT(channelAmount(*env.current(), chan) == chanAmt); @@ -166,8 +150,7 @@ struct PayChan_test : public beast::unit_test::suite // claim again preBob = env.balance(bob); - env(claim(bob, chan, reqBal, authAmt, Slice(sig), alice.pk()), - ter(tecUNFUNDED_PAYMENT)); + env(claim(bob, chan, reqBal, authAmt, Slice(sig), alice.pk()), ter(tecUNFUNDED_PAYMENT)); BEAST_EXPECT(channelBalance(*env.current(), chan) == chanBal); BEAST_EXPECT(channelAmount(*env.current(), chan) == chanAmt); BEAST_EXPECT(env.balance(bob) == preBob - feeDrops); @@ -178,10 +161,8 @@ struct PayChan_test : public beast::unit_test::suite STAmount const authAmt = chanBal + XRP(500); STAmount const reqAmt = authAmt + STAmount{1}; assert(reqAmt <= chanAmt); - auto const sig = - signClaimAuth(alice.pk(), alice.sk(), chan, authAmt); - env(claim(bob, chan, reqAmt, authAmt, Slice(sig), alice.pk()), - ter(temBAD_AMOUNT)); + auto const sig = signClaimAuth(alice.pk(), alice.sk(), chan, authAmt); + env(claim(bob, chan, reqAmt, authAmt, Slice(sig), alice.pk()), ter(temBAD_AMOUNT)); BEAST_EXPECT(channelBalance(*env.current(), chan) == chanBal); BEAST_EXPECT(channelAmount(*env.current(), chan) == chanAmt); BEAST_EXPECT(env.balance(bob) == preBob); @@ -195,28 +176,14 @@ struct PayChan_test : public beast::unit_test::suite { // Wrong signing key auto const sig = signClaimAuth(bob.pk(), bob.sk(), chan, XRP(1500)); - env(claim( - bob, - chan, - XRP(1500).value(), - XRP(1500).value(), - Slice(sig), - bob.pk()), - ter(temBAD_SIGNER)); + env(claim(bob, chan, XRP(1500).value(), XRP(1500).value(), Slice(sig), bob.pk()), ter(temBAD_SIGNER)); BEAST_EXPECT(channelBalance(*env.current(), chan) == chanBal); BEAST_EXPECT(channelAmount(*env.current(), chan) == chanAmt); } { // Bad signature auto const sig = signClaimAuth(bob.pk(), bob.sk(), chan, XRP(1500)); - env(claim( - bob, - chan, - XRP(1500).value(), - XRP(1500).value(), - Slice(sig), - alice.pk()), - ter(temBAD_SIGNATURE)); + env(claim(bob, chan, XRP(1500).value(), XRP(1500).value(), Slice(sig), alice.pk()), ter(temBAD_SIGNATURE)); BEAST_EXPECT(channelBalance(*env.current(), chan) == chanBal); BEAST_EXPECT(channelAmount(*env.current(), chan) == chanAmt); } @@ -256,8 +223,7 @@ struct PayChan_test : public beast::unit_test::suite // channel creation from alice to bob is disallowed { auto const chan = channel(alice, bob, env.seq(alice)); - env(create(alice, bob, XRP(1000), settleDelay, pk), - ter(tecNO_PERMISSION)); + env(create(alice, bob, XRP(1000), settleDelay, pk), ter(tecNO_PERMISSION)); BEAST_EXPECT(!channelExists(*env.current(), chan)); } @@ -268,8 +234,7 @@ struct PayChan_test : public beast::unit_test::suite // channel creation from bob to alice is now disallowed { auto const chan = channel(bob, alice, env.seq(bob)); - env(create(bob, alice, XRP(1000), settleDelay, pk), - ter(tecNO_PERMISSION)); + env(create(bob, alice, XRP(1000), settleDelay, pk), ter(tecNO_PERMISSION)); BEAST_EXPECT(!channelExists(*env.current(), chan)); } @@ -280,16 +245,14 @@ struct PayChan_test : public beast::unit_test::suite // now the channel between alice and bob can exist { auto const chan = channel(alice, bob, env.seq(alice)); - env(create(alice, bob, XRP(1000), settleDelay, pk), - ter(tesSUCCESS)); + env(create(alice, bob, XRP(1000), settleDelay, pk), ter(tesSUCCESS)); BEAST_EXPECT(channelExists(*env.current(), chan)); } // a channel from cho to alice isn't allowed { auto const chan = channel(cho, alice, env.seq(cho)); - env(create(cho, alice, XRP(1000), settleDelay, pk), - ter(tecNO_PERMISSION)); + env(create(cho, alice, XRP(1000), settleDelay, pk), ter(tecNO_PERMISSION)); BEAST_EXPECT(!channelExists(*env.current(), chan)); } @@ -300,8 +263,7 @@ struct PayChan_test : public beast::unit_test::suite // now a channel from cho to alice is allowed { auto const chan = channel(cho, alice, env.seq(cho)); - env(create(cho, alice, XRP(1000), settleDelay, pk), - ter(tesSUCCESS)); + env(create(cho, alice, XRP(1000), settleDelay, pk), ter(tesSUCCESS)); BEAST_EXPECT(channelExists(*env.current(), chan)); } } @@ -321,8 +283,7 @@ struct PayChan_test : public beast::unit_test::suite env.fund(XRP(10000), alice, bob); auto const pk = alice.pk(); auto const settleDelay = 100s; - NetClock::time_point const cancelAfter = - env.current()->header().parentCloseTime + 3600s; + NetClock::time_point const cancelAfter = env.current()->header().parentCloseTime + 3600s; auto const channelFunds = XRP(1000); auto const chan = channel(alice, bob, env.seq(alice)); env(create(alice, bob, channelFunds, settleDelay, pk, cancelAfter)); @@ -338,8 +299,7 @@ struct PayChan_test : public beast::unit_test::suite auto const reqBal = chanBal + delta; auto const authAmt = reqBal + XRP(100); assert(reqBal <= chanAmt); - auto const sig = - signClaimAuth(alice.pk(), alice.sk(), chan, authAmt); + auto const sig = signClaimAuth(alice.pk(), alice.sk(), chan, authAmt); env(claim(bob, chan, reqBal, authAmt, Slice(sig), alice.pk())); auto const feeDrops = env.current()->fees().base; BEAST_EXPECT(!channelExists(*env.current(), chan)); @@ -353,8 +313,7 @@ struct PayChan_test : public beast::unit_test::suite env.fund(XRP(10000), alice, bob, carol); auto const pk = alice.pk(); auto const settleDelay = 100s; - NetClock::time_point const cancelAfter = - env.current()->header().parentCloseTime + 3600s; + NetClock::time_point const cancelAfter = env.current()->header().parentCloseTime + 3600s; auto const channelFunds = XRP(1000); auto const chan = channel(alice, bob, env.seq(alice)); env(create(alice, bob, channelFunds, settleDelay, pk, cancelAfter)); @@ -374,9 +333,7 @@ struct PayChan_test : public beast::unit_test::suite { for (bool const withFixPayChan : {true, false}) { - auto const amend = withFixPayChan - ? features - : features - fixPayChanCancelAfter; + auto const amend = withFixPayChan ? features : features - fixPayChanCancelAfter; Env env{*this, amend}; env.fund(XRP(10000), alice, bob); env.close(); @@ -384,13 +341,9 @@ struct PayChan_test : public beast::unit_test::suite auto const pk = alice.pk(); auto const settleDelay = 100s; auto const channelFunds = XRP(1000); - NetClock::time_point const cancelAfter = - env.current()->header().parentCloseTime - 1s; - auto const txResult = - withFixPayChan ? ter(tecEXPIRED) : ter(tesSUCCESS); - env(create( - alice, bob, channelFunds, settleDelay, pk, cancelAfter), - txResult); + NetClock::time_point const cancelAfter = env.current()->header().parentCloseTime - 1s; + auto const txResult = withFixPayChan ? ter(tecEXPIRED) : ter(tesSUCCESS); + env(create(alice, bob, channelFunds, settleDelay, pk, cancelAfter), txResult); } } // fixPayChanCancelAfter @@ -398,9 +351,7 @@ struct PayChan_test : public beast::unit_test::suite { for (bool const withFixPayChan : {true, false}) { - auto const amend = withFixPayChan - ? features - : features - fixPayChanCancelAfter; + auto const amend = withFixPayChan ? features : features - fixPayChanCancelAfter; Env env{*this, amend}; env.fund(XRP(10000), alice, bob); env.close(); @@ -408,11 +359,8 @@ struct PayChan_test : public beast::unit_test::suite auto const pk = alice.pk(); auto const settleDelay = 100s; auto const channelFunds = XRP(1000); - NetClock::time_point const cancelAfter = - env.current()->header().parentCloseTime; - env(create( - alice, bob, channelFunds, settleDelay, pk, cancelAfter), - ter(tesSUCCESS)); + NetClock::time_point const cancelAfter = env.current()->header().parentCloseTime; + env(create(alice, bob, channelFunds, settleDelay, pk, cancelAfter), ter(tesSUCCESS)); } } } @@ -440,46 +388,28 @@ struct PayChan_test : public beast::unit_test::suite BEAST_EXPECT(!channelExpiration(*env.current(), chan)); // Owner closes, will close after settleDelay env(claim(alice, chan), txflags(tfClose)); - auto counts = [](auto const& t) { - return t.time_since_epoch().count(); - }; - BEAST_EXPECT( - *channelExpiration(*env.current(), chan) == counts(minExpiration)); + auto counts = [](auto const& t) { return t.time_since_epoch().count(); }; + BEAST_EXPECT(*channelExpiration(*env.current(), chan) == counts(minExpiration)); // increase the expiration time - env(fund( - alice, chan, XRP(1), NetClock::time_point{minExpiration + 100s})); - BEAST_EXPECT( - *channelExpiration(*env.current(), chan) == - counts(minExpiration) + 100); + env(fund(alice, chan, XRP(1), NetClock::time_point{minExpiration + 100s})); + BEAST_EXPECT(*channelExpiration(*env.current(), chan) == counts(minExpiration) + 100); // decrease the expiration, but still above minExpiration - env(fund( - alice, chan, XRP(1), NetClock::time_point{minExpiration + 50s})); - BEAST_EXPECT( - *channelExpiration(*env.current(), chan) == - counts(minExpiration) + 50); + env(fund(alice, chan, XRP(1), NetClock::time_point{minExpiration + 50s})); + BEAST_EXPECT(*channelExpiration(*env.current(), chan) == counts(minExpiration) + 50); // decrease the expiration below minExpiration - env(fund( - alice, chan, XRP(1), NetClock::time_point{minExpiration - 50s}), - ter(temBAD_EXPIRATION)); - BEAST_EXPECT( - *channelExpiration(*env.current(), chan) == - counts(minExpiration) + 50); + env(fund(alice, chan, XRP(1), NetClock::time_point{minExpiration - 50s}), ter(temBAD_EXPIRATION)); + BEAST_EXPECT(*channelExpiration(*env.current(), chan) == counts(minExpiration) + 50); env(claim(bob, chan), txflags(tfRenew), ter(tecNO_PERMISSION)); - BEAST_EXPECT( - *channelExpiration(*env.current(), chan) == - counts(minExpiration) + 50); + BEAST_EXPECT(*channelExpiration(*env.current(), chan) == counts(minExpiration) + 50); env(claim(alice, chan), txflags(tfRenew)); BEAST_EXPECT(!channelExpiration(*env.current(), chan)); // decrease the expiration below minExpiration - env(fund( - alice, chan, XRP(1), NetClock::time_point{minExpiration - 50s}), - ter(temBAD_EXPIRATION)); + env(fund(alice, chan, XRP(1), NetClock::time_point{minExpiration - 50s}), ter(temBAD_EXPIRATION)); BEAST_EXPECT(!channelExpiration(*env.current(), chan)); env(fund(alice, chan, XRP(1), NetClock::time_point{minExpiration})); env.close(minExpiration); // Try to extend the expiration after the expiration has already passed - env(fund( - alice, chan, XRP(1), NetClock::time_point{minExpiration + 1000s})); + env(fund(alice, chan, XRP(1), NetClock::time_point{minExpiration + 1000s})); BEAST_EXPECT(!channelExists(*env.current(), chan)); } @@ -495,8 +425,7 @@ struct PayChan_test : public beast::unit_test::suite env.fund(XRP(10000), alice, bob); auto const pk = alice.pk(); auto const settleDelay = 3600s; - NetClock::time_point const settleTimepoint = - env.current()->header().parentCloseTime + settleDelay; + NetClock::time_point const settleTimepoint = env.current()->header().parentCloseTime + settleDelay; auto const channelFunds = XRP(1000); auto const chan = channel(alice, bob, env.seq(alice)); env(create(alice, bob, channelFunds, settleDelay, pk)); @@ -514,8 +443,7 @@ struct PayChan_test : public beast::unit_test::suite auto const reqBal = chanBal + delta; auto const authAmt = reqBal + XRP(100); assert(reqBal <= chanAmt); - auto const sig = - signClaimAuth(alice.pk(), alice.sk(), chan, authAmt); + auto const sig = signClaimAuth(alice.pk(), alice.sk(), chan, authAmt); env(claim(bob, chan, reqBal, authAmt, Slice(sig), alice.pk())); BEAST_EXPECT(channelBalance(*env.current(), chan) == reqBal); BEAST_EXPECT(channelAmount(*env.current(), chan) == chanAmt); @@ -533,8 +461,7 @@ struct PayChan_test : public beast::unit_test::suite auto const reqBal = chanBal + delta; auto const authAmt = reqBal + XRP(100); assert(reqBal <= chanAmt); - auto const sig = - signClaimAuth(alice.pk(), alice.sk(), chan, authAmt); + auto const sig = signClaimAuth(alice.pk(), alice.sk(), chan, authAmt); env(claim(bob, chan, reqBal, authAmt, Slice(sig), alice.pk())); BEAST_EXPECT(!channelExists(*env.current(), chan)); auto const feeDrops = env.current()->fees().base; @@ -605,8 +532,7 @@ struct PayChan_test : public beast::unit_test::suite auto const delta = XRP(500); auto const reqBal = chanBal + delta; assert(reqBal <= chanAmt); - auto const sig = - signClaimAuth(alice.pk(), alice.sk(), chan, reqBal); + auto const sig = signClaimAuth(alice.pk(), alice.sk(), chan, reqBal); env(claim(bob, chan, reqBal, std::nullopt, Slice(sig), alice.pk())); BEAST_EXPECT(channelBalance(*env.current(), chan) == reqBal); auto const feeDrops = env.current()->fees().base; @@ -622,8 +548,7 @@ struct PayChan_test : public beast::unit_test::suite auto const delta = XRP(500); auto const reqBal = chanBal + delta; assert(reqBal <= chanAmt); - auto const sig = - signClaimAuth(alice.pk(), alice.sk(), chan, reqBal); + auto const sig = signClaimAuth(alice.pk(), alice.sk(), chan, reqBal); env(claim(bob, chan, reqBal, std::nullopt, Slice(sig), alice.pk())); BEAST_EXPECT(channelBalance(*env.current(), chan) == reqBal); auto const feeDrops = env.current()->fees().base; @@ -687,14 +612,12 @@ struct PayChan_test : public beast::unit_test::suite auto const channelFunds = XRP(1000); { auto const chan = channel(alice, bob, env.seq(alice)); - env(create(alice, bob, channelFunds, settleDelay, pk), - ter(tecDST_TAG_NEEDED)); + env(create(alice, bob, channelFunds, settleDelay, pk), ter(tecDST_TAG_NEEDED)); BEAST_EXPECT(!channelExists(*env.current(), chan)); } { auto const chan = channel(alice, bob, env.seq(alice)); - env(create( - alice, bob, channelFunds, settleDelay, pk, std::nullopt, 1)); + env(create(alice, bob, channelFunds, settleDelay, pk, std::nullopt, 1)); BEAST_EXPECT(channelExists(*env.current(), chan)); } } @@ -732,8 +655,7 @@ struct PayChan_test : public beast::unit_test::suite env.close(); // alice claims. Fails because bob's lsfDepositAuth flag is set. - env(claim(alice, chan, XRP(500).value(), XRP(500).value()), - ter(tecNO_PERMISSION)); + env(claim(alice, chan, XRP(500).value(), XRP(500).value()), ter(tecNO_PERMISSION)); env.close(); // Claim with signature @@ -745,8 +667,7 @@ struct PayChan_test : public beast::unit_test::suite // alice claims with signature. Fails since bob has // lsfDepositAuth flag set. - env(claim(alice, chan, delta, delta, Slice(sig), pk), - ter(tecNO_PERMISSION)); + env(claim(alice, chan, delta, delta, Slice(sig), pk), ter(tecNO_PERMISSION)); env.close(); BEAST_EXPECT(env.balance(bob) == preBob); @@ -769,8 +690,7 @@ struct PayChan_test : public beast::unit_test::suite // carol claims and fails. Only channel participants (bob or // alice) may claim. - env(claim(carol, chan, delta, delta, Slice(sig), pk), - ter(tecNO_PERMISSION)); + env(claim(carol, chan, delta, delta, Slice(sig), pk), ter(tecNO_PERMISSION)); env.close(); // bob preauthorizes carol for deposit. But after that carol @@ -778,13 +698,11 @@ struct PayChan_test : public beast::unit_test::suite env(deposit::auth(bob, carol)); env.close(); - env(claim(carol, chan, delta, delta, Slice(sig), pk), - ter(tecNO_PERMISSION)); + env(claim(carol, chan, delta, delta, Slice(sig), pk), ter(tecNO_PERMISSION)); // Since alice is not preauthorized she also may not claim // for bob. - env(claim(alice, chan, delta, delta, Slice(sig), pk), - ter(tecNO_PERMISSION)); + env(claim(alice, chan, delta, delta, Slice(sig), pk), ter(tecNO_PERMISSION)); env.close(); // However if bob preauthorizes alice for deposit then she can @@ -795,8 +713,7 @@ struct PayChan_test : public beast::unit_test::suite env(claim(alice, chan, delta, delta, Slice(sig), pk)); env.close(); - BEAST_EXPECT( - env.balance(bob) == preBob + delta - (3 * baseFee)); + BEAST_EXPECT(env.balance(bob) == preBob + delta - (3 * baseFee)); } { // bob removes pre-authorization of alice. Once again she @@ -817,8 +734,7 @@ struct PayChan_test : public beast::unit_test::suite // alice claims successfully. env(claim(alice, chan, delta, delta)); env.close(); - BEAST_EXPECT( - env.balance(bob) == preBob + XRP(800) - (5 * baseFee)); + BEAST_EXPECT(env.balance(bob) == preBob + XRP(800) - (5 * baseFee)); } } } @@ -860,18 +776,13 @@ struct PayChan_test : public beast::unit_test::suite { // create credentials auto jv = credentials::create(alice, carol, credType); - uint32_t const t = env.current() - ->header() - .parentCloseTime.time_since_epoch() - .count() + - 100; + uint32_t const t = env.current()->header().parentCloseTime.time_since_epoch().count() + 100; jv[sfExpiration.jsonName] = t; env(jv); env.close(); } - auto const jv = - credentials::ledgerEntry(env, alice, carol, credType); + auto const jv = credentials::ledgerEntry(env, alice, carol, credType); std::string const credIdx = jv[jss::result][jss::index].asString(); // Bob require pre-authorization @@ -879,18 +790,14 @@ struct PayChan_test : public beast::unit_test::suite env.close(); // Fail, credentials not accepted - env(claim(alice, chan, delta, delta), - credentials::ids({credIdx}), - ter(tecBAD_CREDENTIALS)); + env(claim(alice, chan, delta, delta), credentials::ids({credIdx}), ter(tecBAD_CREDENTIALS)); env.close(); env(credentials::accept(alice, carol, credType)); env.close(); // Fail, no depositPreauth object - env(claim(alice, chan, delta, delta), - credentials::ids({credIdx}), - ter(tecNO_PERMISSION)); + env(claim(alice, chan, delta, delta), credentials::ids({credIdx}), ter(tecNO_PERMISSION)); env.close(); // Setup deposit authorization @@ -898,22 +805,16 @@ struct PayChan_test : public beast::unit_test::suite env.close(); // Fail, credentials doesn’t belong to root account - env(claim(dillon, chan, delta, delta), - credentials::ids({credIdx}), - ter(tecBAD_CREDENTIALS)); + env(claim(dillon, chan, delta, delta), credentials::ids({credIdx}), ter(tecBAD_CREDENTIALS)); // Fails because bob's lsfDepositAuth flag is set. env(claim(alice, chan, delta, delta), ter(tecNO_PERMISSION)); // Fail, bad credentials index. - env(claim(alice, chan, delta, delta), - credentials::ids({credBadIdx}), - ter(tecBAD_CREDENTIALS)); + env(claim(alice, chan, delta, delta), credentials::ids({credBadIdx}), ter(tecBAD_CREDENTIALS)); // Fail, empty credentials - env(claim(alice, chan, delta, delta), - credentials::ids({}), - ter(temMALFORMED)); + env(claim(alice, chan, delta, delta), credentials::ids({}), ter(temMALFORMED)); { // claim fails cause of expired credentials @@ -922,9 +823,7 @@ struct PayChan_test : public beast::unit_test::suite for (int i = 0; i < 10; ++i) env.close(); - env(claim(alice, chan, delta, delta), - credentials::ids({credIdx}), - ter(tecEXPIRED)); + env(claim(alice, chan, delta, delta), credentials::ids({credIdx}), ter(tecEXPIRED)); env.close(); } @@ -934,14 +833,11 @@ struct PayChan_test : public beast::unit_test::suite env(credentials::accept(alice, carol, credType)); env.close(); - auto const jv = - credentials::ledgerEntry(env, alice, carol, credType); - std::string const credIdx = - jv[jss::result][jss::index].asString(); + auto const jv = credentials::ledgerEntry(env, alice, carol, credType); + std::string const credIdx = jv[jss::result][jss::index].asString(); // Success - env(claim(alice, chan, delta, delta), - credentials::ids({credIdx})); + env(claim(alice, chan, delta, delta), credentials::ids({credIdx})); } } @@ -968,8 +864,7 @@ struct PayChan_test : public beast::unit_test::suite env.close(); } - auto const jv = - credentials::ledgerEntry(env, alice, carol, credType); + auto const jv = credentials::ledgerEntry(env, alice, carol, credType); std::string const credIdx = jv[jss::result][jss::index].asString(); // Succeed, lsfDepositAuth is not set @@ -1001,9 +896,7 @@ struct PayChan_test : public beast::unit_test::suite env(deposit::auth(bob, alice)); env.close(); - env(claim(alice, chan, XRP(500).value(), XRP(500).value()), - credentials::ids({credIdx}), - ter(temDISABLED)); + env(claim(alice, chan, XRP(500).value(), XRP(500).value()), credentials::ids({credIdx}), ter(temDISABLED)); } } @@ -1053,11 +946,9 @@ struct PayChan_test : public beast::unit_test::suite auto testInvalidAccountParam = [&](auto const& param) { Json::Value params; params[jss::account] = param; - auto jrr = env.rpc( - "json", "account_channels", to_string(params))[jss::result]; + auto jrr = env.rpc("json", "account_channels", to_string(params))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); - BEAST_EXPECT( - jrr[jss::error_message] == "Invalid field 'account'."); + BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'account'."); }; testInvalidAccountParam(1); @@ -1068,23 +959,19 @@ struct PayChan_test : public beast::unit_test::suite testInvalidAccountParam(Json::Value(Json::arrayValue)); } { - auto const r = - env.rpc("account_channels", alice.human(), bob.human()); + auto const r = env.rpc("account_channels", alice.human(), bob.human()); BEAST_EXPECT(r[jss::result][jss::channels].size() == 1); - BEAST_EXPECT( - r[jss::result][jss::channels][0u][jss::channel_id] == chan1Str); + BEAST_EXPECT(r[jss::result][jss::channels][0u][jss::channel_id] == chan1Str); BEAST_EXPECT(r[jss::result][jss::validated]); } { auto const r = env.rpc("account_channels", alice.human()); BEAST_EXPECT(r[jss::result][jss::channels].size() == 1); - BEAST_EXPECT( - r[jss::result][jss::channels][0u][jss::channel_id] == chan1Str); + BEAST_EXPECT(r[jss::result][jss::channels][0u][jss::channel_id] == chan1Str); BEAST_EXPECT(r[jss::result][jss::validated]); } { - auto const r = - env.rpc("account_channels", bob.human(), alice.human()); + auto const r = env.rpc("account_channels", bob.human(), alice.human()); BEAST_EXPECT(r[jss::result][jss::channels].size() == 0); BEAST_EXPECT(r[jss::result][jss::validated]); } @@ -1092,8 +979,7 @@ struct PayChan_test : public beast::unit_test::suite env(create(alice, bob, channelFunds, settleDelay, pk)); env.close(); { - auto const r = - env.rpc("account_channels", alice.human(), bob.human()); + auto const r = env.rpc("account_channels", alice.human(), bob.human()); BEAST_EXPECT(r[jss::result][jss::channels].size() == 2); BEAST_EXPECT(r[jss::result][jss::validated]); BEAST_EXPECT(chan1Str != chan2Str); @@ -1146,8 +1032,7 @@ struct PayChan_test : public beast::unit_test::suite test::jtx::Account const& src, std::optional limit = std::nullopt, Json::Value const& marker = Json::nullValue, - std::optional const& dst = - std::nullopt) { + std::optional const& dst = std::nullopt) { Json::Value jvc; jvc[jss::account] = src.human(); if (dst) @@ -1157,8 +1042,7 @@ struct PayChan_test : public beast::unit_test::suite if (marker) jvc[jss::marker] = marker; - return env.rpc( - "json", "account_channels", to_string(jvc))[jss::result]; + return env.rpc("json", "account_channels", to_string(jvc))[jss::result]; }; { @@ -1193,8 +1077,7 @@ struct PayChan_test : public beast::unit_test::suite auto const s = r[jss::channels].size(); for (int j = 0; j < s; ++j) { - auto const dstAcc = - c[j][jss::destination_account].asString(); + auto const dstAcc = c[j][jss::destination_account].asString(); BEAST_EXPECT(leftToFind.count(dstAcc)); leftToFind.erase(dstAcc); } @@ -1247,14 +1130,11 @@ struct PayChan_test : public beast::unit_test::suite Json::Value jvc; jvc[jss::account] = alice.human(); - return env.rpc( - "json", "account_channels", to_string(jvc))[jss::result]; + return env.rpc("json", "account_channels", to_string(jvc))[jss::result]; }(); BEAST_EXPECT(r.isMember(jss::channels)); BEAST_EXPECT(r[jss::channels].size() == 1); - BEAST_EXPECT( - r[jss::channels][0u][jss::destination_account].asString() == - bob.human()); + BEAST_EXPECT(r[jss::channels][0u][jss::destination_account].asString() == bob.human()); } void @@ -1283,13 +1163,9 @@ struct PayChan_test : public beast::unit_test::suite // test for all api versions forAllApiVersions([&, this](unsigned apiVersion) { - testcase( - "PayChan Channel_Auth RPC Api " + std::to_string(apiVersion)); + testcase("PayChan Channel_Auth RPC Api " + std::to_string(apiVersion)); args[jss::api_version] = apiVersion; - auto const rs = env.rpc( - "json", - "channel_authorize", - args.toStyledString())[jss::result]; + auto const rs = env.rpc("json", "channel_authorize", args.toStyledString())[jss::result]; auto const error = apiVersion < 2u ? "invalidParams" : "badKeyType"; BEAST_EXPECT(rs[jss::error] == error); }); @@ -1314,27 +1190,21 @@ struct PayChan_test : public beast::unit_test::suite env.close(); std::string chan1PkStr; { - auto const r = - env.rpc("account_channels", alice.human(), bob.human()); + auto const r = env.rpc("account_channels", alice.human(), bob.human()); BEAST_EXPECT(r[jss::result][jss::channels].size() == 1); - BEAST_EXPECT( - r[jss::result][jss::channels][0u][jss::channel_id] == chan1Str); + BEAST_EXPECT(r[jss::result][jss::channels][0u][jss::channel_id] == chan1Str); BEAST_EXPECT(r[jss::result][jss::validated]); - chan1PkStr = - r[jss::result][jss::channels][0u][jss::public_key].asString(); + chan1PkStr = r[jss::result][jss::channels][0u][jss::public_key].asString(); } { auto const r = env.rpc("account_channels", alice.human()); BEAST_EXPECT(r[jss::result][jss::channels].size() == 1); - BEAST_EXPECT( - r[jss::result][jss::channels][0u][jss::channel_id] == chan1Str); + BEAST_EXPECT(r[jss::result][jss::channels][0u][jss::channel_id] == chan1Str); BEAST_EXPECT(r[jss::result][jss::validated]); - chan1PkStr = - r[jss::result][jss::channels][0u][jss::public_key].asString(); + chan1PkStr = r[jss::result][jss::channels][0u][jss::public_key].asString(); } { - auto const r = - env.rpc("account_channels", bob.human(), alice.human()); + auto const r = env.rpc("account_channels", bob.human(), alice.human()); BEAST_EXPECT(r[jss::result][jss::channels].size() == 0); BEAST_EXPECT(r[jss::result][jss::validated]); } @@ -1342,8 +1212,7 @@ struct PayChan_test : public beast::unit_test::suite env(create(alice, bob, channelFunds, settleDelay, pk)); env.close(); { - auto const r = - env.rpc("account_channels", alice.human(), bob.human()); + auto const r = env.rpc("account_channels", alice.human(), bob.human()); BEAST_EXPECT(r[jss::result][jss::channels].size() == 2); BEAST_EXPECT(r[jss::result][jss::validated]); BEAST_EXPECT(chan1Str != chan2Str); @@ -1366,28 +1235,24 @@ struct PayChan_test : public beast::unit_test::suite { // Verify chan1 auth - auto const rs = - env.rpc("channel_authorize", "alice", chan1Str, "1000"); + auto const rs = env.rpc("channel_authorize", "alice", chan1Str, "1000"); auto const sig = rs[jss::result][jss::signature].asString(); BEAST_EXPECT(!sig.empty()); { - auto const rv = env.rpc( - "channel_verify", chan1PkStr, chan1Str, "1000", sig); + auto const rv = env.rpc("channel_verify", chan1PkStr, chan1Str, "1000", sig); BEAST_EXPECT(rv[jss::result][jss::signature_verified].asBool()); } { // use pk hex to verify auto const pkAsHex = sliceToHex(pk.slice()); - auto const rv = - env.rpc("channel_verify", pkAsHex, chan1Str, "1000", sig); + auto const rv = env.rpc("channel_verify", pkAsHex, chan1Str, "1000", sig); BEAST_EXPECT(rv[jss::result][jss::signature_verified].asBool()); } { // malformed amount auto const pkAsHex = sliceToHex(pk.slice()); - auto rv = - env.rpc("channel_verify", pkAsHex, chan1Str, "1000x", sig); + auto rv = env.rpc("channel_verify", pkAsHex, chan1Str, "1000x", sig); BEAST_EXPECT(rv[jss::error] == "channelAmtMalformed"); rv = env.rpc("channel_verify", pkAsHex, chan1Str, "1000 ", sig); BEAST_EXPECT(rv[jss::error] == "channelAmtMalformed"); @@ -1397,8 +1262,7 @@ struct PayChan_test : public beast::unit_test::suite BEAST_EXPECT(rv[jss::error] == "channelAmtMalformed"); rv = env.rpc("channel_verify", pkAsHex, chan1Str, " ", sig); BEAST_EXPECT(rv[jss::error] == "channelAmtMalformed"); - rv = env.rpc( - "channel_verify", pkAsHex, chan1Str, "1000 1000", sig); + rv = env.rpc("channel_verify", pkAsHex, chan1Str, "1000 1000", sig); BEAST_EXPECT(rv[jss::error] == "channelAmtMalformed"); rv = env.rpc("channel_verify", pkAsHex, chan1Str, "1,000", sig); BEAST_EXPECT(rv[jss::error] == "channelAmtMalformed"); @@ -1412,24 +1276,21 @@ struct PayChan_test : public beast::unit_test::suite auto const pkAsHex = sliceToHex(pk.slice()); auto chan1StrBad = chan1Str; chan1StrBad.pop_back(); - auto rv = env.rpc( - "channel_verify", pkAsHex, chan1StrBad, "1000", sig); + auto rv = env.rpc("channel_verify", pkAsHex, chan1StrBad, "1000", sig); BEAST_EXPECT(rv[jss::error] == "channelMalformed"); rv = env.rpc("channel_authorize", "alice", chan1StrBad, "1000"); BEAST_EXPECT(rv[jss::error] == "channelMalformed"); chan1StrBad = chan1Str; chan1StrBad.push_back('0'); - rv = env.rpc( - "channel_verify", pkAsHex, chan1StrBad, "1000", sig); + rv = env.rpc("channel_verify", pkAsHex, chan1StrBad, "1000", sig); BEAST_EXPECT(rv[jss::error] == "channelMalformed"); rv = env.rpc("channel_authorize", "alice", chan1StrBad, "1000"); BEAST_EXPECT(rv[jss::error] == "channelMalformed"); chan1StrBad = chan1Str; chan1StrBad.back() = 'x'; - rv = env.rpc( - "channel_verify", pkAsHex, chan1StrBad, "1000", sig); + rv = env.rpc("channel_verify", pkAsHex, chan1StrBad, "1000", sig); BEAST_EXPECT(rv[jss::error] == "channelMalformed"); rv = env.rpc("channel_authorize", "alice", chan1StrBad, "1000"); BEAST_EXPECT(rv[jss::error] == "channelMalformed"); @@ -1437,100 +1298,77 @@ struct PayChan_test : public beast::unit_test::suite { // give an ill formed base 58 public key auto illFormedPk = chan1PkStr.substr(0, chan1PkStr.size() - 1); - auto const rv = env.rpc( - "channel_verify", illFormedPk, chan1Str, "1000", sig); - BEAST_EXPECT( - !rv[jss::result][jss::signature_verified].asBool()); + auto const rv = env.rpc("channel_verify", illFormedPk, chan1Str, "1000", sig); + BEAST_EXPECT(!rv[jss::result][jss::signature_verified].asBool()); } { // give an ill formed hex public key auto const pkAsHex = sliceToHex(pk.slice()); auto illFormedPk = pkAsHex.substr(0, chan1PkStr.size() - 1); - auto const rv = env.rpc( - "channel_verify", illFormedPk, chan1Str, "1000", sig); - BEAST_EXPECT( - !rv[jss::result][jss::signature_verified].asBool()); + auto const rv = env.rpc("channel_verify", illFormedPk, chan1Str, "1000", sig); + BEAST_EXPECT(!rv[jss::result][jss::signature_verified].asBool()); } } { // Try to verify chan2 auth with chan1 key - auto const rs = - env.rpc("channel_authorize", "alice", chan2Str, "1000"); + auto const rs = env.rpc("channel_authorize", "alice", chan2Str, "1000"); auto const sig = rs[jss::result][jss::signature].asString(); BEAST_EXPECT(!sig.empty()); { - auto const rv = env.rpc( - "channel_verify", chan1PkStr, chan1Str, "1000", sig); - BEAST_EXPECT( - !rv[jss::result][jss::signature_verified].asBool()); + auto const rv = env.rpc("channel_verify", chan1PkStr, chan1Str, "1000", sig); + BEAST_EXPECT(!rv[jss::result][jss::signature_verified].asBool()); } { // use pk hex to verify auto const pkAsHex = sliceToHex(pk.slice()); - auto const rv = - env.rpc("channel_verify", pkAsHex, chan1Str, "1000", sig); - BEAST_EXPECT( - !rv[jss::result][jss::signature_verified].asBool()); + auto const rv = env.rpc("channel_verify", pkAsHex, chan1Str, "1000", sig); + BEAST_EXPECT(!rv[jss::result][jss::signature_verified].asBool()); } } { // Try to explicitly specify secp256k1 and Ed25519 keys: - auto const chan = - to_string(channel(charlie, alice, env.seq(charlie))); - env(create( - charlie, alice, channelFunds, settleDelay, charlie.pk())); + auto const chan = to_string(channel(charlie, alice, env.seq(charlie))); + env(create(charlie, alice, channelFunds, settleDelay, charlie.pk())); env.close(); std::string cpk; { - auto const r = - env.rpc("account_channels", charlie.human(), alice.human()); + auto const r = env.rpc("account_channels", charlie.human(), alice.human()); BEAST_EXPECT(r[jss::result][jss::channels].size() == 1); - BEAST_EXPECT( - r[jss::result][jss::channels][0u][jss::channel_id] == chan); + BEAST_EXPECT(r[jss::result][jss::channels][0u][jss::channel_id] == chan); BEAST_EXPECT(r[jss::result][jss::validated]); - cpk = r[jss::result][jss::channels][0u][jss::public_key] - .asString(); + cpk = r[jss::result][jss::channels][0u][jss::public_key].asString(); } // Try to authorize without specifying a key type, expect an error: - auto const rs = - env.rpc("channel_authorize", "charlie", chan, "1000"); + auto const rs = env.rpc("channel_authorize", "charlie", chan, "1000"); auto const sig = rs[jss::result][jss::signature].asString(); BEAST_EXPECT(!sig.empty()); { - auto const rv = - env.rpc("channel_verify", cpk, chan, "1000", sig); - BEAST_EXPECT( - !rv[jss::result][jss::signature_verified].asBool()); + auto const rv = env.rpc("channel_verify", cpk, chan, "1000", sig); + BEAST_EXPECT(!rv[jss::result][jss::signature_verified].asBool()); } // Try to authorize using an unknown key type, except an error: - auto const rs1 = - env.rpc("channel_authorize", "charlie", "nyx", chan, "1000"); + auto const rs1 = env.rpc("channel_authorize", "charlie", "nyx", chan, "1000"); BEAST_EXPECT(rs1[jss::error] == "badKeyType"); // Try to authorize using secp256k1; the authorization _should_ // succeed but the verification should fail: - auto const rs2 = env.rpc( - "channel_authorize", "charlie", "secp256k1", chan, "1000"); + auto const rs2 = env.rpc("channel_authorize", "charlie", "secp256k1", chan, "1000"); auto const sig2 = rs2[jss::result][jss::signature].asString(); BEAST_EXPECT(!sig2.empty()); { - auto const rv = - env.rpc("channel_verify", cpk, chan, "1000", sig2); - BEAST_EXPECT( - !rv[jss::result][jss::signature_verified].asBool()); + auto const rv = env.rpc("channel_verify", cpk, chan, "1000", sig2); + BEAST_EXPECT(!rv[jss::result][jss::signature_verified].asBool()); } // Try to authorize using Ed25519; expect success: - auto const rs3 = env.rpc( - "channel_authorize", "charlie", "ed25519", chan, "1000"); + auto const rs3 = env.rpc("channel_authorize", "charlie", "ed25519", chan, "1000"); auto const sig3 = rs3[jss::result][jss::signature].asString(); BEAST_EXPECT(!sig3.empty()); { - auto const rv = - env.rpc("channel_verify", cpk, chan, "1000", sig3); + auto const rv = env.rpc("channel_verify", cpk, chan, "1000", sig3); BEAST_EXPECT(rv[jss::result][jss::signature_verified].asBool()); } } @@ -1549,10 +1387,7 @@ struct PayChan_test : public beast::unit_test::suite args[jss::amount] = "2000"; args[jss::key_type] = "secp256k1"; args[jss::passphrase] = "passphrase_can_be_anything"; - rs = env.rpc( - "json", - "channel_authorize", - args.toStyledString())[jss::result]; + rs = env.rpc("json", "channel_authorize", args.toStyledString())[jss::result]; BEAST_EXPECT(rs[jss::error] == "invalidParams"); } { @@ -1561,10 +1396,7 @@ struct PayChan_test : public beast::unit_test::suite args[jss::channel_id] = chan1Str; args[jss::key_type] = "secp256k1"; args[jss::passphrase] = "passphrase_can_be_anything"; - rs = env.rpc( - "json", - "channel_authorize", - args.toStyledString())[jss::result]; + rs = env.rpc("json", "channel_authorize", args.toStyledString())[jss::result]; BEAST_EXPECT(rs[jss::error] == "invalidParams"); } { @@ -1573,10 +1405,7 @@ struct PayChan_test : public beast::unit_test::suite args[jss::amount] = "2000"; args[jss::channel_id] = chan1Str; args[jss::passphrase] = "passphrase_can_be_anything"; - rs = env.rpc( - "json", - "channel_authorize", - args.toStyledString())[jss::result]; + rs = env.rpc("json", "channel_authorize", args.toStyledString())[jss::result]; BEAST_EXPECT(rs[jss::error] == "invalidParams"); } { @@ -1587,10 +1416,7 @@ struct PayChan_test : public beast::unit_test::suite args[jss::key_type] = "secp256k1"; args[jss::passphrase] = "passphrase_can_be_anything"; args[jss::seed] = "seed can be anything"; - rs = env.rpc( - "json", - "channel_authorize", - args.toStyledString())[jss::result]; + rs = env.rpc("json", "channel_authorize", args.toStyledString())[jss::result]; BEAST_EXPECT(rs[jss::error] == "invalidParams"); } { @@ -1600,10 +1426,7 @@ struct PayChan_test : public beast::unit_test::suite args[jss::channel_id] = chan1Str + "1"; args[jss::key_type] = "secp256k1"; args[jss::passphrase] = "passphrase_can_be_anything"; - rs = env.rpc( - "json", - "channel_authorize", - args.toStyledString())[jss::result]; + rs = env.rpc("json", "channel_authorize", args.toStyledString())[jss::result]; BEAST_EXPECT(rs[jss::error] == "channelMalformed"); } { @@ -1613,10 +1436,7 @@ struct PayChan_test : public beast::unit_test::suite args[jss::channel_id] = chan1Str; args[jss::key_type] = "secp256k1"; args[jss::passphrase] = "passphrase_can_be_anything"; - rs = env.rpc( - "json", - "channel_authorize", - args.toStyledString())[jss::result]; + rs = env.rpc("json", "channel_authorize", args.toStyledString())[jss::result]; BEAST_EXPECT(rs[jss::error] == "channelAmtMalformed"); } { @@ -1626,10 +1446,7 @@ struct PayChan_test : public beast::unit_test::suite args[jss::channel_id] = chan1Str; args[jss::key_type] = "secp256k1"; args[jss::passphrase] = "passphrase_can_be_anything"; - rs = env.rpc( - "json", - "channel_authorize", - args.toStyledString())[jss::result]; + rs = env.rpc("json", "channel_authorize", args.toStyledString())[jss::result]; BEAST_EXPECT(rs[jss::error] == "channelAmtMalformed"); } } @@ -1656,33 +1473,19 @@ struct PayChan_test : public beast::unit_test::suite { auto const chan = to_string(channel(alice, bob, env.seq(alice))); env(create(alice, bob, channelFunds, settleDelay, pk)); - auto const r = - env.rpc("account_channels", alice.human(), bob.human()); + auto const r = env.rpc("account_channels", alice.human(), bob.human()); BEAST_EXPECT(r[jss::result][jss::channels].size() == 1); - BEAST_EXPECT( - r[jss::result][jss::channels][0u][jss::channel_id] == chan); - BEAST_EXPECT(!r[jss::result][jss::channels][0u].isMember( - jss::destination_tag)); + BEAST_EXPECT(r[jss::result][jss::channels][0u][jss::channel_id] == chan); + BEAST_EXPECT(!r[jss::result][jss::channels][0u].isMember(jss::destination_tag)); } { std::uint32_t dstTag = 42; auto const chan = to_string(channel(alice, carol, env.seq(alice))); - env(create( - alice, - carol, - channelFunds, - settleDelay, - pk, - cancelAfter, - dstTag)); - auto const r = - env.rpc("account_channels", alice.human(), carol.human()); + env(create(alice, carol, channelFunds, settleDelay, pk, cancelAfter, dstTag)); + auto const r = env.rpc("account_channels", alice.human(), carol.human()); BEAST_EXPECT(r[jss::result][jss::channels].size() == 1); - BEAST_EXPECT( - r[jss::result][jss::channels][0u][jss::channel_id] == chan); - BEAST_EXPECT( - r[jss::result][jss::channels][0u][jss::destination_tag] == - dstTag); + BEAST_EXPECT(r[jss::result][jss::channels][0u][jss::channel_id] == chan); + BEAST_EXPECT(r[jss::result][jss::channels][0u][jss::destination_tag] == dstTag); } } @@ -1718,13 +1521,7 @@ struct PayChan_test : public beast::unit_test::suite auto const authAmt = XRP(100); auto const sig = signClaimAuth(alice.pk(), alice.sk(), chan, authAmt); - jv = claim( - bob, - chan, - authAmt.value(), - authAmt.value(), - Slice(sig), - alice.pk()); + jv = claim(bob, chan, authAmt.value(), authAmt.value(), Slice(sig), alice.pk()); jv["PublicKey"] = pkHex.substr(2, pkHex.size() - 2); env(jv, ter(temMALFORMED)); jv["PublicKey"] = pkHex.substr(0, pkHex.size() - 2); @@ -1769,16 +1566,12 @@ struct PayChan_test : public beast::unit_test::suite auto const settleDelay = 100s; auto const pk = alice.pk(); - auto inOwnerDir = [](ReadView const& view, - Account const& acc, - std::shared_ptr const& chan) -> bool { + auto inOwnerDir = [](ReadView const& view, Account const& acc, std::shared_ptr const& chan) -> bool { xrpl::Dir const ownerDir(view, keylet::ownerDir(acc.id())); - return std::find(ownerDir.begin(), ownerDir.end(), chan) != - ownerDir.end(); + return std::find(ownerDir.begin(), ownerDir.end(), chan) != ownerDir.end(); }; - auto ownerDirCount = [](ReadView const& view, - Account const& acc) -> std::size_t { + auto ownerDirCount = [](ReadView const& view, Account const& acc) -> std::size_t { xrpl::Dir const ownerDir(view, keylet::ownerDir(acc.id())); return std::distance(ownerDir.begin(), ownerDir.end()); }; @@ -1789,8 +1582,7 @@ struct PayChan_test : public beast::unit_test::suite env.fund(XRP(10000), alice, bob); env(create(alice, bob, XRP(1000), settleDelay, pk)); env.close(); - auto const [chan, chanSle] = - channelKeyAndSle(*env.current(), alice, bob); + auto const [chan, chanSle] = channelKeyAndSle(*env.current(), alice, bob); BEAST_EXPECT(inOwnerDir(*env.current(), alice, chanSle)); BEAST_EXPECT(ownerDirCount(*env.current(), alice) == 1); BEAST_EXPECT(inOwnerDir(*env.current(), bob, chanSle)); @@ -1812,8 +1604,7 @@ struct PayChan_test : public beast::unit_test::suite // create the channel before the amendment activates env(create(alice, bob, XRP(1000), settleDelay, pk)); env.close(); - auto const [chan, chanSle] = - channelKeyAndSle(*env.current(), alice, bob); + auto const [chan, chanSle] = channelKeyAndSle(*env.current(), alice, bob); BEAST_EXPECT(inOwnerDir(*env.current(), alice, chanSle)); BEAST_EXPECT(ownerDirCount(*env.current(), alice) == 1); BEAST_EXPECT(inOwnerDir(*env.current(), bob, chanSle)); @@ -1834,26 +1625,16 @@ struct PayChan_test : public beast::unit_test::suite testcase("Account Delete"); using namespace test::jtx; using namespace std::literals::chrono_literals; - auto rmAccount = [this]( - Env& env, - Account const& toRm, - Account const& dst, - TER expectedTer = tesSUCCESS) { + auto rmAccount = [this](Env& env, Account const& toRm, Account const& dst, TER expectedTer = tesSUCCESS) { // only allow an account to be deleted if the account's sequence // number is at least 256 less than the current ledger sequence - for (auto minRmSeq = env.seq(toRm) + 257; - env.current()->seq() < minRmSeq; - env.close()) + for (auto minRmSeq = env.seq(toRm) + 257; env.current()->seq() < minRmSeq; env.close()) { } - env(acctdelete(toRm, dst), - fee(drops(env.current()->fees().increment)), - ter(expectedTer)); + env(acctdelete(toRm, dst), fee(drops(env.current()->fees().increment)), ter(expectedTer)); env.close(); - this->BEAST_EXPECT( - isTesSuccess(expectedTer) == - !env.closed()->exists(keylet::account(toRm.id()))); + this->BEAST_EXPECT(isTesSuccess(expectedTer) == !env.closed()->exists(keylet::account(toRm.id()))); }; auto const alice = Account("alice"); @@ -1900,8 +1681,7 @@ struct PayChan_test : public beast::unit_test::suite env(fund(alice, chan, XRP(1000))); env.close(); BEAST_EXPECT(env.balance(alice) == preAlice - XRP(1000) - feeDrops); - BEAST_EXPECT( - channelAmount(*env.current(), chan) == chanAmt + XRP(1000)); + BEAST_EXPECT(channelAmount(*env.current(), chan) == chanAmt + XRP(1000)); chanAmt = chanAmt + XRP(1000); { @@ -1946,8 +1726,7 @@ struct PayChan_test : public beast::unit_test::suite auto const settleDelay = 100s; auto const chan = channel(alice, bob, aliceTicketSeq); - env(create(alice, bob, XRP(1000), settleDelay, pk), - ticket::use(aliceTicketSeq++)); + env(create(alice, bob, XRP(1000), settleDelay, pk), ticket::use(aliceTicketSeq++)); env.require(tickets(alice, env.seq(alice) - aliceTicketSeq)); BEAST_EXPECT(env.seq(alice) == aliceSeq); @@ -1978,8 +1757,7 @@ struct PayChan_test : public beast::unit_test::suite auto const reqBal = chanBal + delta; auto const authAmt = reqBal + XRP(100); assert(reqBal <= chanAmt); - env(claim(alice, chan, reqBal, authAmt), - ticket::use(aliceTicketSeq++)); + env(claim(alice, chan, reqBal, authAmt), ticket::use(aliceTicketSeq++)); env.require(tickets(alice, env.seq(alice) - aliceTicketSeq)); BEAST_EXPECT(env.seq(alice) == aliceSeq); @@ -1996,10 +1774,8 @@ struct PayChan_test : public beast::unit_test::suite auto const reqBal = chanBal + delta; auto const authAmt = reqBal + XRP(100); assert(reqBal <= chanAmt); - auto const sig = - signClaimAuth(alice.pk(), alice.sk(), chan, authAmt); - env(claim(bob, chan, reqBal, authAmt, Slice(sig), alice.pk()), - ticket::use(bobTicketSeq++)); + auto const sig = signClaimAuth(alice.pk(), alice.sk(), chan, authAmt); + env(claim(bob, chan, reqBal, authAmt, Slice(sig), alice.pk()), ticket::use(bobTicketSeq++)); env.require(tickets(bob, env.seq(bob) - bobTicketSeq)); BEAST_EXPECT(env.seq(bob) == bobSeq); @@ -2032,8 +1808,7 @@ struct PayChan_test : public beast::unit_test::suite assert(reqAmt <= chanAmt); // Note that since claim() returns a tem (neither tec nor tes), // the ticket is not consumed. So we don't increment bobTicket. - auto const sig = - signClaimAuth(alice.pk(), alice.sk(), chan, authAmt); + auto const sig = signClaimAuth(alice.pk(), alice.sk(), chan, authAmt); env(claim(bob, chan, reqAmt, authAmt, Slice(sig), alice.pk()), ticket::use(bobTicketSeq), ter(temBAD_AMOUNT)); @@ -2047,9 +1822,7 @@ struct PayChan_test : public beast::unit_test::suite } // Dst tries to fund the channel - env(fund(bob, chan, XRP(1000)), - ticket::use(bobTicketSeq++), - ter(tecNO_PERMISSION)); + env(fund(bob, chan, XRP(1000)), ticket::use(bobTicketSeq++), ter(tecNO_PERMISSION)); env.require(tickets(bob, env.seq(bob) - bobTicketSeq)); BEAST_EXPECT(env.seq(bob) == bobSeq); @@ -2061,9 +1834,7 @@ struct PayChan_test : public beast::unit_test::suite // Dst closes channel auto const preAlice = env.balance(alice); auto const preBob = env.balance(bob); - env(claim(bob, chan), - txflags(tfClose), - ticket::use(bobTicketSeq++)); + env(claim(bob, chan), txflags(tfClose), ticket::use(bobTicketSeq++)); env.require(tickets(bob, env.seq(bob) - bobTicketSeq)); BEAST_EXPECT(env.seq(bob) == bobSeq); diff --git a/src/test/app/PayStrand_test.cpp b/src/test/app/PayStrand_test.cpp index 8e0ff337b4..9b534d9284 100644 --- a/src/test/app/PayStrand_test.cpp +++ b/src/test/app/PayStrand_test.cpp @@ -53,12 +53,7 @@ trustFlag(TrustFlag f, bool useHigh) } bool -getTrustFlag( - jtx::Env const& env, - jtx::Account const& src, - jtx::Account const& dst, - Currency const& cur, - TrustFlag flag) +getTrustFlag(jtx::Env const& env, jtx::Account const& src, jtx::Account const& dst, Currency const& cur, TrustFlag flag) { if (auto sle = env.le(keylet::line(src, dst, cur))) { @@ -78,11 +73,11 @@ equal(std::unique_ptr const& s1, DirectStepInfo const& dsi) } bool -equal(std::unique_ptr const& s1, XRPEndpointStepInfo const& xrpsi) +equal(std::unique_ptr const& s1, XRPEndpointStepInfo const& xrpStepInfo) { if (!s1) return false; - return test::xrpEndpointStepEqual(*s1, xrpsi.acc); + return test::xrpEndpointStepEqual(*s1, xrpStepInfo.acc); } bool @@ -124,8 +119,7 @@ equal(Strand const& strand, Args&&... args) STPathElement ape(AccountID const& a) { - return STPathElement( - STPathElement::typeAccount, a, xrpCurrency(), xrpAccount()); + return STPathElement(STPathElement::typeAccount, a, xrpCurrency(), xrpAccount()); }; // Issue path element @@ -133,18 +127,14 @@ STPathElement ipe(Issue const& iss) { return STPathElement( - STPathElement::typeCurrency | STPathElement::typeIssuer, - xrpAccount(), - iss.currency, - iss.account); + STPathElement::typeCurrency | STPathElement::typeIssuer, xrpAccount(), iss.currency, iss.account); }; // Issuer path element STPathElement iape(AccountID const& account) { - return STPathElement( - STPathElement::typeIssuer, xrpAccount(), xrpCurrency(), account); + return STPathElement(STPathElement::typeIssuer, xrpAccount(), xrpCurrency(), account); }; class ElementComboIter @@ -169,9 +159,7 @@ class ElementComboIter }; std::uint16_t state_ = 0; - static_assert( - safe_cast(SB::last) <= sizeof(decltype(state_)) * 8, - ""); + static_assert(safe_cast(SB::last) <= sizeof(decltype(state_)) * 8, ""); STPathElement const* prev_ = nullptr; // disallow iss and cur to be specified with acc is specified (simplifies // some tests) @@ -211,17 +199,11 @@ public: bool valid() const { - return (allowCompound_ || - !(has(SB::acc) && hasAny({SB::cur, SB::iss}))) && + return (allowCompound_ || !(has(SB::acc) && hasAny({SB::cur, SB::iss}))) && (!hasAny({SB::prevAcc, SB::prevCur, SB::prevIss}) || prev_) && - (!hasAny( - {SB::rootAcc, SB::sameAccIss, SB::existingAcc, SB::prevAcc}) || - has(SB::acc)) && - (!hasAny( - {SB::rootIss, SB::sameAccIss, SB::existingIss, SB::prevIss}) || - has(SB::iss)) && - (!hasAny({SB::xrp, SB::existingCur, SB::prevCur}) || - has(SB::cur)) && + (!hasAny({SB::rootAcc, SB::sameAccIss, SB::existingAcc, SB::prevAcc}) || has(SB::acc)) && + (!hasAny({SB::rootIss, SB::sameAccIss, SB::existingIss, SB::prevIss}) || has(SB::iss)) && + (!hasAny({SB::xrp, SB::existingCur, SB::prevCur}) || has(SB::cur)) && // These will be duplicates (count({SB::xrp, SB::existingCur, SB::prevCur}) <= 1) && (count({SB::rootAcc, SB::existingAcc, SB::prevAcc}) <= 1) && @@ -240,11 +222,7 @@ public: return !has(SB::last); } - template < - class Col, - class AccFactory, - class IssFactory, - class CurrencyFactory> + template void emplace_into( Col& col, @@ -340,8 +318,7 @@ struct ExistingElementPool ExistingElementPool& p_; ResetState state_; - explicit StateGuard(ExistingElementPool& p) - : p_{p}, state_{p.getResetState()} + explicit StateGuard(ExistingElementPool& p) : p_{p}, state_{p.getResetState()} { } ~StateGuard() @@ -356,11 +333,7 @@ struct ExistingElementPool // currency/account; the offer owner is either the specified // account or the issuer of the "taker gets" account void - setupEnv( - jtx::Env& env, - size_t numAct, - size_t numCur, - std::optional const& offererIndex) + setupEnv(jtx::Env& env, size_t numAct, size_t numCur, std::optional const& offererIndex) { using namespace jtx; @@ -398,8 +371,7 @@ struct ExistingElementPool env.fund(XRP(100000), a); // Every account trusts every other account with every currency - for (auto ai1 = accounts.begin(), aie = accounts.end(); ai1 != aie; - ++ai1) + for (auto ai1 = accounts.begin(), aie = accounts.end(); ai1 != aie; ++ai1) { for (auto ai2 = accounts.begin(); ai2 != aie; ++ai2) { @@ -429,20 +401,17 @@ struct ExistingElementPool ious.emplace_back(a[cn]); // create offers from every currency to every other currency - for (auto takerPays = ious.begin(), ie = ious.end(); takerPays != ie; - ++takerPays) + for (auto takerPays = ious.begin(), ie = ious.end(); takerPays != ie; ++takerPays) { for (auto takerGets = ious.begin(); takerGets != ie; ++takerGets) { if (takerPays == takerGets) continue; - auto const owner = - offererIndex ? accounts[*offererIndex] : takerGets->account; + auto const owner = offererIndex ? accounts[*offererIndex] : takerGets->account; if (owner.id() != takerGets->account.id()) env(pay(takerGets->account, owner, (*takerGets)(1000))); - env(offer(owner, (*takerPays)(1000), (*takerGets)(1000)), - txflags(tfPassive)); + env(offer(owner, (*takerPays)(1000), (*takerGets)(1000)), txflags(tfPassive)); } env.close(); } @@ -450,8 +419,7 @@ struct ExistingElementPool // create offers to/from xrp to every other ious for (auto const& iou : ious) { - auto const owner = - offererIndex ? accounts[*offererIndex] : iou.account; + auto const owner = offererIndex ? accounts[*offererIndex] : iou.account; env(offer(owner, iou(1000), XRP(1000)), txflags(tfPassive)); env(offer(owner, XRP(1000), iou(1000)), txflags(tfPassive)); env.close(); @@ -497,8 +465,7 @@ struct ExistingElementPool return (*sle)[sfBalance]; }; std::uint64_t totalXRP[2]{}; - for (auto ai1 = accounts.begin(), aie = accounts.end(); ai1 != aie; - ++ai1) + for (auto ai1 = accounts.begin(), aie = accounts.end(); ai1 != aie; ++ai1) { { // XRP balance @@ -556,8 +523,7 @@ struct ExistingElementPool auto issF = [&] { return this->getAvailAccount(); }; auto currencyF = [&] { return this->getAvailCurrency(); }; - STPathElement const* prevOuter = - prefix.empty() ? nullptr : &prefix.back(); + STPathElement const* prevOuter = prefix.empty() ? nullptr : &prefix.back(); ElementComboIter outer(prevOuter); std::vector outerResult; @@ -569,28 +535,14 @@ struct ExistingElementPool { StateGuard og{*this}; outerResult = prefix; - outer.emplace_into( - outerResult, - accF, - issF, - currencyF, - existingAcc, - existingCur, - existingIss); + outer.emplace_into(outerResult, accF, issF, currencyF, existingAcc, existingCur, existingIss); STPathElement const* prevInner = &outerResult.back(); ElementComboIter inner(prevInner); while (inner.next()) { StateGuard ig{*this}; result = outerResult; - inner.emplace_into( - result, - accF, - issF, - currencyF, - existingAcc, - existingCur, - existingIss); + inner.emplace_into(result, accF, issF, currencyF, existingAcc, existingCur, existingIss); result.insert(result.end(), suffix.begin(), suffix.end()); f(sendMax, deliver, result); } @@ -646,8 +598,7 @@ struct PayStrand_test : public beast::unit_test::suite env.app().logs().journal("Flow")); BEAST_EXPECT(ter == expTer); if (sizeof...(expSteps) != 0) - BEAST_EXPECT(equal( - strand, std::forward(expSteps)...)); + BEAST_EXPECT(equal(strand, std::forward(expSteps)...)); }; { @@ -658,8 +609,7 @@ struct PayStrand_test : public beast::unit_test::suite env(pay(gw, alice, EUR(100))); { - STPath const path = - STPath({ipe(bob["USD"]), cpe(EUR.currency)}); + STPath const path = STPath({ipe(bob["USD"]), cpe(EUR.currency)}); auto [ter, _] = toStrand( *env.current(), alice, @@ -709,14 +659,7 @@ struct PayStrand_test : public beast::unit_test::suite env(pay(gw, carol, USD(100))); // Insert implied account - test( - env, - USD, - std::nullopt, - STPath(), - tesSUCCESS, - D{alice, gw, usdC}, - D{gw, bob, usdC}); + test(env, USD, std::nullopt, STPath(), tesSUCCESS, D{alice, gw, usdC}, D{gw, bob, usdC}); env.trust(EUR(1000), alice, bob); // Insert implied offer @@ -769,11 +712,7 @@ struct PayStrand_test : public beast::unit_test::suite env, xrpIssue(), USD.issue(), - STPath({STPathElement{ - STPathElement::typeCurrency, - xrpAccount(), - xrpCurrency(), - xrpAccount()}}), + STPath({STPathElement{STPathElement::typeCurrency, xrpAccount(), xrpCurrency(), xrpAccount()}}), tesSUCCESS, D{alice, gw, usdC}, B{USD, XRP, std::nullopt}, @@ -851,39 +790,23 @@ struct PayStrand_test : public beast::unit_test::suite } // Create an offer with the same in/out issue - test( - env, - EUR, - USD.issue(), - STPath({ipe(USD), ipe(EUR)}), - temBAD_PATH); + test(env, EUR, USD.issue(), STPath({ipe(USD), ipe(EUR)}), temBAD_PATH); // Path element with type zero test( env, USD, std::nullopt, - STPath({STPathElement( - 0, xrpAccount(), xrpCurrency(), xrpAccount())}), + STPath({STPathElement(0, xrpAccount(), xrpCurrency(), xrpAccount())}), temBAD_PATH); // The same account can't appear more than once on a path // `gw` will be used from alice->carol and implied between carol // and bob - test( - env, - USD, - std::nullopt, - STPath({ape(gw), ape(carol)}), - temBAD_PATH_LOOP); + test(env, USD, std::nullopt, STPath({ape(gw), ape(carol)}), temBAD_PATH_LOOP); // The same offer can't appear more than once on a path - test( - env, - EUR, - USD.issue(), - STPath({ipe(EUR), ipe(USD), ipe(EUR)}), - temBAD_PATH_LOOP); + test(env, EUR, USD.issue(), STPath({ipe(EUR), ipe(USD), ipe(EUR)}), temBAD_PATH_LOOP); } { @@ -1013,11 +936,7 @@ struct PayStrand_test : public beast::unit_test::suite std::nullopt, env.app().logs().journal("Flow")); BEAST_EXPECT(ter == tesSUCCESS); - BEAST_EXPECT(equal( - strand, - D{alice, gw, usdC}, - B{USD.issue(), xrpIssue(), std::nullopt}, - XRPS{bob})); + BEAST_EXPECT(equal(strand, D{alice, gw, usdC}, B{USD.issue(), xrpIssue(), std::nullopt}, XRPS{bob})); } } @@ -1046,13 +965,12 @@ struct PayStrand_test : public beast::unit_test::suite env(offer(bob, XRP(100), bob["USD"](100)), txflags(tfPassive)); env(offer(gw, XRP(100), USD(100)), txflags(tfPassive)); - env(offer(bob, bob["USD"](100), bob["EUR"](100)), - txflags(tfPassive)); + env(offer(bob, bob["USD"](100), bob["EUR"](100)), txflags(tfPassive)); env(offer(gw, USD(100), EUR(100)), txflags(tfPassive)); Path const p = [&] { Path result; - result.push_back(allpe(gw, bob["USD"])); + result.push_back(allPathElements(gw, bob["USD"])); result.push_back(cpe(EUR.currency)); return result; }(); @@ -1078,10 +996,7 @@ struct PayStrand_test : public beast::unit_test::suite env(offer(bob, USD(100), XRP(100)), txflags(tfPassive)); // payment path: XRP -> XRP/USD -> USD/XRP - env(pay(alice, carol, XRP(100)), - path(~USD, ~XRP), - txflags(tfNoRippleDirect), - ter(temBAD_SEND_XRP_PATHS)); + env(pay(alice, carol, XRP(100)), path(~USD, ~XRP), txflags(tfNoRippleDirect), ter(temBAD_SEND_XRP_PATHS)); } { @@ -1189,54 +1104,22 @@ struct PayStrand_test : public beast::unit_test::suite PaymentSandbox sb{env.current().get(), tapNONE}; { auto const r = ::xrpl::path::RippleCalc::rippleCalculate( - sb, - sendMax, - deliver, - dstAcc, - noAccount(), - pathSet, - std::nullopt, - env.app().logs(), - &inputs); + sb, sendMax, deliver, dstAcc, noAccount(), pathSet, std::nullopt, env.app().logs(), &inputs); BEAST_EXPECT(r.result() == temBAD_PATH); } { auto const r = ::xrpl::path::RippleCalc::rippleCalculate( - sb, - sendMax, - deliver, - noAccount(), - srcAcc, - pathSet, - std::nullopt, - env.app().logs(), - &inputs); + sb, sendMax, deliver, noAccount(), srcAcc, pathSet, std::nullopt, env.app().logs(), &inputs); BEAST_EXPECT(r.result() == temBAD_PATH); } { auto const r = ::xrpl::path::RippleCalc::rippleCalculate( - sb, - noAccountAmount, - deliver, - dstAcc, - srcAcc, - pathSet, - std::nullopt, - env.app().logs(), - &inputs); + sb, noAccountAmount, deliver, dstAcc, srcAcc, pathSet, std::nullopt, env.app().logs(), &inputs); BEAST_EXPECT(r.result() == temBAD_PATH); } { auto const r = ::xrpl::path::RippleCalc::rippleCalculate( - sb, - sendMax, - noAccountAmount, - dstAcc, - srcAcc, - pathSet, - std::nullopt, - env.app().logs(), - &inputs); + sb, sendMax, noAccountAmount, dstAcc, srcAcc, pathSet, std::nullopt, env.app().logs(), &inputs); BEAST_EXPECT(r.result() == temBAD_PATH); } } diff --git a/src/test/app/PermissionedDEX_test.cpp b/src/test/app/PermissionedDEX_test.cpp index c29b5344e2..7a55866780 100644 --- a/src/test/app/PermissionedDEX_test.cpp +++ b/src/test/app/PermissionedDEX_test.cpp @@ -53,8 +53,7 @@ class PermissionedDEX_test : public beast::unit_test::suite { auto offerInDir = [&](uint256 const& directory, uint64_t const pageIndex, - std::optional domain = - std::nullopt) -> bool { + std::optional domain = std::nullopt) -> bool { auto const page = env.le(keylet::page(directory, pageIndex)); if (!page) return false; @@ -85,10 +84,7 @@ class PermissionedDEX_test : public beast::unit_test::suite return false; if (!domainOffer && sle->isFieldPresent(sfDomainID)) return false; - if (!offerInDir( - sle->getFieldH256(sfBookDirectory), - sle->getFieldU64(sfBookNode), - (*sle)[~sfDomainID])) + if (!offerInDir(sle->getFieldH256(sfBookDirectory), sle->getFieldU64(sfBookNode), (*sle)[~sfDomainID])) return false; if (sle->isFlag(lsfHybrid)) @@ -100,8 +96,7 @@ class PermissionedDEX_test : public beast::unit_test::suite if (sle->getFieldArray(sfAdditionalBooks).size() != 1) return false; - auto const& additionalBookDirs = - sle->getFieldArray(sfAdditionalBooks); + auto const& additionalBookDirs = sle->getFieldArray(sfAdditionalBooks); for (auto const& bookDir : additionalBookDirs) { @@ -124,21 +119,13 @@ class PermissionedDEX_test : public beast::unit_test::suite } uint256 - getBookDirKey( - Book const& book, - STAmount const& takerPays, - STAmount const& takerGets) + getBookDirKey(Book const& book, STAmount const& takerPays, STAmount const& takerGets) { - return keylet::quality( - keylet::book(book), getRate(takerGets, takerPays)) - .key; + return keylet::quality(keylet::book(book), getRate(takerGets, takerPays)).key; } std::optional - getDefaultOfferDirKey( - Env const& env, - Account const& account, - std::uint32_t offerSeq) + getDefaultOfferDirKey(Env const& env, Account const& account, std::uint32_t offerSeq) { if (auto const sle = env.le(keylet::offer(account.id(), offerSeq))) return Keylet(ltDIR_NODE, (*sle)[sfBookDirectory]).key; @@ -174,12 +161,9 @@ class PermissionedDEX_test : public beast::unit_test::suite // test preflight { Env env(*this, features - featurePermissionedDEX); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = - PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); - env(offer(bob, XRP(10), USD(10)), - domain(domainID), - ter(temDISABLED)); + env(offer(bob, XRP(10), USD(10)), domain(domainID), ter(temDISABLED)); env.close(); env.enableFeature(featurePermissionedDEX); @@ -191,8 +175,7 @@ class PermissionedDEX_test : public beast::unit_test::suite // preclaim - someone outside of the domain cannot create domain offer { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = - PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); // create devin account who is not part of the domain Account devin("devin"); @@ -203,9 +186,7 @@ class PermissionedDEX_test : public beast::unit_test::suite env(pay(gw, devin, USD(100))); env.close(); - env(offer(devin, XRP(10), USD(10)), - domain(domainID), - ter(tecNO_PERMISSION)); + env(offer(devin, XRP(10), USD(10)), domain(domainID), ter(tecNO_PERMISSION)); env.close(); // domain owner also issues a credential for devin @@ -213,9 +194,7 @@ class PermissionedDEX_test : public beast::unit_test::suite env.close(); // devin still cannot create offer since he didn't accept credential - env(offer(devin, XRP(10), USD(10)), - domain(domainID), - ter(tecNO_PERMISSION)); + env(offer(devin, XRP(10), USD(10)), domain(domainID), ter(tecNO_PERMISSION)); env.close(); env(credentials::accept(devin, domainOwner, credType)); @@ -228,8 +207,7 @@ class PermissionedDEX_test : public beast::unit_test::suite // preclaim - someone with expired cred cannot create domain offer { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = - PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); // create devin account who is not part of the domain Account devin("devin"); @@ -241,10 +219,7 @@ class PermissionedDEX_test : public beast::unit_test::suite env.close(); auto jv = credentials::create(devin, domainOwner, credType); - uint32_t const t = env.current() - ->header() - .parentCloseTime.time_since_epoch() - .count(); + uint32_t const t = env.current()->header().parentCloseTime.time_since_epoch().count(); jv[sfExpiration.jsonName] = t + 20; env(jv); @@ -259,24 +234,19 @@ class PermissionedDEX_test : public beast::unit_test::suite env.close(std::chrono::seconds(20)); // devin cannot create offer with expired cred - env(offer(devin, XRP(10), USD(10)), - domain(domainID), - ter(tecNO_PERMISSION)); + env(offer(devin, XRP(10), USD(10)), domain(domainID), ter(tecNO_PERMISSION)); env.close(); } // preclaim - cannot create an offer in a non existent domain { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = - PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); uint256 const badDomain{ "F10D0CC9A0F9A3CBF585B80BE09A186483668FDBDD39AA7E3370F3649CE134" "E5"}; - env(offer(bob, XRP(10), USD(10)), - domain(badDomain), - ter(tecNO_PERMISSION)); + env(offer(bob, XRP(10), USD(10)), domain(badDomain), ter(tecNO_PERMISSION)); env.close(); } @@ -284,60 +254,51 @@ class PermissionedDEX_test : public beast::unit_test::suite // domain { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = - PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); - env(credentials::deleteCred( - domainOwner, gw, domainOwner, credType)); + env(credentials::deleteCred(domainOwner, gw, domainOwner, credType)); env.close(); auto const bobOfferSeq{env.seq(bob)}; env(offer(bob, XRP(10), USD(10)), domain(domainID)); env.close(); - BEAST_EXPECT( - checkOffer(env, bob, bobOfferSeq, XRP(10), USD(10), 0, true)); + BEAST_EXPECT(checkOffer(env, bob, bobOfferSeq, XRP(10), USD(10), 0, true)); } // apply - offer can be created even if takerpays issuer is not in // domain { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = - PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); - env(credentials::deleteCred( - domainOwner, gw, domainOwner, credType)); + env(credentials::deleteCred(domainOwner, gw, domainOwner, credType)); env.close(); auto const bobOfferSeq{env.seq(bob)}; env(offer(bob, USD(10), XRP(10)), domain(domainID)); env.close(); - BEAST_EXPECT( - checkOffer(env, bob, bobOfferSeq, USD(10), XRP(10), 0, true)); + BEAST_EXPECT(checkOffer(env, bob, bobOfferSeq, USD(10), XRP(10), 0, true)); } // apply - two domain offers cross with each other { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = - PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); auto const bobOfferSeq{env.seq(bob)}; env(offer(bob, XRP(10), USD(10)), domain(domainID)); env.close(); - BEAST_EXPECT( - checkOffer(env, bob, bobOfferSeq, XRP(10), USD(10), 0, true)); + BEAST_EXPECT(checkOffer(env, bob, bobOfferSeq, XRP(10), USD(10), 0, true)); BEAST_EXPECT(ownerCount(env, bob) == 3); // a non domain offer cannot cross with domain offer env(offer(carol, USD(10), XRP(10))); env.close(); - BEAST_EXPECT( - checkOffer(env, bob, bobOfferSeq, XRP(10), USD(10), 0, true)); + BEAST_EXPECT(checkOffer(env, bob, bobOfferSeq, XRP(10), USD(10), 0, true)); auto const aliceOfferSeq{env.seq(alice)}; env(offer(alice, USD(10), XRP(10)), domain(domainID)); @@ -351,8 +312,7 @@ class PermissionedDEX_test : public beast::unit_test::suite // apply - create lots of domain offers { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = - PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); std::vector offerSeqs; offerSeqs.reserve(100); @@ -364,8 +324,7 @@ class PermissionedDEX_test : public beast::unit_test::suite env(offer(bob, XRP(10), USD(10)), domain(domainID)); env.close(); - BEAST_EXPECT(checkOffer( - env, bob, bobOfferSeq, XRP(10), USD(10), 0, true)); + BEAST_EXPECT(checkOffer(env, bob, bobOfferSeq, XRP(10), USD(10), 0, true)); } for (auto const offerSeq : offerSeqs) @@ -385,14 +344,9 @@ class PermissionedDEX_test : public beast::unit_test::suite // test preflight - without enabling featurePermissionedDEX amendment { Env env(*this, features - featurePermissionedDEX); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = - PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); - env(pay(bob, alice, USD(10)), - path(~USD), - sendmax(XRP(10)), - domain(domainID), - ter(temDISABLED)); + env(pay(bob, alice, USD(10)), path(~USD), sendmax(XRP(10)), domain(domainID), ter(temDISABLED)); env.close(); env.enableFeature(featurePermissionedDEX); @@ -401,35 +355,26 @@ class PermissionedDEX_test : public beast::unit_test::suite env(offer(bob, XRP(10), USD(10)), domain(domainID)); env.close(); - env(pay(bob, alice, USD(10)), - path(~USD), - sendmax(XRP(10)), - domain(domainID)); + env(pay(bob, alice, USD(10)), path(~USD), sendmax(XRP(10)), domain(domainID)); env.close(); } // preclaim - cannot send payment with non existent domain { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = - PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); uint256 const badDomain{ "F10D0CC9A0F9A3CBF585B80BE09A186483668FDBDD39AA7E3370F3649CE134" "E5"}; - env(pay(bob, alice, USD(10)), - path(~USD), - sendmax(XRP(10)), - domain(badDomain), - ter(tecNO_PERMISSION)); + env(pay(bob, alice, USD(10)), path(~USD), sendmax(XRP(10)), domain(badDomain), ter(tecNO_PERMISSION)); env.close(); } // preclaim - payment with non-domain destination fails { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = - PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); env(offer(bob, XRP(10), USD(10)), domain(domainID)); env.close(); @@ -444,11 +389,7 @@ class PermissionedDEX_test : public beast::unit_test::suite env.close(); // devin is not part of domain - env(pay(alice, devin, USD(10)), - path(~USD), - sendmax(XRP(10)), - domain(domainID), - ter(tecNO_PERMISSION)); + env(pay(alice, devin, USD(10)), path(~USD), sendmax(XRP(10)), domain(domainID), ter(tecNO_PERMISSION)); env.close(); // domain owner also issues a credential for devin @@ -456,29 +397,21 @@ class PermissionedDEX_test : public beast::unit_test::suite env.close(); // devin has not yet accepted cred - env(pay(alice, devin, USD(10)), - path(~USD), - sendmax(XRP(10)), - domain(domainID), - ter(tecNO_PERMISSION)); + env(pay(alice, devin, USD(10)), path(~USD), sendmax(XRP(10)), domain(domainID), ter(tecNO_PERMISSION)); env.close(); env(credentials::accept(devin, domainOwner, credType)); env.close(); // devin can now receive payment after he is in domain - env(pay(alice, devin, USD(10)), - path(~USD), - sendmax(XRP(10)), - domain(domainID)); + env(pay(alice, devin, USD(10)), path(~USD), sendmax(XRP(10)), domain(domainID)); env.close(); } // preclaim - non-domain sender cannot send payment { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = - PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); env(offer(bob, XRP(10), USD(10)), domain(domainID)); env.close(); @@ -493,11 +426,7 @@ class PermissionedDEX_test : public beast::unit_test::suite env.close(); // devin tries to send domain payment - env(pay(devin, alice, USD(10)), - path(~USD), - sendmax(XRP(10)), - domain(domainID), - ter(tecNO_PERMISSION)); + env(pay(devin, alice, USD(10)), path(~USD), sendmax(XRP(10)), domain(domainID), ter(tecNO_PERMISSION)); env.close(); // domain owner also issues a credential for devin @@ -505,48 +434,34 @@ class PermissionedDEX_test : public beast::unit_test::suite env.close(); // devin has not yet accepted cred - env(pay(devin, alice, USD(10)), - path(~USD), - sendmax(XRP(10)), - domain(domainID), - ter(tecNO_PERMISSION)); + env(pay(devin, alice, USD(10)), path(~USD), sendmax(XRP(10)), domain(domainID), ter(tecNO_PERMISSION)); env.close(); env(credentials::accept(devin, domainOwner, credType)); env.close(); // devin can now send payment after he is in domain - env(pay(devin, alice, USD(10)), - path(~USD), - sendmax(XRP(10)), - domain(domainID)); + env(pay(devin, alice, USD(10)), path(~USD), sendmax(XRP(10)), domain(domainID)); env.close(); } // apply - domain owner can always send and receive domain payment { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = - PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); env(offer(bob, XRP(10), USD(10)), domain(domainID)); env.close(); // domain owner can always be destination - env(pay(alice, domainOwner, USD(10)), - path(~USD), - sendmax(XRP(10)), - domain(domainID)); + env(pay(alice, domainOwner, USD(10)), path(~USD), sendmax(XRP(10)), domain(domainID)); env.close(); env(offer(bob, XRP(10), USD(10)), domain(domainID)); env.close(); // domain owner can send - env(pay(domainOwner, alice, USD(10)), - path(~USD), - sendmax(XRP(10)), - domain(domainID)); + env(pay(domainOwner, alice, USD(10)), path(~USD), sendmax(XRP(10)), domain(domainID)); env.close(); } } @@ -559,27 +474,20 @@ class PermissionedDEX_test : public beast::unit_test::suite // test domain cross currency payment consuming one offer { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = - PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); // create a regular offer without domain auto const regularOfferSeq{env.seq(bob)}; env(offer(bob, XRP(10), USD(10))); env.close(); - BEAST_EXPECT( - checkOffer(env, bob, regularOfferSeq, XRP(10), USD(10))); + BEAST_EXPECT(checkOffer(env, bob, regularOfferSeq, XRP(10), USD(10))); - auto const regularDirKey = - getDefaultOfferDirKey(env, bob, regularOfferSeq); + auto const regularDirKey = getDefaultOfferDirKey(env, bob, regularOfferSeq); BEAST_EXPECT(regularDirKey); BEAST_EXPECT(checkDirectorySize(env, *regularDirKey, 1)); // a domain payment cannot consume regular offers - env(pay(alice, carol, USD(10)), - path(~USD), - sendmax(XRP(10)), - domain(domainID), - ter(tecPATH_PARTIAL)); + env(pay(alice, carol, USD(10)), path(~USD), sendmax(XRP(10)), domain(domainID), ter(tecPATH_PARTIAL)); env.close(); // create a domain offer @@ -587,24 +495,18 @@ class PermissionedDEX_test : public beast::unit_test::suite env(offer(bob, XRP(10), USD(10)), domain(domainID)); env.close(); - BEAST_EXPECT(checkOffer( - env, bob, domainOfferSeq, XRP(10), USD(10), 0, true)); + BEAST_EXPECT(checkOffer(env, bob, domainOfferSeq, XRP(10), USD(10), 0, true)); - auto const domainDirKey = - getDefaultOfferDirKey(env, bob, domainOfferSeq); + auto const domainDirKey = getDefaultOfferDirKey(env, bob, domainOfferSeq); BEAST_EXPECT(domainDirKey); BEAST_EXPECT(checkDirectorySize(env, *domainDirKey, 1)); // cross-currency permissioned payment consumed // domain offer instead of regular offer - env(pay(alice, carol, USD(10)), - path(~USD), - sendmax(XRP(10)), - domain(domainID)); + env(pay(alice, carol, USD(10)), path(~USD), sendmax(XRP(10)), domain(domainID)); env.close(); BEAST_EXPECT(!offerExists(env, bob, domainOfferSeq)); - BEAST_EXPECT( - checkOffer(env, bob, regularOfferSeq, XRP(10), USD(10))); + BEAST_EXPECT(checkOffer(env, bob, regularOfferSeq, XRP(10), USD(10))); // domain directory is empty BEAST_EXPECT(checkDirectorySize(env, *domainDirKey, 0)); @@ -614,8 +516,7 @@ class PermissionedDEX_test : public beast::unit_test::suite // test domain payment consuming two offers in the path { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = - PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); auto const EUR = gw["EUR"]; env.trust(EUR(1000), alice); @@ -632,75 +533,53 @@ class PermissionedDEX_test : public beast::unit_test::suite env(offer(bob, XRP(10), USD(10)), domain(domainID)); env.close(); - BEAST_EXPECT( - checkOffer(env, bob, usdOfferSeq, XRP(10), USD(10), 0, true)); + BEAST_EXPECT(checkOffer(env, bob, usdOfferSeq, XRP(10), USD(10), 0, true)); // payment fail because there isn't eur offer - env(pay(alice, carol, EUR(10)), - path(~USD, ~EUR), - sendmax(XRP(10)), - domain(domainID), - ter(tecPATH_PARTIAL)); + env(pay(alice, carol, EUR(10)), path(~USD, ~EUR), sendmax(XRP(10)), domain(domainID), ter(tecPATH_PARTIAL)); env.close(); - BEAST_EXPECT( - checkOffer(env, bob, usdOfferSeq, XRP(10), USD(10), 0, true)); + BEAST_EXPECT(checkOffer(env, bob, usdOfferSeq, XRP(10), USD(10), 0, true)); // bob creates a regular USD/EUR offer auto const regularOfferSeq{env.seq(bob)}; env(offer(bob, USD(10), EUR(10))); env.close(); - BEAST_EXPECT( - checkOffer(env, bob, regularOfferSeq, USD(10), EUR(10))); + BEAST_EXPECT(checkOffer(env, bob, regularOfferSeq, USD(10), EUR(10))); // alice tries to pay again, but still fails because the regular // offer cannot be consumed - env(pay(alice, carol, EUR(10)), - path(~USD, ~EUR), - sendmax(XRP(10)), - domain(domainID), - ter(tecPATH_PARTIAL)); + env(pay(alice, carol, EUR(10)), path(~USD, ~EUR), sendmax(XRP(10)), domain(domainID), ter(tecPATH_PARTIAL)); env.close(); // bob creates a domain USD/EUR offer auto const eurOfferSeq{env.seq(bob)}; env(offer(bob, USD(10), EUR(10)), domain(domainID)); env.close(); - BEAST_EXPECT( - checkOffer(env, bob, eurOfferSeq, USD(10), EUR(10), 0, true)); + BEAST_EXPECT(checkOffer(env, bob, eurOfferSeq, USD(10), EUR(10), 0, true)); // alice successfully consume two domain offers: xrp/usd and usd/eur - env(pay(alice, carol, EUR(5)), - sendmax(XRP(5)), - domain(domainID), - path(~USD, ~EUR)); + env(pay(alice, carol, EUR(5)), sendmax(XRP(5)), domain(domainID), path(~USD, ~EUR)); env.close(); - BEAST_EXPECT( - checkOffer(env, bob, usdOfferSeq, XRP(5), USD(5), 0, true)); - BEAST_EXPECT( - checkOffer(env, bob, eurOfferSeq, USD(5), EUR(5), 0, true)); + BEAST_EXPECT(checkOffer(env, bob, usdOfferSeq, XRP(5), USD(5), 0, true)); + BEAST_EXPECT(checkOffer(env, bob, eurOfferSeq, USD(5), EUR(5), 0, true)); // alice successfully consume two domain offers and deletes them // we compute path this time using `paths` - env(pay(alice, carol, EUR(5)), - sendmax(XRP(5)), - domain(domainID), - paths(XRP)); + env(pay(alice, carol, EUR(5)), sendmax(XRP(5)), domain(domainID), paths(XRP)); env.close(); BEAST_EXPECT(!offerExists(env, bob, usdOfferSeq)); BEAST_EXPECT(!offerExists(env, bob, eurOfferSeq)); // regular offer is not consumed - BEAST_EXPECT( - checkOffer(env, bob, regularOfferSeq, USD(10), EUR(10))); + BEAST_EXPECT(checkOffer(env, bob, regularOfferSeq, USD(10), EUR(10))); } // domain payment cannot consume offer from another domain { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = - PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); // Fund devin and create USD trustline Account badDomainOwner("badDomainOwner"); @@ -728,25 +607,17 @@ class PermissionedDEX_test : public beast::unit_test::suite env.close(); // domain payment can't consume an offer from another domain - env(pay(alice, carol, USD(10)), - path(~USD), - sendmax(XRP(10)), - domain(domainID), - ter(tecPATH_PARTIAL)); + env(pay(alice, carol, USD(10)), path(~USD), sendmax(XRP(10)), domain(domainID), ter(tecPATH_PARTIAL)); env.close(); // bob creates an offer under the right domain auto const bobOfferSeq{env.seq(bob)}; env(offer(bob, XRP(10), USD(10)), domain(domainID)); env.close(); - BEAST_EXPECT( - checkOffer(env, bob, bobOfferSeq, XRP(10), USD(10), 0, true)); + BEAST_EXPECT(checkOffer(env, bob, bobOfferSeq, XRP(10), USD(10), 0, true)); // domain payment now consumes from the right domain - env(pay(alice, carol, USD(10)), - path(~USD), - sendmax(XRP(10)), - domain(domainID)); + env(pay(alice, carol, USD(10)), path(~USD), sendmax(XRP(10)), domain(domainID)); env.close(); BEAST_EXPECT(!offerExists(env, bob, bobOfferSeq)); @@ -757,8 +628,7 @@ class PermissionedDEX_test : public beast::unit_test::suite // offer { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = - PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); env(offer(bob, XRP(10), USD(10)), domain(domainID)); env.close(); @@ -783,8 +653,7 @@ class PermissionedDEX_test : public beast::unit_test::suite // offer becomes unfunded when offer owner's cred expires { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = - PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); // create devin account who is not part of the domain Account devin("devin"); @@ -796,10 +665,7 @@ class PermissionedDEX_test : public beast::unit_test::suite env.close(); auto jv = credentials::create(devin, domainOwner, credType); - uint32_t const t = env.current() - ->header() - .parentCloseTime.time_since_epoch() - .count(); + uint32_t const t = env.current()->header().parentCloseTime.time_since_epoch().count(); jv[sfExpiration.jsonName] = t + 20; env(jv); @@ -812,61 +678,41 @@ class PermissionedDEX_test : public beast::unit_test::suite env.close(); // devin's offer can still be consumed while his cred isn't expired - env(pay(alice, carol, USD(5)), - path(~USD), - sendmax(XRP(5)), - domain(domainID)); + env(pay(alice, carol, USD(5)), path(~USD), sendmax(XRP(5)), domain(domainID)); env.close(); - BEAST_EXPECT( - checkOffer(env, devin, offerSeq, XRP(5), USD(5), 0, true)); + BEAST_EXPECT(checkOffer(env, devin, offerSeq, XRP(5), USD(5), 0, true)); // advance time env.close(std::chrono::seconds(20)); // devin's offer is unfunded now due to expired cred - env(pay(alice, carol, USD(5)), - path(~USD), - sendmax(XRP(5)), - domain(domainID), - ter(tecPATH_PARTIAL)); + env(pay(alice, carol, USD(5)), path(~USD), sendmax(XRP(5)), domain(domainID), ter(tecPATH_PARTIAL)); env.close(); - BEAST_EXPECT( - checkOffer(env, devin, offerSeq, XRP(5), USD(5), 0, true)); + BEAST_EXPECT(checkOffer(env, devin, offerSeq, XRP(5), USD(5), 0, true)); } // offer becomes unfunded when offer owner's cred is removed { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = - PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); auto const offerSeq{env.seq(bob)}; env(offer(bob, XRP(10), USD(10)), domain(domainID)); env.close(); // bob's offer can still be consumed while his cred exists - env(pay(alice, carol, USD(5)), - path(~USD), - sendmax(XRP(5)), - domain(domainID)); + env(pay(alice, carol, USD(5)), path(~USD), sendmax(XRP(5)), domain(domainID)); env.close(); - BEAST_EXPECT( - checkOffer(env, bob, offerSeq, XRP(5), USD(5), 0, true)); + BEAST_EXPECT(checkOffer(env, bob, offerSeq, XRP(5), USD(5), 0, true)); // remove bob's cred - env(credentials::deleteCred( - domainOwner, bob, domainOwner, credType)); + env(credentials::deleteCred(domainOwner, bob, domainOwner, credType)); env.close(); // bob's offer is unfunded now due to expired cred - env(pay(alice, carol, USD(5)), - path(~USD), - sendmax(XRP(5)), - domain(domainID), - ter(tecPATH_PARTIAL)); + env(pay(alice, carol, USD(5)), path(~USD), sendmax(XRP(5)), domain(domainID), ter(tecPATH_PARTIAL)); env.close(); - BEAST_EXPECT( - checkOffer(env, bob, offerSeq, XRP(5), USD(5), 0, true)); + BEAST_EXPECT(checkOffer(env, bob, offerSeq, XRP(5), USD(5), 0, true)); } } @@ -879,8 +725,7 @@ class PermissionedDEX_test : public beast::unit_test::suite // payment. If the domain wishes to control who is allowed to ripple // through, they should set the rippling individually Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = - PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); auto const EURA = alice["EUR"]; auto const EURB = bob["EUR"]; @@ -904,10 +749,7 @@ class PermissionedDEX_test : public beast::unit_test::suite env.close(); // payment no longer works because carol has no ripple on bob - env(pay(alice, carol, EURB(5)), - paths(EURA), - domain(domainID), - ter(tecPATH_DRY)); + env(pay(alice, carol, EURB(5)), paths(EURA), domain(domainID), ter(tecPATH_DRY)); env.close(); env.require(balance(bob, EURA(10)), balance(carol, EURB(10))); } @@ -920,8 +762,7 @@ class PermissionedDEX_test : public beast::unit_test::suite // whether the issuer is in the domain should NOT affect whether an // offer can be consumed in domain payment Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = - PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); // create an xrp/usd offer with usd as takergets auto const bobOffer1Seq{env.seq(bob)}; @@ -933,10 +774,8 @@ class PermissionedDEX_test : public beast::unit_test::suite env(offer(bob, USD(10), XRP(10)), domain(domainID), txflags(tfPassive)); env.close(); - BEAST_EXPECT( - checkOffer(env, bob, bobOffer1Seq, XRP(10), USD(10), 0, true)); - BEAST_EXPECT(checkOffer( - env, bob, bobOffer2Seq, USD(10), XRP(10), lsfPassive, true)); + BEAST_EXPECT(checkOffer(env, bob, bobOffer1Seq, XRP(10), USD(10), 0, true)); + BEAST_EXPECT(checkOffer(env, bob, bobOffer2Seq, USD(10), XRP(10), lsfPassive, true)); // remove gateway from domain env(credentials::deleteCred(domainOwner, gw, domainOwner, credType)); @@ -944,19 +783,13 @@ class PermissionedDEX_test : public beast::unit_test::suite // payment succeeds even if issuer is not in domain // xrp/usd offer is consumed - env(pay(alice, carol, USD(10)), - path(~USD), - sendmax(XRP(10)), - domain(domainID)); + env(pay(alice, carol, USD(10)), path(~USD), sendmax(XRP(10)), domain(domainID)); env.close(); BEAST_EXPECT(!offerExists(env, bob, bobOffer1Seq)); // payment succeeds even if issuer is not in domain // usd/xrp offer is consumed - env(pay(alice, carol, XRP(10)), - path(~XRP), - sendmax(USD(10)), - domain(domainID)); + env(pay(alice, carol, XRP(10)), path(~XRP), sendmax(USD(10)), domain(domainID)); env.close(); BEAST_EXPECT(!offerExists(env, bob, bobOffer2Seq)); } @@ -969,8 +802,7 @@ class PermissionedDEX_test : public beast::unit_test::suite // checking that an unfunded offer will be implicitly removed by a // successful payment tx Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = - PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); auto const aliceOfferSeq{env.seq(alice)}; env(offer(alice, XRP(100), USD(100)), domain(domainID)); @@ -980,10 +812,8 @@ class PermissionedDEX_test : public beast::unit_test::suite env(offer(bob, XRP(20), USD(20)), domain(domainID)); env.close(); - BEAST_EXPECT( - checkOffer(env, bob, bobOfferSeq, XRP(20), USD(20), 0, true)); - BEAST_EXPECT( - checkOffer(env, alice, aliceOfferSeq, XRP(100), USD(100), 0, true)); + BEAST_EXPECT(checkOffer(env, bob, bobOfferSeq, XRP(20), USD(20), 0, true)); + BEAST_EXPECT(checkOffer(env, alice, aliceOfferSeq, XRP(100), USD(100), 0, true)); auto const domainDirKey = getDefaultOfferDirKey(env, bob, bobOfferSeq); BEAST_EXPECT(domainDirKey); @@ -993,14 +823,10 @@ class PermissionedDEX_test : public beast::unit_test::suite env(credentials::deleteCred(domainOwner, alice, domainOwner, credType)); env.close(); - env(pay(gw, carol, USD(10)), - path(~USD), - sendmax(XRP(10)), - domain(domainID)); + env(pay(gw, carol, USD(10)), path(~USD), sendmax(XRP(10)), domain(domainID)); env.close(); - BEAST_EXPECT( - checkOffer(env, bob, bobOfferSeq, XRP(10), USD(10), 0, true)); + BEAST_EXPECT(checkOffer(env, bob, bobOfferSeq, XRP(10), USD(10), 0, true)); // alice's unfunded offer is removed implicitly BEAST_EXPECT(!offerExists(env, alice, aliceOfferSeq)); @@ -1013,16 +839,11 @@ class PermissionedDEX_test : public beast::unit_test::suite testcase("AMM not used"); Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = - PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); AMM amm(env, alice, XRP(10), USD(50)); // a domain payment isn't able to consume AMM - env(pay(bob, carol, USD(5)), - path(~USD), - sendmax(XRP(5)), - domain(domainID), - ter(tecPATH_PARTIAL)); + env(pay(bob, carol, USD(5)), path(~USD), sendmax(XRP(5)), domain(domainID), ter(tecPATH_PARTIAL)); env.close(); // a non domain payment can use AMM @@ -1042,53 +863,38 @@ class PermissionedDEX_test : public beast::unit_test::suite // test preflight - invalid hybrid flag { Env env(*this, features - featurePermissionedDEX); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = - PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); - env(offer(bob, XRP(10), USD(10)), - domain(domainID), - txflags(tfHybrid), - ter(temDISABLED)); + env(offer(bob, XRP(10), USD(10)), domain(domainID), txflags(tfHybrid), ter(temDISABLED)); env.close(); - env(offer(bob, XRP(10), USD(10)), - txflags(tfHybrid), - ter(temINVALID_FLAG)); + env(offer(bob, XRP(10), USD(10)), txflags(tfHybrid), ter(temINVALID_FLAG)); env.close(); env.enableFeature(featurePermissionedDEX); env.close(); // hybrid offer must have domainID - env(offer(bob, XRP(10), USD(10)), - txflags(tfHybrid), - ter(temINVALID_FLAG)); + env(offer(bob, XRP(10), USD(10)), txflags(tfHybrid), ter(temINVALID_FLAG)); env.close(); // hybrid offer must have domainID auto const offerSeq{env.seq(bob)}; - env(offer(bob, XRP(10), USD(10)), - txflags(tfHybrid), - domain(domainID)); + env(offer(bob, XRP(10), USD(10)), txflags(tfHybrid), domain(domainID)); env.close(); - BEAST_EXPECT(checkOffer( - env, bob, offerSeq, XRP(10), USD(10), lsfHybrid, true)); + BEAST_EXPECT(checkOffer(env, bob, offerSeq, XRP(10), USD(10), lsfHybrid, true)); } // apply - domain offer can cross with hybrid { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = - PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); auto const bobOfferSeq{env.seq(bob)}; - env(offer(bob, XRP(10), USD(10)), - txflags(tfHybrid), - domain(domainID)); + env(offer(bob, XRP(10), USD(10)), txflags(tfHybrid), domain(domainID)); env.close(); - BEAST_EXPECT(checkOffer( - env, bob, bobOfferSeq, XRP(10), USD(10), lsfHybrid, true)); + BEAST_EXPECT(checkOffer(env, bob, bobOfferSeq, XRP(10), USD(10), lsfHybrid, true)); BEAST_EXPECT(offerExists(env, bob, bobOfferSeq)); BEAST_EXPECT(ownerCount(env, bob) == 3); @@ -1104,19 +910,15 @@ class PermissionedDEX_test : public beast::unit_test::suite // apply - open offer can cross with hybrid { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = - PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); auto const bobOfferSeq{env.seq(bob)}; - env(offer(bob, XRP(10), USD(10)), - txflags(tfHybrid), - domain(domainID)); + env(offer(bob, XRP(10), USD(10)), txflags(tfHybrid), domain(domainID)); env.close(); BEAST_EXPECT(offerExists(env, bob, bobOfferSeq)); BEAST_EXPECT(ownerCount(env, bob) == 3); - BEAST_EXPECT(checkOffer( - env, bob, bobOfferSeq, XRP(10), USD(10), lsfHybrid, true)); + BEAST_EXPECT(checkOffer(env, bob, bobOfferSeq, XRP(10), USD(10), lsfHybrid, true)); auto const aliceOfferSeq{env.seq(alice)}; env(offer(alice, USD(10), XRP(10))); @@ -1131,22 +933,18 @@ class PermissionedDEX_test : public beast::unit_test::suite // domain book { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = - PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); auto const bobOfferSeq{env.seq(bob)}; env(offer(bob, XRP(10), USD(10)), domain(domainID)); env.close(); - BEAST_EXPECT( - checkOffer(env, bob, bobOfferSeq, XRP(10), USD(10), 0, true)); + BEAST_EXPECT(checkOffer(env, bob, bobOfferSeq, XRP(10), USD(10), 0, true)); BEAST_EXPECT(ownerCount(env, bob) == 3); // hybrid offer auto crosses with domain offer auto const aliceOfferSeq{env.seq(alice)}; - env(offer(alice, USD(10), XRP(10)), - domain(domainID), - txflags(tfHybrid)); + env(offer(alice, USD(10), XRP(10)), domain(domainID), txflags(tfHybrid)); env.close(); BEAST_EXPECT(!offerExists(env, alice, aliceOfferSeq)); @@ -1158,30 +956,24 @@ class PermissionedDEX_test : public beast::unit_test::suite // because by default, it only tries to cross domain offers { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = - PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); auto const bobOfferSeq{env.seq(bob)}; env(offer(bob, XRP(10), USD(10))); env.close(); - BEAST_EXPECT( - checkOffer(env, bob, bobOfferSeq, XRP(10), USD(10), 0, false)); + BEAST_EXPECT(checkOffer(env, bob, bobOfferSeq, XRP(10), USD(10), 0, false)); BEAST_EXPECT(ownerCount(env, bob) == 3); // hybrid offer auto crosses with domain offer auto const aliceOfferSeq{env.seq(alice)}; - env(offer(alice, USD(10), XRP(10)), - domain(domainID), - txflags(tfHybrid)); + env(offer(alice, USD(10), XRP(10)), domain(domainID), txflags(tfHybrid)); env.close(); BEAST_EXPECT(offerExists(env, alice, aliceOfferSeq)); BEAST_EXPECT(offerExists(env, bob, bobOfferSeq)); - BEAST_EXPECT( - checkOffer(env, bob, bobOfferSeq, XRP(10), USD(10), 0, false)); - BEAST_EXPECT(checkOffer( - env, alice, aliceOfferSeq, USD(10), XRP(10), lsfHybrid, true)); + BEAST_EXPECT(checkOffer(env, bob, bobOfferSeq, XRP(10), USD(10), 0, false)); + BEAST_EXPECT(checkOffer(env, alice, aliceOfferSeq, USD(10), XRP(10), lsfHybrid, true)); BEAST_EXPECT(ownerCount(env, alice) == 3); } } @@ -1195,8 +987,7 @@ class PermissionedDEX_test : public beast::unit_test::suite // in this case, the hybrid offer will be considered as unfunded even in // a regular payment Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = - PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); auto const hybridOfferSeq{env.seq(bob)}; env(offer(bob, XRP(50), USD(50)), txflags(tfHybrid), domain(domainID)); @@ -1208,24 +999,15 @@ class PermissionedDEX_test : public beast::unit_test::suite // bob's hybrid offer is unfunded and can not be consumed in a domain // payment - env(pay(alice, carol, USD(5)), - path(~USD), - sendmax(XRP(5)), - domain(domainID), - ter(tecPATH_PARTIAL)); + env(pay(alice, carol, USD(5)), path(~USD), sendmax(XRP(5)), domain(domainID), ter(tecPATH_PARTIAL)); env.close(); - BEAST_EXPECT(checkOffer( - env, bob, hybridOfferSeq, XRP(50), USD(50), lsfHybrid, true)); + BEAST_EXPECT(checkOffer(env, bob, hybridOfferSeq, XRP(50), USD(50), lsfHybrid, true)); // bob's unfunded hybrid offer can't be consumed even with a regular // payment - env(pay(alice, carol, USD(5)), - path(~USD), - sendmax(XRP(5)), - ter(tecPATH_PARTIAL)); + env(pay(alice, carol, USD(5)), path(~USD), sendmax(XRP(5)), ter(tecPATH_PARTIAL)); env.close(); - BEAST_EXPECT(checkOffer( - env, bob, hybridOfferSeq, XRP(50), USD(50), lsfHybrid, true)); + BEAST_EXPECT(checkOffer(env, bob, hybridOfferSeq, XRP(50), USD(50), lsfHybrid, true)); // create a regular offer auto const regularOfferSeq{env.seq(bob)}; @@ -1234,12 +1016,9 @@ class PermissionedDEX_test : public beast::unit_test::suite BEAST_EXPECT(offerExists(env, bob, regularOfferSeq)); BEAST_EXPECT(checkOffer(env, bob, regularOfferSeq, XRP(10), USD(10))); - auto const sleHybridOffer = - env.le(keylet::offer(bob.id(), hybridOfferSeq)); + auto const sleHybridOffer = env.le(keylet::offer(bob.id(), hybridOfferSeq)); BEAST_EXPECT(sleHybridOffer); - auto const openDir = - sleHybridOffer->getFieldArray(sfAdditionalBooks)[0].getFieldH256( - sfBookDirectory); + auto const openDir = sleHybridOffer->getFieldArray(sfAdditionalBooks)[0].getFieldH256(sfBookDirectory); BEAST_EXPECT(checkDirectorySize(env, openDir, 2)); // this normal payment should consume the regular offer and remove the @@ -1260,22 +1039,15 @@ class PermissionedDEX_test : public beast::unit_test::suite // both non domain and domain payments can consume hybrid offer { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = - PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); auto const hybridOfferSeq{env.seq(bob)}; - env(offer(bob, XRP(10), USD(10)), - txflags(tfHybrid), - domain(domainID)); + env(offer(bob, XRP(10), USD(10)), txflags(tfHybrid), domain(domainID)); env.close(); - env(pay(alice, carol, USD(5)), - path(~USD), - sendmax(XRP(5)), - domain(domainID)); + env(pay(alice, carol, USD(5)), path(~USD), sendmax(XRP(5)), domain(domainID)); env.close(); - BEAST_EXPECT(checkOffer( - env, bob, hybridOfferSeq, XRP(5), USD(5), lsfHybrid, true)); + BEAST_EXPECT(checkOffer(env, bob, hybridOfferSeq, XRP(5), USD(5), lsfHybrid, true)); // hybrid offer can't be consumed since bob is not in domain anymore env(pay(alice, carol, USD(5)), path(~USD), sendmax(XRP(5))); @@ -1288,8 +1060,7 @@ class PermissionedDEX_test : public beast::unit_test::suite // wrong domainID { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = - PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); // Fund accounts Account badDomainOwner("badDomainOwner"); @@ -1310,28 +1081,17 @@ class PermissionedDEX_test : public beast::unit_test::suite env.close(); auto const hybridOfferSeq{env.seq(bob)}; - env(offer(bob, XRP(10), USD(10)), - txflags(tfHybrid), - domain(domainID)); + env(offer(bob, XRP(10), USD(10)), txflags(tfHybrid), domain(domainID)); env.close(); // other domains can't consume the offer - env(pay(devin, badDomainOwner, USD(5)), - path(~USD), - sendmax(XRP(5)), - domain(badDomainID), - ter(tecPATH_DRY)); + env(pay(devin, badDomainOwner, USD(5)), path(~USD), sendmax(XRP(5)), domain(badDomainID), ter(tecPATH_DRY)); env.close(); - BEAST_EXPECT(checkOffer( - env, bob, hybridOfferSeq, XRP(10), USD(10), lsfHybrid, true)); + BEAST_EXPECT(checkOffer(env, bob, hybridOfferSeq, XRP(10), USD(10), lsfHybrid, true)); - env(pay(alice, carol, USD(5)), - path(~USD), - sendmax(XRP(5)), - domain(domainID)); + env(pay(alice, carol, USD(5)), path(~USD), sendmax(XRP(5)), domain(domainID)); env.close(); - BEAST_EXPECT(checkOffer( - env, bob, hybridOfferSeq, XRP(5), USD(5), lsfHybrid, true)); + BEAST_EXPECT(checkOffer(env, bob, hybridOfferSeq, XRP(5), USD(5), lsfHybrid, true)); // hybrid offer can't be consumed since bob is not in domain anymore env(pay(alice, carol, USD(5)), path(~USD), sendmax(XRP(5))); @@ -1343,8 +1103,7 @@ class PermissionedDEX_test : public beast::unit_test::suite // test domain payment consuming two offers w/ hybrid offer { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = - PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); auto const EUR = gw["EUR"]; env.trust(EUR(1000), alice); @@ -1360,46 +1119,31 @@ class PermissionedDEX_test : public beast::unit_test::suite env(offer(bob, XRP(10), USD(10)), domain(domainID)); env.close(); - BEAST_EXPECT( - checkOffer(env, bob, usdOfferSeq, XRP(10), USD(10), 0, true)); + BEAST_EXPECT(checkOffer(env, bob, usdOfferSeq, XRP(10), USD(10), 0, true)); // payment fail because there isn't eur offer - env(pay(alice, carol, EUR(5)), - path(~USD, ~EUR), - sendmax(XRP(5)), - domain(domainID), - ter(tecPATH_PARTIAL)); + env(pay(alice, carol, EUR(5)), path(~USD, ~EUR), sendmax(XRP(5)), domain(domainID), ter(tecPATH_PARTIAL)); env.close(); - BEAST_EXPECT( - checkOffer(env, bob, usdOfferSeq, XRP(10), USD(10), 0, true)); + BEAST_EXPECT(checkOffer(env, bob, usdOfferSeq, XRP(10), USD(10), 0, true)); // bob creates a hybrid eur offer auto const eurOfferSeq{env.seq(bob)}; - env(offer(bob, USD(10), EUR(10)), - domain(domainID), - txflags(tfHybrid)); + env(offer(bob, USD(10), EUR(10)), domain(domainID), txflags(tfHybrid)); env.close(); - BEAST_EXPECT(checkOffer( - env, bob, eurOfferSeq, USD(10), EUR(10), lsfHybrid, true)); + BEAST_EXPECT(checkOffer(env, bob, eurOfferSeq, USD(10), EUR(10), lsfHybrid, true)); // alice successfully consume two domain offers: xrp/usd and usd/eur - env(pay(alice, carol, EUR(5)), - path(~USD, ~EUR), - sendmax(XRP(5)), - domain(domainID)); + env(pay(alice, carol, EUR(5)), path(~USD, ~EUR), sendmax(XRP(5)), domain(domainID)); env.close(); - BEAST_EXPECT( - checkOffer(env, bob, usdOfferSeq, XRP(5), USD(5), 0, true)); - BEAST_EXPECT(checkOffer( - env, bob, eurOfferSeq, USD(5), EUR(5), lsfHybrid, true)); + BEAST_EXPECT(checkOffer(env, bob, usdOfferSeq, XRP(5), USD(5), 0, true)); + BEAST_EXPECT(checkOffer(env, bob, eurOfferSeq, USD(5), EUR(5), lsfHybrid, true)); } // test regular payment using a regular offer and a hybrid offer { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = - PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); auto const EUR = gw["EUR"]; env.trust(EUR(1000), alice); @@ -1416,26 +1160,20 @@ class PermissionedDEX_test : public beast::unit_test::suite env(offer(bob, XRP(10), USD(10))); env.close(); - BEAST_EXPECT( - checkOffer(env, bob, usdOfferSeq, XRP(10), USD(10), 0, false)); + BEAST_EXPECT(checkOffer(env, bob, usdOfferSeq, XRP(10), USD(10), 0, false)); // bob creates a hybrid eur offer auto const eurOfferSeq{env.seq(bob)}; - env(offer(bob, USD(10), EUR(10)), - domain(domainID), - txflags(tfHybrid)); + env(offer(bob, USD(10), EUR(10)), domain(domainID), txflags(tfHybrid)); env.close(); - BEAST_EXPECT(checkOffer( - env, bob, eurOfferSeq, USD(10), EUR(10), lsfHybrid, true)); + BEAST_EXPECT(checkOffer(env, bob, eurOfferSeq, USD(10), EUR(10), lsfHybrid, true)); // alice successfully consume two offers: xrp/usd and usd/eur env(pay(alice, carol, EUR(5)), path(~USD, ~EUR), sendmax(XRP(5))); env.close(); - BEAST_EXPECT( - checkOffer(env, bob, usdOfferSeq, XRP(5), USD(5), 0, false)); - BEAST_EXPECT(checkOffer( - env, bob, eurOfferSeq, USD(5), EUR(5), lsfHybrid, true)); + BEAST_EXPECT(checkOffer(env, bob, usdOfferSeq, XRP(5), USD(5), 0, false)); + BEAST_EXPECT(checkOffer(env, bob, eurOfferSeq, USD(5), EUR(5), lsfHybrid, true)); } } @@ -1443,8 +1181,7 @@ class PermissionedDEX_test : public beast::unit_test::suite testHybridOfferDirectories(FeatureBitset features) { Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = - PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); std::vector offerSeqs; offerSeqs.reserve(100); @@ -1461,22 +1198,16 @@ class PermissionedDEX_test : public beast::unit_test::suite { auto const bobOfferSeq{env.seq(bob)}; offerSeqs.emplace_back(bobOfferSeq); - env(offer(bob, XRP(10), USD(10)), - txflags(tfHybrid), - domain(domainID)); + env(offer(bob, XRP(10), USD(10)), txflags(tfHybrid), domain(domainID)); env.close(); auto const sleOffer = env.le(keylet::offer(bob.id(), bobOfferSeq)); BEAST_EXPECT(sleOffer); BEAST_EXPECT(sleOffer->getFieldH256(sfBookDirectory) == domainDir); - BEAST_EXPECT( - sleOffer->getFieldArray(sfAdditionalBooks).size() == 1); - BEAST_EXPECT( - sleOffer->getFieldArray(sfAdditionalBooks)[0].getFieldH256( - sfBookDirectory) == openDir); + BEAST_EXPECT(sleOffer->getFieldArray(sfAdditionalBooks).size() == 1); + BEAST_EXPECT(sleOffer->getFieldArray(sfAdditionalBooks)[0].getFieldH256(sfBookDirectory) == openDir); - BEAST_EXPECT(checkOffer( - env, bob, bobOfferSeq, XRP(10), USD(10), lsfHybrid, true)); + BEAST_EXPECT(checkOffer(env, bob, bobOfferSeq, XRP(10), USD(10), lsfHybrid, true)); BEAST_EXPECT(checkDirectorySize(env, domainDir, i)); BEAST_EXPECT(checkDirectorySize(env, openDir, i)); } @@ -1498,8 +1229,7 @@ class PermissionedDEX_test : public beast::unit_test::suite testcase("Auto bridge"); Env env(*this, features); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = - PermissionedDEX(env); + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = PermissionedDEX(env); auto const EUR = gw["EUR"]; for (auto const& account : {alice, bob, carol}) diff --git a/src/test/app/PermissionedDomains_test.cpp b/src/test/app/PermissionedDomains_test.cpp index a7dff84cff..8485202144 100644 --- a/src/test/app/PermissionedDomains_test.cpp +++ b/src/test/app/PermissionedDomains_test.cpp @@ -33,19 +33,22 @@ exceptionExpected(Env& env, Json::Value const& jv) class PermissionedDomains_test : public beast::unit_test::suite { - FeatureBitset withoutFeature_{ - testable_amendments() - featurePermissionedDomains}; + FeatureBitset withoutFeature_{testable_amendments() - featurePermissionedDomains}; FeatureBitset withFeature_{ testable_amendments() // | featurePermissionedDomains | featureCredentials}; + FeatureBitset withFix_{ + testable_amendments() // + | featurePermissionedDomains | featureCredentials}; + // Verify that each tx type can execute if the feature is enabled. void - testEnabled() + testEnabled(FeatureBitset features) { testcase("Enabled"); Account const alice("alice"); - Env env(*this, withFeature_); + Env env(*this, features); env.fund(XRP(1000), alice); pdomain::Credentials credentials{{alice, "first credential"}}; env(pdomain::setTx(alice, credentials)); @@ -89,10 +92,7 @@ class PermissionedDomains_test : public beast::unit_test::suite // Verify that bad inputs fail for each of create new and update // behaviors of PermissionedDomainSet void - testBadData( - Account const& account, - Env& env, - std::optional domain = std::nullopt) + testBadData(Account const& account, Env& env, std::optional domain = std::nullopt) { Account const alice2("alice2"); Account const alice3("alice3"); @@ -108,8 +108,7 @@ class PermissionedDomains_test : public beast::unit_test::suite auto const setFee(drops(env.current()->fees().increment)); // Test empty credentials. - env(pdomain::setTx(account, pdomain::Credentials(), domain), - ter(temARRAY_EMPTY)); + env(pdomain::setTx(account, pdomain::Credentials(), domain), ter(temARRAY_EMPTY)); // Test 11 credentials. pdomain::Credentials const credentials11{ @@ -124,11 +123,8 @@ class PermissionedDomains_test : public beast::unit_test::suite {alice10, "credential9"}, {alice11, "credential10"}, {alice12, "credential11"}}; - BEAST_EXPECT( - credentials11.size() == - maxPermissionedDomainCredentialsArraySize + 1); - env(pdomain::setTx(account, credentials11, domain), - ter(temARRAY_TOO_LARGE)); + BEAST_EXPECT(credentials11.size() == maxPermissionedDomainCredentialsArraySize + 1); + env(pdomain::setTx(account, credentials11, domain), ter(temARRAY_TOO_LARGE)); // Test credentials including non-existent issuer. Account const nobody("nobody"); @@ -143,9 +139,7 @@ class PermissionedDomains_test : public beast::unit_test::suite env(pdomain::setTx(account, credentialsNon, domain), ter(tecNO_ISSUER)); // Test bad fee - env(pdomain::setTx(account, credentials11, domain), - fee(1, true), - ter(temBAD_FEE)); + env(pdomain::setTx(account, credentials11, domain), fee(1, true), ter(temBAD_FEE)); pdomain::Credentials const credentials4{ {alice2, "credential1"}, @@ -157,15 +151,12 @@ class PermissionedDomains_test : public beast::unit_test::suite auto const credentialOrig = txJsonMutable["AcceptedCredentials"][2u]; // Remove Issuer from a credential and apply. - txJsonMutable["AcceptedCredentials"][2u][jss::Credential].removeMember( - jss::Issuer); - BEAST_EXPECT( - exceptionExpected(env, txJsonMutable).starts_with("invalidParams")); + txJsonMutable["AcceptedCredentials"][2u][jss::Credential].removeMember(jss::Issuer); + BEAST_EXPECT(exceptionExpected(env, txJsonMutable).starts_with("invalidParams")); // Make an empty CredentialType. txJsonMutable["AcceptedCredentials"][2u] = credentialOrig; - txJsonMutable["AcceptedCredentials"][2u][jss::Credential] - ["CredentialType"] = ""; + txJsonMutable["AcceptedCredentials"][2u][jss::Credential]["CredentialType"] = ""; env(txJsonMutable, ter(temMALFORMED)); // Make too long CredentialType. @@ -173,22 +164,16 @@ class PermissionedDomains_test : public beast::unit_test::suite "Cred0123456789012345678901234567890123456789012345678901234567890"; static_assert(longCredentialType.size() == maxCredentialTypeLength + 1); txJsonMutable["AcceptedCredentials"][2u] = credentialOrig; - txJsonMutable["AcceptedCredentials"][2u][jss::Credential] - ["CredentialType"] = std::string(longCredentialType); - BEAST_EXPECT( - exceptionExpected(env, txJsonMutable).starts_with("invalidParams")); + txJsonMutable["AcceptedCredentials"][2u][jss::Credential]["CredentialType"] = std::string(longCredentialType); + BEAST_EXPECT(exceptionExpected(env, txJsonMutable).starts_with("invalidParams")); // Remove Credentialtype from a credential and apply. - txJsonMutable["AcceptedCredentials"][2u][jss::Credential].removeMember( - "CredentialType"); - BEAST_EXPECT( - exceptionExpected(env, txJsonMutable).starts_with("invalidParams")); + txJsonMutable["AcceptedCredentials"][2u][jss::Credential].removeMember("CredentialType"); + BEAST_EXPECT(exceptionExpected(env, txJsonMutable).starts_with("invalidParams")); // Remove both - txJsonMutable["AcceptedCredentials"][2u][jss::Credential].removeMember( - jss::Issuer); - BEAST_EXPECT( - exceptionExpected(env, txJsonMutable).starts_with("invalidParams")); + txJsonMutable["AcceptedCredentials"][2u][jss::Credential].removeMember(jss::Issuer); + BEAST_EXPECT(exceptionExpected(env, txJsonMutable).starts_with("invalidParams")); // Make 2 identical credentials. Duplicates are not supported by // permissioned domains, so transactions should return errors @@ -207,8 +192,7 @@ class PermissionedDomains_test : public beast::unit_test::suite auto const sorted = pdomain::sortCredentials(credentialsDup); BEAST_EXPECT(sorted.size() == 4); - env(pdomain::setTx(account, credentialsDup, domain), - ter(temMALFORMED)); + env(pdomain::setTx(account, credentialsDup, domain), ter(temMALFORMED)); env.close(); env(pdomain::setTx(account, sorted, domain)); @@ -220,8 +204,7 @@ class PermissionedDomains_test : public beast::unit_test::suite d = pdomain::getNewDomain(env.meta()); env.close(); auto objects = pdomain::getObjects(account, env); - auto const fromObject = - pdomain::credentialsFromJson(objects[d], human2Acc); + auto const fromObject = pdomain::credentialsFromJson(objects[d], human2Acc); auto const sortedCreds = pdomain::sortCredentials(credentialsDup); BEAST_EXPECT(fromObject == sortedCreds); } @@ -240,8 +223,7 @@ class PermissionedDomains_test : public beast::unit_test::suite for (auto const& c : credentialsSame) human2Acc.emplace(c.issuer.human(), c.issuer); - BEAST_EXPECT( - credentialsSame != pdomain::sortCredentials(credentialsSame)); + BEAST_EXPECT(credentialsSame != pdomain::sortCredentials(credentialsSame)); env(pdomain::setTx(account, credentialsSame, domain)); uint256 d; @@ -251,8 +233,7 @@ class PermissionedDomains_test : public beast::unit_test::suite d = pdomain::getNewDomain(env.meta()); env.close(); auto objects = pdomain::getObjects(account, env); - auto const fromObject = - pdomain::credentialsFromJson(objects[d], human2Acc); + auto const fromObject = pdomain::credentialsFromJson(objects[d], human2Acc); auto const sortedCreds = pdomain::sortCredentials(credentialsSame); BEAST_EXPECT(fromObject == sortedCreds); } @@ -260,10 +241,10 @@ class PermissionedDomains_test : public beast::unit_test::suite // Test PermissionedDomainSet void - testSet() + testSet(FeatureBitset features) { testcase("Set"); - Env env(*this, withFeature_); + Env env(*this, features); env.set_parse_failure_expected(true); int const accNum = 12; @@ -302,9 +283,7 @@ class PermissionedDomains_test : public beast::unit_test::suite BEAST_EXPECT(object["LedgerEntryType"] == "PermissionedDomain"); BEAST_EXPECT(object["Owner"] == alice[0].human()); BEAST_EXPECT(object["Sequence"] == tx["Sequence"]); - BEAST_EXPECT( - pdomain::credentialsFromJson(object, human2Acc) == - credentials1); + BEAST_EXPECT(pdomain::credentialsFromJson(object, human2Acc) == credentials1); } // Make longest possible CredentialType. @@ -313,8 +292,7 @@ class PermissionedDomains_test : public beast::unit_test::suite "Cred0123456789012345678901234567890123456789012345678901234567" "89"; static_assert(longCredentialType.size() == maxCredentialTypeLength); - pdomain::Credentials const longCredentials{ - {alice[1], std::string(longCredentialType)}}; + pdomain::Credentials const longCredentials{{alice[1], std::string(longCredentialType)}}; env(pdomain::setTx(alice[0], longCredentials)); @@ -326,19 +304,15 @@ class PermissionedDomains_test : public beast::unit_test::suite BEAST_EXPECT(tx["Account"] == alice[0].human()); bool findSeq = false; - for (auto const& [domain, object] : - pdomain::getObjects(alice[0], env)) + for (auto const& [domain, object] : pdomain::getObjects(alice[0], env)) { findSeq = object["Sequence"] == tx["Sequence"]; if (findSeq) { BEAST_EXPECT(domain.isNonZero()); - BEAST_EXPECT( - object["LedgerEntryType"] == "PermissionedDomain"); + BEAST_EXPECT(object["LedgerEntryType"] == "PermissionedDomain"); BEAST_EXPECT(object["Owner"] == alice[0].human()); - BEAST_EXPECT( - pdomain::credentialsFromJson(object, human2Acc) == - longCredentials); + BEAST_EXPECT(pdomain::credentialsFromJson(object, human2Acc) == longCredentials); break; } } @@ -361,52 +335,39 @@ class PermissionedDomains_test : public beast::unit_test::suite }; uint256 domain2; { - BEAST_EXPECT( - credentials10.size() == - maxPermissionedDomainCredentialsArraySize); - BEAST_EXPECT( - credentials10 != pdomain::sortCredentials(credentials10)); + BEAST_EXPECT(credentials10.size() == maxPermissionedDomainCredentialsArraySize); + BEAST_EXPECT(credentials10 != pdomain::sortCredentials(credentials10)); env(pdomain::setTx(alice[0], credentials10)); auto tx = env.tx()->getJson(JsonOptions::none); domain2 = pdomain::getNewDomain(env.meta()); auto objects = pdomain::getObjects(alice[0], env); auto object = objects[domain2]; - BEAST_EXPECT( - pdomain::credentialsFromJson(object, human2Acc) == - pdomain::sortCredentials(credentials10)); + BEAST_EXPECT(pdomain::credentialsFromJson(object, human2Acc) == pdomain::sortCredentials(credentials10)); } // Update with 1 credential. env(pdomain::setTx(alice[0], credentials1, domain2)); BEAST_EXPECT( - pdomain::credentialsFromJson( - pdomain::getObjects(alice[0], env)[domain2], human2Acc) == - credentials1); + pdomain::credentialsFromJson(pdomain::getObjects(alice[0], env)[domain2], human2Acc) == credentials1); // Update with 10 credentials. env(pdomain::setTx(alice[0], credentials10, domain2)); env.close(); BEAST_EXPECT( - pdomain::credentialsFromJson( - pdomain::getObjects(alice[0], env)[domain2], human2Acc) == + pdomain::credentialsFromJson(pdomain::getObjects(alice[0], env)[domain2], human2Acc) == pdomain::sortCredentials(credentials10)); // Update from the wrong owner. - env(pdomain::setTx(alice[2], credentials1, domain2), - ter(tecNO_PERMISSION)); + env(pdomain::setTx(alice[2], credentials1, domain2), ter(tecNO_PERMISSION)); // Update a uint256(0) domain - env(pdomain::setTx(alice[0], credentials1, uint256(0)), - ter(temMALFORMED)); + env(pdomain::setTx(alice[0], credentials1, uint256(0)), ter(temMALFORMED)); // Update non-existent domain - env(pdomain::setTx(alice[0], credentials1, uint256(75)), - ter(tecNO_ENTRY)); + env(pdomain::setTx(alice[0], credentials1, uint256(75)), ter(tecNO_ENTRY)); // Wrong flag - env(pdomain::setTx(alice[0], credentials1), - txflags(tfClawTwoAssets), - ter(temINVALID_FLAG)); + env(pdomain::setTx(alice[0], credentials1), txflags(tfClawTwoAssets), ter(temINVALID_FLAG)); // Test bad data when creating a domain. testBadData(alice[0], env); @@ -421,9 +382,7 @@ class PermissionedDomains_test : public beast::unit_test::suite std::size_t ownerSeq = env.seq(alice[0]); while (deleteDelta + ownerSeq > env.current()->seq()) env.close(); - env(acctdelete(alice[0], alice[2]), - fee(acctDelFee), - ter(tecHAS_OBLIGATIONS)); + env(acctdelete(alice[0], alice[2]), fee(acctDelFee), ter(tecHAS_OBLIGATIONS)); } { @@ -440,10 +399,10 @@ class PermissionedDomains_test : public beast::unit_test::suite // Test PermissionedDomainDelete void - testDelete() + testDelete(FeatureBitset features) { testcase("Delete"); - Env env(*this, withFeature_); + Env env(*this, features); Account const alice("alice"); env.fund(XRP(1000), alice); @@ -466,14 +425,10 @@ class PermissionedDomains_test : public beast::unit_test::suite env(pdomain::deleteTx(alice, uint256(75)), ter(tecNO_ENTRY)); // Test bad fee - env(pdomain::deleteTx(alice, uint256(75)), - ter(temBAD_FEE), - fee(1, true)); + env(pdomain::deleteTx(alice, uint256(75)), ter(temBAD_FEE), fee(1, true)); // Wrong flag - env(pdomain::deleteTx(alice, domain), - ter(temINVALID_FLAG), - txflags(tfClawTwoAssets)); + env(pdomain::deleteTx(alice, domain), ter(temINVALID_FLAG), txflags(tfClawTwoAssets)); // Delete a zero domain. env(pdomain::deleteTx(alice, uint256(0)), ter(temMALFORMED)); @@ -497,14 +452,14 @@ class PermissionedDomains_test : public beast::unit_test::suite } void - testAccountReserve() + testAccountReserve(FeatureBitset features) { // Verify that the reserve behaves as expected for creating. testcase("Account Reserve"); using namespace test::jtx; - Env env(*this, withFeature_); + Env env(*this, features); Account const alice("alice"); // Fund alice enough to exist, but not enough to meet @@ -527,9 +482,7 @@ class PermissionedDomains_test : public beast::unit_test::suite // Pay alice almost enough to make the reserve. env(pay(env.master, alice, incReserve + drops(2 * baseFee) - drops(1))); - BEAST_EXPECT( - env.balance(alice) == - acctReserve + incReserve + drops(baseFee) - drops(1)); + BEAST_EXPECT(env.balance(alice) == acctReserve + incReserve + drops(baseFee) - drops(1)); env.close(); // alice still does not have enough XRP for the reserve. @@ -551,12 +504,16 @@ public: void run() override { - testEnabled(); + testEnabled(withFeature_); + testEnabled(withFix_); testCredentialsDisabled(); testDisabled(); - testSet(); - testDelete(); - testAccountReserve(); + testSet(withFeature_); + testSet(withFix_); + testDelete(withFeature_); + testDelete(withFix_); + testAccountReserve(withFeature_); + testAccountReserve(withFix_); } }; diff --git a/src/test/app/PseudoTx_test.cpp b/src/test/app/PseudoTx_test.cpp index f01ba616c8..29e13888c3 100644 --- a/src/test/app/PseudoTx_test.cpp +++ b/src/test/app/PseudoTx_test.cpp @@ -49,8 +49,7 @@ struct PseudoTx_test : public beast::unit_test::suite { std::vector res; - res.emplace_back(STTx( - ttACCOUNT_SET, [&](auto& obj) { obj[sfAccount] = AccountID(1); })); + res.emplace_back(STTx(ttACCOUNT_SET, [&](auto& obj) { obj[sfAccount] = AccountID(1); })); res.emplace_back(STTx(ttPAYMENT, [&](auto& obj) { obj.setAccountID(sfAccount, AccountID(2)); @@ -66,20 +65,17 @@ struct PseudoTx_test : public beast::unit_test::suite using namespace jtx; Env env(*this, features); - for (auto const& stx : - getPseudoTxs(env.closed()->rules(), env.closed()->seq() + 1)) + for (auto const& stx : getPseudoTxs(env.closed()->rules(), env.closed()->seq() + 1)) { std::string reason; BEAST_EXPECT(isPseudoTx(stx)); BEAST_EXPECT(!passesLocalChecks(stx, reason)); BEAST_EXPECT(reason == "Cannot submit pseudo transactions."); - env.app().openLedger().modify( - [&](OpenView& view, beast::Journal j) { - auto const result = - xrpl::apply(env.app(), view, stx, tapNONE, j); - BEAST_EXPECT(!result.applied && result.ter == temINVALID); - return result.applied; - }); + env.app().openLedger().modify([&](OpenView& view, beast::Journal j) { + auto const result = xrpl::apply(env.app(), view, stx, tapNONE, j); + BEAST_EXPECT(!result.applied && result.ter == temINVALID); + return result.applied; + }); } } diff --git a/src/test/app/RCLValidations_test.cpp b/src/test/app/RCLValidations_test.cpp index 729f373738..495176104b 100644 --- a/src/test/app/RCLValidations_test.cpp +++ b/src/test/app/RCLValidations_test.cpp @@ -17,11 +17,9 @@ class RCLValidations_test : public beast::unit_test::suite testcase("Change validation trusted status"); auto keys = randomKeyPair(KeyType::secp256k1); auto v = std::make_shared( - xrpl::NetClock::time_point{}, - keys.first, - keys.second, - calcNodeID(keys.first), - [&](STValidation& v) { v.setFieldU32(sfLedgerSequence, 123456); }); + xrpl::NetClock::time_point{}, keys.first, keys.second, calcNodeID(keys.first), [&](STValidation& v) { + v.setFieldU32(sfLedgerSequence, 123456); + }); BEAST_EXPECT(v->isTrusted()); v->setUntrusted(); @@ -56,16 +54,12 @@ class RCLValidations_test : public beast::unit_test::suite jtx::Env env(*this); Config config; - auto prev = std::make_shared( - create_genesis, - config, - std::vector{}, - env.app().getNodeFamily()); + auto prev = + std::make_shared(create_genesis, config, std::vector{}, env.app().getNodeFamily()); history.push_back(prev); for (auto i = 0; i < (2 * maxAncestors + 1); ++i) { - auto next = std::make_shared( - *prev, env.app().timeKeeper().closeTime()); + auto next = std::make_shared(*prev, env.app().timeKeeper().closeTime()); next->updateSkipList(); history.push_back(next); prev = next; @@ -73,8 +67,7 @@ class RCLValidations_test : public beast::unit_test::suite // altHistory agrees with first half of regular history Seq const diverge = history.size() / 2; - std::vector> altHistory( - history.begin(), history.begin() + diverge); + std::vector> altHistory(history.begin(), history.begin() + diverge); // advance clock to get new ledgers using namespace std::chrono_literals; env.timeKeeper().set(env.timeKeeper().now() + 1200s); @@ -82,8 +75,7 @@ class RCLValidations_test : public beast::unit_test::suite bool forceHash = true; while (altHistory.size() < history.size()) { - auto next = std::make_shared( - *prev, env.app().timeKeeper().closeTime()); + auto next = std::make_shared(*prev, env.app().timeKeeper().closeTime()); // Force a different hash on the first iteration next->updateSkipList(); BEAST_EXPECT(next->read(keylet::fees())); @@ -219,16 +211,12 @@ class RCLValidations_test : public beast::unit_test::suite jtx::Env env(*this); auto& j = env.journal; Config config; - auto prev = std::make_shared( - create_genesis, - config, - std::vector{}, - env.app().getNodeFamily()); + auto prev = + std::make_shared(create_genesis, config, std::vector{}, env.app().getNodeFamily()); history.push_back(prev); for (auto i = 0; i < (maxAncestors + 10); ++i) { - auto next = std::make_shared( - *prev, env.app().timeKeeper().closeTime()); + auto next = std::make_shared(*prev, env.app().timeKeeper().closeTime()); next->updateSkipList(); history.push_back(next); prev = next; @@ -279,8 +267,7 @@ class RCLValidations_test : public beast::unit_test::suite // quirk of RCLValidation and prevents deleting the old support // for ledger 257 - BEAST_EXPECT( - trie.remove(RCLValidatedLedger{history[257], env.journal}, 1)); + BEAST_EXPECT(trie.remove(RCLValidatedLedger{history[257], env.journal}, 1)); trie.insert(RCLValidatedLedger{history[258], env.journal}, 1); trie.getPreferred(1); // trie.dump(std::cout); diff --git a/src/test/app/ReducedOffer_test.cpp b/src/test/app/ReducedOffer_test.cpp index 8a395913b2..b967096eb8 100644 --- a/src/test/app/ReducedOffer_test.cpp +++ b/src/test/app/ReducedOffer_test.cpp @@ -12,36 +12,24 @@ namespace test { class ReducedOffer_test : public beast::unit_test::suite { static auto - ledgerEntryOffer( - jtx::Env& env, - jtx::Account const& acct, - std::uint32_t offer_seq) + ledgerEntryOffer(jtx::Env& env, jtx::Account const& acct, std::uint32_t offer_seq) { Json::Value jvParams; jvParams[jss::offer][jss::account] = acct.human(); jvParams[jss::offer][jss::seq] = offer_seq; - return env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; + return env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; } static bool - offerInLedger( - jtx::Env& env, - jtx::Account const& acct, - std::uint32_t offerSeq) + offerInLedger(jtx::Env& env, jtx::Account const& acct, std::uint32_t offerSeq) { Json::Value ledgerOffer = ledgerEntryOffer(env, acct, offerSeq); - return !( - ledgerOffer.isMember(jss::error) && - ledgerOffer[jss::error].asString() == "entryNotFound"); + return !(ledgerOffer.isMember(jss::error) && ledgerOffer[jss::error].asString() == "entryNotFound"); } // Common code to clean up unneeded offers. static void - cleanupOldOffers( - jtx::Env& env, - std::initializer_list> - list) + cleanupOldOffers(jtx::Env& env, std::initializer_list> list) { for (auto [acct, offerSeq] : list) env(offer_cancel(acct, offerSeq)); @@ -80,10 +68,8 @@ public: // 2. Collects the results, and // 3. Cleans up for the next offer pair. // Returns 1 if the crossed offer has a bad rate for the book. - auto exerciseOfferPair = - [this, &env, &alice, &bob]( - Amounts const& inLedger, - Amounts const& newOffer) -> unsigned int { + auto exerciseOfferPair = [this, &env, &alice, &bob]( + Amounts const& inLedger, Amounts const& newOffer) -> unsigned int { // Put inLedger offer in the ledger so newOffer can cross it. std::uint32_t const aliceOfferSeq = env.seq(alice); env(offer(alice, inLedger.in, inLedger.out)); @@ -93,9 +79,8 @@ public: STAmount const initialRate = Quality(newOffer).rate(); std::uint32_t const bobOfferSeq = env.seq(bob); STAmount const bobInitialBalance = env.balance(bob); - STAmount const bobsFee = env.current()->fees().base; - env(offer(bob, newOffer.in, newOffer.out, tfSell), - fee(bobsFee)); + STAmount const bobFee = env.current()->fees().base; + env(offer(bob, newOffer.in, newOffer.out, tfSell), fee(bobFee)); env.close(); STAmount const bobFinalBalance = env.balance(bob); @@ -109,20 +94,16 @@ public: // bob's offer should be in the ledger, but reduced in size. unsigned int badRate = 1; { - Json::Value bobOffer = - ledgerEntryOffer(env, bob, bobOfferSeq); + Json::Value bobOffer = ledgerEntryOffer(env, bob, bobOfferSeq); - STAmount const reducedTakerGets = amountFromJson( - sfTakerGets, bobOffer[jss::node][sfTakerGets.jsonName]); - STAmount const reducedTakerPays = amountFromJson( - sfTakerPays, bobOffer[jss::node][sfTakerPays.jsonName]); - STAmount const bobGot = - env.balance(bob) + bobsFee - bobInitialBalance; + STAmount const reducedTakerGets = + amountFromJson(sfTakerGets, bobOffer[jss::node][sfTakerGets.jsonName]); + STAmount const reducedTakerPays = + amountFromJson(sfTakerPays, bobOffer[jss::node][sfTakerPays.jsonName]); + STAmount const bobGot = env.balance(bob) + bobFee - bobInitialBalance; BEAST_EXPECT(reducedTakerPays < newOffer.in); BEAST_EXPECT(reducedTakerGets < newOffer.out); - STAmount const inLedgerRate = - Quality(Amounts{reducedTakerPays, reducedTakerGets}) - .rate(); + STAmount const inLedgerRate = Quality(Amounts{reducedTakerPays, reducedTakerGets}).rate(); badRate = inLedgerRate > initialRate ? 1 : 0; @@ -133,11 +114,8 @@ public: // was computed. if (badRate == 0) { - STAmount const tweakedTakerPays = - reducedTakerPays + drops(1); - STAmount const tweakedRate = - Quality(Amounts{tweakedTakerPays, reducedTakerGets}) - .rate(); + STAmount const tweakedTakerPays = reducedTakerPays + drops(1); + STAmount const tweakedRate = Quality(Amounts{tweakedTakerPays, reducedTakerGets}).rate(); BEAST_EXPECT(tweakedRate > initialRate); } #if 0 @@ -158,31 +136,25 @@ public: // In preparation for the next iteration make sure the two // offers are gone from the ledger. - cleanupOldOffers( - env, {{alice, aliceOfferSeq}, {bob, bobOfferSeq}}); + cleanupOldOffers(env, {{alice, aliceOfferSeq}, {bob, bobOfferSeq}}); return badRate; }; // bob's offer (the new offer) is the same every time: - Amounts const bobsOffer{ - STAmount(XRP(1)), STAmount(USD.issue(), 1, 0)}; + Amounts const bobOffer{STAmount(XRP(1)), STAmount(USD.issue(), 1, 0)}; // alice's offer has a slightly smaller TakerPays with each // iteration. This should mean that the size of the offer bob // places in the ledger should increase with each iteration. unsigned int blockedCount = 0; - for (std::uint64_t mantissaReduce = 1'000'000'000ull; - mantissaReduce <= 5'000'000'000ull; + for (std::uint64_t mantissaReduce = 1'000'000'000ull; mantissaReduce <= 5'000'000'000ull; mantissaReduce += 20'000'000ull) { STAmount aliceUSD{ - bobsOffer.out.issue(), - bobsOffer.out.mantissa() - mantissaReduce, - bobsOffer.out.exponent()}; - STAmount aliceXRP{ - bobsOffer.in.issue(), bobsOffer.in.mantissa() - 1}; - Amounts alicesOffer{aliceUSD, aliceXRP}; - blockedCount += exerciseOfferPair(alicesOffer, bobsOffer); + bobOffer.out.issue(), bobOffer.out.mantissa() - mantissaReduce, bobOffer.out.exponent()}; + STAmount aliceXRP{bobOffer.in.issue(), bobOffer.in.mantissa() - 1}; + Amounts aliceOffer{aliceUSD, aliceXRP}; + blockedCount += exerciseOfferPair(aliceOffer, bobOffer); } // None of the test cases should produce a potentially blocking @@ -220,10 +192,8 @@ public: // 1. Exercises one offer pair, // 2. Collects the results, and // 3. Cleans up for the next offer pair. - auto exerciseOfferPair = - [this, &env, &alice, &bob]( - Amounts const& inLedger, - Amounts const& newOffer) -> unsigned int { + auto exerciseOfferPair = [this, &env, &alice, &bob]( + Amounts const& inLedger, Amounts const& newOffer) -> unsigned int { // Get the inLedger offer into the ledger so newOffer can cross // it. STAmount const initialRate = Quality(inLedger).rate(); @@ -243,30 +213,23 @@ public: { // If the in-ledger offer was not consumed then further // results are meaningless. - cleanupOldOffers( - env, {{alice, aliceOfferSeq}, {bob, bobOfferSeq}}); + cleanupOldOffers(env, {{alice, aliceOfferSeq}, {bob, bobOfferSeq}}); return 1; } // alice's offer should still be in the ledger, but reduced in // size. unsigned int badRate = 1; { - Json::Value aliceOffer = - ledgerEntryOffer(env, alice, aliceOfferSeq); + Json::Value aliceOffer = ledgerEntryOffer(env, alice, aliceOfferSeq); - STAmount const reducedTakerGets = amountFromJson( - sfTakerGets, - aliceOffer[jss::node][sfTakerGets.jsonName]); - STAmount const reducedTakerPays = amountFromJson( - sfTakerPays, - aliceOffer[jss::node][sfTakerPays.jsonName]); - STAmount const aliceGot = - env.balance(alice) - aliceInitialBalance; + STAmount const reducedTakerGets = + amountFromJson(sfTakerGets, aliceOffer[jss::node][sfTakerGets.jsonName]); + STAmount const reducedTakerPays = + amountFromJson(sfTakerPays, aliceOffer[jss::node][sfTakerPays.jsonName]); + STAmount const aliceGot = env.balance(alice) - aliceInitialBalance; BEAST_EXPECT(reducedTakerPays < inLedger.in); BEAST_EXPECT(reducedTakerGets < inLedger.out); - STAmount const inLedgerRate = - Quality(Amounts{reducedTakerPays, reducedTakerGets}) - .rate(); + STAmount const inLedgerRate = Quality(Amounts{reducedTakerPays, reducedTakerGets}).rate(); badRate = inLedgerRate > initialRate ? 1 : 0; // If the inLedgerRate is less than initial rate, then @@ -276,11 +239,8 @@ public: // was computed. if (badRate == 0) { - STAmount const tweakedTakerPays = - reducedTakerPays + drops(1); - STAmount const tweakedRate = - Quality(Amounts{tweakedTakerPays, reducedTakerGets}) - .rate(); + STAmount const tweakedTakerPays = reducedTakerPays + drops(1); + STAmount const tweakedRate = Quality(Amounts{tweakedTakerPays, reducedTakerGets}).rate(); BEAST_EXPECT(tweakedRate > initialRate); } #if 0 @@ -302,32 +262,26 @@ public: // In preparation for the next iteration make sure the two // offers are gone from the ledger. - cleanupOldOffers( - env, {{alice, aliceOfferSeq}, {bob, bobOfferSeq}}); + cleanupOldOffers(env, {{alice, aliceOfferSeq}, {bob, bobOfferSeq}}); return badRate; }; // alice's offer (the old offer) is the same every time: - Amounts const aliceOffer{ - STAmount(XRP(1)), STAmount(USD.issue(), 1, 0)}; + Amounts const aliceOffer{STAmount(XRP(1)), STAmount(USD.issue(), 1, 0)}; // bob's offer has a slightly smaller TakerPays with each iteration. // This should mean that the size of the offer alice leaves in the // ledger should increase with each iteration. unsigned int blockedCount = 0; - for (std::uint64_t mantissaReduce = 1'000'000'000ull; - mantissaReduce <= 4'000'000'000ull; + for (std::uint64_t mantissaReduce = 1'000'000'000ull; mantissaReduce <= 4'000'000'000ull; mantissaReduce += 20'000'000ull) { STAmount bobUSD{ - aliceOffer.out.issue(), - aliceOffer.out.mantissa() - mantissaReduce, - aliceOffer.out.exponent()}; - STAmount bobXRP{ - aliceOffer.in.issue(), aliceOffer.in.mantissa() - 1}; - Amounts bobsOffer{bobUSD, bobXRP}; + aliceOffer.out.issue(), aliceOffer.out.mantissa() - mantissaReduce, aliceOffer.out.exponent()}; + STAmount bobXRP{aliceOffer.in.issue(), aliceOffer.in.mantissa() - 1}; + Amounts bobOffer{bobUSD, bobXRP}; - blockedCount += exerciseOfferPair(aliceOffer, bobsOffer); + blockedCount += exerciseOfferPair(aliceOffer, bobOffer); } // None of the test cases should produce a potentially blocking @@ -357,8 +311,7 @@ public: env.trust(USD(1000), alice, bob); int blockedOrderBookCount = 0; - for (STAmount initialBobUSD = USD(0.45); initialBobUSD <= USD(1); - initialBobUSD += USD(0.025)) + for (STAmount initialBobUSD = USD(0.45); initialBobUSD <= USD(1); initialBobUSD += USD(0.025)) { // underfund bob's offer env(pay(gw, bob, initialBobUSD)); @@ -380,8 +333,7 @@ public: // then we use that as evidence that bob's offer blocked the // order book. { - bool const bobsOfferGone = - !offerInLedger(env, bob, bobOfferSeq); + bool const bobOfferGone = !offerInLedger(env, bob, bobOfferSeq); STAmount const aliceBalanceUSD = env.balance(alice, USD); // Sanity check the ledger if alice got USD. @@ -389,27 +341,24 @@ public: { BEAST_EXPECT(aliceBalanceUSD == initialBobUSD); BEAST_EXPECT(env.balance(bob, USD) == USD(0)); - BEAST_EXPECT(bobsOfferGone); + BEAST_EXPECT(bobOfferGone); } // Track occurrences of order book blocking. - if (!bobsOfferGone && aliceBalanceUSD.signum() == 0) + if (!bobOfferGone && aliceBalanceUSD.signum() == 0) { ++blockedOrderBookCount; } // In preparation for the next iteration clean up any // leftover offers. - cleanupOldOffers( - env, {{alice, aliceOfferSeq}, {bob, bobOfferSeq}}); + cleanupOldOffers(env, {{alice, aliceOfferSeq}, {bob, bobOfferSeq}}); // Zero out alice's and bob's USD balances. - if (STAmount const aliceBalance = env.balance(alice, USD); - aliceBalance.signum() > 0) + if (STAmount const aliceBalance = env.balance(alice, USD); aliceBalance.signum() > 0) env(pay(alice, gw, aliceBalance)); - if (STAmount const bobBalance = env.balance(bob, USD); - bobBalance.signum() > 0) + if (STAmount const bobBalance = env.balance(bob, USD); bobBalance.signum() > 0) env(pay(bob, gw, bobBalance)); env.close(); @@ -448,17 +397,13 @@ public: env.trust(USD(1000), alice, bob); env.trust(EUR(1000), alice, bob); - STAmount const eurOffer( - EUR.issue(), /*mantissa*/ 2957, /*exponent*/ -76); - STAmount const usdOffer( - USD.issue(), /*mantissa*/ 7109, /*exponent*/ -76); + STAmount const eurOffer(EUR.issue(), /*mantissa*/ 2957, /*exponent*/ -76); + STAmount const usdOffer(USD.issue(), /*mantissa*/ 7109, /*exponent*/ -76); - STAmount const endLoop( - USD.issue(), /*mantissa*/ 50, /*exponent*/ -81); + STAmount const endLoop(USD.issue(), /*mantissa*/ 50, /*exponent*/ -81); int blockedOrderBookCount = 0; - for (STAmount initialBobUSD = tinyUSD; initialBobUSD <= endLoop; - initialBobUSD += tinyUSD) + for (STAmount initialBobUSD = tinyUSD; initialBobUSD <= endLoop; initialBobUSD += tinyUSD) { // underfund bob's offer env(pay(gw, bob, initialBobUSD)); @@ -478,14 +423,13 @@ public: // Examine the aftermath of alice's offer. { - bool const bobsOfferGone = - !offerInLedger(env, bob, bobOfferSeq); + bool const bobOfferGone = !offerInLedger(env, bob, bobOfferSeq); STAmount aliceBalanceUSD = env.balance(alice, USD); #if 0 std::cout - << "bobs initial: " << initialBobUSD + << "bob initial: " << initialBobUSD << "; alice final: " << aliceBalanceUSD - << "; bobs offer: " << bobsOfferJson.toStyledString() + << "; bob offer: " << bobOfferJson.toStyledString() << std::endl; #endif // Sanity check the ledger if alice got USD. @@ -493,11 +437,11 @@ public: { BEAST_EXPECT(aliceBalanceUSD == initialBobUSD); BEAST_EXPECT(env.balance(bob, USD) == USD(0)); - BEAST_EXPECT(bobsOfferGone); + BEAST_EXPECT(bobOfferGone); } // Track occurrences of order book blocking. - if (!bobsOfferGone && aliceBalanceUSD.signum() == 0) + if (!bobOfferGone && aliceBalanceUSD.signum() == 0) { ++blockedOrderBookCount; } @@ -505,14 +449,11 @@ public: // In preparation for the next iteration clean up any // leftover offers. - cleanupOldOffers( - env, {{alice, aliceOfferSeq}, {bob, bobOfferSeq}}); + cleanupOldOffers(env, {{alice, aliceOfferSeq}, {bob, bobOfferSeq}}); // Zero out alice's and bob's IOU balances. - auto zeroBalance = [&env, &gw]( - Account const& acct, IOU const& iou) { - if (STAmount const balance = env.balance(acct, iou); - balance.signum() > 0) + auto zeroBalance = [&env, &gw](Account const& acct, IOU const& iou) { + if (STAmount const balance = env.balance(acct, iou); balance.signum() > 0) env(pay(acct, gw, balance)); }; @@ -532,10 +473,8 @@ public: Amounts jsonOfferToAmounts(Json::Value const& json) { - STAmount const in = - amountFromJson(sfTakerPays, json[sfTakerPays.jsonName]); - STAmount const out = - amountFromJson(sfTakerGets, json[sfTakerGets.jsonName]); + STAmount const in = amountFromJson(sfTakerPays, json[sfTakerPays.jsonName]); + STAmount const out = amountFromJson(sfTakerGets, json[sfTakerGets.jsonName]); return {in, out}; } @@ -558,8 +497,7 @@ public: // Make one test run without fixReducedOffersV2 and one with. for (FeatureBitset features : - {testable_amendments() - fixReducedOffersV2, - testable_amendments() | fixReducedOffersV2}) + {testable_amendments() - fixReducedOffersV2, testable_amendments() | fixReducedOffersV2}) { // Make sure none of the offers we generate are under funded. Env env{*this, features}; @@ -581,17 +519,14 @@ public: // 2. Collects the results, and // 3. Cleans up for the next offer trio. auto exerciseOfferTrio = - [this, &env, &alice, &bob, &carol, &USD]( - Amounts const& carolOffer) -> unsigned int { + [this, &env, &alice, &bob, &carol, &USD](Amounts const& carolOffer) -> unsigned int { // alice submits an offer that may become a blocker. std::uint32_t const aliceOfferSeq = env.seq(alice); static Amounts const aliceInitialOffer(USD(2), drops(3382562)); env(offer(alice, aliceInitialOffer.in, aliceInitialOffer.out)); env.close(); STAmount const initialRate = - Quality(jsonOfferToAmounts(ledgerEntryOffer( - env, alice, aliceOfferSeq)[jss::node])) - .rate(); + Quality(jsonOfferToAmounts(ledgerEntryOffer(env, alice, aliceOfferSeq)[jss::node])).rate(); // bob submits an offer that is more desirable than alice's std::uint32_t const bobOfferSeq = env.seq(bob); @@ -601,39 +536,29 @@ public: // Now carol's offer consumes bob's and partially crosses // alice's. The tfSell flag is important. std::uint32_t const carolOfferSeq = env.seq(carol); - env(offer(carol, carolOffer.in, carolOffer.out), - txflags(tfSell)); + env(offer(carol, carolOffer.in, carolOffer.out), txflags(tfSell)); env.close(); // carol's offer should not have made it into the ledger and // bob's offer should be fully consumed. - if (!BEAST_EXPECT( - !offerInLedger(env, carol, carolOfferSeq) && - !offerInLedger(env, bob, bobOfferSeq))) + if (!BEAST_EXPECT(!offerInLedger(env, carol, carolOfferSeq) && !offerInLedger(env, bob, bobOfferSeq))) { // If carol's or bob's offers are still in the ledger then // further results are meaningless. - cleanupOldOffers( - env, - {{alice, aliceOfferSeq}, - {bob, bobOfferSeq}, - {carol, carolOfferSeq}}); + cleanupOldOffers(env, {{alice, aliceOfferSeq}, {bob, bobOfferSeq}, {carol, carolOfferSeq}}); return 1; } // alice's offer should still be in the ledger, but reduced in // size. unsigned int badRate = 1; { - Json::Value aliceOffer = - ledgerEntryOffer(env, alice, aliceOfferSeq); + Json::Value aliceOffer = ledgerEntryOffer(env, alice, aliceOfferSeq); - Amounts aliceReducedOffer = - jsonOfferToAmounts(aliceOffer[jss::node]); + Amounts aliceReducedOffer = jsonOfferToAmounts(aliceOffer[jss::node]); BEAST_EXPECT(aliceReducedOffer.in < aliceInitialOffer.in); BEAST_EXPECT(aliceReducedOffer.out < aliceInitialOffer.out); - STAmount const inLedgerRate = - Quality(aliceReducedOffer).rate(); + STAmount const inLedgerRate = Quality(aliceReducedOffer).rate(); badRate = inLedgerRate > initialRate ? 1 : 0; // If the inLedgerRate is less than initial rate, then @@ -648,10 +573,7 @@ public: aliceReducedOffer.in.mantissa() + 1, aliceReducedOffer.in.exponent(), aliceReducedOffer.in.negative()); - STAmount const tweakedRate = - Quality( - Amounts{aliceReducedOffer.in, tweakedTakerGets}) - .rate(); + STAmount const tweakedRate = Quality(Amounts{aliceReducedOffer.in, tweakedTakerGets}).rate(); BEAST_EXPECT(tweakedRate > initialRate); } #if 0 @@ -671,11 +593,7 @@ public: // In preparation for the next iteration make sure all three // offers are gone from the ledger. - cleanupOldOffers( - env, - {{alice, aliceOfferSeq}, - {bob, bobOfferSeq}, - {carol, carolOfferSeq}}); + cleanupOldOffers(env, {{alice, aliceOfferSeq}, {bob, bobOfferSeq}, {carol, carolOfferSeq}}); return badRate; }; @@ -686,8 +604,7 @@ public: STAmount const step(increaseGets.issue(), 1, -8); for (unsigned int i = 0; i < loopCount; ++i) { - blockedCount += exerciseOfferTrio( - Amounts(drops(1642020), USD(1) + increaseGets)); + blockedCount += exerciseOfferTrio(Amounts(drops(1642020), USD(1) + increaseGets)); increaseGets += step; } } diff --git a/src/test/app/Regression_test.cpp b/src/test/app/Regression_test.cpp index 56f0de9e07..052b334ef5 100644 --- a/src/test/app/Regression_test.cpp +++ b/src/test/app/Regression_test.cpp @@ -45,25 +45,20 @@ struct Regression_test : public beast::unit_test::suite // be reproduced against an open ledger. Make a local // closed ledger and work with it directly. auto closed = std::make_shared( - create_genesis, - env.app().config(), - std::vector{}, - env.app().getNodeFamily()); + create_genesis, env.app().config(), std::vector{}, env.app().getNodeFamily()); auto expectedDrops = INITIAL_XRP; BEAST_EXPECT(closed->header().drops == expectedDrops); auto const aliceXRP = 400; auto const aliceAmount = XRP(aliceXRP); - auto next = std::make_shared( - *closed, env.app().timeKeeper().closeTime()); + auto next = std::make_shared(*closed, env.app().timeKeeper().closeTime()); { // Fund alice auto const jt = env.jt(pay(env.master, "alice", aliceAmount)); OpenView accum(&*next); - auto const result = - xrpl::apply(env.app(), accum, *jt.stx, tapNONE, env.journal); + auto const result = xrpl::apply(env.app(), accum, *jt.stx, tapNONE, env.journal); BEAST_EXPECT(result.ter == tesSUCCESS); BEAST_EXPECT(result.applied); @@ -86,8 +81,7 @@ struct Regression_test : public beast::unit_test::suite OpenView accum(&*next); - auto const result = - xrpl::apply(env.app(), accum, *jt.stx, tapNONE, env.journal); + auto const result = xrpl::apply(env.app(), accum, *jt.stx, tapNONE, env.journal); BEAST_EXPECT(result.ter == tecINSUFF_FEE); BEAST_EXPECT(result.applied); @@ -115,8 +109,7 @@ struct Regression_test : public beast::unit_test::suite auto test256r1key = [&env](Account const& acct) { auto const baseFee = env.current()->fees().base; std::uint32_t const acctSeq = env.seq(acct); - Json::Value jsonNoop = - env.json(noop(acct), fee(baseFee), seq(acctSeq), sig(acct)); + Json::Value jsonNoop = env.json(noop(acct), fee(baseFee), seq(acctSeq), sig(acct)); JTx jt = env.jt(jsonNoop); jt.fill_sig = false; @@ -137,9 +130,7 @@ struct Regression_test : public beast::unit_test::suite secp256r1Sig->setFieldVL(sfSigningPubKey, *pubKeyBlob); jt.stx.reset(secp256r1Sig.release()); - env(jt, - rpc("invalidTransaction", - "fails local checks: Invalid signature.")); + env(jt, rpc("invalidTransaction", "fails local checks: Invalid signature.")); }; Account const alice{"alice", KeyType::secp256k1}; @@ -157,8 +148,7 @@ struct Regression_test : public beast::unit_test::suite testcase("Autofilled fee should use the escalated fee"); using namespace jtx; Env env(*this, envconfig([](std::unique_ptr cfg) { - cfg->section("transaction_queue") - .set("minimum_txn_in_ledger_standalone", "3"); + cfg->section("transaction_queue").set("minimum_txn_in_ledger_standalone", "3"); cfg->FEES.reference_fee = 10; return cfg; })); @@ -230,10 +220,8 @@ struct Regression_test : public beast::unit_test::suite std::vector buffers; buffers.emplace_back(buffer(request, 1024)); - buffers.emplace_back( - buffer(request.data() + 1024, request.length() - 1024)); - BEAST_EXPECT( - jrReader.parse(jvRequest, buffers) && jvRequest.isObject()); + buffers.emplace_back(buffer(request.data() + 1024, request.length() - 1024)); + BEAST_EXPECT(jrReader.parse(jvRequest, buffers) && jvRequest.isObject()); } void @@ -254,9 +242,7 @@ struct Regression_test : public beast::unit_test::suite auto const alice_index = keylet::account(alice).key; if (BEAST_EXPECT(alice_index.isNonZero())) { - env(check::cash( - alice, alice_index, check::DeliverMin(XRP(100))), - ter(tecNO_ENTRY)); + env(check::cash(alice, alice_index, check::DeliverMin(XRP(100))), ter(tecNO_ENTRY)); } } @@ -264,8 +250,7 @@ struct Regression_test : public beast::unit_test::suite auto const bob_index = keylet::account(bob).key; auto const digest = [&]() -> std::optional { - auto const& state = - env.app().getLedgerMaster().getClosedLedger()->stateMap(); + auto const& state = env.app().getLedgerMaster().getClosedLedger()->stateMap(); SHAMapHash digest; if (!state.peekItem(bob_index, digest)) return std::nullopt; @@ -282,30 +267,21 @@ struct Regression_test : public beast::unit_test::suite return result; }; - if (BEAST_EXPECT(bob_index.isNonZero()) && - BEAST_EXPECT(digest.has_value())) + if (BEAST_EXPECT(bob_index.isNonZero()) && BEAST_EXPECT(digest.has_value())) { auto& cache = env.app().cachedSLEs(); cache.del(*digest, false); - auto const beforeCounts = - mapCounts(CountedObjects::getInstance().getCounts(0)); + auto const beforeCounts = mapCounts(CountedObjects::getInstance().getCounts(0)); - env(check::cash(alice, bob_index, check::DeliverMin(XRP(100))), - ter(tecNO_ENTRY)); + env(check::cash(alice, bob_index, check::DeliverMin(XRP(100))), ter(tecNO_ENTRY)); - auto const afterCounts = - mapCounts(CountedObjects::getInstance().getCounts(0)); + auto const afterCounts = mapCounts(CountedObjects::getInstance().getCounts(0)); using namespace std::string_literals; + BEAST_EXPECT(beforeCounts.at("CachedView::hit"s) == afterCounts.at("CachedView::hit"s)); BEAST_EXPECT( - beforeCounts.at("CachedView::hit"s) == - afterCounts.at("CachedView::hit"s)); - BEAST_EXPECT( - beforeCounts.at("CachedView::hitExpired"s) + 1 == - afterCounts.at("CachedView::hitExpired"s)); - BEAST_EXPECT( - beforeCounts.at("CachedView::miss"s) == - afterCounts.at("CachedView::miss"s)); + beforeCounts.at("CachedView::hitExpired"s) + 1 == afterCounts.at("CachedView::hitExpired"s)); + BEAST_EXPECT(beforeCounts.at("CachedView::miss"s) == afterCounts.at("CachedView::miss"s)); } } } diff --git a/src/test/app/SHAMapStore_test.cpp b/src/test/app/SHAMapStore_test.cpp index d9689dc977..9e0a971685 100644 --- a/src/test/app/SHAMapStore_test.cpp +++ b/src/test/app/SHAMapStore_test.cpp @@ -35,49 +35,37 @@ class SHAMapStore_test : public beast::unit_test::suite } bool - goodLedger( - jtx::Env& env, - Json::Value const& json, - std::string ledgerID, - bool checkDB = false) + goodLedger(jtx::Env& env, Json::Value const& json, std::string ledgerID, bool checkDB = false) { - auto good = json.isMember(jss::result) && - !RPC::contains_error(json[jss::result]) && + auto good = json.isMember(jss::result) && !RPC::contains_error(json[jss::result]) && json[jss::result][jss::ledger][jss::ledger_index] == ledgerID; if (!good || !checkDB) return good; auto const seq = json[jss::result][jss::ledger_index].asUInt(); - std::optional oinfo = - env.app().getRelationalDatabase().getLedgerInfoByIndex(seq); - if (!oinfo) + std::optional outInfo = env.app().getRelationalDatabase().getLedgerInfoByIndex(seq); + if (!outInfo) return false; - LedgerHeader const& info = oinfo.value(); + LedgerHeader const& info = outInfo.value(); std::string const outHash = to_string(info.hash); LedgerIndex const outSeq = info.seq; std::string const outParentHash = to_string(info.parentHash); std::string const outDrops = to_string(info.drops); - std::uint64_t const outCloseTime = - info.closeTime.time_since_epoch().count(); - std::uint64_t const outParentCloseTime = - info.parentCloseTime.time_since_epoch().count(); - std::uint64_t const outCloseTimeResolution = - info.closeTimeResolution.count(); + std::uint64_t const outCloseTime = info.closeTime.time_since_epoch().count(); + std::uint64_t const outParentCloseTime = info.parentCloseTime.time_since_epoch().count(); + std::uint64_t const outCloseTimeResolution = info.closeTimeResolution.count(); std::uint64_t const outCloseFlags = info.closeFlags; std::string const outAccountHash = to_string(info.accountHash); std::string const outTxHash = to_string(info.txHash); auto const& ledger = json[jss::result][jss::ledger]; - return outHash == ledger[jss::ledger_hash].asString() && - outSeq == seq && - outParentHash == ledger[jss::parent_hash].asString() && - outDrops == ledger[jss::total_coins].asString() && + return outHash == ledger[jss::ledger_hash].asString() && outSeq == seq && + outParentHash == ledger[jss::parent_hash].asString() && outDrops == ledger[jss::total_coins].asString() && outCloseTime == ledger[jss::close_time].asUInt() && outParentCloseTime == ledger[jss::parent_close_time].asUInt() && - outCloseTimeResolution == - ledger[jss::close_time_resolution].asUInt() && + outCloseTimeResolution == ledger[jss::close_time_resolution].asUInt() && outCloseFlags == ledger[jss::close_flags].asUInt() && outAccountHash == ledger[jss::account_hash].asString() && outTxHash == ledger[jss::transaction_hash].asString(); @@ -86,8 +74,7 @@ class SHAMapStore_test : public beast::unit_test::suite bool bad(Json::Value const& json, error_code_i error = rpcLGR_NOT_FOUND) { - return json.isMember(jss::result) && - RPC::contains_error(json[jss::result]) && + return json.isMember(jss::result) && RPC::contains_error(json[jss::result]) && json[jss::result][jss::error_code] == error; } @@ -95,8 +82,7 @@ class SHAMapStore_test : public beast::unit_test::suite getHash(Json::Value const& json) { BEAST_EXPECT( - json.isMember(jss::result) && - json[jss::result].isMember(jss::ledger) && + json.isMember(jss::result) && json[jss::result].isMember(jss::ledger) && json[jss::result][jss::ledger].isMember(jss::ledger_hash) && json[jss::result][jss::ledger][jss::ledger_hash].isString()); return json[jss::result][jss::ledger][jss::ledger_hash].asString(); @@ -105,9 +91,7 @@ class SHAMapStore_test : public beast::unit_test::suite void ledgerCheck(jtx::Env& env, int const rows, int const first) { - auto const [actualRows, actualFirst, actualLast] = - dynamic_cast(&env.app().getRelationalDatabase()) - ->getLedgerCountMinMax(); + auto const [actualRows, actualFirst, actualLast] = env.app().getRelationalDatabase().getLedgerCountMinMax(); BEAST_EXPECT(actualRows == rows); BEAST_EXPECT(actualFirst == first); @@ -117,17 +101,13 @@ class SHAMapStore_test : public beast::unit_test::suite void transactionCheck(jtx::Env& env, int const rows) { - BEAST_EXPECT( - dynamic_cast(&env.app().getRelationalDatabase()) - ->getTransactionCount() == rows); + BEAST_EXPECT(env.app().getRelationalDatabase().getTransactionCount() == rows); } void accountTransactionCheck(jtx::Env& env, int const rows) { - BEAST_EXPECT( - dynamic_cast(&env.app().getRelationalDatabase()) - ->getAccountTransactionCount() == rows); + BEAST_EXPECT(env.app().getRelationalDatabase().getAccountTransactionCount() == rows); } int @@ -204,11 +184,8 @@ public: for (auto i = 3; i < deleteInterval + lastRotated; ++i) { - ledgers.emplace( - std::make_pair(i, env.rpc("ledger", std::to_string(i)))); - BEAST_EXPECT( - goodLedger(env, ledgers[i], std::to_string(i), true) && - getHash(ledgers[i]).length()); + ledgers.emplace(std::make_pair(i, env.rpc("ledger", std::to_string(i)))); + BEAST_EXPECT(goodLedger(env, ledgers[i], std::to_string(i), true) && getHash(ledgers[i]).length()); } ledgerCheck(env, deleteInterval + 1, 2); @@ -220,8 +197,7 @@ public: env.close(); auto ledger = env.rpc("ledger", "current"); - BEAST_EXPECT( - goodLedger(env, ledger, std::to_string(deleteInterval + 4))); + BEAST_EXPECT(goodLedger(env, ledger, std::to_string(deleteInterval + 4))); } store.rendezvous(); @@ -236,22 +212,16 @@ public: accountTransactionCheck(env, 2 * deleteInterval); // The last iteration of this loop should trigger a rotate - for (auto i = lastRotated - 1; i < lastRotated + deleteInterval - 1; - ++i) + for (auto i = lastRotated - 1; i < lastRotated + deleteInterval - 1; ++i) { env.close(); ledgerTmp = env.rpc("ledger", "current"); BEAST_EXPECT(goodLedger(env, ledgerTmp, std::to_string(i + 3))); - ledgers.emplace( - std::make_pair(i, env.rpc("ledger", std::to_string(i)))); - BEAST_EXPECT( - store.getLastRotated() == lastRotated || - i == lastRotated + deleteInterval - 2); - BEAST_EXPECT( - goodLedger(env, ledgers[i], std::to_string(i), true) && - getHash(ledgers[i]).length()); + ledgers.emplace(std::make_pair(i, env.rpc("ledger", std::to_string(i)))); + BEAST_EXPECT(store.getLastRotated() == lastRotated || i == lastRotated + deleteInterval - 2); + BEAST_EXPECT(goodLedger(env, ledgers[i], std::to_string(i), true) && getHash(ledgers[i]).length()); } store.rendezvous(); @@ -289,8 +259,7 @@ public: env.close(); auto ledger = env.rpc("ledger", "validated"); - BEAST_EXPECT( - goodLedger(env, ledger, std::to_string(ledgerSeq), true)); + BEAST_EXPECT(goodLedger(env, ledger, std::to_string(ledgerSeq), true)); } store.rendezvous(); @@ -305,8 +274,7 @@ public: env.close(); auto ledger = env.rpc("ledger", "validated"); - BEAST_EXPECT( - goodLedger(env, ledger, std::to_string(ledgerSeq++), true)); + BEAST_EXPECT(goodLedger(env, ledger, std::to_string(ledgerSeq++), true)); } store.rendezvous(); @@ -322,8 +290,7 @@ public: env.close(); auto ledger = env.rpc("ledger", "validated"); - BEAST_EXPECT( - goodLedger(env, ledger, std::to_string(ledgerSeq), true)); + BEAST_EXPECT(goodLedger(env, ledger, std::to_string(ledgerSeq), true)); } store.rendezvous(); @@ -362,8 +329,7 @@ public: env.close(); auto ledger = env.rpc("ledger", "validated"); - BEAST_EXPECT( - goodLedger(env, ledger, std::to_string(ledgerSeq), true)); + BEAST_EXPECT(goodLedger(env, ledger, std::to_string(ledgerSeq), true)); } store.rendezvous(); @@ -372,12 +338,9 @@ public: BEAST_EXPECT(lastRotated == store.getLastRotated()); // This does not kick off a cleanup - canDelete = env.rpc( - "can_delete", std::to_string(ledgerSeq + deleteInterval / 2)); + canDelete = env.rpc("can_delete", std::to_string(ledgerSeq + deleteInterval / 2)); BEAST_EXPECT(!RPC::contains_error(canDelete[jss::result])); - BEAST_EXPECT( - canDelete[jss::result][jss::can_delete] == - ledgerSeq + deleteInterval / 2); + BEAST_EXPECT(canDelete[jss::result][jss::can_delete] == ledgerSeq + deleteInterval / 2); store.rendezvous(); @@ -389,8 +352,7 @@ public: env.close(); auto ledger = env.rpc("ledger", "validated"); - BEAST_EXPECT( - goodLedger(env, ledger, std::to_string(ledgerSeq++), true)); + BEAST_EXPECT(goodLedger(env, ledger, std::to_string(ledgerSeq++), true)); } store.rendezvous(); @@ -406,8 +368,7 @@ public: env.close(); auto ledger = env.rpc("ledger", "validated"); - BEAST_EXPECT( - goodLedger(env, ledger, std::to_string(ledgerSeq), true)); + BEAST_EXPECT(goodLedger(env, ledger, std::to_string(ledgerSeq), true)); } store.rendezvous(); @@ -419,8 +380,7 @@ public: env.close(); auto ledger = env.rpc("ledger", "validated"); - BEAST_EXPECT( - goodLedger(env, ledger, std::to_string(ledgerSeq++), true)); + BEAST_EXPECT(goodLedger(env, ledger, std::to_string(ledgerSeq++), true)); } store.rendezvous(); @@ -433,9 +393,7 @@ public: // This does not kick off a cleanup canDelete = env.rpc("can_delete", "always"); BEAST_EXPECT(!RPC::contains_error(canDelete[jss::result])); - BEAST_EXPECT( - canDelete[jss::result][jss::can_delete] == - std::numeric_limits::max()); + BEAST_EXPECT(canDelete[jss::result][jss::can_delete] == std::numeric_limits::max()); for (; ledgerSeq < lastRotated + deleteInterval; ++ledgerSeq) { @@ -443,8 +401,7 @@ public: env.close(); auto ledger = env.rpc("ledger", "validated"); - BEAST_EXPECT( - goodLedger(env, ledger, std::to_string(ledgerSeq), true)); + BEAST_EXPECT(goodLedger(env, ledger, std::to_string(ledgerSeq), true)); } store.rendezvous(); @@ -456,8 +413,7 @@ public: env.close(); auto ledger = env.rpc("ledger", "validated"); - BEAST_EXPECT( - goodLedger(env, ledger, std::to_string(ledgerSeq++), true)); + BEAST_EXPECT(goodLedger(env, ledger, std::to_string(ledgerSeq++), true)); } store.rendezvous(); @@ -478,8 +434,7 @@ public: env.close(); auto ledger = env.rpc("ledger", "validated"); - BEAST_EXPECT( - goodLedger(env, ledger, std::to_string(ledgerSeq), true)); + BEAST_EXPECT(goodLedger(env, ledger, std::to_string(ledgerSeq), true)); } store.rendezvous(); @@ -491,8 +446,7 @@ public: env.close(); auto ledger = env.rpc("ledger", "validated"); - BEAST_EXPECT( - goodLedger(env, ledger, std::to_string(ledgerSeq++), true)); + BEAST_EXPECT(goodLedger(env, ledger, std::to_string(ledgerSeq++), true)); } store.rendezvous(); @@ -504,13 +458,9 @@ public: } std::unique_ptr - makeBackendRotating( - jtx::Env& env, - NodeStoreScheduler& scheduler, - std::string path) + makeBackendRotating(jtx::Env& env, NodeStoreScheduler& scheduler, std::string path) { - Section section{ - env.app().config().section(ConfigSection::nodeDatabase())}; + Section section{env.app().config().section(ConfigSection::nodeDatabase())}; boost::filesystem::path newPath; if (!BEAST_EXPECT(path.size())) @@ -520,8 +470,7 @@ public: auto backend{NodeStore::Manager::instance().make_Backend( section, - megabytes(env.app().config().getValueFor( - SizedItem::burstSize, std::nullopt)), + megabytes(env.app().config().getValueFor(SizedItem::burstSize, std::nullopt)), scheduler, env.app().logs().journal("NodeStoreTest"))}; backend->open(); @@ -539,23 +488,8 @@ public: Env env(*this, envconfig(onlineDelete)); ///////////////////////////////////////////////////////////// - // Create the backend. Normally, SHAMapStoreImp handles all these - // details - auto nscfg = env.app().config().section(ConfigSection::nodeDatabase()); - - // Provide default values: - if (!nscfg.exists("cache_size")) - nscfg.set( - "cache_size", - std::to_string(env.app().config().getValueFor( - SizedItem::treeCacheSize, std::nullopt))); - - if (!nscfg.exists("cache_age")) - nscfg.set( - "cache_age", - std::to_string(env.app().config().getValueFor( - SizedItem::treeCacheAge, std::nullopt))); - + // Create NodeStore with two backends to allow online deletion of data. + // Normally, SHAMapStoreImp handles all these details. NodeStoreScheduler scheduler(env.app().getJobQueue()); std::string const writableDb = "write"; @@ -563,9 +497,8 @@ public: auto writableBackend = makeBackendRotating(env, scheduler, writableDb); auto archiveBackend = makeBackendRotating(env, scheduler, archiveDb); - // Create NodeStore with two backends to allow online deletion of - // data constexpr int readThreads = 4; + auto nscfg = env.app().config().section(ConfigSection::nodeDatabase()); auto dbr = std::make_unique( scheduler, readThreads, @@ -580,11 +513,9 @@ public: std::atomic threadNum = 0; { - auto newBackend = makeBackendRotating( - env, scheduler, std::to_string(++threadNum)); + auto newBackend = makeBackendRotating(env, scheduler, std::to_string(++threadNum)); - auto const cb = [&](std::string const& writableName, - std::string const& archiveName) { + auto const cb = [&](std::string const& writableName, std::string const& archiveName) { BEAST_EXPECT(writableName == "1"); BEAST_EXPECT(archiveName == "write"); // Ensure that dbr functions can be called from within the @@ -600,25 +531,21 @@ public: ///////////////////////////////////////////////////////////// // Do something stupid. Try to re-enter rotate from inside the callback. { - auto const cb = [&](std::string const& writableName, - std::string const& archiveName) { + auto const cb = [&](std::string const& writableName, std::string const& archiveName) { BEAST_EXPECT(writableName == "3"); BEAST_EXPECT(archiveName == "2"); // Ensure that dbr functions can be called from within the // callback BEAST_EXPECT(dbr->getName() == "3"); }; - auto const cbReentrant = [&](std::string const& writableName, - std::string const& archiveName) { + auto const cbReentrant = [&](std::string const& writableName, std::string const& archiveName) { BEAST_EXPECT(writableName == "2"); BEAST_EXPECT(archiveName == "1"); - auto newBackend = makeBackendRotating( - env, scheduler, std::to_string(++threadNum)); + auto newBackend = makeBackendRotating(env, scheduler, std::to_string(++threadNum)); // Reminder: doing this is stupid and should never happen dbr->rotate(std::move(newBackend), cb); }; - auto newBackend = makeBackendRotating( - env, scheduler, std::to_string(++threadNum)); + auto newBackend = makeBackendRotating(env, scheduler, std::to_string(++threadNum)); dbr->rotate(std::move(newBackend), cbReentrant); } diff --git a/src/test/app/SetAuth_test.cpp b/src/test/app/SetAuth_test.cpp index 29f1e46ca4..400e2b0e29 100644 --- a/src/test/app/SetAuth_test.cpp +++ b/src/test/app/SetAuth_test.cpp @@ -12,16 +12,12 @@ struct SetAuth_test : public beast::unit_test::suite // If the trust line does not exist, then it should // be created under the new rules. static Json::Value - auth( - jtx::Account const& account, - jtx::Account const& dest, - std::string const& currency) + auth(jtx::Account const& account, jtx::Account const& dest, std::string const& currency) { using namespace jtx; Json::Value jv; jv[jss::Account] = account.human(); - jv[jss::LimitAmount] = STAmount(Issue{to_currency(currency), dest}) - .getJson(JsonOptions::none); + jv[jss::LimitAmount] = STAmount(Issue{to_currency(currency), dest}).getJson(JsonOptions::none); jv[jss::TransactionType] = jss::TrustSet; jv[jss::Flags] = tfSetfAuth; return jv; @@ -40,8 +36,7 @@ struct SetAuth_test : public beast::unit_test::suite env(fset(gw, asfRequireAuth)); env.close(); env(auth(gw, "alice", "USD")); - BEAST_EXPECT( - env.le(keylet::line(Account("alice").id(), gw.id(), USD.currency))); + BEAST_EXPECT(env.le(keylet::line(Account("alice").id(), gw.id(), USD.currency))); env(trust("alice", USD(1000))); env(trust("bob", USD(1000))); env(pay(gw, "alice", USD(100))); diff --git a/src/test/app/SetRegularKey_test.cpp b/src/test/app/SetRegularKey_test.cpp index 308e5527f7..aec8dddc7a 100644 --- a/src/test/app/SetRegularKey_test.cpp +++ b/src/test/app/SetRegularKey_test.cpp @@ -28,9 +28,7 @@ public: env(noop(alice), sig(alice), ter(tefMASTER_DISABLED)); testcase("Re-enable master key"); - env(fclear(alice, asfDisableMaster), - sig(alice), - ter(tefMASTER_DISABLED)); + env(fclear(alice, asfDisableMaster), sig(alice), ter(tefMASTER_DISABLED)); env(fclear(alice, asfDisableMaster), sig(bob)); env(noop(alice), sig(bob)); @@ -67,17 +65,13 @@ public: env.fund(XRP(10000), alice, bob); auto ar = env.le(alice); - BEAST_EXPECT( - ar->isFieldPresent(sfFlags) && - ((ar->getFieldU32(sfFlags) & lsfPasswordSpent) == 0)); + BEAST_EXPECT(ar->isFieldPresent(sfFlags) && ((ar->getFieldU32(sfFlags) & lsfPasswordSpent) == 0)); env(regkey(alice, bob), sig(alice), fee(0)); ar = env.le(alice); BEAST_EXPECT( - ar->isFieldPresent(sfFlags) && - ((ar->getFieldU32(sfFlags) & lsfPasswordSpent) == - lsfPasswordSpent)); + ar->isFieldPresent(sfFlags) && ((ar->getFieldU32(sfFlags) & lsfPasswordSpent) == lsfPasswordSpent)); // The second SetRegularKey transaction with Fee=0 should fail. env(regkey(alice, bob), sig(alice), fee(0), ter(telINSUF_FEE_P)); @@ -85,9 +79,7 @@ public: env.trust(bob["USD"](1), alice); env(pay(bob, alice, bob["USD"](1))); ar = env.le(alice); - BEAST_EXPECT( - ar->isFieldPresent(sfFlags) && - ((ar->getFieldU32(sfFlags) & lsfPasswordSpent) == 0)); + BEAST_EXPECT(ar->isFieldPresent(sfFlags) && ((ar->getFieldU32(sfFlags) & lsfPasswordSpent) == 0)); } void @@ -128,9 +120,7 @@ public: env.close(); // Disable alice's master key using a ticket. - env(fset(alice, asfDisableMaster), - sig(alice), - ticket::use(--ticketSeq)); + env(fset(alice, asfDisableMaster), sig(alice), ticket::use(--ticketSeq)); env.close(); // alice should be able to sign using the regular key but not the @@ -142,9 +132,7 @@ public: BEAST_EXPECT(env.seq(alice) == aliceSeq + 1); // Re-enable the master key using a ticket. - env(fclear(alice, asfDisableMaster), - sig(alie), - ticket::use(--ticketSeq)); + env(fclear(alice, asfDisableMaster), sig(alie), ticket::use(--ticketSeq)); env.close(); // Disable the regular key using a ticket. diff --git a/src/test/app/SetTrust_test.cpp b/src/test/app/SetTrust_test.cpp index f8309c4271..4704365550 100644 --- a/src/test/app/SetTrust_test.cpp +++ b/src/test/app/SetTrust_test.cpp @@ -13,8 +13,7 @@ public: void testTrustLineDelete() { - testcase( - "Test deletion of trust lines: revert trust line limit to zero"); + testcase("Test deletion of trust lines: revert trust line limit to zero"); using namespace jtx; Env env(*this); @@ -149,10 +148,7 @@ public: } void - testFreeTrustlines( - FeatureBitset features, - bool thirdLineCreatesLE, - bool createOnHighAcct) + testFreeTrustlines(FeatureBitset features, bool thirdLineCreatesLE, bool createOnHighAcct) { if (thirdLineCreatesLE) testcase("Allow two free trustlines"); @@ -188,20 +184,16 @@ public: if (thirdLineCreatesLE) { // creator does not have enough for the third trust line - env(trust(creator, assistor["USD"](100)), - ter(tecNO_LINE_INSUF_RESERVE), - require(lines(creator, 2))); + env(trust(creator, assistor["USD"](100)), ter(tecNO_LINE_INSUF_RESERVE), require(lines(creator, 2))); } else { // First establish opposite trust direction from assistor - env(trust(assistor, creator["USD"](100)), - require(lines(creator, 3))); + env(trust(assistor, creator["USD"](100)), require(lines(creator, 3))); // creator does not have enough to create the other direction on // the existing trust line ledger entry - env(trust(creator, assistor["USD"](100)), - ter(tecINSUF_RESERVE_LINE)); + env(trust(creator, assistor["USD"](100)), ter(tecINSUF_RESERVE_LINE)); } // Fund creator additional amount to cover @@ -209,13 +201,11 @@ public: if (thirdLineCreatesLE) { - env(trust(creator, assistor["USD"](100)), - require(lines(creator, 3))); + env(trust(creator, assistor["USD"](100)), require(lines(creator, 3))); } else { - env(trust(creator, assistor["USD"](100)), - require(lines(creator, 3))); + env(trust(creator, assistor["USD"](100)), require(lines(creator, 3))); Json::Value jv; jv["account"] = creator.human(); @@ -288,32 +278,23 @@ public: env.fund(XRP(10000), gw, alice); // Require valid tf flags - for (std::uint64_t badFlag = 1u; - badFlag <= std::numeric_limits::max(); - badFlag *= 2) + for (std::uint64_t badFlag = 1u; badFlag <= std::numeric_limits::max(); badFlag *= 2) { if (badFlag & tfTrustSetMask) - env(trust( - alice, - gw["USD"](100), - static_cast(badFlag)), - ter(temINVALID_FLAG)); + env(trust(alice, gw["USD"](100), static_cast(badFlag)), ter(temINVALID_FLAG)); } // trust amount can't be XRP env(trust_explicit_amt(alice, drops(10000)), ter(temBAD_LIMIT)); // trust amount can't be badCurrency IOU - env(trust_explicit_amt(alice, gw[to_string(badCurrency())](100)), - ter(temBAD_CURRENCY)); + env(trust_explicit_amt(alice, gw[to_string(badCurrency())](100)), ter(temBAD_CURRENCY)); // trust amount can't be negative env(trust(alice, gw["USD"](-1000)), ter(temBAD_LIMIT)); // trust amount can't be from invalid issuer - env(trust_explicit_amt( - alice, STAmount{Issue{to_currency("USD"), noAccount()}, 100}), - ter(temDST_NEEDED)); + env(trust_explicit_amt(alice, STAmount{Issue{to_currency("USD"), noAccount()}, 100}), ter(temDST_NEEDED)); // trust cannot be to self env(trust(alice, alice["USD"](100)), ter(temDST_IS_SRC)); @@ -417,13 +398,9 @@ public: } void - testModifyQualityOfTrustline( - FeatureBitset features, - bool createQuality, - bool createOnHighAcct) + testModifyQualityOfTrustline(FeatureBitset features, bool createQuality, bool createOnHighAcct) { - testcase << "SetTrust " << (createQuality ? "creates" : "removes") - << " quality of trustline for " + testcase << "SetTrust " << (createQuality ? "creates" : "removes") << " quality of trustline for " << (createOnHighAcct ? "high" : "low") << " account"; using namespace jtx; @@ -455,11 +432,8 @@ public: auto quality = exists ? 1000 : 0; BEAST_EXPECT(lines[jss::result][jss::lines].isArray()); BEAST_EXPECT(lines[jss::result][jss::lines].size() == 1); - BEAST_EXPECT( - lines[jss::result][jss::lines][0u][jss::quality_in] == quality); - BEAST_EXPECT( - lines[jss::result][jss::lines][0u][jss::quality_out] == - quality); + BEAST_EXPECT(lines[jss::result][jss::lines][0u][jss::quality_in] == quality); + BEAST_EXPECT(lines[jss::result][jss::lines][0u][jss::quality_out] == quality); }; env(tx1, require(lines(toAcct, 1)), require(lines(fromAcct, 1))); @@ -480,8 +454,7 @@ public: { for (bool const withFix : {true, false}) { - auto const amend = - withFix ? features : features - fixDisallowIncomingV1; + auto const amend = withFix ? features : features - fixDisallowIncomingV1; Env env{*this, amend}; auto const dist = Account("dist"); @@ -503,15 +476,11 @@ public: // withFix: can set trustline // withOutFix: cannot set trustline - auto const trustResult = - withFix ? ter(tesSUCCESS) : ter(tecNO_PERMISSION); - env(trust(gw, distUSD(10000)), - txflags(tfSetfAuth), - trustResult); + auto const trustResult = withFix ? ter(tesSUCCESS) : ter(tecNO_PERMISSION); + env(trust(gw, distUSD(10000)), txflags(tfSetfAuth), trustResult); env.close(); - auto const txResult = - withFix ? ter(tesSUCCESS) : ter(tecPATH_DRY); + auto const txResult = withFix ? ter(tesSUCCESS) : ter(tecPATH_DRY); env(pay(gw, dist, USD(1000)), txResult); env.close(); } diff --git a/src/test/app/TheoreticalQuality_test.cpp b/src/test/app/TheoreticalQuality_test.cpp index ed4a62c4b0..1f626ad477 100644 --- a/src/test/app/TheoreticalQuality_test.cpp +++ b/src/test/app/TheoreticalQuality_test.cpp @@ -44,27 +44,18 @@ struct RippleCalcTestParams { if (pe.isMember(jss::account)) { - assert( - !pe.isMember(jss::currency) && - !pe.isMember(jss::issuer)); + assert(!pe.isMember(jss::currency) && !pe.isMember(jss::issuer)); p.emplace_back( - *parseBase58( - pe[jss::account].asString()), - std::nullopt, - std::nullopt); + *parseBase58(pe[jss::account].asString()), std::nullopt, std::nullopt); } - else if ( - pe.isMember(jss::currency) && pe.isMember(jss::issuer)) + else if (pe.isMember(jss::currency) && pe.isMember(jss::issuer)) { - auto const currency = - to_currency(pe[jss::currency].asString()); + auto const currency = to_currency(pe[jss::currency].asString()); std::optional issuer; if (!isXRP(currency)) - issuer = *parseBase58( - pe[jss::issuer].asString()); + issuer = *parseBase58(pe[jss::issuer].asString()); else - assert(isXRP(*parseBase58( - pe[jss::issuer].asString()))); + assert(isXRP(*parseBase58(pe[jss::issuer].asString()))); p.emplace_back(std::nullopt, currency, issuer); } else @@ -112,20 +103,14 @@ class RandomAccountParams return; auto const percent = qualityPercentDist_(engine_); - auto const& field = - qDir == QualityDirection::in ? sfQualityIn : sfQualityOut; - auto const value = - static_cast((percent / 100) * QUALITY_ONE); + auto const& field = qDir == QualityDirection::in ? sfQualityIn : sfQualityOut; + auto const value = static_cast((percent / 100) * QUALITY_ONE); jv[field.jsonName] = value; }; // Setup the trust amounts and in/out qualities (but not the balances) void - setupTrustLine( - jtx::Env& env, - jtx::Account const& acc, - jtx::Account const& peer, - Currency const& currency) + setupTrustLine(jtx::Env& env, jtx::Account const& acc, jtx::Account const& peer, Currency const& currency) { using namespace jtx; IOU const iou{peer, currency}; @@ -137,13 +122,9 @@ class RandomAccountParams }; public: - explicit RandomAccountParams( - std::uint32_t trustAmount = 100, - std::uint32_t initialBalance = 50) + explicit RandomAccountParams(std::uint32_t trustAmount = 100, std::uint32_t initialBalance = 50) // Use a deterministic seed so the unit tests run in a reproducible way - : engine_{1977u} - , trustAmount_{trustAmount} - , initialBalance_{initialBalance} {}; + : engine_{1977u}, trustAmount_{trustAmount}, initialBalance_{initialBalance} {}; void maybeSetTransferRate(jtx::Env& env, jtx::Account const& acc) @@ -154,29 +135,19 @@ public: // Set the initial balance, taking into account the qualities void - setInitialBalance( - jtx::Env& env, - jtx::Account const& acc, - jtx::Account const& peer, - Currency const& currency) + setInitialBalance(jtx::Env& env, jtx::Account const& acc, jtx::Account const& peer, Currency const& currency) { using namespace jtx; IOU const iou{acc, currency}; // This payment sets the acc's balance to `initialBalance`. // Since input qualities complicate this payment, use `sendMax` with // `initialBalance` to make sure the balance is set correctly. - env(pay(peer, acc, iou(trustAmount_)), - sendmax(iou(initialBalance_)), - txflags(tfPartialPayment)); + env(pay(peer, acc, iou(trustAmount_)), sendmax(iou(initialBalance_)), txflags(tfPartialPayment)); env.close(); } void - maybeSetInitialBalance( - jtx::Env& env, - jtx::Account const& acc, - jtx::Account const& peer, - Currency const& currency) + maybeSetInitialBalance(jtx::Env& env, jtx::Account const& acc, jtx::Account const& peer, Currency const& currency) { using namespace jtx; if (zeroOneDist_(engine_) > probRedeem_) @@ -187,11 +158,7 @@ public: // Setup the trust amounts and in/out qualities (but not the balances) on // both sides of the trust line void - setupTrustLines( - jtx::Env& env, - jtx::Account const& acc1, - jtx::Account const& acc2, - Currency const& currency) + setupTrustLines(jtx::Env& env, jtx::Account const& acc1, jtx::Account const& acc2, Currency const& currency) { setupTrustLine(env, acc1, acc2, currency); setupTrustLine(env, acc2, acc1, currency); @@ -270,8 +237,7 @@ class TheoreticalQuality_test : public beast::unit_test::suite for (auto const& strand : sr.second) { Quality const theoreticalQ = *qualityUpperBound(sb, strand); - auto const f = flow( - sb, strand, IOUAmount(10, 0), IOUAmount(5, 0), dummyJ); + auto const f = flow(sb, strand, IOUAmount(10, 0), IOUAmount(5, 0), dummyJ); BEAST_EXPECT(f.success); Quality const actualQ(f.out, f.in); if (actualQ != theoreticalQ && !compareClose(actualQ, theoreticalQ)) @@ -282,8 +248,7 @@ class TheoreticalQuality_test : public beast::unit_test::suite log << "AQ: " << prettyQuality(actualQ) << "\n"; logStrand(log, strand); } - if (expectedQ && expectedQ != theoreticalQ && - !compareClose(*expectedQ, theoreticalQ)) + if (expectedQ && expectedQ != theoreticalQ && !compareClose(*expectedQ, theoreticalQ)) { BEAST_EXPECT(expectedQ == theoreticalQ); // get the failure log << "\nExpected != Theoretical\n"; @@ -351,8 +316,7 @@ public: auto const carol = Account("carol" + iterAsStr); auto const dan = Account("dan" + iterAsStr); std::array accounts{{alice, bob, carol, dan}}; - static_assert( - numAccounts == 4, "Path is only correct for four accounts"); + static_assert(numAccounts == 4, "Path is only correct for four accounts"); path const accountsPath(accounts[1], accounts[2]); env.fund(XRP(10000), alice, bob, carol, dan); env.close(); @@ -370,18 +334,14 @@ public: if (j == numAccounts) continue; - rndAccParams.setupTrustLines( - env, accounts[ii], accounts[j], currency); - rndAccParams.maybeSetInitialBalance( - env, accounts[ii], accounts[j], currency); + rndAccParams.setupTrustLines(env, accounts[ii], accounts[j], currency); + rndAccParams.maybeSetInitialBalance(env, accounts[ii], accounts[j], currency); } // Accounts are set up, make the payment IOU const iou{accounts.back(), currency}; RippleCalcTestParams rcp{env.json( - pay(accounts.front(), accounts.back(), iou(paymentAmount)), - accountsPath, - txflags(tfNoRippleDirect))}; + pay(accounts.front(), accounts.back(), iou(paymentAmount)), accountsPath, txflags(tfNoRippleDirect))}; testCase(rcp, env.closed()); } @@ -427,8 +387,7 @@ public: auto const USDB = bob["USD"]; auto const EURC = carol["EUR"]; constexpr std::size_t const numAccounts = 5; - std::array accounts{ - {alice, bob, carol, dan, oscar}}; + std::array accounts{{alice, bob, carol, dan, oscar}}; // sendmax should be in USDB and delivered amount should be in EURC // normalized path should be: @@ -443,14 +402,10 @@ public: for (auto const& currency : {usdCurrency, eurCurrency}) { - rndAccParams.setupTrustLines( - env, alice, bob, currency); // first step in payment - rndAccParams.setupTrustLines( - env, carol, dan, currency); // last step in payment - rndAccParams.setupTrustLines( - env, oscar, bob, currency); // offer owner - rndAccParams.setupTrustLines( - env, oscar, carol, currency); // offer owner + rndAccParams.setupTrustLines(env, alice, bob, currency); // first step in payment + rndAccParams.setupTrustLines(env, carol, dan, currency); // last step in payment + rndAccParams.setupTrustLines(env, oscar, bob, currency); // offer owner + rndAccParams.setupTrustLines(env, oscar, carol, currency); // offer owner } rndAccParams.maybeSetInitialBalance(env, alice, bob, usdCurrency); @@ -479,8 +434,7 @@ public: { testcase("Relative quality distance"); - auto toQuality = [](std::uint64_t mantissa, - int exponent = 0) -> Quality { + auto toQuality = [](std::uint64_t mantissa, int exponent = 0) -> Quality { // The only way to construct a Quality from an STAmount is to take // their ratio. Set the denominator STAmount to `one` to easily // create a quality from a single amount @@ -492,18 +446,14 @@ public: BEAST_EXPECT(relativeDistance(toQuality(100), toQuality(100)) == 0); BEAST_EXPECT(relativeDistance(toQuality(100), toQuality(100, 1)) == 9); BEAST_EXPECT(relativeDistance(toQuality(100), toQuality(110)) == .1); - BEAST_EXPECT( - relativeDistance(toQuality(100, 90), toQuality(110, 90)) == .1); - BEAST_EXPECT( - relativeDistance(toQuality(100, 90), toQuality(110, 91)) == 10); - BEAST_EXPECT( - relativeDistance(toQuality(100, 0), toQuality(100, 90)) == 1e90); + BEAST_EXPECT(relativeDistance(toQuality(100, 90), toQuality(110, 90)) == .1); + BEAST_EXPECT(relativeDistance(toQuality(100, 90), toQuality(110, 91)) == 10); + BEAST_EXPECT(relativeDistance(toQuality(100, 0), toQuality(100, 90)) == 1e90); // Make the mantissa in the smaller value bigger than the mantissa in // the larger value. Instead of checking the exact result, we check that // it's large. If the values did not compare correctly in // `relativeDistance`, then the returned value would be negative. - BEAST_EXPECT( - relativeDistance(toQuality(102, 0), toQuality(101, 90)) >= 1e89); + BEAST_EXPECT(relativeDistance(toQuality(102, 0), toQuality(101, 90)) >= 1e89); } void diff --git a/src/test/app/Ticket_test.cpp b/src/test/app/Ticket_test.cpp index 3136699103..0835c02289 100644 --- a/src/test/app/Ticket_test.cpp +++ b/src/test/app/Ticket_test.cpp @@ -19,19 +19,14 @@ class Ticket_test : public beast::unit_test::suite Json::Value const& tx{env.tx()->getJson(JsonOptions::none)}; { - std::string const txType = - tx[sfTransactionType.jsonName].asString(); + std::string const txType = tx[sfTransactionType.jsonName].asString(); - if (!BEAST_EXPECTS( - txType == jss::TicketCreate, - "Unexpected TransactionType: "s + txType)) + if (!BEAST_EXPECTS(txType == jss::TicketCreate, "Unexpected TransactionType: "s + txType)) return; } std::uint32_t const count = {tx[sfTicketCount.jsonName].asUInt()}; - if (!BEAST_EXPECTS( - count >= 1, - "Unexpected ticket count: "s + std::to_string(count))) + if (!BEAST_EXPECTS(count >= 1, "Unexpected ticket count: "s + std::to_string(count))) return; std::uint32_t const txSeq = {tx[sfSequence.jsonName].asUInt()}; @@ -40,8 +35,7 @@ class Ticket_test : public beast::unit_test::suite Json::Value const& metadata = env.meta()->getJson(JsonOptions::none); if (!BEAST_EXPECTS( metadata.isMember(sfTransactionResult.jsonName) && - metadata[sfTransactionResult.jsonName].asString() == - "tesSUCCESS", + metadata[sfTransactionResult.jsonName].asString() == "tesSUCCESS", "Not metadata for successful TicketCreate.")) return; @@ -57,20 +51,16 @@ class Ticket_test : public beast::unit_test::suite if (node.isMember(sfModifiedNode.jsonName)) { Json::Value const& modified = node[sfModifiedNode.jsonName]; - std::string const entryType = - modified[sfLedgerEntryType.jsonName].asString(); + std::string const entryType = modified[sfLedgerEntryType.jsonName].asString(); if (entryType == jss::AccountRoot) { - auto const& previousFields = - modified[sfPreviousFields.jsonName]; + auto const& previousFields = modified[sfPreviousFields.jsonName]; auto const& finalFields = modified[sfFinalFields.jsonName]; { // Verify the account root Sequence did the right thing. - std::uint32_t const prevSeq = - previousFields[sfSequence.jsonName].asUInt(); + std::uint32_t const prevSeq = previousFields[sfSequence.jsonName].asUInt(); - acctRootFinalSeq = - finalFields[sfSequence.jsonName].asUInt(); + acctRootFinalSeq = finalFields[sfSequence.jsonName].asUInt(); if (txSeq == 0) { @@ -81,13 +71,11 @@ class Ticket_test : public beast::unit_test::suite { // Transaction used a (plain) Sequence. BEAST_EXPECT(prevSeq == txSeq); - BEAST_EXPECT( - acctRootFinalSeq == prevSeq + count + 1); + BEAST_EXPECT(acctRootFinalSeq == prevSeq + count + 1); } } - std::uint32_t const consumedTickets = { - txSeq == 0u ? 1u : 0u}; + std::uint32_t const consumedTickets = {txSeq == 0u ? 1u : 0u}; // If... // 1. The TicketCount is 1 and @@ -96,28 +84,23 @@ class Ticket_test : public beast::unit_test::suite // previous TicketCount is not reported. // But, since the count did not change, we know it equals // the final Ticket count. - bool const unreportedPrevTicketCount = { - count == 1 && txSeq == 0}; + bool const unreportedPrevTicketCount = {count == 1 && txSeq == 0}; // Verify the OwnerCount did the right thing if (unreportedPrevTicketCount) { // The number of Tickets should not have changed, so // the previous OwnerCount should not be reported. - BEAST_EXPECT( - !previousFields.isMember(sfOwnerCount.jsonName)); + BEAST_EXPECT(!previousFields.isMember(sfOwnerCount.jsonName)); } else { // Verify the OwnerCount did the right thing. - std::uint32_t const prevCount = { - previousFields[sfOwnerCount.jsonName].asUInt()}; + std::uint32_t const prevCount = {previousFields[sfOwnerCount.jsonName].asUInt()}; - std::uint32_t const finalCount = { - finalFields[sfOwnerCount.jsonName].asUInt()}; + std::uint32_t const finalCount = {finalFields[sfOwnerCount.jsonName].asUInt()}; - BEAST_EXPECT( - prevCount + count - consumedTickets == finalCount); + BEAST_EXPECT(prevCount + count - consumedTickets == finalCount); } // Verify TicketCount metadata. @@ -127,8 +110,7 @@ class Ticket_test : public beast::unit_test::suite { // The number of Tickets should not have changed, so // the previous TicketCount should not be reported. - BEAST_EXPECT( - !previousFields.isMember(sfTicketCount.jsonName)); + BEAST_EXPECT(!previousFields.isMember(sfTicketCount.jsonName)); } else { @@ -136,17 +118,12 @@ class Ticket_test : public beast::unit_test::suite // should have been greater than zero. std::uint32_t const startCount = { previousFields.isMember(sfTicketCount.jsonName) - ? previousFields[sfTicketCount.jsonName] - .asUInt() + ? previousFields[sfTicketCount.jsonName].asUInt() : 0u}; - BEAST_EXPECT( - (startCount == 0u) ^ - previousFields.isMember(sfTicketCount.jsonName)); + BEAST_EXPECT((startCount == 0u) ^ previousFields.isMember(sfTicketCount.jsonName)); - BEAST_EXPECT( - startCount + count - consumedTickets == - finalFields[sfTicketCount.jsonName]); + BEAST_EXPECT(startCount + count - consumedTickets == finalFields[sfTicketCount.jsonName]); } } else if (entryType == jss::DirectoryNode) @@ -155,25 +132,19 @@ class Ticket_test : public beast::unit_test::suite } else { - fail( - "Unexpected modified node: "s + entryType, - __FILE__, - __LINE__); + fail("Unexpected modified node: "s + entryType, __FILE__, __LINE__); } } else if (node.isMember(sfCreatedNode.jsonName)) { Json::Value const& created = node[sfCreatedNode.jsonName]; - std::string const entryType = - created[sfLedgerEntryType.jsonName].asString(); + std::string const entryType = created[sfLedgerEntryType.jsonName].asString(); if (entryType == jss::Ticket) { auto const& newFields = created[sfNewFields.jsonName]; - BEAST_EXPECT( - newFields[sfAccount.jsonName].asString() == account); - ticketSeqs.push_back( - newFields[sfTicketSequence.jsonName].asUInt()); + BEAST_EXPECT(newFields[sfAccount.jsonName].asString() == account); + ticketSeqs.push_back(newFields[sfTicketSequence.jsonName].asUInt()); } else if (entryType == jss::DirectoryNode) { @@ -181,17 +152,13 @@ class Ticket_test : public beast::unit_test::suite } else { - fail( - "Unexpected created node: "s + entryType, - __FILE__, - __LINE__); + fail("Unexpected created node: "s + entryType, __FILE__, __LINE__); } } else if (node.isMember(sfDeletedNode.jsonName)) { Json::Value const& deleted = node[sfDeletedNode.jsonName]; - std::string const entryType = - deleted[sfLedgerEntryType.jsonName].asString(); + std::string const entryType = deleted[sfLedgerEntryType.jsonName].asString(); if (entryType == jss::Ticket) { @@ -200,21 +167,16 @@ class Ticket_test : public beast::unit_test::suite // Verify the account of the deleted ticket. auto const& finalFields = deleted[sfFinalFields.jsonName]; - BEAST_EXPECT( - finalFields[sfAccount.jsonName].asString() == account); + BEAST_EXPECT(finalFields[sfAccount.jsonName].asString() == account); // Verify the deleted ticket has the right TicketSequence. BEAST_EXPECT( - finalFields[sfTicketSequence.jsonName].asUInt() == - tx[sfTicketSequence.jsonName].asUInt()); + finalFields[sfTicketSequence.jsonName].asUInt() == tx[sfTicketSequence.jsonName].asUInt()); } } else { - fail( - "Unexpected node type in TicketCreate metadata.", - __FILE__, - __LINE__); + fail("Unexpected node type in TicketCreate metadata.", __FILE__, __LINE__); } } BEAST_EXPECT(directoryChanged); @@ -222,9 +184,7 @@ class Ticket_test : public beast::unit_test::suite // Verify that all the expected Tickets were created. BEAST_EXPECT(ticketSeqs.size() == count); std::sort(ticketSeqs.begin(), ticketSeqs.end()); - BEAST_EXPECT( - std::adjacent_find(ticketSeqs.begin(), ticketSeqs.end()) == - ticketSeqs.end()); + BEAST_EXPECT(std::adjacent_find(ticketSeqs.begin(), ticketSeqs.end()) == ticketSeqs.end()); BEAST_EXPECT(*ticketSeqs.rbegin() == acctRootFinalSeq - 1); } @@ -262,25 +222,19 @@ class Ticket_test : public beast::unit_test::suite // was deleted. BEAST_EXPECT(tx[sfSequence.jsonName].asUInt() == 0); std::string const account{tx[sfAccount.jsonName].asString()}; - if (!BEAST_EXPECTS( - tx.isMember(sfTicketSequence.jsonName), - "Not metadata for a ticket consuming transaction.")) + if (!BEAST_EXPECTS(tx.isMember(sfTicketSequence.jsonName), "Not metadata for a ticket consuming transaction.")) return; std::uint32_t const ticketSeq{tx[sfTicketSequence.jsonName].asUInt()}; Json::Value const& metadata{env.meta()->getJson(JsonOptions::none)}; - if (!BEAST_EXPECTS( - metadata.isMember(sfTransactionResult.jsonName), - "Metadata is missing TransactionResult.")) + if (!BEAST_EXPECTS(metadata.isMember(sfTransactionResult.jsonName), "Metadata is missing TransactionResult.")) return; { - std::string const transactionResult{ - metadata[sfTransactionResult.jsonName].asString()}; + std::string const transactionResult{metadata[sfTransactionResult.jsonName].asString()}; if (!BEAST_EXPECTS( - transactionResult == "tesSUCCESS" || - transactionResult.compare(0, 3, "tec") == 0, + transactionResult == "tesSUCCESS" || transactionResult.compare(0, 3, "tec") == 0, transactionResult + " neither tesSUCCESS nor tec")) return; } @@ -296,16 +250,13 @@ class Ticket_test : public beast::unit_test::suite if (node.isMember(sfModifiedNode.jsonName)) { Json::Value const& modified{node[sfModifiedNode.jsonName]}; - std::string const entryType = - modified[sfLedgerEntryType.jsonName].asString(); + std::string const entryType = modified[sfLedgerEntryType.jsonName].asString(); if (entryType == "AccountRoot" && - modified[sfFinalFields.jsonName][sfAccount.jsonName] - .asString() == account) + modified[sfFinalFields.jsonName][sfAccount.jsonName].asString() == account) { acctRootFound = true; - auto const& previousFields = - modified[sfPreviousFields.jsonName]; + auto const& previousFields = modified[sfPreviousFields.jsonName]; auto const& finalFields = modified[sfFinalFields.jsonName]; acctRootSeq = finalFields[sfSequence.jsonName].asUInt(); @@ -318,38 +269,29 @@ class Ticket_test : public beast::unit_test::suite "AccountRoot previous is missing TicketCount")) return; - std::uint32_t const prevTicketCount = - previousFields[sfTicketCount.jsonName].asUInt(); + std::uint32_t const prevTicketCount = previousFields[sfTicketCount.jsonName].asUInt(); BEAST_EXPECT(prevTicketCount > 0); if (prevTicketCount == 1) - BEAST_EXPECT( - !finalFields.isMember(sfTicketCount.jsonName)); + BEAST_EXPECT(!finalFields.isMember(sfTicketCount.jsonName)); else BEAST_EXPECT( finalFields.isMember(sfTicketCount.jsonName) && - finalFields[sfTicketCount.jsonName].asUInt() == - prevTicketCount - 1); + finalFields[sfTicketCount.jsonName].asUInt() == prevTicketCount - 1); } } else if (node.isMember(sfDeletedNode.jsonName)) { Json::Value const& deleted{node[sfDeletedNode.jsonName]}; - std::string const entryType{ - deleted[sfLedgerEntryType.jsonName].asString()}; + std::string const entryType{deleted[sfLedgerEntryType.jsonName].asString()}; if (entryType == jss::Ticket) { // Verify the account of the deleted ticket. - BEAST_EXPECT( - deleted[sfFinalFields.jsonName][sfAccount.jsonName] - .asString() == account); + BEAST_EXPECT(deleted[sfFinalFields.jsonName][sfAccount.jsonName].asString() == account); // Verify the deleted ticket has the right TicketSequence. - BEAST_EXPECT( - deleted[sfFinalFields.jsonName] - [sfTicketSequence.jsonName] - .asUInt() == ticketSeq); + BEAST_EXPECT(deleted[sfFinalFields.jsonName][sfTicketSequence.jsonName].asUInt() == ticketSeq); ++ticketsRemoved; } @@ -419,9 +361,7 @@ class Ticket_test : public beast::unit_test::suite Account alice{"alice"}; env.memoize(alice); - env(ticket::create(alice, 1), - json(jss::Sequence, 1), - ter(terNO_ACCOUNT)); + env(ticket::create(alice, 1), json(jss::Sequence, 1), ter(terNO_ACCOUNT)); } { // Exceed the threshold where tickets can no longer be @@ -445,9 +385,7 @@ class Ticket_test : public beast::unit_test::suite env.require(owners(alice, 250), tickets(alice, 250)); // Adding one more ticket will exceed the threshold. - env(ticket::create(alice, 2), - ticket::use(ticketSeq + 1), - ter(tecDIR_FULL)); + env(ticket::create(alice, 2), ticket::use(ticketSeq + 1), ter(tecDIR_FULL)); env.close(); env.require(owners(alice, 249), tickets(alice, 249)); @@ -479,9 +417,7 @@ class Ticket_test : public beast::unit_test::suite // Adding 250 tickets (while consuming one) will exceed the // threshold. - env(ticket::create(alice, 250), - ticket::use(ticketSeq_AB + 0), - ter(tecDIR_FULL)); + env(ticket::create(alice, 250), ticket::use(ticketSeq_AB + 0), ter(tecDIR_FULL)); env.close(); env.require(owners(alice, 1), tickets(alice, 1)); @@ -517,10 +453,7 @@ class Ticket_test : public beast::unit_test::suite env.require(owners(alice, 0), tickets(alice, 0)); // Give alice enough to exactly meet the reserve for one Ticket. - env( - pay(env.master, - alice, - env.current()->fees().accountReserve(1) - env.balance(alice))); + env(pay(env.master, alice, env.current()->fees().accountReserve(1) - env.balance(alice))); env.close(); env(ticket::create(alice, 1)); @@ -530,11 +463,7 @@ class Ticket_test : public beast::unit_test::suite // Give alice not quite enough to make the reserve for a total of // 250 Tickets. - env( - pay(env.master, - alice, - env.current()->fees().accountReserve(250) - drops(1) - - env.balance(alice))); + env(pay(env.master, alice, env.current()->fees().accountReserve(250) - drops(1) - env.balance(alice))); env.close(); // alice doesn't quite have the reserve for a total of 250 @@ -545,10 +474,7 @@ class Ticket_test : public beast::unit_test::suite // Give alice enough so she can make the reserve for all 250 // Tickets. - env(pay( - env.master, - alice, - env.current()->fees().accountReserve(250) - env.balance(alice))); + env(pay(env.master, alice, env.current()->fees().accountReserve(250) - env.balance(alice))); env.close(); std::uint32_t const ticketSeq{env.seq(alice) + 1}; @@ -637,10 +563,7 @@ class Ticket_test : public beast::unit_test::suite checkTicketCreateMeta(env); env.close(); - env(noop(alice), - ticket::use(ticketSeq_G), - json(R"({"AccountTxnID": "0"})"), - ter(temINVALID)); + env(noop(alice), ticket::use(ticketSeq_G), json(R"({"AccountTxnID": "0"})"), ter(temINVALID)); env.close(); env.require(owners(alice, 2), tickets(alice, 1)); } @@ -733,10 +656,8 @@ class Ticket_test : public beast::unit_test::suite TxType txType) { error_code_i txErrCode{rpcSUCCESS}; - using TxPair = std:: - pair, std::shared_ptr>; - std::variant maybeTx = - Transaction::load(txID, env.app(), txErrCode); + using TxPair = std::pair, std::shared_ptr>; + std::variant maybeTx = Transaction::load(txID, env.app(), txErrCode); BEAST_EXPECT(txErrCode == rpcSUCCESS); if (auto txPtr = std::get_if(&maybeTx)) @@ -810,11 +731,9 @@ class Ticket_test : public beast::unit_test::suite Json::Value jr = env.rpc("json", "sign", to_string(tx)); // Verify that "sign" inserted a "Sequence": 0 field. - if (BEAST_EXPECT(jr[jss::result][jss::tx_json].isMember( - sfSequence.jsonName))) + if (BEAST_EXPECT(jr[jss::result][jss::tx_json].isMember(sfSequence.jsonName))) { - BEAST_EXPECT( - jr[jss::result][jss::tx_json][sfSequence.jsonName] == 0); + BEAST_EXPECT(jr[jss::result][jss::tx_json][sfSequence.jsonName] == 0); } // "sign" should not have consumed any of alice's tickets. @@ -845,11 +764,9 @@ class Ticket_test : public beast::unit_test::suite Json::Value jr = env.rpc("json", "submit", to_string(tx)); // Verify that "submit" inserted a "Sequence": 0 field. - if (BEAST_EXPECT(jr[jss::result][jss::tx_json].isMember( - sfSequence.jsonName))) + if (BEAST_EXPECT(jr[jss::result][jss::tx_json].isMember(sfSequence.jsonName))) { - BEAST_EXPECT( - jr[jss::result][jss::tx_json][sfSequence.jsonName] == 0); + BEAST_EXPECT(jr[jss::result][jss::tx_json][sfSequence.jsonName] == 0); } // "submit" should have consumed the last of alice's tickets. @@ -882,10 +799,7 @@ class Ticket_test : public beast::unit_test::suite // Create a transaction that includes both a ticket and a non-zero // sequence number. The transaction fails with temSEQ_AND_TICKET. - env(noop(alice), - ticket::use(ticketSeq), - seq(env.seq(alice)), - ter(temSEQ_AND_TICKET)); + env(noop(alice), ticket::use(ticketSeq), seq(env.seq(alice)), ter(temSEQ_AND_TICKET)); env.close(); // Verify that the transaction failed by looking at alice's diff --git a/src/test/app/Transaction_ordering_test.cpp b/src/test/app/Transaction_ordering_test.cpp index 81c9ae196c..f7d431fc90 100644 --- a/src/test/app/Transaction_ordering_test.cpp +++ b/src/test/app/Transaction_ordering_test.cpp @@ -20,8 +20,7 @@ struct Transaction_ordering_test : public beast::unit_test::suite auto const aliceSequence = env.seq(alice); auto const tx1 = env.jt(noop(alice), seq(aliceSequence)); - auto const tx2 = - env.jt(noop(alice), seq(aliceSequence + 1), last_ledger_seq(7)); + auto const tx2 = env.jt(noop(alice), seq(aliceSequence + 1), last_ledger_seq(7)); env(tx1); env.close(); @@ -33,16 +32,12 @@ struct Transaction_ordering_test : public beast::unit_test::suite env.close(); { - auto const result = - env.rpc("tx", to_string(tx1.stx->getTransactionID())); - BEAST_EXPECT( - result["result"]["meta"]["TransactionResult"] == "tesSUCCESS"); + auto const result = env.rpc("tx", to_string(tx1.stx->getTransactionID())); + BEAST_EXPECT(result["result"]["meta"]["TransactionResult"] == "tesSUCCESS"); } { - auto const result = - env.rpc("tx", to_string(tx2.stx->getTransactionID())); - BEAST_EXPECT( - result["result"]["meta"]["TransactionResult"] == "tesSUCCESS"); + auto const result = env.rpc("tx", to_string(tx2.stx->getTransactionID())); + BEAST_EXPECT(result["result"]["meta"]["TransactionResult"] == "tesSUCCESS"); } } @@ -64,8 +59,7 @@ struct Transaction_ordering_test : public beast::unit_test::suite auto const aliceSequence = env.seq(alice); auto const tx1 = env.jt(noop(alice), seq(aliceSequence)); - auto const tx2 = - env.jt(noop(alice), seq(aliceSequence + 1), last_ledger_seq(7)); + auto const tx2 = env.jt(noop(alice), seq(aliceSequence + 1), last_ledger_seq(7)); env(tx2, ter(terPRE_SEQ)); BEAST_EXPECT(env.seq(alice) == aliceSequence); @@ -76,16 +70,12 @@ struct Transaction_ordering_test : public beast::unit_test::suite env.close(); { - auto const result = - env.rpc("tx", to_string(tx1.stx->getTransactionID())); - BEAST_EXPECT( - result["result"]["meta"]["TransactionResult"] == "tesSUCCESS"); + auto const result = env.rpc("tx", to_string(tx1.stx->getTransactionID())); + BEAST_EXPECT(result["result"]["meta"]["TransactionResult"] == "tesSUCCESS"); } { - auto const result = - env.rpc("tx", to_string(tx2.stx->getTransactionID())); - BEAST_EXPECT( - result["result"]["meta"]["TransactionResult"] == "tesSUCCESS"); + auto const result = env.rpc("tx", to_string(tx2.stx->getTransactionID())); + BEAST_EXPECT(result["result"]["meta"]["TransactionResult"] == "tesSUCCESS"); } } @@ -109,8 +99,7 @@ struct Transaction_ordering_test : public beast::unit_test::suite std::vector tx; for (auto i = 0; i < 5; ++i) { - tx.emplace_back(env.jt( - noop(alice), seq(aliceSequence + i), last_ledger_seq(7))); + tx.emplace_back(env.jt(noop(alice), seq(aliceSequence + i), last_ledger_seq(7))); } for (auto i = 1; i < 5; ++i) @@ -127,10 +116,8 @@ struct Transaction_ordering_test : public beast::unit_test::suite for (auto i = 0; i < 5; ++i) { - auto const result = - env.rpc("tx", to_string(tx[i].stx->getTransactionID())); - BEAST_EXPECT( - result["result"]["meta"]["TransactionResult"] == "tesSUCCESS"); + auto const result = env.rpc("tx", to_string(tx[i].stx->getTransactionID())); + BEAST_EXPECT(result["result"]["meta"]["TransactionResult"] == "tesSUCCESS"); } } diff --git a/src/test/app/TrustAndBalance_test.cpp b/src/test/app/TrustAndBalance_test.cpp index 25c22b823b..aa06ccbdf1 100644 --- a/src/test/app/TrustAndBalance_test.cpp +++ b/src/test/app/TrustAndBalance_test.cpp @@ -57,36 +57,24 @@ class TrustAndBalance_test : public beast::unit_test::suite jrr = ledgerEntryState(env, gw, alice, "USD"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "0"); - BEAST_EXPECT( - jrr[jss::node][sfHighLimit.fieldName][jss::value] == "800"); - BEAST_EXPECT( - jrr[jss::node][sfHighLimit.fieldName][jss::issuer] == - alice.human()); - BEAST_EXPECT( - jrr[jss::node][sfHighLimit.fieldName][jss::currency] == "USD"); + BEAST_EXPECT(jrr[jss::node][sfHighLimit.fieldName][jss::value] == "800"); + BEAST_EXPECT(jrr[jss::node][sfHighLimit.fieldName][jss::issuer] == alice.human()); + BEAST_EXPECT(jrr[jss::node][sfHighLimit.fieldName][jss::currency] == "USD"); BEAST_EXPECT(jrr[jss::node][sfLowLimit.fieldName][jss::value] == "0"); - BEAST_EXPECT( - jrr[jss::node][sfLowLimit.fieldName][jss::issuer] == gw.human()); - BEAST_EXPECT( - jrr[jss::node][sfLowLimit.fieldName][jss::currency] == "USD"); + BEAST_EXPECT(jrr[jss::node][sfLowLimit.fieldName][jss::issuer] == gw.human()); + BEAST_EXPECT(jrr[jss::node][sfLowLimit.fieldName][jss::currency] == "USD"); // modify the credit limit env(trust(alice, gw["USD"](700))); jrr = ledgerEntryState(env, gw, alice, "USD"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "0"); - BEAST_EXPECT( - jrr[jss::node][sfHighLimit.fieldName][jss::value] == "700"); - BEAST_EXPECT( - jrr[jss::node][sfHighLimit.fieldName][jss::issuer] == - alice.human()); - BEAST_EXPECT( - jrr[jss::node][sfHighLimit.fieldName][jss::currency] == "USD"); + BEAST_EXPECT(jrr[jss::node][sfHighLimit.fieldName][jss::value] == "700"); + BEAST_EXPECT(jrr[jss::node][sfHighLimit.fieldName][jss::issuer] == alice.human()); + BEAST_EXPECT(jrr[jss::node][sfHighLimit.fieldName][jss::currency] == "USD"); BEAST_EXPECT(jrr[jss::node][sfLowLimit.fieldName][jss::value] == "0"); - BEAST_EXPECT( - jrr[jss::node][sfLowLimit.fieldName][jss::issuer] == gw.human()); - BEAST_EXPECT( - jrr[jss::node][sfLowLimit.fieldName][jss::currency] == "USD"); + BEAST_EXPECT(jrr[jss::node][sfLowLimit.fieldName][jss::issuer] == gw.human()); + BEAST_EXPECT(jrr[jss::node][sfLowLimit.fieldName][jss::currency] == "USD"); // set negative limit - expect failure env(trust(alice, gw["USD"](-1)), ter(temBAD_LIMIT)); @@ -109,17 +97,12 @@ class TrustAndBalance_test : public beast::unit_test::suite // check the ledger state for the trust line jrr = ledgerEntryState(env, alice, bob, "USD"); BEAST_EXPECT(jrr[jss::node][sfBalance.fieldName][jss::value] == "0"); - BEAST_EXPECT( - jrr[jss::node][sfHighLimit.fieldName][jss::value] == "500"); - BEAST_EXPECT( - jrr[jss::node][sfHighLimit.fieldName][jss::issuer] == bob.human()); - BEAST_EXPECT( - jrr[jss::node][sfHighLimit.fieldName][jss::currency] == "USD"); + BEAST_EXPECT(jrr[jss::node][sfHighLimit.fieldName][jss::value] == "500"); + BEAST_EXPECT(jrr[jss::node][sfHighLimit.fieldName][jss::issuer] == bob.human()); + BEAST_EXPECT(jrr[jss::node][sfHighLimit.fieldName][jss::currency] == "USD"); BEAST_EXPECT(jrr[jss::node][sfLowLimit.fieldName][jss::value] == "600"); - BEAST_EXPECT( - jrr[jss::node][sfLowLimit.fieldName][jss::issuer] == alice.human()); - BEAST_EXPECT( - jrr[jss::node][sfLowLimit.fieldName][jss::currency] == "USD"); + BEAST_EXPECT(jrr[jss::node][sfLowLimit.fieldName][jss::issuer] == alice.human()); + BEAST_EXPECT(jrr[jss::node][sfLowLimit.fieldName][jss::currency] == "USD"); } void @@ -167,8 +150,7 @@ class TrustAndBalance_test : public beast::unit_test::suite testWithTransferFee(bool subscribe, bool with_rate, FeatureBitset features) { testcase( - std::string("Direct Payment: ") + - (with_rate ? "With " : "Without ") + " Xfer Fee, " + + std::string("Direct Payment: ") + (with_rate ? "With " : "Without ") + " Xfer Fee, " + (subscribe ? "With " : "Without ") + " Subscribe"); using namespace test::jtx; @@ -233,12 +215,9 @@ class TrustAndBalance_test : public beast::unit_test::suite auto const& t = jval[jss::transaction]; return t[jss::TransactionType] == jss::Payment; })); - BEAST_EXPECT(wsc->findMsg(5s, [](auto const& jval) { - return jval[jss::type] == "ledgerClosed"; - })); + BEAST_EXPECT(wsc->findMsg(5s, [](auto const& jval) { return jval[jss::type] == "ledgerClosed"; })); - BEAST_EXPECT( - wsc->invoke("unsubscribe", jv)[jss::status] == "success"); + BEAST_EXPECT(wsc->invoke("unsubscribe", jv)[jss::status] == "success"); } } @@ -283,9 +262,7 @@ class TrustAndBalance_test : public beast::unit_test::suite // alice sends bob issues to bob with a max spend in alice issues. // expect fail since gw is not involved - env(pay(alice, bob, bob["AUD"](1)), - sendmax(alice["AUD"](1.1)), - ter(tecPATH_DRY)); + env(pay(alice, bob, bob["AUD"](1)), sendmax(alice["AUD"](1.1)), ter(tecPATH_DRY)); env.require(balance(alice, gw["AUD"](1.1))); env.require(balance(bob, gw["AUD"](3))); @@ -335,9 +312,7 @@ class TrustAndBalance_test : public beast::unit_test::suite void testIndirectMultiPath(bool with_rate, FeatureBitset features) { - testcase( - std::string("Indirect Payment, Multi Path, ") + - (with_rate ? "With " : "Without ") + " Xfer Fee, "); + testcase(std::string("Indirect Payment, Multi Path, ") + (with_rate ? "With " : "Without ") + " Xfer Fee, "); using namespace test::jtx; Env env{*this, features}; @@ -370,20 +345,12 @@ class TrustAndBalance_test : public beast::unit_test::suite test::jtx::path(bob), test::jtx::path(carol)); else - env(pay(alice, amazon, gw["USD"](150)), - test::jtx::path(bob), - test::jtx::path(carol)); + env(pay(alice, amazon, gw["USD"](150)), test::jtx::path(bob), test::jtx::path(carol)); if (with_rate) { - env.require(balance( - alice, - STAmount( - carol["USD"].issue(), - 6500000000000000ull, - -14, - true, - STAmount::unchecked{}))); + env.require( + balance(alice, STAmount(carol["USD"].issue(), 6500000000000000ull, -14, true, STAmount::unchecked{}))); env.require(balance(carol, gw["USD"](35))); } else @@ -416,24 +383,20 @@ class TrustAndBalance_test : public beast::unit_test::suite jvs[jss::streams].append("transactions"); BEAST_EXPECT(wsc->invoke("subscribe", jvs)[jss::status] == "success"); - char const* invoiceid = - "243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89"; + char const* invoiceId = "243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89"; Json::Value jv; - auto tx = env.jt( - pay(env.master, alice, XRP(10000)), - json(sfInvoiceID.fieldName, invoiceid)); + auto tx = env.jt(pay(env.master, alice, XRP(10000)), json(sfInvoiceID.fieldName, invoiceId)); jv[jss::tx_blob] = strHex(tx.stx->getSerializer().slice()); auto jrr = wsc->invoke("submit", jv)[jss::result]; BEAST_EXPECT(jrr[jss::status] == "success"); - BEAST_EXPECT(jrr[jss::tx_json][sfInvoiceID.fieldName] == invoiceid); + BEAST_EXPECT(jrr[jss::tx_json][sfInvoiceID.fieldName] == invoiceId); env.close(); using namespace std::chrono_literals; - BEAST_EXPECT(wsc->findMsg(2s, [invoiceid](auto const& jval) { + BEAST_EXPECT(wsc->findMsg(2s, [invoiceId](auto const& jval) { auto const& t = jval[jss::transaction]; - return t[jss::TransactionType] == jss::Payment && - t[sfInvoiceID.fieldName] == invoiceid; + return t[jss::TransactionType] == jss::Payment && t[sfInvoiceID.fieldName] == invoiceId; })); BEAST_EXPECT(wsc->invoke("unsubscribe", jv)[jss::status] == "success"); diff --git a/src/test/app/TxQ_test.cpp b/src/test/app/TxQ_test.cpp index 9489bb7f04..13feceb74e 100644 --- a/src/test/app/TxQ_test.cpp +++ b/src/test/app/TxQ_test.cpp @@ -68,8 +68,7 @@ class TxQPosNegFlows_test : public beast::unit_test::suite auto calcMedFeeLevel(FeeLevel64 const feeLevel1, FeeLevel64 const feeLevel2) { - FeeLevel64 const expectedMedFeeLevel = - (feeLevel1 + feeLevel2 + FeeLevel64{1}) / 2; + FeeLevel64 const expectedMedFeeLevel = (feeLevel1 + feeLevel2 + FeeLevel64{1}) / 2; return std::max(expectedMedFeeLevel, minEscalationFeeLevel).fee(); } @@ -331,13 +330,7 @@ public: env(noop(env.master), fee(baseFee * 2), queued); ++metrics.txCount; - checkMetrics( - *this, - env, - metrics.txCount, - metrics.txQMaxSize, - metrics.txPerLedger + 1, - metrics.txPerLedger); + checkMetrics(*this, env, metrics.txCount, metrics.txQMaxSize, metrics.txPerLedger + 1, metrics.txPerLedger); } void @@ -400,10 +393,7 @@ public: env(noop(alice), ticket::use(tkt1 + 10), fee(baseFee * 2.0), queued); env(noop(alice), ticket::use(tkt1 + 11), fee(baseFee * 2.1), queued); env(noop(alice), ticket::use(tkt1 + 12), fee(baseFee * 2.2), queued); - env(noop(alice), - ticket::use(tkt1 + 13), - fee(baseFee * 2.3), - ter(telCAN_NOT_QUEUE_FULL)); + env(noop(alice), ticket::use(tkt1 + 13), fee(baseFee * 2.3), ter(telCAN_NOT_QUEUE_FULL)); checkMetrics(*this, env, 8, 8, 5, 4, expectedMinFeeLevel); // Check which of the queued transactions got into the ledger by @@ -509,22 +499,10 @@ public: env(noop(alice), ticket::use(tkt1 + 15), fee(baseFee * 2.7), queued); env(noop(alice), ticket::use(tkt250 - 2), fee(baseFee * 2.6), queued); env(noop(alice), ticket::use(tkt1 + 16), fee(baseFee * 2.5), queued); - env(noop(alice), - ticket::use(tkt250 - 3), - fee(baseFee * 2.4), - ter(telCAN_NOT_QUEUE_FULL)); - env(noop(alice), - ticket::use(tkt1 + 17), - fee(baseFee * 2.3), - ter(telCAN_NOT_QUEUE_FULL)); - env(noop(alice), - ticket::use(tkt250 - 4), - fee(baseFee * 2.2), - ter(telCAN_NOT_QUEUE_FULL)); - env(noop(alice), - ticket::use(tkt1 + 18), - fee(baseFee * 2.1), - ter(telCAN_NOT_QUEUE_FULL)); + env(noop(alice), ticket::use(tkt250 - 3), fee(baseFee * 2.4), ter(telCAN_NOT_QUEUE_FULL)); + env(noop(alice), ticket::use(tkt1 + 17), fee(baseFee * 2.3), ter(telCAN_NOT_QUEUE_FULL)); + env(noop(alice), ticket::use(tkt250 - 4), fee(baseFee * 2.2), ter(telCAN_NOT_QUEUE_FULL)); + env(noop(alice), ticket::use(tkt1 + 18), fee(baseFee * 2.1), ter(telCAN_NOT_QUEUE_FULL)); checkMetrics(*this, env, 10, 12, 7, 6); @@ -565,24 +543,12 @@ public: // let's try replacing them. // The lowest fee ticket is baseFee * 2.1, trying to replace it - env(noop(alice), - ticket::use(tkt1 + 18), - fee(baseFee * 2.1 * 1.25 - 1), - ter(telCAN_NOT_QUEUE_FEE)); - env(noop(alice), - ticket::use(tkt1 + 18), - fee(baseFee * 2.1 * 1.25 + 1), - queued); + env(noop(alice), ticket::use(tkt1 + 18), fee(baseFee * 2.1 * 1.25 - 1), ter(telCAN_NOT_QUEUE_FEE)); + env(noop(alice), ticket::use(tkt1 + 18), fee(baseFee * 2.1 * 1.25 + 1), queued); // New lowest fee ticket is baseFee * 2.2 - env(noop(alice), - ticket::use(tkt250 - 4), - fee(baseFee * 2.2 * 1.25 - 1), - ter(telCAN_NOT_QUEUE_FEE)); - env(noop(alice), - ticket::use(tkt250 - 4), - fee(baseFee * 2.2 * 1.25 + 1), - queued); + env(noop(alice), ticket::use(tkt250 - 4), fee(baseFee * 2.2 * 1.25 - 1), ter(telCAN_NOT_QUEUE_FEE)); + env(noop(alice), ticket::use(tkt250 - 4), fee(baseFee * 2.2 * 1.25 + 1), queued); env.close(); env.require(owners(alice, 227), tickets(alice, 227)); @@ -658,10 +624,7 @@ public: checkMetrics(*this, env, 0, std::nullopt, 3, 2); // Future transaction for Alice - fails - env(noop(alice), - fee(openLedgerCost(env)), - seq(env.seq(alice) + 1), - ter(terPRE_SEQ)); + env(noop(alice), fee(openLedgerCost(env)), seq(env.seq(alice) + 1), ter(terPRE_SEQ)); checkMetrics(*this, env, 0, std::nullopt, 3, 2); // Current transaction for Alice: held @@ -747,16 +710,12 @@ public: auto aliceStat = txQ.getAccountTxs(alice.id()); BEAST_EXPECT(aliceStat.size() == 1); BEAST_EXPECT(aliceStat.begin()->feeLevel == baseFeeLevel); - BEAST_EXPECT( - aliceStat.begin()->lastValid && - *aliceStat.begin()->lastValid == 8); + BEAST_EXPECT(aliceStat.begin()->lastValid && *aliceStat.begin()->lastValid == 8); BEAST_EXPECT(!aliceStat.begin()->consequences.isBlocker()); auto bobStat = txQ.getAccountTxs(bob.id()); BEAST_EXPECT(bobStat.size() == 1); - BEAST_EXPECT( - bobStat.begin()->feeLevel == - FeeLevel64{baseFeeLevel.fee() * largeFeeMultiplier}); + BEAST_EXPECT(bobStat.begin()->feeLevel == FeeLevel64{baseFeeLevel.fee() * largeFeeMultiplier}); BEAST_EXPECT(!bobStat.begin()->lastValid); BEAST_EXPECT(!bobStat.begin()->consequences.isBlocker()); @@ -977,10 +936,8 @@ public: Env::ParsedResult parsed; - env.app().openLedger().modify([&](OpenView& view, - beast::Journal j) { - auto const result = - xrpl::apply(env.app(), view, *jt.stx, tapNONE, env.journal); + env.app().openLedger().modify([&](OpenView& view, beast::Journal j) { + auto const result = xrpl::apply(env.app(), view, *jt.stx, tapNONE, env.journal); parsed.ter = result.ter; return result.applied; }); @@ -1003,8 +960,7 @@ public: Env env( *this, makeConfig( - {{"minimum_txn_in_ledger_standalone", "3"}}, - {{"account_reserve", "200"}, {"owner_reserve", "50"}})); + {{"minimum_txn_in_ledger_standalone", "3"}}, {{"account_reserve", "200"}, {"owner_reserve", "50"}})); auto alice = Account("alice"); auto bob = Account("bob"); @@ -1078,11 +1034,7 @@ public: auto lastLedgerSeq = env.current()->header().seq + 2; for (auto i = 0; i < 7; i++) { - env(noop(alice), - seq(aliceSeq), - json(jss::LastLedgerSequence, lastLedgerSeq + i), - fee(--aliceFee), - queued); + env(noop(alice), seq(aliceSeq), json(jss::LastLedgerSequence, lastLedgerSeq + i), fee(--aliceFee), queued); ++aliceSeq; } checkMetrics(*this, env, 8, 8, 5, 4, 513); @@ -1096,12 +1048,10 @@ public: for (auto const& tx : aliceStat) { BEAST_EXPECT(tx.seqProxy.isSeq() && tx.seqProxy.value() == seq); - BEAST_EXPECT( - tx.feeLevel == toFeeLevel(XRPAmount(--aliceFee), baseFee)); + BEAST_EXPECT(tx.feeLevel == toFeeLevel(XRPAmount(--aliceFee), baseFee)); BEAST_EXPECT(tx.lastValid); BEAST_EXPECT( - (tx.consequences.fee() == drops(aliceFee) && - tx.consequences.potentialSpend() == drops(0) && + (tx.consequences.fee() == drops(aliceFee) && tx.consequences.potentialSpend() == drops(0) && !tx.consequences.isBlocker()) || tx.seqProxy.value() == env.seq(alice) + 6); ++seq; @@ -1138,20 +1088,14 @@ public: // Alice wants this tx more than the dropped tx, // so resubmits with higher fee, but the queue // is full, and her account is the cheapest. - env(noop(alice), - seq(aliceSeq - 1), - fee(aliceFee), - ter(telCAN_NOT_QUEUE_FULL)); + env(noop(alice), seq(aliceSeq - 1), fee(aliceFee), ter(telCAN_NOT_QUEUE_FULL)); checkMetrics(*this, env, 8, 8, 5, 4, 538); // Try to replace a middle item in the queue // without enough fee. aliceSeq = env.seq(alice) + 2; aliceFee = 29; - env(noop(alice), - seq(aliceSeq), - fee(aliceFee), - ter(telCAN_NOT_QUEUE_FEE)); + env(noop(alice), seq(aliceSeq), fee(aliceFee), ter(telCAN_NOT_QUEUE_FEE)); checkMetrics(*this, env, 8, 8, 5, 4, 538); // Replace a middle item from the queue successfully @@ -1171,12 +1115,8 @@ public: // bankrupt Alice. Fails, because an account can't have // more than the minimum reserve in flight before the // last queued transaction - aliceFee = - env.le(alice)->getFieldAmount(sfBalance).xrp().drops() - (62); - env(noop(alice), - seq(aliceSeq), - fee(aliceFee), - ter(telCAN_NOT_QUEUE_BALANCE)); + aliceFee = env.le(alice)->getFieldAmount(sfBalance).xrp().drops() - (62); + env(noop(alice), seq(aliceSeq), fee(aliceFee), ter(telCAN_NOT_QUEUE_BALANCE)); checkMetrics(*this, env, 4, 10, 6, 5); // Try to spend more than Alice can afford with all the other txs. @@ -1195,10 +1135,7 @@ public: // the fee is checked against the balance aliceFee /= 5; ++aliceSeq; - env(noop(alice), - seq(aliceSeq), - fee(aliceFee), - ter(telCAN_NOT_QUEUE_BALANCE)); + env(noop(alice), seq(aliceSeq), fee(aliceFee), ter(telCAN_NOT_QUEUE_BALANCE)); checkMetrics(*this, env, 4, 10, 6, 5); env.close(); @@ -1231,12 +1168,8 @@ public: // Try to replace a middle item in the queue // with enough fee to bankrupt bob and make the // later transactions unable to pay their fees - std::int64_t bobFee = - env.le(bob)->getFieldAmount(sfBalance).xrp().drops() - (9 * 10 - 1); - env(noop(bob), - seq(bobSeq + 5), - fee(bobFee), - ter(telCAN_NOT_QUEUE_BALANCE)); + std::int64_t bobFee = env.le(bob)->getFieldAmount(sfBalance).xrp().drops() - (9 * 10 - 1); + env(noop(bob), seq(bobSeq + 5), fee(bobFee), ter(telCAN_NOT_QUEUE_BALANCE)); checkMetrics(*this, env, 10, 12, 7, 6); // Attempt to replace a middle item in the queue with enough fee @@ -1245,12 +1178,8 @@ public: // // The attempt fails because the sum of bob's fees now exceeds the // (artificially lowered to 200 drops) account reserve. - bobFee = - env.le(bob)->getFieldAmount(sfBalance).xrp().drops() - (9 * 10); - env(noop(bob), - seq(bobSeq + 5), - fee(bobFee), - ter(telCAN_NOT_QUEUE_BALANCE)); + bobFee = env.le(bob)->getFieldAmount(sfBalance).xrp().drops() - (9 * 10); + env(noop(bob), seq(bobSeq + 5), fee(bobFee), ter(telCAN_NOT_QUEUE_BALANCE)); checkMetrics(*this, env, 10, 12, 7, 6); // Close the ledger and verify that the queued transactions succeed @@ -1361,44 +1290,29 @@ public: // This next test should remain unchanged regardless of // transaction ordering BEAST_EXPECT( - aliceSeq + bobSeq + charlieSeq + dariaSeq + elmoSeq + fredSeq + - gwenSeq + hankSeq + 6 == - env.seq(alice) + env.seq(bob) + env.seq(charlie) + env.seq(daria) + - env.seq(elmo) + env.seq(fred) + env.seq(gwen) + env.seq(hank)); + aliceSeq + bobSeq + charlieSeq + dariaSeq + elmoSeq + fredSeq + gwenSeq + hankSeq + 6 == + env.seq(alice) + env.seq(bob) + env.seq(charlie) + env.seq(daria) + env.seq(elmo) + env.seq(fred) + + env.seq(gwen) + env.seq(hank)); // These tests may change if TxQ ordering is changed using namespace std::string_literals; BEAST_EXPECTS( - aliceSeq == env.seq(alice), - "alice: "s + std::to_string(aliceSeq) + ", " + - std::to_string(env.seq(alice))); + aliceSeq == env.seq(alice), "alice: "s + std::to_string(aliceSeq) + ", " + std::to_string(env.seq(alice))); BEAST_EXPECTS( - bobSeq + 1 == env.seq(bob), - "bob: "s + std::to_string(bobSeq) + ", " + - std::to_string(env.seq(bob))); + bobSeq + 1 == env.seq(bob), "bob: "s + std::to_string(bobSeq) + ", " + std::to_string(env.seq(bob))); BEAST_EXPECTS( charlieSeq + 2 == env.seq(charlie), - "charlie: "s + std::to_string(charlieSeq) + ", " + - std::to_string(env.seq(charlie))); + "charlie: "s + std::to_string(charlieSeq) + ", " + std::to_string(env.seq(charlie))); BEAST_EXPECTS( dariaSeq + 1 == env.seq(daria), - "daria: "s + std::to_string(dariaSeq) + ", " + - std::to_string(env.seq(daria))); + "daria: "s + std::to_string(dariaSeq) + ", " + std::to_string(env.seq(daria))); BEAST_EXPECTS( - elmoSeq + 1 == env.seq(elmo), - "elmo: "s + std::to_string(elmoSeq) + ", " + - std::to_string(env.seq(elmo))); + elmoSeq + 1 == env.seq(elmo), "elmo: "s + std::to_string(elmoSeq) + ", " + std::to_string(env.seq(elmo))); BEAST_EXPECTS( - fredSeq == env.seq(fred), - "fred: "s + std::to_string(fredSeq) + ", " + - std::to_string(env.seq(fred))); + fredSeq == env.seq(fred), "fred: "s + std::to_string(fredSeq) + ", " + std::to_string(env.seq(fred))); BEAST_EXPECTS( - gwenSeq == env.seq(gwen), - "gwen: "s + std::to_string(gwenSeq) + ", " + - std::to_string(env.seq(gwen))); + gwenSeq == env.seq(gwen), "gwen: "s + std::to_string(gwenSeq) + ", " + std::to_string(env.seq(gwen))); BEAST_EXPECTS( - hankSeq + 1 == env.seq(hank), - "hank: "s + std::to_string(hankSeq) + ", " + - std::to_string(env.seq(hank))); + hankSeq + 1 == env.seq(hank), "hank: "s + std::to_string(hankSeq) + ", " + std::to_string(env.seq(hank))); // Which sequences get incremented may change if TxQ ordering is // changed @@ -1424,19 +1338,10 @@ public: BEAST_EXPECT(qTxCount1.size() <= 3); // Fill up the queue again - env(noop(alice), - seq(aliceSeq + qTxCount1[alice.id()]++), - fee(15), - queued); + env(noop(alice), seq(aliceSeq + qTxCount1[alice.id()]++), fee(15), queued); env(noop(bob), seq(bobSeq + qTxCount1[bob.id()]++), fee(15), queued); - env(noop(charlie), - seq(charlieSeq + qTxCount1[charlie.id()]++), - fee(15), - queued); - env(noop(daria), - seq(dariaSeq + qTxCount1[daria.id()]++), - fee(15), - queued); + env(noop(charlie), seq(charlieSeq + qTxCount1[charlie.id()]++), fee(15), queued); + env(noop(daria), seq(dariaSeq + qTxCount1[daria.id()]++), fee(15), queued); env(noop(elmo), seq(elmoSeq + qTxCount1[elmo.id()]++), fee(15), queued); env(noop(fred), seq(fredSeq + qTxCount1[fred.id()]++), fee(15), queued); env(noop(gwen), seq(gwenSeq + qTxCount1[gwen.id()]++), fee(15), queued); @@ -1447,10 +1352,7 @@ public: // Add another transaction, with a higher fee, // Not high enough to get into the ledger, but high // enough to get into the queue (and kick somebody out) - env(noop(alice), - fee(100), - seq(aliceSeq + qTxCount1[alice.id()]++), - queued); + env(noop(alice), fee(100), seq(aliceSeq + qTxCount1[alice.id()]++), queued); checkMetrics(*this, env, 10, 10, 6, 5, minFeeLevel); @@ -1467,50 +1369,34 @@ public: // This next test should remain unchanged regardless of // transaction ordering BEAST_EXPECT( - aliceSeq + bobSeq + charlieSeq + dariaSeq + elmoSeq + fredSeq + - gwenSeq + hankSeq + 7 == - env.seq(alice) + env.seq(bob) + env.seq(charlie) + env.seq(daria) + - env.seq(elmo) + env.seq(fred) + env.seq(gwen) + env.seq(hank)); + aliceSeq + bobSeq + charlieSeq + dariaSeq + elmoSeq + fredSeq + gwenSeq + hankSeq + 7 == + env.seq(alice) + env.seq(bob) + env.seq(charlie) + env.seq(daria) + env.seq(elmo) + env.seq(fred) + + env.seq(gwen) + env.seq(hank)); // These tests may change if TxQ ordering is changed BEAST_EXPECTS( - aliceSeq + qTxCount1[alice.id()] - qTxCount2[alice.id()] == - env.seq(alice), - "alice: "s + std::to_string(aliceSeq) + ", " + - std::to_string(env.seq(alice))); + aliceSeq + qTxCount1[alice.id()] - qTxCount2[alice.id()] == env.seq(alice), + "alice: "s + std::to_string(aliceSeq) + ", " + std::to_string(env.seq(alice))); BEAST_EXPECTS( bobSeq + qTxCount1[bob.id()] - qTxCount2[bob.id()] == env.seq(bob), - "bob: "s + std::to_string(bobSeq) + ", " + - std::to_string(env.seq(bob))); + "bob: "s + std::to_string(bobSeq) + ", " + std::to_string(env.seq(bob))); BEAST_EXPECTS( - charlieSeq + qTxCount1[charlie.id()] - qTxCount2[charlie.id()] == - env.seq(charlie), - "charlie: "s + std::to_string(charlieSeq) + ", " + - std::to_string(env.seq(charlie))); + charlieSeq + qTxCount1[charlie.id()] - qTxCount2[charlie.id()] == env.seq(charlie), + "charlie: "s + std::to_string(charlieSeq) + ", " + std::to_string(env.seq(charlie))); BEAST_EXPECTS( - dariaSeq + qTxCount1[daria.id()] - qTxCount2[daria.id()] == - env.seq(daria), - "daria: "s + std::to_string(dariaSeq) + ", " + - std::to_string(env.seq(daria))); + dariaSeq + qTxCount1[daria.id()] - qTxCount2[daria.id()] == env.seq(daria), + "daria: "s + std::to_string(dariaSeq) + ", " + std::to_string(env.seq(daria))); BEAST_EXPECTS( - elmoSeq + qTxCount1[elmo.id()] - qTxCount2[elmo.id()] == - env.seq(elmo), - "elmo: "s + std::to_string(elmoSeq) + ", " + - std::to_string(env.seq(elmo))); + elmoSeq + qTxCount1[elmo.id()] - qTxCount2[elmo.id()] == env.seq(elmo), + "elmo: "s + std::to_string(elmoSeq) + ", " + std::to_string(env.seq(elmo))); BEAST_EXPECTS( - fredSeq + qTxCount1[fred.id()] - qTxCount2[fred.id()] == - env.seq(fred), - "fred: "s + std::to_string(fredSeq) + ", " + - std::to_string(env.seq(fred))); + fredSeq + qTxCount1[fred.id()] - qTxCount2[fred.id()] == env.seq(fred), + "fred: "s + std::to_string(fredSeq) + ", " + std::to_string(env.seq(fred))); BEAST_EXPECTS( - gwenSeq + qTxCount1[gwen.id()] - qTxCount2[gwen.id()] == - env.seq(gwen), - "gwen: "s + std::to_string(gwenSeq) + ", " + - std::to_string(env.seq(gwen))); + gwenSeq + qTxCount1[gwen.id()] - qTxCount2[gwen.id()] == env.seq(gwen), + "gwen: "s + std::to_string(gwenSeq) + ", " + std::to_string(env.seq(gwen))); BEAST_EXPECTS( - hankSeq + qTxCount1[hank.id()] - qTxCount2[hank.id()] == - env.seq(hank), - "hank: "s + std::to_string(hankSeq) + ", " + - std::to_string(env.seq(hank))); + hankSeq + qTxCount1[hank.id()] - qTxCount2[hank.id()] == env.seq(hank), + "hank: "s + std::to_string(hankSeq) + ", " + std::to_string(env.seq(hank))); } void @@ -1534,9 +1420,7 @@ public: // Immediately after the fset, the sfAccountTxnID field // is still uninitialized, so preflight succeeds here, // and this txn fails because it can't be stored in the queue. - env(noop(alice), - json(R"({"AccountTxnID": "0"})"), - ter(telCAN_NOT_QUEUE)); + env(noop(alice), json(R"({"AccountTxnID": "0"})"), ter(telCAN_NOT_QUEUE)); checkMetrics(*this, env, 0, std::nullopt, 2, 1); env.close(); @@ -1583,10 +1467,8 @@ public: // calculate median fee level. if (i == 4) { - double const feeMultiplier = - static_cast(cost.drops()) / baseFee; - medFeeLevel = FeeLevel64{static_cast( - feeMultiplier * baseFeeLevel.fee())}; + double const feeMultiplier = static_cast(cost.drops()) / baseFee; + medFeeLevel = FeeLevel64{static_cast(feeMultiplier * baseFeeLevel.fee())}; } env(noop(alice), fee(cost)); @@ -1675,8 +1557,7 @@ public: Env env( *this, makeConfig( - {{"minimum_txn_in_ledger_standalone", "3"}}, - {{"account_reserve", "200"}, {"owner_reserve", "50"}})); + {{"minimum_txn_in_ledger_standalone", "3"}}, {{"account_reserve", "200"}, {"owner_reserve", "50"}})); auto alice = Account("alice"); auto bob = Account("bob"); @@ -1716,16 +1597,12 @@ public: // up to Alice's reserve. env(offer(bob, drops(5000), USD(5000)), fee(openLedgerCost(env)), - require( - balance(alice, drops(250)), owners(alice, 1), lines(alice, 1))); + require(balance(alice, drops(250)), owners(alice, 1), lines(alice, 1))); checkMetrics(*this, env, 4, 6, 5, 3); // Try adding a new transaction. // Too many fees in flight. - env(noop(alice), - fee(drops(200)), - seq(aliceSeq + 1), - ter(telCAN_NOT_QUEUE_BALANCE)); + env(noop(alice), fee(drops(200)), seq(aliceSeq + 1), ter(telCAN_NOT_QUEUE_BALANCE)); checkMetrics(*this, env, 4, 6, 5, 3); // Close the ledger. All of Alice's transactions @@ -1736,10 +1613,7 @@ public: // Still can't add a new transaction for Alice, // no matter the fee. - env(noop(alice), - fee(drops(200)), - seq(aliceSeq + 1), - ter(telCAN_NOT_QUEUE_BALANCE)); + env(noop(alice), fee(drops(200)), seq(aliceSeq + 1), ter(telCAN_NOT_QUEUE_BALANCE)); checkMetrics(*this, env, 1, 10, 3, 5); /* At this point, Alice's transaction is indefinitely @@ -1798,15 +1672,9 @@ public: env(noop(alice), seq(aliceSeq + 1), queued); // Can't replace either queued transaction with a blocker - env(fset(alice, asfAccountTxnID), - seq(aliceSeq + 0), - fee(baseFee * 2), - ter(telCAN_NOT_QUEUE_BLOCKS)); + env(fset(alice, asfAccountTxnID), seq(aliceSeq + 0), fee(baseFee * 2), ter(telCAN_NOT_QUEUE_BLOCKS)); - env(regkey(alice, bob), - seq(aliceSeq + 1), - fee(baseFee * 2), - ter(telCAN_NOT_QUEUE_BLOCKS)); + env(regkey(alice, bob), seq(aliceSeq + 1), fee(baseFee * 2), ter(telCAN_NOT_QUEUE_BLOCKS)); // Can't append a blocker to the queue. env(signers(alice, 2, {{bob}, {charlie}, {daria}}), @@ -1833,10 +1701,7 @@ public: // Since there's only one entry in the queue we can replace // that entry with a blocker. - env(regkey(alice, bob), - seq(aliceSeq + 0), - fee(baseFee * 2), - queued); + env(regkey(alice, bob), seq(aliceSeq + 0), fee(baseFee * 2), queued); // Now that there's a blocker in the queue we can't append to // the queue. @@ -1846,10 +1711,7 @@ public: env(noop(bob), queued); // We can replace the blocker with a different blocker. - env(signers(alice, 2, {{bob}, {charlie}, {daria}}), - seq(aliceSeq + 0), - fee(baseFee * 2.6), - queued); + env(signers(alice, 2, {{bob}, {charlie}, {daria}}), seq(aliceSeq + 0), fee(baseFee * 2.6), queued); // Prove that the queue is still blocked. env(noop(alice), seq(aliceSeq + 1), ter(telCAN_NOT_QUEUE_BLOCKED)); @@ -1933,20 +1795,12 @@ public: env(noop(alice), ticket::use(tkt + 1), queued); // Can't replace either queued transaction with a blocker - env(fset(alice, asfAccountTxnID), - ticket::use(tkt + 1), - fee(baseFee * 2), - ter(telCAN_NOT_QUEUE_BLOCKS)); + env(fset(alice, asfAccountTxnID), ticket::use(tkt + 1), fee(baseFee * 2), ter(telCAN_NOT_QUEUE_BLOCKS)); - env(regkey(alice, bob), - ticket::use(tkt + 2), - fee(baseFee * 2), - ter(telCAN_NOT_QUEUE_BLOCKS)); + env(regkey(alice, bob), ticket::use(tkt + 2), fee(baseFee * 2), ter(telCAN_NOT_QUEUE_BLOCKS)); // Can't append a blocker to the queue. - env(signers(alice, 2, {{bob}, {charlie}, {daria}}), - fee(baseFee * 2), - ter(telCAN_NOT_QUEUE_BLOCKS)); + env(signers(alice, 2, {{bob}, {charlie}, {daria}}), fee(baseFee * 2), ter(telCAN_NOT_QUEUE_BLOCKS)); env(signers(alice, 2, {{bob}, {charlie}, {daria}}), ticket::use(tkt + 0), @@ -1977,41 +1831,26 @@ public: // Since there's an entry in the queue we cannot append a // blocker to the account's queue. - env(regkey(alice, bob), - fee(baseFee * 2), - ter(telCAN_NOT_QUEUE_BLOCKS)); - env(regkey(alice, bob), - ticket::use(tkt + 1), - fee(baseFee * 2), - ter(telCAN_NOT_QUEUE_BLOCKS)); + env(regkey(alice, bob), fee(baseFee * 2), ter(telCAN_NOT_QUEUE_BLOCKS)); + env(regkey(alice, bob), ticket::use(tkt + 1), fee(baseFee * 2), ter(telCAN_NOT_QUEUE_BLOCKS)); // However we can _replace_ that lone entry with a blocker. - env(regkey(alice, bob), - ticket::use(tkt + 0), - fee(baseFee * 2), - queued); + env(regkey(alice, bob), ticket::use(tkt + 0), fee(baseFee * 2), queued); // Now that there's a blocker in the queue we can't append to // the queue. env(noop(alice), ter(telCAN_NOT_QUEUE_BLOCKED)); - env(noop(alice), - ticket::use(tkt + 1), - ter(telCAN_NOT_QUEUE_BLOCKED)); + env(noop(alice), ticket::use(tkt + 1), ter(telCAN_NOT_QUEUE_BLOCKED)); // Other accounts are unaffected. env(noop(bob), queued); // We can replace the blocker with a different blocker. - env(signers(alice, 2, {{bob}, {charlie}, {daria}}), - ticket::use(tkt + 0), - fee(baseFee * 2.6), - queued); + env(signers(alice, 2, {{bob}, {charlie}, {daria}}), ticket::use(tkt + 0), fee(baseFee * 2.6), queued); // Prove that the queue is still blocked. env(noop(alice), ter(telCAN_NOT_QUEUE_BLOCKED)); - env(noop(alice), - ticket::use(tkt + 1), - ter(telCAN_NOT_QUEUE_BLOCKED)); + env(noop(alice), ticket::use(tkt + 1), ter(telCAN_NOT_QUEUE_BLOCKED)); // We can replace the blocker with a non-blocker. Then we can // successfully append to the queue. @@ -2041,9 +1880,7 @@ public: // Since there's a blocker in the queue we can't append to // the queue. - env(noop(alice), - ticket::use(tkt + 1), - ter(telCAN_NOT_QUEUE_BLOCKED)); + env(noop(alice), ticket::use(tkt + 1), ter(telCAN_NOT_QUEUE_BLOCKED)); // Other accounts are unaffected. env(noop(bob), queued); @@ -2068,8 +1905,7 @@ public: Env env( *this, makeConfig( - {{"minimum_txn_in_ledger_standalone", "3"}}, - {{"account_reserve", "200"}, {"owner_reserve", "50"}})); + {{"minimum_txn_in_ledger_standalone", "3"}}, {{"account_reserve", "200"}, {"owner_reserve", "50"}})); auto alice = Account("alice"); auto charlie = Account("charlie"); @@ -2143,10 +1979,7 @@ public: // So even a noop will look like alice // doesn't have the balance to pay the fee - env(noop(alice), - fee(drops(51)), - seq(aliceSeq + 2), - ter(terINSUF_FEE_B)); + env(noop(alice), fee(drops(51)), seq(aliceSeq + 2), ter(terINSUF_FEE_B)); checkMetrics(*this, env, 2, limit * 2, limit + 1, limit); env.close(); @@ -2176,10 +2009,7 @@ public: // So even a noop will look like alice // doesn't have the balance to pay the fee - env(noop(alice), - fee(drops(51)), - seq(aliceSeq + 1), - ter(telCAN_NOT_QUEUE_BALANCE)); + env(noop(alice), fee(drops(51)), seq(aliceSeq + 1), ter(telCAN_NOT_QUEUE_BALANCE)); checkMetrics(*this, env, 1, limit * 2, limit + 1, limit); env.close(); @@ -2267,8 +2097,7 @@ public: checkMetrics(*this, env, 0, limit * 2, 2, limit); // The payment succeeds - env.require( - balance(alice, aliceBal - XRP(500) - drops(20)), owners(alice, 0)); + env.require(balance(alice, aliceBal - XRP(500) - drops(20)), owners(alice, 0)); ////////////////////////////////////////// // Large IOU payment allows later txs @@ -2427,12 +2256,7 @@ public: env.memoize("carol"); { auto const jtx = env.jt(offer_cancel(alice, 3), seq(5), fee(10)); - auto const pf = preflight( - env.app(), - env.current()->rules(), - *jtx.stx, - tapNONE, - env.journal); + auto const pf = preflight(env.app(), env.current()->rules(), *jtx.stx, tapNONE, env.journal); BEAST_EXPECT(pf.ter == tesSUCCESS); BEAST_EXPECT(!pf.consequences.isBlocker()); BEAST_EXPECT(pf.consequences.fee() == drops(10)); @@ -2442,14 +2266,8 @@ public: { auto USD = alice["USD"]; - auto const jtx = - env.jt(trust("carol", USD(50000000)), seq(1), fee(10)); - auto const pf = preflight( - env.app(), - env.current()->rules(), - *jtx.stx, - tapNONE, - env.journal); + auto const jtx = env.jt(trust("carol", USD(50000000)), seq(1), fee(10)); + auto const pf = preflight(env.app(), env.current()->rules(), *jtx.stx, tapNONE, env.journal); BEAST_EXPECT(pf.ter == tesSUCCESS); BEAST_EXPECT(!pf.consequences.isBlocker()); BEAST_EXPECT(pf.consequences.fee() == drops(10)); @@ -2458,12 +2276,7 @@ public: { auto const jtx = env.jt(ticket::create(alice, 1), seq(1), fee(10)); - auto const pf = preflight( - env.app(), - env.current()->rules(), - *jtx.stx, - tapNONE, - env.journal); + auto const pf = preflight(env.app(), env.current()->rules(), *jtx.stx, tapNONE, env.journal); BEAST_EXPECT(pf.ter == tesSUCCESS); BEAST_EXPECT(!pf.consequences.isBlocker()); BEAST_EXPECT(pf.consequences.fee() == drops(10)); @@ -2571,18 +2384,9 @@ public: // Charlie is paying a high enough fee to go straight into the // ledger in order to get into the vicinity of an assert which // should no longer fire :-). - env(noop(charlie), - fee(baseFee * 800), - seq(charlieSeq - 1), - ter(tefPAST_SEQ)); - env(noop(charlie), - fee(baseFee * 800), - seq(charlieSeq + 1), - ter(terPRE_SEQ)); - env(noop(charlie), - fee(baseFee * 800), - seq(charlieSeq), - ter(tesSUCCESS)); + env(noop(charlie), fee(baseFee * 800), seq(charlieSeq - 1), ter(tefPAST_SEQ)); + env(noop(charlie), fee(baseFee * 800), seq(charlieSeq + 1), ter(terPRE_SEQ)); + env(noop(charlie), fee(baseFee * 800), seq(charlieSeq), ter(tesSUCCESS)); } void @@ -2595,13 +2399,10 @@ public: auto fee = env.rpc("fee"); - if (BEAST_EXPECT(fee.isMember(jss::result)) && - BEAST_EXPECT(!RPC::contains_error(fee[jss::result]))) + if (BEAST_EXPECT(fee.isMember(jss::result)) && BEAST_EXPECT(!RPC::contains_error(fee[jss::result]))) { auto const& result = fee[jss::result]; - BEAST_EXPECT( - result.isMember(jss::ledger_current_index) && - result[jss::ledger_current_index] == 3); + BEAST_EXPECT(result.isMember(jss::ledger_current_index) && result[jss::ledger_current_index] == 3); BEAST_EXPECT(result.isMember(jss::current_ledger_size)); BEAST_EXPECT(result.isMember(jss::current_queue_size)); BEAST_EXPECT(result.isMember(jss::expected_ledger_size)); @@ -2624,13 +2425,10 @@ public: fee = env.rpc("fee"); - if (BEAST_EXPECT(fee.isMember(jss::result)) && - BEAST_EXPECT(!RPC::contains_error(fee[jss::result]))) + if (BEAST_EXPECT(fee.isMember(jss::result)) && BEAST_EXPECT(!RPC::contains_error(fee[jss::result]))) { auto const& result = fee[jss::result]; - BEAST_EXPECT( - result.isMember(jss::ledger_current_index) && - result[jss::ledger_current_index] == 4); + BEAST_EXPECT(result.isMember(jss::ledger_current_index) && result[jss::ledger_current_index] == 4); BEAST_EXPECT(result.isMember(jss::current_ledger_size)); BEAST_EXPECT(result.isMember(jss::current_queue_size)); BEAST_EXPECT(result.isMember(jss::expected_ledger_size)); @@ -2686,14 +2484,8 @@ public: BEAST_EXPECT(env.current()->header().seq == 3); env(noop(alice), seq(aliceSeq), last_ledger_seq(5), ter(terQUEUED)); env(noop(alice), seq(aliceSeq + 1), last_ledger_seq(5), ter(terQUEUED)); - env(noop(alice), - seq(aliceSeq + 2), - last_ledger_seq(10), - ter(terQUEUED)); - env(noop(alice), - seq(aliceSeq + 3), - last_ledger_seq(11), - ter(terQUEUED)); + env(noop(alice), seq(aliceSeq + 2), last_ledger_seq(10), ter(terQUEUED)); + env(noop(alice), seq(aliceSeq + 3), last_ledger_seq(11), ter(terQUEUED)); checkMetrics(*this, env, 4, std::nullopt, 2, 1); auto const bobSeq = env.seq(bob); // Ledger 4 gets 3, @@ -2719,9 +2511,7 @@ public: env(noop(alice), seq(aliceSeq + 1), ter(terPRE_SEQ)); // Cannot fill the gap with a blocker since Alice's queue is not empty. - env(fset(alice, asfAccountTxnID), - seq(aliceSeq), - ter(telCAN_NOT_QUEUE_BLOCKS)); + env(fset(alice, asfAccountTxnID), seq(aliceSeq), ter(telCAN_NOT_QUEUE_BLOCKS)); checkMetrics(*this, env, 2, 40, 5, 4); // However we can fill the gap with a non-blocker. @@ -2729,9 +2519,7 @@ public: checkMetrics(*this, env, 3, 40, 5, 4); // Attempt to queue up a new aliceSeq + 1 tx that's a blocker. - env(fset(alice, asfAccountTxnID), - seq(aliceSeq + 1), - ter(telCAN_NOT_QUEUE_BLOCKS)); + env(fset(alice, asfAccountTxnID), seq(aliceSeq + 1), ter(telCAN_NOT_QUEUE_BLOCKS)); checkMetrics(*this, env, 3, 40, 5, 4); // Queue up a non-blocker replacement for aliceSeq + 1. @@ -2761,9 +2549,7 @@ public: testcase("full queue gap handling"); auto cfg = makeConfig( - {{"minimum_txn_in_ledger_standalone", "1"}, - {"ledgers_in_queue", "10"}, - {"maximum_txn_per_account", "11"}}); + {{"minimum_txn_in_ledger_standalone", "1"}, {"ledgers_in_queue", "10"}, {"maximum_txn_per_account", "11"}}); cfg->FEES.reference_fee = 10; Env env(*this, std::move(cfg)); @@ -2783,46 +2569,16 @@ public: // Start by procuring tickets for alice to use to keep her queue full // without affecting the sequence gap that will appear later. - env(ticket::create(alice, 11), - seq(aliceSeq + 0), - fee(baseFee * 20 + 1), - ter(terQUEUED)); - env(noop(alice), - seq(aliceSeq + 11), - last_ledger_seq(11), - ter(terQUEUED)); - env(noop(alice), - seq(aliceSeq + 12), - last_ledger_seq(11), - ter(terQUEUED)); - env(noop(alice), - seq(aliceSeq + 13), - last_ledger_seq(11), - ter(terQUEUED)); - env(noop(alice), - seq(aliceSeq + 14), - last_ledger_seq(11), - ter(terQUEUED)); - env(noop(alice), - seq(aliceSeq + 15), - last_ledger_seq(11), - ter(terQUEUED)); - env(noop(alice), - seq(aliceSeq + 16), - last_ledger_seq(5), - ter(terQUEUED)); - env(noop(alice), - seq(aliceSeq + 17), - last_ledger_seq(5), - ter(terQUEUED)); - env(noop(alice), - seq(aliceSeq + 18), - last_ledger_seq(5), - ter(terQUEUED)); - env(noop(alice), - seq(aliceSeq + 19), - last_ledger_seq(11), - ter(terQUEUED)); + env(ticket::create(alice, 11), seq(aliceSeq + 0), fee(baseFee * 20 + 1), ter(terQUEUED)); + env(noop(alice), seq(aliceSeq + 11), last_ledger_seq(11), ter(terQUEUED)); + env(noop(alice), seq(aliceSeq + 12), last_ledger_seq(11), ter(terQUEUED)); + env(noop(alice), seq(aliceSeq + 13), last_ledger_seq(11), ter(terQUEUED)); + env(noop(alice), seq(aliceSeq + 14), last_ledger_seq(11), ter(terQUEUED)); + env(noop(alice), seq(aliceSeq + 15), last_ledger_seq(11), ter(terQUEUED)); + env(noop(alice), seq(aliceSeq + 16), last_ledger_seq(5), ter(terQUEUED)); + env(noop(alice), seq(aliceSeq + 17), last_ledger_seq(5), ter(terQUEUED)); + env(noop(alice), seq(aliceSeq + 18), last_ledger_seq(5), ter(terQUEUED)); + env(noop(alice), seq(aliceSeq + 19), last_ledger_seq(11), ter(terQUEUED)); checkMetrics(*this, env, 10, std::nullopt, 2, 1); auto const bobSeq = env.seq(bob); @@ -2945,9 +2701,7 @@ public: json(jss::LastLedgerSequence, lastLedgerSeq), ter(terQUEUED))(submitParams); else - envs( - noop(alice), fee(baseFee * 100), seq(none), ter(terQUEUED))( - submitParams); + envs(noop(alice), fee(baseFee * 100), seq(none), ter(terQUEUED))(submitParams); } checkMetrics(*this, env, 5, std::nullopt, 7, 6); { @@ -2957,12 +2711,10 @@ public: for (auto const& tx : aliceStat) { BEAST_EXPECT(tx.seqProxy == seq); - BEAST_EXPECT( - tx.feeLevel == FeeLevel64{baseFeeLevel.fee() * 100}); + BEAST_EXPECT(tx.feeLevel == FeeLevel64{baseFeeLevel.fee() * 100}); if (seq.value() == aliceSeq + 2) { - BEAST_EXPECT( - tx.lastValid && *tx.lastValid == lastLedgerSeq); + BEAST_EXPECT(tx.lastValid && *tx.lastValid == lastLedgerSeq); } else { @@ -3012,15 +2764,13 @@ public: ++seq; BEAST_EXPECT(tx.seqProxy.isSeq() && tx.seqProxy.value() == seq); - BEAST_EXPECT( - tx.feeLevel == FeeLevel64{baseFeeLevel.fee() * 100}); + BEAST_EXPECT(tx.feeLevel == FeeLevel64{baseFeeLevel.fee() * 100}); BEAST_EXPECT(!tx.lastValid); ++seq; } } // Now, fill the gap. - envs(noop(alice), fee(baseFee * 100), seq(none), ter(terQUEUED))( - submitParams); + envs(noop(alice), fee(baseFee * 100), seq(none), ter(terQUEUED))(submitParams); checkMetrics(*this, env, 5, 18, 10, 9); { auto aliceStat = txQ.getAccountTxs(alice.id()); @@ -3077,20 +2827,14 @@ public: { // account_info without the "queue" argument. - auto const info = - env.rpc("json", "account_info", to_string(withoutQueue)); - BEAST_EXPECT( - info.isMember(jss::result) && - info[jss::result].isMember(jss::account_data)); + auto const info = env.rpc("json", "account_info", to_string(withoutQueue)); + BEAST_EXPECT(info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); BEAST_EXPECT(!info[jss::result].isMember(jss::queue_data)); } { // account_info with the "queue" argument. - auto const info = - env.rpc("json", "account_info", to_string(withQueue)); - BEAST_EXPECT( - info.isMember(jss::result) && - info[jss::result].isMember(jss::account_data)); + auto const info = env.rpc("json", "account_info", to_string(withQueue)); + BEAST_EXPECT(info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); auto const& result = info[jss::result]; BEAST_EXPECT(result.isMember(jss::queue_data)); auto const& queue_data = result[jss::queue_data]; @@ -3109,11 +2853,8 @@ public: checkMetrics(*this, env, 0, 6, 4, 3); { - auto const info = - env.rpc("json", "account_info", to_string(withQueue)); - BEAST_EXPECT( - info.isMember(jss::result) && - info[jss::result].isMember(jss::account_data)); + auto const info = env.rpc("json", "account_info", to_string(withQueue)); + BEAST_EXPECT(info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); auto const& result = info[jss::result]; BEAST_EXPECT(result.isMember(jss::queue_data)); auto const& queue_data = result[jss::queue_data]; @@ -3128,22 +2869,15 @@ public: } auto submitParams = Json::Value(Json::objectValue); - envs(noop(alice), fee(baseFee * 10), seq(none), ter(terQUEUED))( - submitParams); - envs(noop(alice), fee(baseFee * 10), seq(none), ter(terQUEUED))( - submitParams); - envs(noop(alice), fee(baseFee * 10), seq(none), ter(terQUEUED))( - submitParams); - envs(noop(alice), fee(baseFee * 10), seq(none), ter(terQUEUED))( - submitParams); + envs(noop(alice), fee(baseFee * 10), seq(none), ter(terQUEUED))(submitParams); + envs(noop(alice), fee(baseFee * 10), seq(none), ter(terQUEUED))(submitParams); + envs(noop(alice), fee(baseFee * 10), seq(none), ter(terQUEUED))(submitParams); + envs(noop(alice), fee(baseFee * 10), seq(none), ter(terQUEUED))(submitParams); checkMetrics(*this, env, 4, 6, 4, 3); { - auto const info = - env.rpc("json", "account_info", to_string(withQueue)); - BEAST_EXPECT( - info.isMember(jss::result) && - info[jss::result].isMember(jss::account_data)); + auto const info = env.rpc("json", "account_info", to_string(withQueue)); + BEAST_EXPECT(info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); auto const& result = info[jss::result]; auto const& data = result[jss::account_data]; BEAST_EXPECT(result.isMember(jss::queue_data)); @@ -3152,19 +2886,15 @@ public: BEAST_EXPECT(queue_data.isMember(jss::txn_count)); BEAST_EXPECT(queue_data[jss::txn_count] == 4); BEAST_EXPECT(queue_data.isMember(jss::lowest_sequence)); - BEAST_EXPECT( - queue_data[jss::lowest_sequence] == data[jss::Sequence]); + BEAST_EXPECT(queue_data[jss::lowest_sequence] == data[jss::Sequence]); BEAST_EXPECT(queue_data.isMember(jss::highest_sequence)); BEAST_EXPECT( queue_data[jss::highest_sequence] == - data[jss::Sequence].asUInt() + - queue_data[jss::txn_count].asUInt() - 1); + data[jss::Sequence].asUInt() + queue_data[jss::txn_count].asUInt() - 1); BEAST_EXPECT(queue_data.isMember(jss::auth_change_queued)); BEAST_EXPECT(queue_data[jss::auth_change_queued] == false); BEAST_EXPECT(queue_data.isMember(jss::max_spend_drops_total)); - BEAST_EXPECT( - queue_data[jss::max_spend_drops_total] == - std::to_string(baseFee * 40)); + BEAST_EXPECT(queue_data[jss::max_spend_drops_total] == std::to_string(baseFee * 40)); BEAST_EXPECT(queue_data.isMember(jss::transactions)); auto const& queued = queue_data[jss::transactions]; BEAST_EXPECT(queued.size() == queue_data[jss::txn_count]); @@ -3172,16 +2902,13 @@ public: { auto const& item = queued[i]; BEAST_EXPECT(item[jss::seq] == data[jss::Sequence].asInt() + i); - BEAST_EXPECT( - item[jss::fee_level] == - std::to_string(baseFeeLevel.fee() * 10)); + BEAST_EXPECT(item[jss::fee_level] == std::to_string(baseFeeLevel.fee() * 10)); BEAST_EXPECT(!item.isMember(jss::LastLedgerSequence)); BEAST_EXPECT(item.isMember(jss::fee)); BEAST_EXPECT(item[jss::fee] == std::to_string(baseFee * 10)); BEAST_EXPECT(item.isMember(jss::max_spend_drops)); - BEAST_EXPECT( - item[jss::max_spend_drops] == std::to_string(baseFee * 10)); + BEAST_EXPECT(item[jss::max_spend_drops] == std::to_string(baseFee * 10)); BEAST_EXPECT(item.isMember(jss::auth_change)); BEAST_EXPECT(item[jss::auth_change].asBool() == false); } @@ -3203,11 +2930,8 @@ public: checkMetrics(*this, env, 1, 8, 5, 4); { - auto const info = - env.rpc("json", "account_info", to_string(withQueue)); - BEAST_EXPECT( - info.isMember(jss::result) && - info[jss::result].isMember(jss::account_data)); + auto const info = env.rpc("json", "account_info", to_string(withQueue)); + BEAST_EXPECT(info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); auto const& result = info[jss::result]; auto const& data = result[jss::account_data]; BEAST_EXPECT(result.isMember(jss::queue_data)); @@ -3216,19 +2940,15 @@ public: BEAST_EXPECT(queue_data.isMember(jss::txn_count)); BEAST_EXPECT(queue_data[jss::txn_count] == 1); BEAST_EXPECT(queue_data.isMember(jss::lowest_sequence)); - BEAST_EXPECT( - queue_data[jss::lowest_sequence] == data[jss::Sequence]); + BEAST_EXPECT(queue_data[jss::lowest_sequence] == data[jss::Sequence]); BEAST_EXPECT(queue_data.isMember(jss::highest_sequence)); BEAST_EXPECT( queue_data[jss::highest_sequence] == - data[jss::Sequence].asUInt() + - queue_data[jss::txn_count].asUInt() - 1); + data[jss::Sequence].asUInt() + queue_data[jss::txn_count].asUInt() - 1); BEAST_EXPECT(queue_data.isMember(jss::auth_change_queued)); BEAST_EXPECT(queue_data[jss::auth_change_queued] == true); BEAST_EXPECT(queue_data.isMember(jss::max_spend_drops_total)); - BEAST_EXPECT( - queue_data[jss::max_spend_drops_total] == - std::to_string(baseFee * 10)); + BEAST_EXPECT(queue_data[jss::max_spend_drops_total] == std::to_string(baseFee * 10)); BEAST_EXPECT(queue_data.isMember(jss::transactions)); auto const& queued = queue_data[jss::transactions]; BEAST_EXPECT(queued.size() == queue_data[jss::txn_count]); @@ -3236,14 +2956,11 @@ public: { auto const& item = queued[i]; BEAST_EXPECT(item[jss::seq] == data[jss::Sequence].asInt() + i); - BEAST_EXPECT( - item[jss::fee_level] == - std::to_string(baseFeeLevel.fee() * 10)); + BEAST_EXPECT(item[jss::fee_level] == std::to_string(baseFeeLevel.fee() * 10)); BEAST_EXPECT(item.isMember(jss::fee)); BEAST_EXPECT(item[jss::fee] == std::to_string(baseFee * 10)); BEAST_EXPECT(item.isMember(jss::max_spend_drops)); - BEAST_EXPECT( - item[jss::max_spend_drops] == std::to_string(baseFee * 10)); + BEAST_EXPECT(item[jss::max_spend_drops] == std::to_string(baseFee * 10)); BEAST_EXPECT(item.isMember(jss::auth_change)); if (i == queued.size() - 1) @@ -3260,19 +2977,12 @@ public: } } - envs( - noop(alice), - fee(baseFee * 10), - seq(none), - ter(telCAN_NOT_QUEUE_BLOCKED))(submitParams); + envs(noop(alice), fee(baseFee * 10), seq(none), ter(telCAN_NOT_QUEUE_BLOCKED))(submitParams); checkMetrics(*this, env, 1, 8, 5, 4); { - auto const info = - env.rpc("json", "account_info", to_string(withQueue)); - BEAST_EXPECT( - info.isMember(jss::result) && - info[jss::result].isMember(jss::account_data)); + auto const info = env.rpc("json", "account_info", to_string(withQueue)); + BEAST_EXPECT(info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); auto const& result = info[jss::result]; auto const& data = result[jss::account_data]; BEAST_EXPECT(result.isMember(jss::queue_data)); @@ -3281,19 +2991,15 @@ public: BEAST_EXPECT(queue_data.isMember(jss::txn_count)); BEAST_EXPECT(queue_data[jss::txn_count] == 1); BEAST_EXPECT(queue_data.isMember(jss::lowest_sequence)); - BEAST_EXPECT( - queue_data[jss::lowest_sequence] == data[jss::Sequence]); + BEAST_EXPECT(queue_data[jss::lowest_sequence] == data[jss::Sequence]); BEAST_EXPECT(queue_data.isMember(jss::highest_sequence)); BEAST_EXPECT( queue_data[jss::highest_sequence] == - data[jss::Sequence].asUInt() + - queue_data[jss::txn_count].asUInt() - 1); + data[jss::Sequence].asUInt() + queue_data[jss::txn_count].asUInt() - 1); BEAST_EXPECT(queue_data.isMember(jss::auth_change_queued)); BEAST_EXPECT(queue_data[jss::auth_change_queued].asBool()); BEAST_EXPECT(queue_data.isMember(jss::max_spend_drops_total)); - BEAST_EXPECT( - queue_data[jss::max_spend_drops_total] == - std::to_string(baseFee * 10)); + BEAST_EXPECT(queue_data[jss::max_spend_drops_total] == std::to_string(baseFee * 10)); BEAST_EXPECT(queue_data.isMember(jss::transactions)); auto const& queued = queue_data[jss::transactions]; BEAST_EXPECT(queued.size() == queue_data[jss::txn_count]); @@ -3301,19 +3007,14 @@ public: { auto const& item = queued[i]; BEAST_EXPECT(item[jss::seq] == data[jss::Sequence].asInt() + i); - BEAST_EXPECT( - item[jss::fee_level] == - std::to_string(baseFeeLevel.fee() * 10)); + BEAST_EXPECT(item[jss::fee_level] == std::to_string(baseFeeLevel.fee() * 10)); if (i == queued.size() - 1) { BEAST_EXPECT(item.isMember(jss::fee)); - BEAST_EXPECT( - item[jss::fee] == std::to_string(baseFee * 10)); + BEAST_EXPECT(item[jss::fee] == std::to_string(baseFee * 10)); BEAST_EXPECT(item.isMember(jss::max_spend_drops)); - BEAST_EXPECT( - item[jss::max_spend_drops] == - std::to_string(baseFee * 10)); + BEAST_EXPECT(item[jss::max_spend_drops] == std::to_string(baseFee * 10)); BEAST_EXPECT(item.isMember(jss::auth_change)); BEAST_EXPECT(item[jss::auth_change].asBool()); BEAST_EXPECT(item.isMember(jss::LastLedgerSequence)); @@ -3322,12 +3023,9 @@ public: else { BEAST_EXPECT(item.isMember(jss::fee)); - BEAST_EXPECT( - item[jss::fee] == std::to_string(baseFee * 10)); + BEAST_EXPECT(item[jss::fee] == std::to_string(baseFee * 10)); BEAST_EXPECT(item.isMember(jss::max_spend_drops)); - BEAST_EXPECT( - item[jss::max_spend_drops] == - std::to_string(baseFee * 10)); + BEAST_EXPECT(item[jss::max_spend_drops] == std::to_string(baseFee * 10)); BEAST_EXPECT(item.isMember(jss::auth_change)); BEAST_EXPECT(!item[jss::auth_change].asBool()); BEAST_EXPECT(!item.isMember(jss::LastLedgerSequence)); @@ -3336,11 +3034,8 @@ public: } { - auto const info = - env.rpc("json", "account_info", to_string(prevLedgerWithQueue)); - BEAST_EXPECT( - info.isMember(jss::result) && - RPC::contains_error(info[jss::result])); + auto const info = env.rpc("json", "account_info", to_string(prevLedgerWithQueue)); + BEAST_EXPECT(info.isMember(jss::result) && RPC::contains_error(info[jss::result])); } env.close(); @@ -3349,11 +3044,8 @@ public: checkMetrics(*this, env, 0, 10, 0, 5); { - auto const info = - env.rpc("json", "account_info", to_string(withQueue)); - BEAST_EXPECT( - info.isMember(jss::result) && - info[jss::result].isMember(jss::account_data)); + auto const info = env.rpc("json", "account_info", to_string(withQueue)); + BEAST_EXPECT(info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); auto const& result = info[jss::result]; BEAST_EXPECT(result.isMember(jss::queue_data)); auto const& queue_data = result[jss::queue_data]; @@ -3384,12 +3076,9 @@ public: { auto const server_info = env.rpc("server_info"); - BEAST_EXPECT( - server_info.isMember(jss::result) && - server_info[jss::result].isMember(jss::info)); + BEAST_EXPECT(server_info.isMember(jss::result) && server_info[jss::result].isMember(jss::info)); auto const& info = server_info[jss::result][jss::info]; - BEAST_EXPECT( - info.isMember(jss::load_factor) && info[jss::load_factor] == 1); + BEAST_EXPECT(info.isMember(jss::load_factor) && info[jss::load_factor] == 1); BEAST_EXPECT(!info.isMember(jss::load_factor_server)); BEAST_EXPECT(!info.isMember(jss::load_factor_local)); BEAST_EXPECT(!info.isMember(jss::load_factor_net)); @@ -3398,23 +3087,14 @@ public: { auto const server_state = env.rpc("server_state"); auto const& state = server_state[jss::result][jss::state]; + BEAST_EXPECT(state.isMember(jss::load_factor) && state[jss::load_factor] == 256); + BEAST_EXPECT(state.isMember(jss::load_base) && state[jss::load_base] == 256); + BEAST_EXPECT(state.isMember(jss::load_factor_server) && state[jss::load_factor_server] == 256); BEAST_EXPECT( - state.isMember(jss::load_factor) && - state[jss::load_factor] == 256); + state.isMember(jss::load_factor_fee_escalation) && state[jss::load_factor_fee_escalation] == 256); + BEAST_EXPECT(state.isMember(jss::load_factor_fee_queue) && state[jss::load_factor_fee_queue] == 256); BEAST_EXPECT( - state.isMember(jss::load_base) && state[jss::load_base] == 256); - BEAST_EXPECT( - state.isMember(jss::load_factor_server) && - state[jss::load_factor_server] == 256); - BEAST_EXPECT( - state.isMember(jss::load_factor_fee_escalation) && - state[jss::load_factor_fee_escalation] == 256); - BEAST_EXPECT( - state.isMember(jss::load_factor_fee_queue) && - state[jss::load_factor_fee_queue] == 256); - BEAST_EXPECT( - state.isMember(jss::load_factor_fee_reference) && - state[jss::load_factor_fee_reference] == 256); + state.isMember(jss::load_factor_fee_reference) && state[jss::load_factor_fee_reference] == 256); } checkMetrics(*this, env, 0, 6, 0, 3); @@ -3425,98 +3105,62 @@ public: auto aliceSeq = env.seq(alice); auto submitParams = Json::Value(Json::objectValue); for (auto i = 0; i < 4; ++i) - envs( - noop(alice), - fee(baseFee * 10), - seq(aliceSeq + i), - ter(terQUEUED))(submitParams); + envs(noop(alice), fee(baseFee * 10), seq(aliceSeq + i), ter(terQUEUED))(submitParams); checkMetrics(*this, env, 4, 6, 4, 3); { auto const server_info = env.rpc("server_info"); - BEAST_EXPECT( - server_info.isMember(jss::result) && - server_info[jss::result].isMember(jss::info)); + BEAST_EXPECT(server_info.isMember(jss::result) && server_info[jss::result].isMember(jss::info)); auto const& info = server_info[jss::result][jss::info]; // Avoid double rounding issues by comparing to a range. BEAST_EXPECT( - info.isMember(jss::load_factor) && - info[jss::load_factor] > 888.88 && - info[jss::load_factor] < 888.89); - BEAST_EXPECT( - info.isMember(jss::load_factor_server) && - info[jss::load_factor_server] == 1); + info.isMember(jss::load_factor) && info[jss::load_factor] > 888.88 && info[jss::load_factor] < 888.89); + BEAST_EXPECT(info.isMember(jss::load_factor_server) && info[jss::load_factor_server] == 1); BEAST_EXPECT(!info.isMember(jss::load_factor_local)); BEAST_EXPECT(!info.isMember(jss::load_factor_net)); BEAST_EXPECT( - info.isMember(jss::load_factor_fee_escalation) && - info[jss::load_factor_fee_escalation] > 888.88 && + info.isMember(jss::load_factor_fee_escalation) && info[jss::load_factor_fee_escalation] > 888.88 && info[jss::load_factor_fee_escalation] < 888.89); } { auto const server_state = env.rpc("server_state"); auto const& state = server_state[jss::result][jss::state]; + BEAST_EXPECT(state.isMember(jss::load_factor) && state[jss::load_factor] == 227555); + BEAST_EXPECT(state.isMember(jss::load_base) && state[jss::load_base] == 256); + BEAST_EXPECT(state.isMember(jss::load_factor_server) && state[jss::load_factor_server] == 256); BEAST_EXPECT( - state.isMember(jss::load_factor) && - state[jss::load_factor] == 227555); + state.isMember(jss::load_factor_fee_escalation) && state[jss::load_factor_fee_escalation] == 227555); + BEAST_EXPECT(state.isMember(jss::load_factor_fee_queue) && state[jss::load_factor_fee_queue] == 256); BEAST_EXPECT( - state.isMember(jss::load_base) && state[jss::load_base] == 256); - BEAST_EXPECT( - state.isMember(jss::load_factor_server) && - state[jss::load_factor_server] == 256); - BEAST_EXPECT( - state.isMember(jss::load_factor_fee_escalation) && - state[jss::load_factor_fee_escalation] == 227555); - BEAST_EXPECT( - state.isMember(jss::load_factor_fee_queue) && - state[jss::load_factor_fee_queue] == 256); - BEAST_EXPECT( - state.isMember(jss::load_factor_fee_reference) && - state[jss::load_factor_fee_reference] == 256); + state.isMember(jss::load_factor_fee_reference) && state[jss::load_factor_fee_reference] == 256); } env.app().getFeeTrack().setRemoteFee(256000); { auto const server_info = env.rpc("server_info"); - BEAST_EXPECT( - server_info.isMember(jss::result) && - server_info[jss::result].isMember(jss::info)); + BEAST_EXPECT(server_info.isMember(jss::result) && server_info[jss::result].isMember(jss::info)); auto const& info = server_info[jss::result][jss::info]; // Avoid double rounding issues by comparing to a range. - BEAST_EXPECT( - info.isMember(jss::load_factor) && - info[jss::load_factor] == 1000); + BEAST_EXPECT(info.isMember(jss::load_factor) && info[jss::load_factor] == 1000); BEAST_EXPECT(!info.isMember(jss::load_factor_server)); BEAST_EXPECT(!info.isMember(jss::load_factor_local)); + BEAST_EXPECT(info.isMember(jss::load_factor_net) && info[jss::load_factor_net] == 1000); BEAST_EXPECT( - info.isMember(jss::load_factor_net) && - info[jss::load_factor_net] == 1000); - BEAST_EXPECT( - info.isMember(jss::load_factor_fee_escalation) && - info[jss::load_factor_fee_escalation] > 888.88 && + info.isMember(jss::load_factor_fee_escalation) && info[jss::load_factor_fee_escalation] > 888.88 && info[jss::load_factor_fee_escalation] < 888.89); } { auto const server_state = env.rpc("server_state"); auto const& state = server_state[jss::result][jss::state]; + BEAST_EXPECT(state.isMember(jss::load_factor) && state[jss::load_factor] == 256000); + BEAST_EXPECT(state.isMember(jss::load_base) && state[jss::load_base] == 256); + BEAST_EXPECT(state.isMember(jss::load_factor_server) && state[jss::load_factor_server] == 256000); BEAST_EXPECT( - state.isMember(jss::load_factor) && - state[jss::load_factor] == 256000); + state.isMember(jss::load_factor_fee_escalation) && state[jss::load_factor_fee_escalation] == 227555); + BEAST_EXPECT(state.isMember(jss::load_factor_fee_queue) && state[jss::load_factor_fee_queue] == 256); BEAST_EXPECT( - state.isMember(jss::load_base) && state[jss::load_base] == 256); - BEAST_EXPECT( - state.isMember(jss::load_factor_server) && - state[jss::load_factor_server] == 256000); - BEAST_EXPECT( - state.isMember(jss::load_factor_fee_escalation) && - state[jss::load_factor_fee_escalation] == 227555); - BEAST_EXPECT( - state.isMember(jss::load_factor_fee_queue) && - state[jss::load_factor_fee_queue] == 256); - BEAST_EXPECT( - state.isMember(jss::load_factor_fee_reference) && - state[jss::load_factor_fee_reference] == 256); + state.isMember(jss::load_factor_fee_reference) && state[jss::load_factor_fee_reference] == 256); } env.app().getFeeTrack().setRemoteFee(256); @@ -3528,65 +3172,48 @@ public: { auto const server_info = env.rpc("server_info"); - BEAST_EXPECT( - server_info.isMember(jss::result) && - server_info[jss::result].isMember(jss::info)); + BEAST_EXPECT(server_info.isMember(jss::result) && server_info[jss::result].isMember(jss::info)); auto const& info = server_info[jss::result][jss::info]; // Avoid double rounding issues by comparing to a range. BEAST_EXPECT( - info.isMember(jss::load_factor) && - info[jss::load_factor] > 888.88 && - info[jss::load_factor] < 888.89); + info.isMember(jss::load_factor) && info[jss::load_factor] > 888.88 && info[jss::load_factor] < 888.89); // There can be a race between LoadManager lowering the fee, // and the call to server_info, so check a wide range. // The important thing is that it's not 1. BEAST_EXPECT( - info.isMember(jss::load_factor_server) && - info[jss::load_factor_server] > 1.245 && + info.isMember(jss::load_factor_server) && info[jss::load_factor_server] > 1.245 && info[jss::load_factor_server] < 2.4415); BEAST_EXPECT( - info.isMember(jss::load_factor_local) && - info[jss::load_factor_local] > 1.245 && + info.isMember(jss::load_factor_local) && info[jss::load_factor_local] > 1.245 && info[jss::load_factor_local] < 2.4415); BEAST_EXPECT(!info.isMember(jss::load_factor_net)); BEAST_EXPECT( - info.isMember(jss::load_factor_fee_escalation) && - info[jss::load_factor_fee_escalation] > 888.88 && + info.isMember(jss::load_factor_fee_escalation) && info[jss::load_factor_fee_escalation] > 888.88 && info[jss::load_factor_fee_escalation] < 888.89); } { auto const server_state = env.rpc("server_state"); auto const& state = server_state[jss::result][jss::state]; - BEAST_EXPECT( - state.isMember(jss::load_factor) && - state[jss::load_factor] == 227555); - BEAST_EXPECT( - state.isMember(jss::load_base) && state[jss::load_base] == 256); + BEAST_EXPECT(state.isMember(jss::load_factor) && state[jss::load_factor] == 227555); + BEAST_EXPECT(state.isMember(jss::load_base) && state[jss::load_base] == 256); // There can be a race between LoadManager lowering the fee, // and the call to server_info, so check a wide range. // The important thing is that it's not 256. BEAST_EXPECT( - state.isMember(jss::load_factor_server) && - state[jss::load_factor_server] >= 320 && + state.isMember(jss::load_factor_server) && state[jss::load_factor_server] >= 320 && state[jss::load_factor_server] <= 625); BEAST_EXPECT( - state.isMember(jss::load_factor_fee_escalation) && - state[jss::load_factor_fee_escalation] == 227555); + state.isMember(jss::load_factor_fee_escalation) && state[jss::load_factor_fee_escalation] == 227555); + BEAST_EXPECT(state.isMember(jss::load_factor_fee_queue) && state[jss::load_factor_fee_queue] == 256); BEAST_EXPECT( - state.isMember(jss::load_factor_fee_queue) && - state[jss::load_factor_fee_queue] == 256); - BEAST_EXPECT( - state.isMember(jss::load_factor_fee_reference) && - state[jss::load_factor_fee_reference] == 256); + state.isMember(jss::load_factor_fee_reference) && state[jss::load_factor_fee_reference] == 256); } env.close(); { auto const server_info = env.rpc("server_info"); - BEAST_EXPECT( - server_info.isMember(jss::result) && - server_info[jss::result].isMember(jss::info)); + BEAST_EXPECT(server_info.isMember(jss::result) && server_info[jss::result].isMember(jss::info)); auto const& info = server_info[jss::result][jss::info]; // Avoid double rounding issues by comparing to a range. @@ -3594,13 +3221,10 @@ public: // and the call to server_info, so check a wide range. // The important thing is that it's not 1. BEAST_EXPECT( - info.isMember(jss::load_factor) && - info[jss::load_factor] > 1.245 && - info[jss::load_factor] < 2.4415); + info.isMember(jss::load_factor) && info[jss::load_factor] > 1.245 && info[jss::load_factor] < 2.4415); BEAST_EXPECT(!info.isMember(jss::load_factor_server)); BEAST_EXPECT( - info.isMember(jss::load_factor_local) && - info[jss::load_factor_local] > 1.245 && + info.isMember(jss::load_factor_local) && info[jss::load_factor_local] > 1.245 && info[jss::load_factor_local] < 2.4415); BEAST_EXPECT(!info.isMember(jss::load_factor_net)); BEAST_EXPECT(!info.isMember(jss::load_factor_fee_escalation)); @@ -3609,27 +3233,19 @@ public: auto const server_state = env.rpc("server_state"); auto const& state = server_state[jss::result][jss::state]; BEAST_EXPECT( - state.isMember(jss::load_factor) && - state[jss::load_factor] >= 320 && - state[jss::load_factor] <= 625); - BEAST_EXPECT( - state.isMember(jss::load_base) && state[jss::load_base] == 256); + state.isMember(jss::load_factor) && state[jss::load_factor] >= 320 && state[jss::load_factor] <= 625); + BEAST_EXPECT(state.isMember(jss::load_base) && state[jss::load_base] == 256); // There can be a race between LoadManager lowering the fee, // and the call to server_info, so check a wide range. // The important thing is that it's not 256. BEAST_EXPECT( - state.isMember(jss::load_factor_server) && - state[jss::load_factor_server] >= 320 && + state.isMember(jss::load_factor_server) && state[jss::load_factor_server] >= 320 && state[jss::load_factor_server] <= 625); BEAST_EXPECT( - state.isMember(jss::load_factor_fee_escalation) && - state[jss::load_factor_fee_escalation] == 256); + state.isMember(jss::load_factor_fee_escalation) && state[jss::load_factor_fee_escalation] == 256); + BEAST_EXPECT(state.isMember(jss::load_factor_fee_queue) && state[jss::load_factor_fee_queue] == 256); BEAST_EXPECT( - state.isMember(jss::load_factor_fee_queue) && - state[jss::load_factor_fee_queue] == 256); - BEAST_EXPECT( - state.isMember(jss::load_factor_fee_reference) && - state[jss::load_factor_fee_reference] == 256); + state.isMember(jss::load_factor_fee_reference) && state[jss::load_factor_fee_reference] == 256); } } @@ -3651,8 +3267,7 @@ public: BEAST_EXPECT(jv[jss::status] == "success"); } - Account a{"a"}, b{"b"}, c{"c"}, d{"d"}, e{"e"}, f{"f"}, g{"g"}, h{"h"}, - i{"i"}; + Account a{"a"}, b{"b"}, c{"c"}, d{"d"}, e{"e"}, f{"f"}, g{"g"}, h{"h"}, i{"i"}; // Fund the first few accounts at non escalated fee env.fund(XRP(50000), noripple(a, b, c, d)); @@ -3661,31 +3276,20 @@ public: // First transaction establishes the messaging using namespace std::chrono_literals; BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { - return jv[jss::type] == "serverStatus" && - jv.isMember(jss::load_factor) && jv[jss::load_factor] == 256 && - jv.isMember(jss::load_base) && jv[jss::load_base] == 256 && - jv.isMember(jss::load_factor_server) && - jv[jss::load_factor_server] == 256 && - jv.isMember(jss::load_factor_fee_escalation) && - jv[jss::load_factor_fee_escalation] == 256 && - jv.isMember(jss::load_factor_fee_queue) && - jv[jss::load_factor_fee_queue] == 256 && - jv.isMember(jss::load_factor_fee_reference) && + return jv[jss::type] == "serverStatus" && jv.isMember(jss::load_factor) && jv[jss::load_factor] == 256 && + jv.isMember(jss::load_base) && jv[jss::load_base] == 256 && jv.isMember(jss::load_factor_server) && + jv[jss::load_factor_server] == 256 && jv.isMember(jss::load_factor_fee_escalation) && + jv[jss::load_factor_fee_escalation] == 256 && jv.isMember(jss::load_factor_fee_queue) && + jv[jss::load_factor_fee_queue] == 256 && jv.isMember(jss::load_factor_fee_reference) && jv[jss::load_factor_fee_reference] == 256; })); // Last transaction escalates the fee BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { - return jv[jss::type] == "serverStatus" && - jv.isMember(jss::load_factor) && - jv[jss::load_factor] == 227555 && jv.isMember(jss::load_base) && - jv[jss::load_base] == 256 && - jv.isMember(jss::load_factor_server) && - jv[jss::load_factor_server] == 256 && - jv.isMember(jss::load_factor_fee_escalation) && - jv[jss::load_factor_fee_escalation] == 227555 && - jv.isMember(jss::load_factor_fee_queue) && - jv[jss::load_factor_fee_queue] == 256 && - jv.isMember(jss::load_factor_fee_reference) && + return jv[jss::type] == "serverStatus" && jv.isMember(jss::load_factor) && jv[jss::load_factor] == 227555 && + jv.isMember(jss::load_base) && jv[jss::load_base] == 256 && jv.isMember(jss::load_factor_server) && + jv[jss::load_factor_server] == 256 && jv.isMember(jss::load_factor_fee_escalation) && + jv[jss::load_factor_fee_escalation] == 227555 && jv.isMember(jss::load_factor_fee_queue) && + jv[jss::load_factor_fee_queue] == 256 && jv.isMember(jss::load_factor_fee_reference) && jv[jss::load_factor_fee_reference] == 256; })); @@ -3693,16 +3297,11 @@ public: // Closing ledger should publish a status update BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { - return jv[jss::type] == "serverStatus" && - jv.isMember(jss::load_factor) && jv[jss::load_factor] == 256 && - jv.isMember(jss::load_base) && jv[jss::load_base] == 256 && - jv.isMember(jss::load_factor_server) && - jv[jss::load_factor_server] == 256 && - jv.isMember(jss::load_factor_fee_escalation) && - jv[jss::load_factor_fee_escalation] == 256 && - jv.isMember(jss::load_factor_fee_queue) && - jv[jss::load_factor_fee_queue] == 256 && - jv.isMember(jss::load_factor_fee_reference) && + return jv[jss::type] == "serverStatus" && jv.isMember(jss::load_factor) && jv[jss::load_factor] == 256 && + jv.isMember(jss::load_base) && jv[jss::load_base] == 256 && jv.isMember(jss::load_factor_server) && + jv[jss::load_factor_server] == 256 && jv.isMember(jss::load_factor_fee_escalation) && + jv[jss::load_factor_fee_escalation] == 256 && jv.isMember(jss::load_factor_fee_queue) && + jv[jss::load_factor_fee_queue] == 256 && jv.isMember(jss::load_factor_fee_reference) && jv[jss::load_factor_fee_reference] == 256; })); @@ -3724,56 +3323,37 @@ public: // Last transaction escalates the fee BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { - return jv[jss::type] == "serverStatus" && - jv.isMember(jss::load_factor) && - jv[jss::load_factor] == 200000 && jv.isMember(jss::load_base) && - jv[jss::load_base] == 256 && - jv.isMember(jss::load_factor_server) && - jv[jss::load_factor_server] == 256 && - jv.isMember(jss::load_factor_fee_escalation) && - jv[jss::load_factor_fee_escalation] == 200000 && - jv.isMember(jss::load_factor_fee_queue) && - jv[jss::load_factor_fee_queue] == 256 && - jv.isMember(jss::load_factor_fee_reference) && + return jv[jss::type] == "serverStatus" && jv.isMember(jss::load_factor) && jv[jss::load_factor] == 200000 && + jv.isMember(jss::load_base) && jv[jss::load_base] == 256 && jv.isMember(jss::load_factor_server) && + jv[jss::load_factor_server] == 256 && jv.isMember(jss::load_factor_fee_escalation) && + jv[jss::load_factor_fee_escalation] == 200000 && jv.isMember(jss::load_factor_fee_queue) && + jv[jss::load_factor_fee_queue] == 256 && jv.isMember(jss::load_factor_fee_reference) && jv[jss::load_factor_fee_reference] == 256; })); env.close(); // Ledger close publishes with escalated fees for queued transactions BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { - return jv[jss::type] == "serverStatus" && - jv.isMember(jss::load_factor) && - jv[jss::load_factor] == 184320 && jv.isMember(jss::load_base) && - jv[jss::load_base] == 256 && - jv.isMember(jss::load_factor_server) && - jv[jss::load_factor_server] == 256 && - jv.isMember(jss::load_factor_fee_escalation) && - jv[jss::load_factor_fee_escalation] == 184320 && - jv.isMember(jss::load_factor_fee_queue) && - jv[jss::load_factor_fee_queue] == 256 && - jv.isMember(jss::load_factor_fee_reference) && + return jv[jss::type] == "serverStatus" && jv.isMember(jss::load_factor) && jv[jss::load_factor] == 184320 && + jv.isMember(jss::load_base) && jv[jss::load_base] == 256 && jv.isMember(jss::load_factor_server) && + jv[jss::load_factor_server] == 256 && jv.isMember(jss::load_factor_fee_escalation) && + jv[jss::load_factor_fee_escalation] == 184320 && jv.isMember(jss::load_factor_fee_queue) && + jv[jss::load_factor_fee_queue] == 256 && jv.isMember(jss::load_factor_fee_reference) && jv[jss::load_factor_fee_reference] == 256; })); env.close(); // ledger close clears queue so fee is back to normal BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { - return jv[jss::type] == "serverStatus" && - jv.isMember(jss::load_factor) && jv[jss::load_factor] == 256 && - jv.isMember(jss::load_base) && jv[jss::load_base] == 256 && - jv.isMember(jss::load_factor_server) && - jv[jss::load_factor_server] == 256 && - jv.isMember(jss::load_factor_fee_escalation) && - jv[jss::load_factor_fee_escalation] == 256 && - jv.isMember(jss::load_factor_fee_queue) && - jv[jss::load_factor_fee_queue] == 256 && - jv.isMember(jss::load_factor_fee_reference) && + return jv[jss::type] == "serverStatus" && jv.isMember(jss::load_factor) && jv[jss::load_factor] == 256 && + jv.isMember(jss::load_base) && jv[jss::load_base] == 256 && jv.isMember(jss::load_factor_server) && + jv[jss::load_factor_server] == 256 && jv.isMember(jss::load_factor_fee_escalation) && + jv[jss::load_factor_fee_escalation] == 256 && jv.isMember(jss::load_factor_fee_queue) && + jv[jss::load_factor_fee_queue] == 256 && jv.isMember(jss::load_factor_fee_reference) && jv[jss::load_factor_fee_reference] == 256; })); - BEAST_EXPECT(!wsc->findMsg(1s, [&](auto const& jv) { - return jv[jss::type] == "serverStatus"; - })); + BEAST_EXPECT(!wsc->findMsg(1s, [&](auto const& jv) { return jv[jss::type] == "serverStatus"; })); auto jv = wsc->invoke("unsubscribe", stream); BEAST_EXPECT(jv[jss::status] == "success"); @@ -3796,8 +3376,7 @@ public: fillQueue(env, alice); auto calcTotalFee = [&](std::int64_t alreadyPaid, - std::optional numToClear = - std::nullopt) -> std::uint64_t { + std::optional numToClear = std::nullopt) -> std::uint64_t { auto totalFactor = 0; auto const metrics = env.app().getTxQ().getMetrics(*env.current()); if (!numToClear) @@ -3809,8 +3388,7 @@ public: } auto const den = (metrics.txPerLedger * metrics.txPerLedger); - FeeLevel64 feeLevel = - (metrics.medFeeLevel * totalFactor + FeeLevel64{den - 1}) / den; + FeeLevel64 feeLevel = (metrics.medFeeLevel * totalFactor + FeeLevel64{den - 1}) / den; auto result = toDrops(feeLevel, env.current()->fees().base).drops(); @@ -3828,10 +3406,7 @@ public: std::uint64_t totalPaid = 0; for (int i = 0; i < 2; ++i) { - env(noop(alice), - fee(baseFee * 10), - seq(aliceSeq++), - ter(terQUEUED)); + env(noop(alice), fee(baseFee * 10), seq(aliceSeq++), ter(terQUEUED)); totalPaid += baseFee * 10; } @@ -3839,10 +3414,7 @@ public: // This will be the first tx to call the operative function, // but it won't succeed. totalPaid += openLedgerCost(env).drops(); - env(noop(alice), - fee(openLedgerCost(env)), - seq(aliceSeq++), - ter(terQUEUED)); + env(noop(alice), fee(openLedgerCost(env)), seq(aliceSeq++), ter(terQUEUED)); checkMetrics(*this, env, 3, std::nullopt, 4, 3); @@ -3876,28 +3448,21 @@ public: uint64_t totalPaid = 0; for (int i = 0; i < 2; ++i) { - env(noop(alice), - fee(baseFee * 10), - seq(aliceSeq++), - ter(terQUEUED)); + env(noop(alice), fee(baseFee * 10), seq(aliceSeq++), ter(terQUEUED)); totalPaid += baseFee * 10; } // Queue up a transaction paying the open ledger fee // This will be the first tx to call the operative function, // but it won't succeed. - env(noop(alice), - fee(openLedgerCost(env)), - seq(aliceSeq++), - ter(terQUEUED)); + env(noop(alice), fee(openLedgerCost(env)), seq(aliceSeq++), ter(terQUEUED)); checkMetrics(*this, env, 3, std::nullopt, 9, 3); // Figure out how much it would cost to cover all the // queued txs + itself auto const metrics = env.app().getTxQ().getMetrics(*env.current()); - std::uint64_t const totalFee = - calcTotalFee(totalPaid, metrics.txCount); + std::uint64_t const totalFee = calcTotalFee(totalPaid, metrics.txCount); // Replacing the last tx with the large fee succeeds. --aliceSeq; env(noop(alice), fee(totalFee), seq(aliceSeq++)); @@ -3916,10 +3481,7 @@ public: auto aliceSeq = env.seq(alice); for (int i = 0; i < 5; ++i) { - env(noop(alice), - fee(baseFee * 10), - seq(aliceSeq++), - ter(terQUEUED)); + env(noop(alice), fee(baseFee * 10), seq(aliceSeq++), ter(terQUEUED)); } checkMetrics(*this, env, 5, 24, 13, 12); @@ -3931,15 +3493,13 @@ public: env(noop(alice), fee(totalFee), seq(aliceSeq++)); checkMetrics(*this, env, 2, 24, 16, 12); - auto const aliceQueue = - env.app().getTxQ().getAccountTxs(alice.id()); + auto const aliceQueue = env.app().getTxQ().getAccountTxs(alice.id()); BEAST_EXPECT(aliceQueue.size() == 2); SeqProxy seq = SeqProxy::sequence(aliceSeq); for (auto const& tx : aliceQueue) { BEAST_EXPECT(tx.seqProxy == seq); - BEAST_EXPECT( - tx.feeLevel == FeeLevel64{baseFeeLevel.fee() * 10}); + BEAST_EXPECT(tx.feeLevel == FeeLevel64{baseFeeLevel.fee() * 10}); seq.advanceBy(1); } @@ -3956,18 +3516,12 @@ public: uint64_t totalPaid = 0; for (int i = 0; i < 2; ++i) { - env(noop(alice), - fee(baseFee * 20), - seq(aliceSeq++), - ter(terQUEUED)); + env(noop(alice), fee(baseFee * 20), seq(aliceSeq++), ter(terQUEUED)); totalPaid += baseFee * 20; } for (int i = 0; i < 2; ++i) { - env(noop(alice), - fee(baseFee * 2.2), - seq(aliceSeq++), - ter(terQUEUED)); + env(noop(alice), fee(baseFee * 2.2), seq(aliceSeq++), ter(terQUEUED)); totalPaid += baseFee * 2.2; } @@ -4188,10 +3742,8 @@ public: // which won't work if unit tests are separated to only // be callable via RPC.) env.app().openLedger().modify([&](OpenView& view, beast::Journal j) { - auto const tx = - env.jt(noop(alice), seq(aliceSeq), fee(openLedgerCost(env))); - auto const result = - xrpl::apply(env.app(), view, *tx.stx, tapUNLIMITED, j); + auto const tx = env.jt(noop(alice), seq(aliceSeq), fee(openLedgerCost(env))); + auto const result = xrpl::apply(env.app(), view, *tx.stx, tapUNLIMITED, j); BEAST_EXPECT(result.ter == tesSUCCESS && result.applied); return result.applied; }); @@ -4258,12 +3810,8 @@ public: // which won't work if unit tests are separated to only // be callable via RPC.) env.app().openLedger().modify([&](OpenView& view, beast::Journal j) { - auto const tx = env.jt( - noop(alice), - ticket::use(tktSeq0 + 1), - fee(openLedgerCost(env))); - auto const result = - xrpl::apply(env.app(), view, *tx.stx, tapUNLIMITED, j); + auto const tx = env.jt(noop(alice), ticket::use(tktSeq0 + 1), fee(openLedgerCost(env))); + auto const result = xrpl::apply(env.app(), view, *tx.stx, tapUNLIMITED, j); BEAST_EXPECT(result.ter == tesSUCCESS && result.applied); return result.applied; }); @@ -4338,12 +3886,9 @@ public: {{"account_reserve", "1000"}, {"owner_reserve", "50"}}); auto& votingSection = cfg->section("voting"); - votingSection.set( - "account_reserve", - std::to_string(cfg->FEES.reference_fee.drops() * 100)); + votingSection.set("account_reserve", std::to_string(cfg->FEES.reference_fee.drops() * 100)); - votingSection.set( - "reference_fee", std::to_string(cfg->FEES.reference_fee.drops())); + votingSection.set("reference_fee", std::to_string(cfg->FEES.reference_fee.drops())); Env env(*this, std::move(cfg)); @@ -4372,13 +3917,7 @@ public: break; } auto expectedPerLedger = xrpl::detail::numUpVotedAmendments() + 1; - checkMetrics( - *this, - env, - 0, - ledgersInQueue * expectedPerLedger, - 0, - expectedPerLedger); + checkMetrics(*this, env, 0, ledgersInQueue * expectedPerLedger, 0, expectedPerLedger); // Now wait 2 weeks modulo 256 ledgers for the amendments to be // enabled. Speed the process by closing ledgers every 80 minutes, @@ -4393,13 +3932,7 @@ public: auto const baseFee = env.current()->fees().base.drops(); // We're very close to the flag ledger. Fill the ledger. fillQueue(env, alice); - checkMetrics( - *this, - env, - 0, - ledgersInQueue * expectedPerLedger, - expectedPerLedger + 1, - expectedPerLedger); + checkMetrics(*this, env, 0, ledgersInQueue * expectedPerLedger, expectedPerLedger + 1, expectedPerLedger); // Fill everyone's queues. auto seqAlice = env.seq(alice); @@ -4411,46 +3944,21 @@ public: // Use fees to guarantee order int txFee{static_cast(baseFee * 9)}; - auto prepareFee = [&](uint64_t multiplier) { - return fee(txFee - multiplier * baseFee / 10); - }; + auto prepareFee = [&](uint64_t multiplier) { return fee(txFee - multiplier * baseFee / 10); }; uint64_t multiplier = 0; for (int i = 0; i < 10; ++i) { - env(noop(alice), - seq(seqAlice++), - prepareFee(++multiplier), - ter(terQUEUED)); - env(noop(bob), - seq(seqBob++), - prepareFee(++multiplier), - ter(terQUEUED)); - env(noop(carol), - seq(seqCarol++), - prepareFee(++multiplier), - ter(terQUEUED)); - env(noop(daria), - seq(seqDaria++), - prepareFee(++multiplier), - ter(terQUEUED)); - env(noop(ellie), - seq(seqEllie++), - prepareFee(++multiplier), - ter(terQUEUED)); - env(noop(fiona), - seq(seqFiona++), - prepareFee(++multiplier), - ter(terQUEUED)); + env(noop(alice), seq(seqAlice++), prepareFee(++multiplier), ter(terQUEUED)); + env(noop(bob), seq(seqBob++), prepareFee(++multiplier), ter(terQUEUED)); + env(noop(carol), seq(seqCarol++), prepareFee(++multiplier), ter(terQUEUED)); + env(noop(daria), seq(seqDaria++), prepareFee(++multiplier), ter(terQUEUED)); + env(noop(ellie), seq(seqEllie++), prepareFee(++multiplier), ter(terQUEUED)); + env(noop(fiona), seq(seqFiona++), prepareFee(++multiplier), ter(terQUEUED)); } std::size_t expectedInQueue = multiplier; checkMetrics( - *this, - env, - expectedInQueue, - ledgersInQueue * expectedPerLedger, - expectedPerLedger + 1, - expectedPerLedger); + *this, env, expectedInQueue, ledgersInQueue * expectedPerLedger, expectedPerLedger + 1, expectedPerLedger); // The next close should cause the in-ledger amendments to change. // Alice's queued transactions have a cached PreflightResult @@ -4465,43 +3973,20 @@ public: { env.close(closeDuration); auto expectedInLedger = expectedInQueue; - expectedInQueue = - (expectedInQueue > expectedPerLedger + 2 - ? expectedInQueue - (expectedPerLedger + 2) - : 0); + expectedInQueue = (expectedInQueue > expectedPerLedger + 2 ? expectedInQueue - (expectedPerLedger + 2) : 0); expectedInLedger -= expectedInQueue; ++expectedPerLedger; checkMetrics( - *this, - env, - expectedInQueue, - ledgersInQueue * expectedPerLedger, - expectedInLedger, - expectedPerLedger); + *this, env, expectedInQueue, ledgersInQueue * expectedPerLedger, expectedInLedger, expectedPerLedger); { auto const expectedPerAccount = expectedInQueue / 6; auto const expectedRemainder = expectedInQueue % 6; BEAST_EXPECT(env.seq(alice) == seqAlice - expectedPerAccount); - BEAST_EXPECT( - env.seq(bob) == - seqBob - expectedPerAccount - - (expectedRemainder > 4 ? 1 : 0)); - BEAST_EXPECT( - env.seq(carol) == - seqCarol - expectedPerAccount - - (expectedRemainder > 3 ? 1 : 0)); - BEAST_EXPECT( - env.seq(daria) == - seqDaria - expectedPerAccount - - (expectedRemainder > 2 ? 1 : 0)); - BEAST_EXPECT( - env.seq(ellie) == - seqEllie - expectedPerAccount - - (expectedRemainder > 1 ? 1 : 0)); - BEAST_EXPECT( - env.seq(fiona) == - seqFiona - expectedPerAccount - - (expectedRemainder > 0 ? 1 : 0)); + BEAST_EXPECT(env.seq(bob) == seqBob - expectedPerAccount - (expectedRemainder > 4 ? 1 : 0)); + BEAST_EXPECT(env.seq(carol) == seqCarol - expectedPerAccount - (expectedRemainder > 3 ? 1 : 0)); + BEAST_EXPECT(env.seq(daria) == seqDaria - expectedPerAccount - (expectedRemainder > 2 ? 1 : 0)); + BEAST_EXPECT(env.seq(ellie) == seqEllie - expectedPerAccount - (expectedRemainder > 1 ? 1 : 0)); + BEAST_EXPECT(env.seq(fiona) == seqFiona - expectedPerAccount - (expectedRemainder > 0 ? 1 : 0)); } } while (expectedInQueue > 0); } @@ -4566,29 +4051,16 @@ public: auto seqAlice = env.seq(alice); auto const seqSaveAlice = seqAlice; int feeDrops = baseFee * 4; - env(noop(alice), - seq(seqAlice++), - fee(--feeDrops), - last_ledger_seq(7), - ter(terQUEUED)); + env(noop(alice), seq(seqAlice++), fee(--feeDrops), last_ledger_seq(7), ter(terQUEUED)); env(noop(alice), seq(seqAlice++), fee(--feeDrops), ter(terQUEUED)); env(noop(alice), seq(seqAlice++), fee(--feeDrops), ter(terQUEUED)); BEAST_EXPECT(env.seq(alice) == seqSaveAlice); // Similarly for bob, but bob uses tickets in his transactions. // The drop penalty works a little differently with tickets. - env(noop(bob), - ticket::use(bobTicketSeq + 0), - last_ledger_seq(7), - ter(terQUEUED)); - env(noop(bob), - ticket::use(bobTicketSeq + 1), - fee(--feeDrops), - ter(terQUEUED)); - env(noop(bob), - ticket::use(bobTicketSeq + 2), - fee(--feeDrops), - ter(terQUEUED)); + env(noop(bob), ticket::use(bobTicketSeq + 0), last_ledger_seq(7), ter(terQUEUED)); + env(noop(bob), ticket::use(bobTicketSeq + 1), fee(--feeDrops), ter(terQUEUED)); + env(noop(bob), ticket::use(bobTicketSeq + 2), fee(--feeDrops), ter(terQUEUED)); // Fill the queue with higher fee transactions so alice's and // bob's transactions are stuck in the queue. @@ -4731,23 +4203,15 @@ public: // Verify that bob's first transaction was removed from the queue // by queueing another low fee transaction into that spot. - env(noop(bob), - ticket::use(bobTicketSeq + 0), - fee(baseFee * 1.2), - ter(terQUEUED)); + env(noop(bob), ticket::use(bobTicketSeq + 0), fee(baseFee * 1.2), ter(terQUEUED)); // Verify that bob's second transaction was removed from the queue // by queueing another low fee transaction into that spot. - env(noop(bob), - ticket::use(bobTicketSeq + 1), - fee(baseFee * 1.1), - ter(terQUEUED)); + env(noop(bob), ticket::use(bobTicketSeq + 1), fee(baseFee * 1.1), ter(terQUEUED)); // Verify that the last entry in bob's queue is still there // by trying to replace it and having that fail. - env(noop(bob), - ticket::use(bobTicketSeq + 2), - ter(telCAN_NOT_QUEUE_FEE)); + env(noop(bob), ticket::use(bobTicketSeq + 2), ter(telCAN_NOT_QUEUE_FEE)); } void @@ -4781,9 +4245,7 @@ public: auto const aliceSeq = env.seq(alice); env(offer(alice, USD(1000), XRP(1000)), ter(terQUEUED)); - env(offer(alice, USD(1000), XRP(1001)), - seq(aliceSeq + 1), - ter(terQUEUED)); + env(offer(alice, USD(1000), XRP(1001)), seq(aliceSeq + 1), ter(terQUEUED)); // Alice creates transactions that cancel the first set of // offers, one through another offer, and one cancel @@ -4792,9 +4254,7 @@ public: json(jss::OfferSequence, aliceSeq), ter(terQUEUED)); - env(offer_cancel(alice, aliceSeq + 1), - seq(aliceSeq + 3), - ter(terQUEUED)); + env(offer_cancel(alice, aliceSeq + 1), seq(aliceSeq + 3), ter(terQUEUED)); env.close(); @@ -4814,13 +4274,9 @@ public: // Alice creates a couple offers using tickets, consuming the // tickets in reverse order auto const aliceSeq = env.seq(alice); - env(offer(alice, USD(1000), XRP(1000)), - ticket::use(aliceTkt + 4), - ter(terQUEUED)); + env(offer(alice, USD(1000), XRP(1000)), ticket::use(aliceTkt + 4), ter(terQUEUED)); - env(offer(alice, USD(1000), XRP(1001)), - ticket::use(aliceTkt + 3), - ter(terQUEUED)); + env(offer(alice, USD(1000), XRP(1001)), ticket::use(aliceTkt + 3), ter(terQUEUED)); // Alice creates a couple more transactions that cancel the first // set of offers, also in reverse order. This allows Alice to submit @@ -4833,16 +4289,12 @@ public: json(jss::OfferSequence, aliceTkt + 4), ter(terQUEUED)); - env(offer_cancel(alice, aliceTkt + 3), - ticket::use(aliceTkt + 1), - ter(terQUEUED)); + env(offer_cancel(alice, aliceTkt + 3), ticket::use(aliceTkt + 1), ter(terQUEUED)); // Create a couple more offers using sequences env(offer(alice, USD(1000), XRP(1000)), ter(terQUEUED)); - env(offer(alice, USD(1000), XRP(1001)), - seq(aliceSeq + 1), - ter(terQUEUED)); + env(offer(alice, USD(1000), XRP(1001)), seq(aliceSeq + 1), ter(terQUEUED)); // And try to cancel those using tickets env(offer(alice, USD(1000), XRP(1002)), @@ -4850,9 +4302,7 @@ public: json(jss::OfferSequence, aliceSeq), ter(terQUEUED)); - env(offer_cancel(alice, aliceSeq + 1), - ticket::use(aliceTkt + 6), - ter(terQUEUED)); + env(offer_cancel(alice, aliceSeq + 1), ticket::use(aliceTkt + 6), ter(terQUEUED)); env.close(); @@ -4876,9 +4326,7 @@ public: *this, makeConfig( {{"minimum_txn_in_ledger_standalone", "3"}}, - {{"reference_fee", "0"}, - {"account_reserve", "0"}, - {"owner_reserve", "0"}})); + {{"reference_fee", "0"}, {"account_reserve", "0"}, {"owner_reserve", "0"}})); checkMetrics(*this, env, 0, std::nullopt, 0, 3); @@ -4890,39 +4338,22 @@ public: { auto const fee = env.rpc("fee"); - if (BEAST_EXPECT(fee.isMember(jss::result)) && - BEAST_EXPECT(!RPC::contains_error(fee[jss::result]))) + if (BEAST_EXPECT(fee.isMember(jss::result)) && BEAST_EXPECT(!RPC::contains_error(fee[jss::result]))) { auto const& result = fee[jss::result]; BEAST_EXPECT(result.isMember(jss::levels)); auto const& levels = result[jss::levels]; - BEAST_EXPECT( - levels.isMember(jss::median_level) && - levels[jss::median_level] == "128000"); - BEAST_EXPECT( - levels.isMember(jss::minimum_level) && - levels[jss::minimum_level] == "256"); - BEAST_EXPECT( - levels.isMember(jss::open_ledger_level) && - levels[jss::open_ledger_level] == "256"); - BEAST_EXPECT( - levels.isMember(jss::reference_level) && - levels[jss::reference_level] == "256"); + BEAST_EXPECT(levels.isMember(jss::median_level) && levels[jss::median_level] == "128000"); + BEAST_EXPECT(levels.isMember(jss::minimum_level) && levels[jss::minimum_level] == "256"); + BEAST_EXPECT(levels.isMember(jss::open_ledger_level) && levels[jss::open_ledger_level] == "256"); + BEAST_EXPECT(levels.isMember(jss::reference_level) && levels[jss::reference_level] == "256"); auto const& drops = result[jss::drops]; - BEAST_EXPECT( - drops.isMember(jss::base_fee) && - drops[jss::base_fee] == "0"); - BEAST_EXPECT( - drops.isMember(jss::median_fee) && - drops[jss::median_fee] == "0"); - BEAST_EXPECT( - drops.isMember(jss::minimum_fee) && - drops[jss::minimum_fee] == "0"); - BEAST_EXPECT( - drops.isMember(jss::open_ledger_fee) && - drops[jss::open_ledger_fee] == "0"); + BEAST_EXPECT(drops.isMember(jss::base_fee) && drops[jss::base_fee] == "0"); + BEAST_EXPECT(drops.isMember(jss::median_fee) && drops[jss::median_fee] == "0"); + BEAST_EXPECT(drops.isMember(jss::minimum_fee) && drops[jss::minimum_fee] == "0"); + BEAST_EXPECT(drops.isMember(jss::open_ledger_fee) && drops[jss::open_ledger_fee] == "0"); } } @@ -4958,39 +4389,22 @@ public: { auto const fee = env.rpc("fee"); - if (BEAST_EXPECT(fee.isMember(jss::result)) && - BEAST_EXPECT(!RPC::contains_error(fee[jss::result]))) + if (BEAST_EXPECT(fee.isMember(jss::result)) && BEAST_EXPECT(!RPC::contains_error(fee[jss::result]))) { auto const& result = fee[jss::result]; BEAST_EXPECT(result.isMember(jss::levels)); auto const& levels = result[jss::levels]; - BEAST_EXPECT( - levels.isMember(jss::median_level) && - levels[jss::median_level] == "128000"); - BEAST_EXPECT( - levels.isMember(jss::minimum_level) && - levels[jss::minimum_level] == "256"); - BEAST_EXPECT( - levels.isMember(jss::open_ledger_level) && - levels[jss::open_ledger_level] == "355555"); - BEAST_EXPECT( - levels.isMember(jss::reference_level) && - levels[jss::reference_level] == "256"); + BEAST_EXPECT(levels.isMember(jss::median_level) && levels[jss::median_level] == "128000"); + BEAST_EXPECT(levels.isMember(jss::minimum_level) && levels[jss::minimum_level] == "256"); + BEAST_EXPECT(levels.isMember(jss::open_ledger_level) && levels[jss::open_ledger_level] == "355555"); + BEAST_EXPECT(levels.isMember(jss::reference_level) && levels[jss::reference_level] == "256"); auto const& drops = result[jss::drops]; - BEAST_EXPECT( - drops.isMember(jss::base_fee) && - drops[jss::base_fee] == "0"); - BEAST_EXPECT( - drops.isMember(jss::median_fee) && - drops[jss::median_fee] == "0"); - BEAST_EXPECT( - drops.isMember(jss::minimum_fee) && - drops[jss::minimum_fee] == "0"); - BEAST_EXPECT( - drops.isMember(jss::open_ledger_fee) && - drops[jss::open_ledger_fee] == "1389"); + BEAST_EXPECT(drops.isMember(jss::base_fee) && drops[jss::base_fee] == "0"); + BEAST_EXPECT(drops.isMember(jss::median_fee) && drops[jss::median_fee] == "0"); + BEAST_EXPECT(drops.isMember(jss::minimum_fee) && drops[jss::minimum_fee] == "0"); + BEAST_EXPECT(drops.isMember(jss::open_ledger_fee) && drops[jss::open_ledger_fee] == "1389"); } } diff --git a/src/test/app/ValidatorKeys_test.cpp b/src/test/app/ValidatorKeys_test.cpp index 943bf5231f..c688b2661f 100644 --- a/src/test/app/ValidatorKeys_test.cpp +++ b/src/test/app/ValidatorKeys_test.cpp @@ -1,12 +1,12 @@ #include -#include #include #include #include #include #include +#include #include @@ -19,8 +19,7 @@ class ValidatorKeys_test : public beast::unit_test::suite std::string const seed = "shUwVw52ofnCUX5m7kPTKzJdr4HEH"; // Used with [validation_token] - std::string const tokenSecretStr = - "paQmjZ37pKKPMrgadBLsuf9ab7Y7EUNzh27LQrZqoexpAs31nJi"; + std::string const tokenSecretStr = "paQmjZ37pKKPMrgadBLsuf9ab7Y7EUNzh27LQrZqoexpAs31nJi"; std::vector const tokenBlob = { " " @@ -61,26 +60,18 @@ public: { // We're only using Env for its Journal. That Journal gives better // coverage in unit tests. - test::jtx::Env env{ - *this, - test::jtx::envconfig(), - nullptr, - beast::severities::kDisabled}; + test::jtx::Env env{*this, test::jtx::envconfig(), nullptr, beast::severities::kDisabled}; beast::Journal journal{env.app().journal("ValidatorKeys_test")}; // Keys/ID when using [validation_seed] - SecretKey const seedSecretKey = - generateSecretKey(KeyType::secp256k1, *parseBase58(seed)); - PublicKey const seedPublicKey = - derivePublicKey(KeyType::secp256k1, seedSecretKey); + SecretKey const seedSecretKey = generateSecretKey(KeyType::secp256k1, *parseBase58(seed)); + PublicKey const seedPublicKey = derivePublicKey(KeyType::secp256k1, seedSecretKey); NodeID const seedNodeID = calcNodeID(seedPublicKey); // Keys when using [validation_token] - auto const tokenSecretKey = - *parseBase58(TokenType::NodePrivate, tokenSecretStr); + auto const tokenSecretKey = *parseBase58(TokenType::NodePrivate, tokenSecretStr); - auto const tokenPublicKey = - derivePublicKey(KeyType::secp256k1, tokenSecretKey); + auto const tokenPublicKey = derivePublicKey(KeyType::secp256k1, tokenSecretKey); auto const m = deserializeManifest(base64_decode(tokenManifest)); BEAST_EXPECT(m); diff --git a/src/test/app/ValidatorList_test.cpp b/src/test/app/ValidatorList_test.cpp index fa3c836cca..4955686966 100644 --- a/src/test/app/ValidatorList_test.cpp +++ b/src/test/app/ValidatorList_test.cpp @@ -42,12 +42,7 @@ private: } static std::string - makeManifestString( - PublicKey const& pk, - SecretKey const& sk, - PublicKey const& spk, - SecretKey const& ssk, - int seq) + makeManifestString(PublicKey const& pk, SecretKey const& sk, PublicKey const& spk, SecretKey const& ssk, int seq) { STObject st(sfGeneric); st[sfSequence] = seq; @@ -59,12 +54,7 @@ private: sign(st, HashPrefix::manifest, *publicKeyType(spk), ssk); } - sign( - st, - HashPrefix::manifest, - *publicKeyType(pk), - sk, - sfMasterSignature); + sign(st, HashPrefix::manifest, *publicKeyType(pk), sk, sfMasterSignature); Serializer s; st.add(s); @@ -79,12 +69,7 @@ private: st[sfSequence] = std::numeric_limits::max(); st[sfPublicKey] = pk; - sign( - st, - HashPrefix::manifest, - *publicKeyType(pk), - sk, - sfMasterSignature); + sign(st, HashPrefix::manifest, *publicKeyType(pk), sk, sfMasterSignature); Serializer s; st.add(s); @@ -101,12 +86,7 @@ private: return { masterPublic, signingKeys.first, - base64_encode(makeManifestString( - masterPublic, - secret, - signingKeys.first, - signingKeys.second, - 1))}; + base64_encode(makeManifestString(masterPublic, secret, signingKeys.first, signingKeys.second, 1))}; } std::string @@ -116,16 +96,16 @@ private: std::size_t validUntil, std::optional validFrom = {}) { - std::string data = "{\"sequence\":" + std::to_string(sequence) + - ",\"expiration\":" + std::to_string(validUntil); + std::string data = + "{\"sequence\":" + std::to_string(sequence) + ",\"expiration\":" + std::to_string(validUntil); if (validFrom) data += ",\"effective\":" + std::to_string(*validFrom); data += ",\"validators\":["; for (auto const& val : validators) { - data += "{\"validation_public_key\":\"" + strHex(val.masterPublic) + - "\",\"manifest\":\"" + val.manifest + "\"},"; + data += "{\"validation_public_key\":\"" + strHex(val.masterPublic) + "\",\"manifest\":\"" + val.manifest + + "\"},"; } data.pop_back(); @@ -134,9 +114,7 @@ private: } std::string - signList( - std::string const& blob, - std::pair const& keys) + signList(std::string const& blob, std::pair const& keys) { auto const data = base64_decode(blob); return strHex(sign(keys.first, keys.second, makeSlice(data))); @@ -176,22 +154,13 @@ private: auto& app = env.app(); { auto trustedKeys = std::make_unique( - manifests, - manifests, - env.timeKeeper(), - app.config().legacy("database_path"), - env.journal); + manifests, manifests, env.timeKeeper(), app.config().legacy("database_path"), env.journal); BEAST_EXPECT(trustedKeys->quorum() == 1); } { std::size_t minQuorum = 0; auto trustedKeys = std::make_unique( - manifests, - manifests, - env.timeKeeper(), - app.config().legacy("database_path"), - env.journal, - minQuorum); + manifests, manifests, env.timeKeeper(), app.config().legacy("database_path"), env.journal, minQuorum); BEAST_EXPECT(trustedKeys->quorum() == minQuorum); } } @@ -201,8 +170,7 @@ private: { testcase("Config Load"); - jtx::Env env( - *this, jtx::envconfig(), nullptr, beast::severities::kDisabled); + jtx::Env env(*this, jtx::envconfig(), nullptr, beast::severities::kDisabled); auto& app = env.app(); std::vector const emptyCfgKeys; std::vector const emptyCfgPublishers; @@ -211,18 +179,12 @@ private: auto const localSigningPublicOuter = localSigningKeys.first; auto const localSigningSecret = localSigningKeys.second; auto const localMasterSecret = randomSecretKey(); - auto const localMasterPublic = - derivePublicKey(KeyType::ed25519, localMasterSecret); + auto const localMasterPublic = derivePublicKey(KeyType::ed25519, localMasterSecret); - std::string const cfgManifest(makeManifestString( - localMasterPublic, - localMasterSecret, - localSigningPublicOuter, - localSigningSecret, - 1)); + std::string const cfgManifest( + makeManifestString(localMasterPublic, localMasterSecret, localSigningPublicOuter, localSigningSecret, 1)); - auto format = [](PublicKey const& publicKey, - char const* comment = nullptr) { + auto format = [](PublicKey const& publicKey, char const* comment = nullptr) { auto ret = toBase58(TokenType::NodePublic, publicKey); if (comment) @@ -245,32 +207,23 @@ private: format(configList[3], " Leading Whitespace"), format(configList[4], " Trailing Whitespace "), format(configList[5], " Leading & Trailing Whitespace "), - format( - configList[6], - " Leading, Trailing & Internal Whitespace "), + format(configList[6], " Leading, Trailing & Internal Whitespace "), format(configList[7], " ")}); { ManifestCache manifests; auto trustedKeys = std::make_unique( - manifests, - manifests, - env.timeKeeper(), - app.config().legacy("database_path"), - env.journal); + manifests, manifests, env.timeKeeper(), app.config().legacy("database_path"), env.journal); // Correct (empty) configuration - BEAST_EXPECT( - trustedKeys->load({}, emptyCfgKeys, emptyCfgPublishers)); + BEAST_EXPECT(trustedKeys->load({}, emptyCfgKeys, emptyCfgPublishers)); // load local validator key with or without manifest - BEAST_EXPECT(trustedKeys->load( - localSigningPublicOuter, emptyCfgKeys, emptyCfgPublishers)); + BEAST_EXPECT(trustedKeys->load(localSigningPublicOuter, emptyCfgKeys, emptyCfgPublishers)); BEAST_EXPECT(trustedKeys->listed(localSigningPublicOuter)); manifests.applyManifest(*deserializeManifest(cfgManifest)); - BEAST_EXPECT(trustedKeys->load( - localSigningPublicOuter, emptyCfgKeys, emptyCfgPublishers)); + BEAST_EXPECT(trustedKeys->load(localSigningPublicOuter, emptyCfgKeys, emptyCfgPublishers)); BEAST_EXPECT(trustedKeys->listed(localMasterPublic)); BEAST_EXPECT(trustedKeys->listed(localSigningPublicOuter)); @@ -279,11 +232,7 @@ private: // load should add validator keys from config ManifestCache manifests; auto trustedKeys = std::make_unique( - manifests, - manifests, - env.timeKeeper(), - app.config().legacy("database_path"), - env.journal); + manifests, manifests, env.timeKeeper(), app.config().legacy("database_path"), env.journal); BEAST_EXPECT(trustedKeys->load({}, cfgKeys, emptyCfgPublishers)); @@ -294,42 +243,29 @@ private: auto const masterNode1 = randomMasterKey(); auto const masterNode2 = randomMasterKey(); - std::vector cfgMasterKeys( - {format(masterNode1), format(masterNode2, " Comment")}); - BEAST_EXPECT( - trustedKeys->load({}, cfgMasterKeys, emptyCfgPublishers)); + std::vector cfgMasterKeys({format(masterNode1), format(masterNode2, " Comment")}); + BEAST_EXPECT(trustedKeys->load({}, cfgMasterKeys, emptyCfgPublishers)); BEAST_EXPECT(trustedKeys->listed(masterNode1)); BEAST_EXPECT(trustedKeys->listed(masterNode2)); // load should reject invalid config keys - BEAST_EXPECT( - !trustedKeys->load({}, {"NotAPublicKey"}, emptyCfgPublishers)); - BEAST_EXPECT(!trustedKeys->load( - {}, {format(randomNode(), "!")}, emptyCfgPublishers)); + BEAST_EXPECT(!trustedKeys->load({}, {"NotAPublicKey"}, emptyCfgPublishers)); + BEAST_EXPECT(!trustedKeys->load({}, {format(randomNode(), "!")}, emptyCfgPublishers)); // load terminates when encountering an invalid entry auto const goodKey = randomNode(); - BEAST_EXPECT(!trustedKeys->load( - {}, - {format(randomNode(), "!"), format(goodKey)}, - emptyCfgPublishers)); + BEAST_EXPECT(!trustedKeys->load({}, {format(randomNode(), "!"), format(goodKey)}, emptyCfgPublishers)); BEAST_EXPECT(!trustedKeys->listed(goodKey)); } { // local validator key on config list ManifestCache manifests; auto trustedKeys = std::make_unique( - manifests, - manifests, - env.timeKeeper(), - app.config().legacy("database_path"), - env.journal); + manifests, manifests, env.timeKeeper(), app.config().legacy("database_path"), env.journal); - auto const localSigningPublic = - parseBase58(TokenType::NodePublic, cfgKeys.front()); + auto const localSigningPublic = parseBase58(TokenType::NodePublic, cfgKeys.front()); - BEAST_EXPECT(trustedKeys->load( - *localSigningPublic, cfgKeys, emptyCfgPublishers)); + BEAST_EXPECT(trustedKeys->load(*localSigningPublic, cfgKeys, emptyCfgPublishers)); BEAST_EXPECT(trustedKeys->localPublicKey() == localSigningPublic); BEAST_EXPECT(trustedKeys->listed(*localSigningPublic)); @@ -340,15 +276,10 @@ private: // local validator key not on config list ManifestCache manifests; auto trustedKeys = std::make_unique( - manifests, - manifests, - env.timeKeeper(), - app.config().legacy("database_path"), - env.journal); + manifests, manifests, env.timeKeeper(), app.config().legacy("database_path"), env.journal); auto const localSigningPublic = randomNode(); - BEAST_EXPECT(trustedKeys->load( - localSigningPublic, cfgKeys, emptyCfgPublishers)); + BEAST_EXPECT(trustedKeys->load(localSigningPublic, cfgKeys, emptyCfgPublishers)); BEAST_EXPECT(trustedKeys->localPublicKey() == localSigningPublic); BEAST_EXPECT(trustedKeys->listed(localSigningPublic)); @@ -359,16 +290,11 @@ private: // local validator key (with manifest) not on config list ManifestCache manifests; auto trustedKeys = std::make_unique( - manifests, - manifests, - env.timeKeeper(), - app.config().legacy("database_path"), - env.journal); + manifests, manifests, env.timeKeeper(), app.config().legacy("database_path"), env.journal); manifests.applyManifest(*deserializeManifest(cfgManifest)); - BEAST_EXPECT(trustedKeys->load( - localSigningPublicOuter, cfgKeys, emptyCfgPublishers)); + BEAST_EXPECT(trustedKeys->load(localSigningPublicOuter, cfgKeys, emptyCfgPublishers)); BEAST_EXPECT(trustedKeys->localPublicKey() == localMasterPublic); BEAST_EXPECT(trustedKeys->listed(localSigningPublicOuter)); @@ -379,11 +305,7 @@ private: { ManifestCache manifests; auto trustedKeys = std::make_unique( - manifests, - manifests, - env.timeKeeper(), - app.config().legacy("database_path"), - env.journal); + manifests, manifests, env.timeKeeper(), app.config().legacy("database_path"), env.journal); // load should reject invalid validator list signing keys std::vector badPublishers({"NotASigningKey"}); @@ -391,8 +313,7 @@ private: // load should reject validator list signing keys with invalid // encoding - std::vector keys( - {randomMasterKey(), randomMasterKey(), randomMasterKey()}); + std::vector keys({randomMasterKey(), randomMasterKey(), randomMasterKey()}); badPublishers.clear(); for (auto const& key : keys) badPublishers.push_back(toBase58(TokenType::NodePublic, key)); @@ -409,30 +330,20 @@ private: BEAST_EXPECT(trustedKeys->load({}, emptyCfgKeys, cfgPublishers)); for (auto const& key : keys) BEAST_EXPECT(trustedKeys->trustedPublisher(key)); - BEAST_EXPECT( - trustedKeys->getListThreshold() == keys.size() / 2 + 1); + BEAST_EXPECT(trustedKeys->getListThreshold() == keys.size() / 2 + 1); } { ManifestCache manifests; auto trustedKeys = std::make_unique( - manifests, - manifests, - env.timeKeeper(), - app.config().legacy("database_path"), - env.journal); + manifests, manifests, env.timeKeeper(), app.config().legacy("database_path"), env.journal); - std::vector keys( - {randomMasterKey(), - randomMasterKey(), - randomMasterKey(), - randomMasterKey()}); + std::vector keys({randomMasterKey(), randomMasterKey(), randomMasterKey(), randomMasterKey()}); std::vector cfgPublishers; for (auto const& key : keys) cfgPublishers.push_back(strHex(key)); // explicitly set the list threshold - BEAST_EXPECT(trustedKeys->load( - {}, emptyCfgKeys, cfgPublishers, std::size_t(2))); + BEAST_EXPECT(trustedKeys->load({}, emptyCfgKeys, cfgPublishers, std::size_t(2))); for (auto const& key : keys) BEAST_EXPECT(trustedKeys->trustedPublisher(key)); BEAST_EXPECT(trustedKeys->getListThreshold() == 2); @@ -443,15 +354,10 @@ private: ManifestCache valManifests; ManifestCache pubManifests; auto trustedKeys = std::make_unique( - valManifests, - pubManifests, - env.timeKeeper(), - app.config().legacy("database_path"), - env.journal); + valManifests, pubManifests, env.timeKeeper(), app.config().legacy("database_path"), env.journal); auto const pubRevokedSecret = randomSecretKey(); - auto const pubRevokedPublic = - derivePublicKey(KeyType::ed25519, pubRevokedSecret); + auto const pubRevokedPublic = derivePublicKey(KeyType::ed25519, pubRevokedSecret); auto const pubRevokedSigning = randomKeyPair(KeyType::secp256k1); // make this manifest revoked (seq num = max) // -- thus should not be loaded @@ -466,8 +372,7 @@ private: auto legitKey1 = randomMasterKey(); auto legitKey2 = randomMasterKey(); - std::vector cfgPublishers = { - strHex(pubRevokedPublic), strHex(legitKey1), strHex(legitKey2)}; + std::vector cfgPublishers = {strHex(pubRevokedPublic), strHex(legitKey1), strHex(legitKey2)}; BEAST_EXPECT(trustedKeys->load({}, emptyCfgKeys, cfgPublishers)); BEAST_EXPECT(!trustedKeys->trustedPublisher(pubRevokedPublic)); @@ -482,15 +387,10 @@ private: ManifestCache valManifests; ManifestCache pubManifests; auto trustedKeys = std::make_unique( - valManifests, - pubManifests, - env.timeKeeper(), - app.config().legacy("database_path"), - env.journal); + valManifests, pubManifests, env.timeKeeper(), app.config().legacy("database_path"), env.journal); auto const pubRevokedSecret = randomSecretKey(); - auto const pubRevokedPublic = - derivePublicKey(KeyType::ed25519, pubRevokedSecret); + auto const pubRevokedPublic = derivePublicKey(KeyType::ed25519, pubRevokedSecret); auto const pubRevokedSigning = randomKeyPair(KeyType::secp256k1); // make this manifest revoked (seq num = max) // -- thus should not be loaded @@ -504,10 +404,8 @@ private: // this one is not revoked (and not in the manifest cache at all.) auto legitKey = randomMasterKey(); - std::vector cfgPublishers = { - strHex(pubRevokedPublic), strHex(legitKey)}; - BEAST_EXPECT(trustedKeys->load( - {}, emptyCfgKeys, cfgPublishers, std::size_t(2))); + std::vector cfgPublishers = {strHex(pubRevokedPublic), strHex(legitKey)}; + BEAST_EXPECT(trustedKeys->load({}, emptyCfgKeys, cfgPublishers, std::size_t(2))); BEAST_EXPECT(!trustedKeys->trustedPublisher(pubRevokedPublic)); BEAST_EXPECT(trustedKeys->trustedPublisher(legitKey)); @@ -524,93 +422,74 @@ private: std::string const siteUri = "testApplyList.test"; - auto checkAvailable = - [this]( - auto const& trustedKeys, - auto const& hexPublic, - auto const& manifest, - auto const version, - std::vector> const& - expected) { - auto const available = trustedKeys->getAvailable(hexPublic); + auto checkAvailable = [this]( + auto const& trustedKeys, + auto const& hexPublic, + auto const& manifest, + auto const version, + std::vector> const& expected) { + auto const available = trustedKeys->getAvailable(hexPublic); - BEAST_EXPECT(!version || available); - if (available) + BEAST_EXPECT(!version || available); + if (available) + { + auto const& a = *available; + BEAST_EXPECT(a[jss::public_key] == hexPublic); + BEAST_EXPECT(a[jss::manifest] == manifest); + // Because multiple lists were processed, the version was + // overridden + BEAST_EXPECT(a[jss::version] == version); + if (version == 1) { - auto const& a = *available; - BEAST_EXPECT(a[jss::public_key] == hexPublic); - BEAST_EXPECT(a[jss::manifest] == manifest); - // Because multiple lists were processed, the version was - // overridden - BEAST_EXPECT(a[jss::version] == version); - if (version == 1) - { - BEAST_EXPECT(expected.size() == 1); - BEAST_EXPECT(a[jss::blob] == expected[0].first); - BEAST_EXPECT(a[jss::signature] == expected[0].second); - BEAST_EXPECT(!a.isMember(jss::blobs_v2)); - } - else if (BEAST_EXPECT(a.isMember(jss::blobs_v2))) - { - BEAST_EXPECT(!a.isMember(jss::blob)); - BEAST_EXPECT(!a.isMember(jss::signature)); - auto const& blobs_v2 = a[jss::blobs_v2]; - BEAST_EXPECT( - blobs_v2.isArray() && - blobs_v2.size() == expected.size()); + BEAST_EXPECT(expected.size() == 1); + BEAST_EXPECT(a[jss::blob] == expected[0].first); + BEAST_EXPECT(a[jss::signature] == expected[0].second); + BEAST_EXPECT(!a.isMember(jss::blobs_v2)); + } + else if (BEAST_EXPECT(a.isMember(jss::blobs_v2))) + { + BEAST_EXPECT(!a.isMember(jss::blob)); + BEAST_EXPECT(!a.isMember(jss::signature)); + auto const& blobs_v2 = a[jss::blobs_v2]; + BEAST_EXPECT(blobs_v2.isArray() && blobs_v2.size() == expected.size()); - for (unsigned int i = 0; i < expected.size(); ++i) - { - BEAST_EXPECT( - blobs_v2[i][jss::blob] == expected[i].first); - BEAST_EXPECT( - blobs_v2[i][jss::signature] == - expected[i].second); - } + for (unsigned int i = 0; i < expected.size(); ++i) + { + BEAST_EXPECT(blobs_v2[i][jss::blob] == expected[i].first); + BEAST_EXPECT(blobs_v2[i][jss::signature] == expected[i].second); } } - }; + } + }; ManifestCache manifests; jtx::Env env(*this); auto& app = env.app(); auto trustedKeys = std::make_unique( - manifests, - manifests, - env.app().timeKeeper(), - app.config().legacy("database_path"), - env.journal); + manifests, manifests, env.app().timeKeeper(), app.config().legacy("database_path"), env.journal); - auto expectTrusted = - [this, &trustedKeys](std::vector const& list) { - for (auto const& val : list) - { - BEAST_EXPECT(trustedKeys->listed(val.masterPublic)); - BEAST_EXPECT(trustedKeys->listed(val.signingPublic)); - } - }; + auto expectTrusted = [this, &trustedKeys](std::vector const& list) { + for (auto const& val : list) + { + BEAST_EXPECT(trustedKeys->listed(val.masterPublic)); + BEAST_EXPECT(trustedKeys->listed(val.signingPublic)); + } + }; - auto expectUntrusted = - [this, &trustedKeys](std::vector const& list) { - for (auto const& val : list) - { - BEAST_EXPECT(!trustedKeys->listed(val.masterPublic)); - BEAST_EXPECT(!trustedKeys->listed(val.signingPublic)); - } - }; + auto expectUntrusted = [this, &trustedKeys](std::vector const& list) { + for (auto const& val : list) + { + BEAST_EXPECT(!trustedKeys->listed(val.masterPublic)); + BEAST_EXPECT(!trustedKeys->listed(val.signingPublic)); + } + }; auto const publisherSecret = randomSecretKey(); - auto const publisherPublic = - derivePublicKey(KeyType::ed25519, publisherSecret); - auto const hexPublic = - strHex(publisherPublic.begin(), publisherPublic.end()); + auto const publisherPublic = derivePublicKey(KeyType::ed25519, publisherSecret); + auto const hexPublic = strHex(publisherPublic.begin(), publisherPublic.end()); auto const pubSigningKeys1 = randomKeyPair(KeyType::secp256k1); - auto const manifest1 = base64_encode(makeManifestString( - publisherPublic, - publisherSecret, - pubSigningKeys1.first, - pubSigningKeys1.second, - 1)); + auto const manifest1 = base64_encode( + makeManifestString(publisherPublic, publisherSecret, pubSigningKeys1.first, pubSigningKeys1.second, 1)); std::vector cfgKeys1({strHex(publisherPublic)}); std::vector emptyCfgKeys; @@ -636,32 +515,23 @@ private: env.timeKeeper().set(env.timeKeeper().now() + 1s); auto const version = 1; auto const sequence1 = 1; - auto const expiredblob = makeList( - lists.at(1), - sequence1, - env.timeKeeper().now().time_since_epoch().count()); + auto const expiredblob = makeList(lists.at(1), sequence1, env.timeKeeper().now().time_since_epoch().count()); auto const expiredSig = signList(expiredblob, pubSigningKeys1); NetClock::time_point const validUntil = env.timeKeeper().now() + 3600s; auto const sequence2 = 2; - auto const blob2 = makeList( - lists.at(2), sequence2, validUntil.time_since_epoch().count()); + auto const blob2 = makeList(lists.at(2), sequence2, validUntil.time_since_epoch().count()); auto const sig2 = signList(blob2, pubSigningKeys1); checkResult( - trustedKeys->applyLists( - manifest1, - version, - {{expiredblob, expiredSig, {}}, {blob2, sig2, {}}}, - siteUri), + trustedKeys->applyLists(manifest1, version, {{expiredblob, expiredSig, {}}, {blob2, sig2, {}}}, siteUri), publisherPublic, ListDisposition::expired, ListDisposition::accepted); expectTrusted(lists.at(2)); - checkAvailable( - trustedKeys, hexPublic, manifest1, version, {{blob2, sig2}}); + checkAvailable(trustedKeys, hexPublic, manifest1, version, {{blob2, sig2}}); // Do not apply future lists, but process them auto const version2 = 2; @@ -669,28 +539,18 @@ private: auto const effective7 = validUntil - 60s; auto const expiration7 = effective7 + 3600s; auto const blob7 = makeList( - lists.at(7), - sequence7, - expiration7.time_since_epoch().count(), - effective7.time_since_epoch().count()); + lists.at(7), sequence7, expiration7.time_since_epoch().count(), effective7.time_since_epoch().count()); auto const sig7 = signList(blob7, pubSigningKeys1); auto const sequence8 = 8; auto const effective8 = expiration7 - 60s; auto const expiration8 = effective8 + 3600s; auto const blob8 = makeList( - lists.at(8), - sequence8, - expiration8.time_since_epoch().count(), - effective8.time_since_epoch().count()); + lists.at(8), sequence8, expiration8.time_since_epoch().count(), effective8.time_since_epoch().count()); auto const sig8 = signList(blob8, pubSigningKeys1); checkResult( - trustedKeys->applyLists( - manifest1, - version2, - {{blob7, sig7, {}}, {blob8, sig8, {}}}, - siteUri), + trustedKeys->applyLists(manifest1, version2, {{blob7, sig7, {}}, {blob8, sig8, {}}}, siteUri), publisherPublic, ListDisposition::pending, ListDisposition::pending); @@ -703,10 +563,7 @@ private: auto const effective6 = effective7 - 60s; auto const expiration6 = effective6 + 3600s; auto const blob6 = makeList( - lists.at(6), - sequence6, - expiration6.time_since_epoch().count(), - effective6.time_since_epoch().count()); + lists.at(6), sequence6, expiration6.time_since_epoch().count(), effective6.time_since_epoch().count()); auto const sig6 = signList(blob6, pubSigningKeys1); // Process future list that is overridden by a later list @@ -714,18 +571,11 @@ private: auto const effective6a = effective6 + 60s; auto const expiration6a = effective6a + 3600s; auto const blob6a = makeList( - lists.at(5), - sequence6a, - expiration6a.time_since_epoch().count(), - effective6a.time_since_epoch().count()); + lists.at(5), sequence6a, expiration6a.time_since_epoch().count(), effective6a.time_since_epoch().count()); auto const sig6a = signList(blob6a, pubSigningKeys1); checkResult( - trustedKeys->applyLists( - manifest1, - version, - {{blob6a, sig6a, {}}, {blob6, sig6, {}}}, - siteUri), + trustedKeys->applyLists(manifest1, version, {{blob6a, sig6a, {}}, {blob6, sig6, {}}}, siteUri), publisherPublic, ListDisposition::pending, ListDisposition::pending); @@ -736,11 +586,7 @@ private: // Do not apply re-process lists known future sequence numbers checkResult( - trustedKeys->applyLists( - manifest1, - version, - {{blob7, sig7, {}}, {blob6, sig6, {}}}, - siteUri), + trustedKeys->applyLists(manifest1, version, {{blob7, sig7, {}}, {blob6, sig6, {}}}, siteUri), publisherPublic, ListDisposition::known_sequence, ListDisposition::known_sequence); @@ -751,33 +597,24 @@ private: // try empty or mangled manifest checkResult( - trustedKeys->applyLists( - "", version, {{blob7, sig7, {}}, {blob6, sig6, {}}}, siteUri), + trustedKeys->applyLists("", version, {{blob7, sig7, {}}, {blob6, sig6, {}}}, siteUri), publisherPublic, ListDisposition::invalid, ListDisposition::invalid); checkResult( trustedKeys->applyLists( - base64_encode("not a manifest"), - version, - {{blob7, sig7, {}}, {blob6, sig6, {}}}, - siteUri), + base64_encode("not a manifest"), version, {{blob7, sig7, {}}, {blob6, sig6, {}}}, siteUri), publisherPublic, ListDisposition::invalid, ListDisposition::invalid); // do not use list from untrusted publisher - auto const untrustedManifest = base64_encode(makeManifestString( - randomMasterKey(), - publisherSecret, - pubSigningKeys1.first, - pubSigningKeys1.second, - 1)); + auto const untrustedManifest = base64_encode( + makeManifestString(randomMasterKey(), publisherSecret, pubSigningKeys1.first, pubSigningKeys1.second, 1)); checkResult( - trustedKeys->applyLists( - untrustedManifest, version, {{blob2, sig2, {}}}, siteUri), + trustedKeys->applyLists(untrustedManifest, version, {{blob2, sig2, {}}}, siteUri), publisherPublic, ListDisposition::untrusted, ListDisposition::untrusted); @@ -785,21 +622,18 @@ private: // do not use list with unhandled version auto const badVersion = 666; checkResult( - trustedKeys->applyLists( - manifest1, badVersion, {{blob2, sig2, {}}}, siteUri), + trustedKeys->applyLists(manifest1, badVersion, {{blob2, sig2, {}}}, siteUri), publisherPublic, ListDisposition::unsupported_version, ListDisposition::unsupported_version); // apply list with highest sequence number auto const sequence3 = 3; - auto const blob3 = makeList( - lists.at(3), sequence3, validUntil.time_since_epoch().count()); + auto const blob3 = makeList(lists.at(3), sequence3, validUntil.time_since_epoch().count()); auto const sig3 = signList(blob3, pubSigningKeys1); checkResult( - trustedKeys->applyLists( - manifest1, version, {{blob3, sig3, {}}}, siteUri), + trustedKeys->applyLists(manifest1, version, {{blob3, sig3, {}}}, siteUri), publisherPublic, ListDisposition::accepted, ListDisposition::accepted); @@ -811,19 +645,11 @@ private: // Note that blob6a is not present, because it was dropped during // processing checkAvailable( - trustedKeys, - hexPublic, - manifest1, - 2, - {{blob3, sig3}, {blob6, sig6}, {blob7, sig7}, {blob8, sig8}}); + trustedKeys, hexPublic, manifest1, 2, {{blob3, sig3}, {blob6, sig6}, {blob7, sig7}, {blob8, sig8}}); // do not re-apply lists with past or current sequence numbers checkResult( - trustedKeys->applyLists( - manifest1, - version, - {{blob2, sig2, {}}, {blob3, sig3, {}}}, - siteUri), + trustedKeys->applyLists(manifest1, version, {{blob2, sig2, {}}, {blob3, sig3, {}}}, siteUri), publisherPublic, ListDisposition::stale, ListDisposition::same_sequence); @@ -831,26 +657,16 @@ private: // apply list with new publisher key updated by manifest. Also send some // old lists along with the old manifest auto const pubSigningKeys2 = randomKeyPair(KeyType::secp256k1); - auto manifest2 = base64_encode(makeManifestString( - publisherPublic, - publisherSecret, - pubSigningKeys2.first, - pubSigningKeys2.second, - 2)); + auto manifest2 = base64_encode( + makeManifestString(publisherPublic, publisherSecret, pubSigningKeys2.first, pubSigningKeys2.second, 2)); auto const sequence4 = 4; - auto const blob4 = makeList( - lists.at(4), sequence4, validUntil.time_since_epoch().count()); + auto const blob4 = makeList(lists.at(4), sequence4, validUntil.time_since_epoch().count()); auto const sig4 = signList(blob4, pubSigningKeys2); checkResult( trustedKeys->applyLists( - manifest2, - version, - {{blob2, sig2, manifest1}, - {blob3, sig3, manifest1}, - {blob4, sig4, {}}}, - siteUri), + manifest2, version, {{blob2, sig2, manifest1}, {blob3, sig3, manifest1}, {blob4, sig4, {}}}, siteUri), publisherPublic, ListDisposition::stale, ListDisposition::accepted); @@ -860,19 +676,13 @@ private: expectTrusted(lists.at(4)); checkAvailable( - trustedKeys, - hexPublic, - manifest2, - 2, - {{blob4, sig4}, {blob6, sig6}, {blob7, sig7}, {blob8, sig8}}); + trustedKeys, hexPublic, manifest2, 2, {{blob4, sig4}, {blob6, sig6}, {blob7, sig7}, {blob8, sig8}}); auto const sequence5 = 5; - auto const blob5 = makeList( - lists.at(5), sequence5, validUntil.time_since_epoch().count()); + auto const blob5 = makeList(lists.at(5), sequence5, validUntil.time_since_epoch().count()); auto const badSig = signList(blob5, pubSigningKeys1); checkResult( - trustedKeys->applyLists( - manifest1, version, {{blob5, badSig, {}}}, siteUri), + trustedKeys->applyLists(manifest1, version, {{blob5, badSig, {}}}, siteUri), publisherPublic, ListDisposition::invalid, ListDisposition::invalid); @@ -884,11 +694,7 @@ private: // Reprocess the pending list, but the signature is no longer valid checkResult( - trustedKeys->applyLists( - manifest1, - version, - {{blob7, sig7, {}}, {blob8, sig8, {}}}, - siteUri), + trustedKeys->applyLists(manifest1, version, {{blob7, sig7, {}}, {blob8, sig8, {}}}, siteUri), publisherPublic, ListDisposition::invalid, ListDisposition::invalid); @@ -901,21 +707,12 @@ private: // updateTrusted. Note that the timekeeper is NOT moved, so the close // time will be ahead of the test's wall clock trustedKeys->updateTrusted( - {}, - effective6 + 1s, - env.app().getOPs(), - env.app().overlay(), - env.app().getHashRouter()); + {}, effective6 + 1s, env.app().getOPs(), env.app().overlay(), env.app().getHashRouter()); expectUntrusted(lists.at(3)); expectTrusted(lists.at(6)); - checkAvailable( - trustedKeys, - hexPublic, - manifest2, - 2, - {{blob6, sig6}, {blob7, sig7}, {blob8, sig8}}); + checkAvailable(trustedKeys, hexPublic, manifest2, 2, {{blob6, sig6}, {blob7, sig7}, {blob8, sig8}}); // Automatically rotate the LAST pending list using updateTrusted, // bypassing blob7. Note that the timekeeper IS moved, so the provided @@ -923,11 +720,7 @@ private: // clock is used. env.timeKeeper().set(effective8); trustedKeys->updateTrusted( - {}, - effective8 + 1s, - env.app().getOPs(), - env.app().overlay(), - env.app().getHashRouter()); + {}, effective8 + 1s, env.app().getOPs(), env.app().overlay(), env.app().getHashRouter()); expectUntrusted(lists.at(6)); expectUntrusted(lists.at(7)); @@ -942,11 +735,7 @@ private: auto const sig8_2 = signList(blob8, pubSigningKeys2); checkResult( - trustedKeys->applyLists( - manifest2, - version, - {{blob8, sig8, manifest1}, {blob8, sig8_2, {}}}, - siteUri), + trustedKeys->applyLists(manifest2, version, {{blob8, sig8, manifest1}, {blob8, sig8_2, {}}}, siteUri), publisherPublic, ListDisposition::invalid, ListDisposition::same_sequence); @@ -958,17 +747,14 @@ private: // do not apply list with revoked publisher key // applied list is removed due to revoked publisher key auto const signingKeysMax = randomKeyPair(KeyType::secp256k1); - auto maxManifest = base64_encode( - makeRevocationString(publisherPublic, publisherSecret)); + auto maxManifest = base64_encode(makeRevocationString(publisherPublic, publisherSecret)); auto const sequence9 = 9; - auto const blob9 = makeList( - lists.at(9), sequence9, validUntil.time_since_epoch().count()); + auto const blob9 = makeList(lists.at(9), sequence9, validUntil.time_since_epoch().count()); auto const sig9 = signList(blob9, signingKeysMax); checkResult( - trustedKeys->applyLists( - maxManifest, version, {{blob9, sig9, {}}}, siteUri), + trustedKeys->applyLists(maxManifest, version, {{blob9, sig9, {}}}, siteUri), publisherPublic, ListDisposition::untrusted, ListDisposition::untrusted); @@ -995,24 +781,14 @@ private: jtx::Env env(*this); auto& app = env.app(); auto trustedKeys = std::make_unique( - manifests, - manifests, - env.app().timeKeeper(), - app.config().legacy("database_path"), - env.journal); + manifests, manifests, env.app().timeKeeper(), app.config().legacy("database_path"), env.journal); auto const publisherSecret = randomSecretKey(); - auto const publisherPublic = - derivePublicKey(KeyType::ed25519, publisherSecret); - auto const hexPublic = - strHex(publisherPublic.begin(), publisherPublic.end()); + auto const publisherPublic = derivePublicKey(KeyType::ed25519, publisherSecret); + auto const hexPublic = strHex(publisherPublic.begin(), publisherPublic.end()); auto const pubSigningKeys1 = randomKeyPair(KeyType::secp256k1); - auto const manifest = base64_encode(makeManifestString( - publisherPublic, - publisherSecret, - pubSigningKeys1.first, - pubSigningKeys1.second, - 1)); + auto const manifest = base64_encode( + makeManifestString(publisherPublic, publisherSecret, pubSigningKeys1.first, pubSigningKeys1.second, 1)); std::vector cfgKeys1({strHex(publisherPublic)}); std::vector emptyCfgKeys; @@ -1031,8 +807,7 @@ private: // Process a list env.timeKeeper().set(env.timeKeeper().now() + 1s); NetClock::time_point const validUntil = env.timeKeeper().now() + 3600s; - auto const blob = - makeList(list, 1, validUntil.time_since_epoch().count()); + auto const blob = makeList(list, 1, validUntil.time_since_epoch().count()); auto const sig = signList(blob, pubSigningKeys1); { @@ -1042,13 +817,12 @@ private: } BEAST_EXPECT( - trustedKeys->applyLists(manifest, 1, {{blob, sig, {}}}, siteUri) - .bestDisposition() == ListDisposition::accepted); + trustedKeys->applyLists(manifest, 1, {{blob, sig, {}}}, siteUri).bestDisposition() == + ListDisposition::accepted); { // invalid public key - auto const available = - trustedKeys->getAvailable(hexPublic + "invalid", 1); + auto const available = trustedKeys->getAvailable(hexPublic + "invalid", 1); BEAST_EXPECT(!available); } @@ -1130,11 +904,7 @@ private: jtx::Env env(*this); auto& app = env.app(); auto trustedKeysOuter = std::make_unique( - manifestsOuter, - manifestsOuter, - env.timeKeeper(), - app.config().legacy("database_path"), - env.journal); + manifestsOuter, manifestsOuter, env.timeKeeper(), app.config().legacy("database_path"), env.journal); std::vector cfgPublishersOuter; hash_set activeValidatorsOuter; @@ -1155,8 +925,7 @@ private: unseenValidators.emplace(calcNodeID(valKey)); } - BEAST_EXPECT( - trustedKeysOuter->load({}, cfgKeys, cfgPublishersOuter)); + BEAST_EXPECT(trustedKeysOuter->load({}, cfgKeys, cfgPublishersOuter)); // updateTrusted should make all configured validators trusted // even if they are not active/seen @@ -1172,12 +941,10 @@ private: BEAST_EXPECT(changes.added == activeValidatorsOuter); BEAST_EXPECT(changes.removed.empty()); - BEAST_EXPECT( - trustedKeysOuter->quorum() == std::ceil(cfgKeys.size() * 0.8f)); + BEAST_EXPECT(trustedKeysOuter->quorum() == std::ceil(cfgKeys.size() * 0.8f)); for (auto const& val : cfgKeys) { - if (auto const valKey = - parseBase58(TokenType::NodePublic, val)) + if (auto const valKey = parseBase58(TokenType::NodePublic, val)) { BEAST_EXPECT(trustedKeysOuter->listed(*valKey)); BEAST_EXPECT(trustedKeysOuter->trusted(*valKey)); @@ -1194,20 +961,16 @@ private: env.app().getHashRouter()); BEAST_EXPECT(changes.added.empty()); BEAST_EXPECT(changes.removed.empty()); - BEAST_EXPECT( - trustedKeysOuter->quorum() == std::ceil(cfgKeys.size() * 0.8f)); + BEAST_EXPECT(trustedKeysOuter->quorum() == std::ceil(cfgKeys.size() * 0.8f)); } { // update with manifests auto const masterPrivate = randomSecretKey(); - auto const masterPublic = - derivePublicKey(KeyType::ed25519, masterPrivate); + auto const masterPublic = derivePublicKey(KeyType::ed25519, masterPrivate); - std::vector cfgKeys( - {toBase58(TokenType::NodePublic, masterPublic)}); + std::vector cfgKeys({toBase58(TokenType::NodePublic, masterPublic)}); - BEAST_EXPECT( - trustedKeysOuter->load({}, cfgKeys, cfgPublishersOuter)); + BEAST_EXPECT(trustedKeysOuter->load({}, cfgKeys, cfgPublishersOuter)); auto const signingKeys1 = randomKeyPair(KeyType::secp256k1); auto const signingPublic1 = signingKeys1.first; @@ -1222,24 +985,17 @@ private: env.app().getHashRouter()); BEAST_EXPECT(changes.added == asNodeIDs({masterPublic})); BEAST_EXPECT(changes.removed.empty()); - BEAST_EXPECT( - trustedKeysOuter->quorum() == std::ceil((maxKeys + 1) * 0.8f)); + BEAST_EXPECT(trustedKeysOuter->quorum() == std::ceil((maxKeys + 1) * 0.8f)); BEAST_EXPECT(trustedKeysOuter->listed(masterPublic)); BEAST_EXPECT(trustedKeysOuter->trusted(masterPublic)); BEAST_EXPECT(!trustedKeysOuter->listed(signingPublic1)); BEAST_EXPECT(!trustedKeysOuter->trusted(signingPublic1)); // Should trust the ephemeral signing key from the applied manifest - auto m1 = deserializeManifest(makeManifestString( - masterPublic, - masterPrivate, - signingPublic1, - signingKeys1.second, - 1)); + auto m1 = deserializeManifest( + makeManifestString(masterPublic, masterPrivate, signingPublic1, signingKeys1.second, 1)); - BEAST_EXPECT( - manifestsOuter.applyManifest(std::move(*m1)) == - ManifestDisposition::accepted); + BEAST_EXPECT(manifestsOuter.applyManifest(std::move(*m1)) == ManifestDisposition::accepted); BEAST_EXPECT(trustedKeysOuter->listed(masterPublic)); BEAST_EXPECT(trustedKeysOuter->trusted(masterPublic)); BEAST_EXPECT(trustedKeysOuter->listed(signingPublic1)); @@ -1249,15 +1005,9 @@ private: // from the newest applied manifest auto const signingKeys2 = randomKeyPair(KeyType::secp256k1); auto const signingPublic2 = signingKeys2.first; - auto m2 = deserializeManifest(makeManifestString( - masterPublic, - masterPrivate, - signingPublic2, - signingKeys2.second, - 2)); - BEAST_EXPECT( - manifestsOuter.applyManifest(std::move(*m2)) == - ManifestDisposition::accepted); + auto m2 = deserializeManifest( + makeManifestString(masterPublic, masterPrivate, signingPublic2, signingKeys2.second, 2)); + BEAST_EXPECT(manifestsOuter.applyManifest(std::move(*m2)) == ManifestDisposition::accepted); BEAST_EXPECT(trustedKeysOuter->listed(masterPublic)); BEAST_EXPECT(trustedKeysOuter->trusted(masterPublic)); BEAST_EXPECT(trustedKeysOuter->listed(signingPublic2)); @@ -1269,15 +1019,11 @@ private: auto const signingKeysMax = randomKeyPair(KeyType::secp256k1); auto const signingPublicMax = signingKeysMax.first; activeValidatorsOuter.emplace(calcNodeID(signingPublicMax)); - auto mMax = deserializeManifest( - makeRevocationString(masterPublic, masterPrivate)); + auto mMax = deserializeManifest(makeRevocationString(masterPublic, masterPrivate)); BEAST_EXPECT(mMax->revoked()); - BEAST_EXPECT( - manifestsOuter.applyManifest(std::move(*mMax)) == - ManifestDisposition::accepted); - BEAST_EXPECT( - manifestsOuter.getSigningKey(masterPublic) == masterPublic); + BEAST_EXPECT(manifestsOuter.applyManifest(std::move(*mMax)) == ManifestDisposition::accepted); + BEAST_EXPECT(manifestsOuter.getSigningKey(masterPublic) == masterPublic); BEAST_EXPECT(manifestsOuter.revoked(masterPublic)); // Revoked key remains trusted until list is updated @@ -1292,8 +1038,7 @@ private: env.app().getHashRouter()); BEAST_EXPECT(changes.removed == asNodeIDs({masterPublic})); BEAST_EXPECT(changes.added.empty()); - BEAST_EXPECT( - trustedKeysOuter->quorum() == std::ceil(maxKeys * 0.8f)); + BEAST_EXPECT(trustedKeysOuter->quorum() == std::ceil(maxKeys * 0.8f)); BEAST_EXPECT(trustedKeysOuter->listed(masterPublic)); BEAST_EXPECT(!trustedKeysOuter->trusted(masterPublic)); BEAST_EXPECT(!trustedKeysOuter->listed(signingPublicMax)); @@ -1307,14 +1052,9 @@ private: // Make quorum unattainable if lists from any publishers are // unavailable auto trustedKeys = std::make_unique( - manifestsOuter, - manifestsOuter, - env.timeKeeper(), - app.config().legacy("database_path"), - env.journal); + manifestsOuter, manifestsOuter, env.timeKeeper(), app.config().legacy("database_path"), env.journal); auto const publisherSecret = randomSecretKey(); - auto const publisherPublic = - derivePublicKey(KeyType::ed25519, publisherSecret); + auto const publisherPublic = derivePublicKey(KeyType::ed25519, publisherSecret); std::vector cfgPublishers({strHex(publisherPublic)}); std::vector emptyCfgKeys; @@ -1329,36 +1069,24 @@ private: env.app().getHashRouter()); BEAST_EXPECT(changes.removed.empty()); BEAST_EXPECT(changes.added.empty()); - BEAST_EXPECT( - trustedKeys->quorum() == - std::numeric_limits::max()); + BEAST_EXPECT(trustedKeys->quorum() == std::numeric_limits::max()); } { // Trust explicitly listed validators also when list threshold is // higher than 1 auto trustedKeys = std::make_unique( - manifestsOuter, - manifestsOuter, - env.timeKeeper(), - app.config().legacy("database_path"), - env.journal); + manifestsOuter, manifestsOuter, env.timeKeeper(), app.config().legacy("database_path"), env.journal); auto const masterPrivate = randomSecretKey(); - auto const masterPublic = - derivePublicKey(KeyType::ed25519, masterPrivate); - std::vector cfgKeys( - {toBase58(TokenType::NodePublic, masterPublic)}); + auto const masterPublic = derivePublicKey(KeyType::ed25519, masterPrivate); + std::vector cfgKeys({toBase58(TokenType::NodePublic, masterPublic)}); auto const publisher1Secret = randomSecretKey(); - auto const publisher1Public = - derivePublicKey(KeyType::ed25519, publisher1Secret); + auto const publisher1Public = derivePublicKey(KeyType::ed25519, publisher1Secret); auto const publisher2Secret = randomSecretKey(); - auto const publisher2Public = - derivePublicKey(KeyType::ed25519, publisher2Secret); - std::vector cfgPublishers( - {strHex(publisher1Public), strHex(publisher2Public)}); + auto const publisher2Public = derivePublicKey(KeyType::ed25519, publisher2Secret); + std::vector cfgPublishers({strHex(publisher1Public), strHex(publisher2Public)}); - BEAST_EXPECT( - trustedKeys->load({}, cfgKeys, cfgPublishers, std::size_t(2))); + BEAST_EXPECT(trustedKeys->load({}, cfgKeys, cfgPublishers, std::size_t(2))); TrustChanges changes = trustedKeys->updateTrusted( activeValidatorsOuter, @@ -1376,12 +1104,7 @@ private: std::size_t const minQuorum = 1; ManifestCache manifests; auto trustedKeys = std::make_unique( - manifests, - manifests, - env.timeKeeper(), - app.config().legacy("database_path"), - env.journal, - minQuorum); + manifests, manifests, env.timeKeeper(), app.config().legacy("database_path"), env.journal, minQuorum); std::size_t n = 10; std::vector cfgKeys; @@ -1438,35 +1161,26 @@ private: auto const publisherKeys = randomKeyPair(KeyType::secp256k1); auto const pubSigningKeys = randomKeyPair(KeyType::secp256k1); auto const manifest = base64_encode(makeManifestString( - publisherKeys.first, - publisherKeys.second, - pubSigningKeys.first, - pubSigningKeys.second, - 1)); + publisherKeys.first, publisherKeys.second, pubSigningKeys.first, pubSigningKeys.second, 1)); std::vector cfgKeys({strHex(publisherKeys.first)}); BEAST_EXPECT(trustedKeys->load({}, emptyCfgKeys, cfgKeys)); std::vector list({randomValidator(), randomValidator()}); - hash_set activeValidators( - asNodeIDs({list[0].masterPublic, list[1].masterPublic})); + hash_set activeValidators(asNodeIDs({list[0].masterPublic, list[1].masterPublic})); // do not apply expired list auto const version = 1; auto const sequence = 1; using namespace std::chrono_literals; - NetClock::time_point const validUntil = - env.timeKeeper().now() + 60s; - auto const blob = - makeList(list, sequence, validUntil.time_since_epoch().count()); + NetClock::time_point const validUntil = env.timeKeeper().now() + 60s; + auto const blob = makeList(list, sequence, validUntil.time_since_epoch().count()); auto const sig = signList(blob, pubSigningKeys); BEAST_EXPECT( ListDisposition::accepted == - trustedKeys - ->applyLists(manifest, version, {{blob, sig, {}}}, siteUri) - .bestDisposition()); + trustedKeys->applyLists(manifest, version, {{blob, sig, {}}}, siteUri).bestDisposition()); TrustChanges changes = trustedKeys->updateTrusted( activeValidators, @@ -1494,26 +1208,19 @@ private: BEAST_EXPECT(changes.added.empty()); BEAST_EXPECT(!trustedKeys->trusted(list[0].masterPublic)); BEAST_EXPECT(!trustedKeys->trusted(list[1].masterPublic)); - BEAST_EXPECT( - trustedKeys->quorum() == - std::numeric_limits::max()); + BEAST_EXPECT(trustedKeys->quorum() == std::numeric_limits::max()); // (Re)trust validators from new valid list std::vector list2({list[0], randomValidator()}); activeValidators.insert(calcNodeID(list2[1].masterPublic)); auto const sequence2 = 2; - NetClock::time_point const expiration2 = - env.timeKeeper().now() + 60s; - auto const blob2 = makeList( - list2, sequence2, expiration2.time_since_epoch().count()); + NetClock::time_point const expiration2 = env.timeKeeper().now() + 60s; + auto const blob2 = makeList(list2, sequence2, expiration2.time_since_epoch().count()); auto const sig2 = signList(blob2, pubSigningKeys); BEAST_EXPECT( ListDisposition::accepted == - trustedKeys - ->applyLists( - manifest, version, {{blob2, sig2, {}}}, siteUri) - .bestDisposition()); + trustedKeys->applyLists(manifest, version, {{blob2, sig2, {}}}, siteUri).bestDisposition()); changes = trustedKeys->updateTrusted( activeValidators, @@ -1522,9 +1229,7 @@ private: env.app().overlay(), env.app().getHashRouter()); BEAST_EXPECT(changes.removed.empty()); - BEAST_EXPECT( - changes.added == - asNodeIDs({list2[0].masterPublic, list2[1].masterPublic})); + BEAST_EXPECT(changes.added == asNodeIDs({list2[0].masterPublic, list2[1].masterPublic})); for (Validator const& val : list2) { BEAST_EXPECT(trustedKeys->trusted(val.masterPublic)); @@ -1537,11 +1242,7 @@ private: { // Test 1-9 configured validators auto trustedKeys = std::make_unique( - manifestsOuter, - manifestsOuter, - env.timeKeeper(), - app.config().legacy("database_path"), - env.journal); + manifestsOuter, manifestsOuter, env.timeKeeper(), app.config().legacy("database_path"), env.journal); std::vector cfgPublishers; hash_set activeValidators; @@ -1565,8 +1266,7 @@ private: env.app().getHashRouter()); BEAST_EXPECT(changes.removed.empty()); BEAST_EXPECT(changes.added == asNodeIDs({valKey})); - BEAST_EXPECT( - trustedKeys->quorum() == std::ceil(cfgKeys.size() * 0.8f)); + BEAST_EXPECT(trustedKeys->quorum() == std::ceil(cfgKeys.size() * 0.8f)); for (auto const& key : activeKeys) BEAST_EXPECT(trustedKeys->trusted(key)); } @@ -1574,18 +1274,13 @@ private: { // Test 2-9 configured validators as validator auto trustedKeys = std::make_unique( - manifestsOuter, - manifestsOuter, - env.timeKeeper(), - app.config().legacy("database_path"), - env.journal); + manifestsOuter, manifestsOuter, env.timeKeeper(), app.config().legacy("database_path"), env.journal); auto const localKey = randomNode(); std::vector cfgPublishers; hash_set activeValidators; hash_set activeKeys; - std::vector cfgKeys{ - toBase58(TokenType::NodePublic, localKey)}; + std::vector cfgKeys{toBase58(TokenType::NodePublic, localKey)}; cfgKeys.reserve(9); while (cfgKeys.size() < cfgKeys.capacity()) @@ -1595,8 +1290,7 @@ private: activeValidators.emplace(calcNodeID(valKey)); activeKeys.emplace(valKey); - BEAST_EXPECT( - trustedKeys->load(localKey, cfgKeys, cfgPublishers)); + BEAST_EXPECT(trustedKeys->load(localKey, cfgKeys, cfgPublishers)); TrustChanges changes = trustedKeys->updateTrusted( activeValidators, env.timeKeeper().now(), @@ -1607,11 +1301,9 @@ private: if (cfgKeys.size() > 2) BEAST_EXPECT(changes.added == asNodeIDs({valKey})); else - BEAST_EXPECT( - changes.added == asNodeIDs({localKey, valKey})); + BEAST_EXPECT(changes.added == asNodeIDs({localKey, valKey})); - BEAST_EXPECT( - trustedKeys->quorum() == std::ceil(cfgKeys.size() * 0.8f)); + BEAST_EXPECT(trustedKeys->quorum() == std::ceil(cfgKeys.size() * 0.8f)); for (auto const& key : activeKeys) BEAST_EXPECT(trustedKeys->trusted(key)); @@ -1621,11 +1313,7 @@ private: // Trusted set should include all validators from multiple lists ManifestCache manifests; auto trustedKeys = std::make_unique( - manifests, - manifests, - env.timeKeeper(), - app.config().legacy("database_path"), - env.journal); + manifests, manifests, env.timeKeeper(), app.config().legacy("database_path"), env.journal); hash_set activeValidators; std::vector valKeys; @@ -1634,19 +1322,14 @@ private: while (valKeys.size() != maxKeys) { valKeys.push_back(randomValidator()); - activeValidators.emplace( - calcNodeID(valKeys.back().masterPublic)); + activeValidators.emplace(calcNodeID(valKeys.back().masterPublic)); } // locals[0]: from 0 to maxKeys - 4 // locals[1]: from 1 to maxKeys - 2 // locals[2]: from 2 to maxKeys constexpr static int publishers = 3; - std::array< - std::pair< - decltype(valKeys)::const_iterator, - decltype(valKeys)::const_iterator>, - publishers> + std::array, publishers> locals = { std::make_pair(valKeys.cbegin(), valKeys.cend() - 4), std::make_pair(valKeys.cbegin() + 1, valKeys.cend() - 2), @@ -1655,41 +1338,28 @@ private: auto addPublishedList = [&, this](int i) { auto const publisherSecret = randomSecretKey(); - auto const publisherPublic = - derivePublicKey(KeyType::ed25519, publisherSecret); + auto const publisherPublic = derivePublicKey(KeyType::ed25519, publisherSecret); auto const pubSigningKeys = randomKeyPair(KeyType::secp256k1); auto const manifest = base64_encode(makeManifestString( - publisherPublic, - publisherSecret, - pubSigningKeys.first, - pubSigningKeys.second, - 1)); + publisherPublic, publisherSecret, pubSigningKeys.first, pubSigningKeys.second, 1)); - std::vector cfgPublishers( - {strHex(publisherPublic)}); + std::vector cfgPublishers({strHex(publisherPublic)}); std::vector emptyCfgKeys; // Threshold of 1 will result in a union of all the lists - BEAST_EXPECT(trustedKeys->load( - {}, emptyCfgKeys, cfgPublishers, std::size_t(1))); + BEAST_EXPECT(trustedKeys->load({}, emptyCfgKeys, cfgPublishers, std::size_t(1))); auto const version = 1; auto const sequence = 1; using namespace std::chrono_literals; - NetClock::time_point const validUntil = - env.timeKeeper().now() + 3600s; - std::vector localKeys{ - locals[i].first, locals[i].second}; - auto const blob = makeList( - localKeys, sequence, validUntil.time_since_epoch().count()); + NetClock::time_point const validUntil = env.timeKeeper().now() + 3600s; + std::vector localKeys{locals[i].first, locals[i].second}; + auto const blob = makeList(localKeys, sequence, validUntil.time_since_epoch().count()); auto const sig = signList(blob, pubSigningKeys); BEAST_EXPECT( ListDisposition::accepted == - trustedKeys - ->applyLists( - manifest, version, {{blob, sig, {}}}, siteUri) - .bestDisposition()); + trustedKeys->applyLists(manifest, version, {{blob, sig, {}}}, siteUri).bestDisposition()); }; // Apply multiple published lists @@ -1704,8 +1374,7 @@ private: env.app().overlay(), env.app().getHashRouter()); - BEAST_EXPECT( - trustedKeys->quorum() == std::ceil(valKeys.size() * 0.8f)); + BEAST_EXPECT(trustedKeys->quorum() == std::ceil(valKeys.size() * 0.8f)); hash_set added; for (auto const& val : valKeys) @@ -1720,11 +1389,7 @@ private: // Trusted set should include validators from intersection of lists ManifestCache manifests; auto trustedKeys = std::make_unique( - manifests, - manifests, - env.timeKeeper(), - app.config().legacy("database_path"), - env.journal); + manifests, manifests, env.timeKeeper(), app.config().legacy("database_path"), env.journal); hash_set activeValidators; std::vector valKeys; @@ -1733,8 +1398,7 @@ private: while (valKeys.size() != maxKeys) { valKeys.push_back(randomValidator()); - activeValidators.emplace( - calcNodeID(valKeys.back().masterPublic)); + activeValidators.emplace(calcNodeID(valKeys.back().masterPublic)); } // locals[0]: from 0 to maxKeys - 4 @@ -1743,11 +1407,7 @@ private: // intersection of at least 2: same as locals[1] // intersection when 1 is dropped: from 2 to maxKeys - 4 constexpr static int publishers = 3; - std::array< - std::pair< - decltype(valKeys)::const_iterator, - decltype(valKeys)::const_iterator>, - publishers> + std::array, publishers> locals = { std::make_pair(valKeys.cbegin(), valKeys.cend() - 4), std::make_pair(valKeys.cbegin() + 1, valKeys.cend() - 2), @@ -1755,51 +1415,34 @@ private: }; auto addPublishedList = [&, this]( - int i, - NetClock::time_point& validUntil1, - NetClock::time_point& validUntil2) { + int i, NetClock::time_point& validUntil1, NetClock::time_point& validUntil2) { auto const publisherSecret = randomSecretKey(); - auto const publisherPublic = - derivePublicKey(KeyType::ed25519, publisherSecret); + auto const publisherPublic = derivePublicKey(KeyType::ed25519, publisherSecret); auto const pubSigningKeys = randomKeyPair(KeyType::secp256k1); auto const manifest = base64_encode(makeManifestString( - publisherPublic, - publisherSecret, - pubSigningKeys.first, - pubSigningKeys.second, - 1)); + publisherPublic, publisherSecret, pubSigningKeys.first, pubSigningKeys.second, 1)); - std::vector cfgPublishers( - {strHex(publisherPublic)}); + std::vector cfgPublishers({strHex(publisherPublic)}); std::vector emptyCfgKeys; - BEAST_EXPECT( - trustedKeys->load({}, emptyCfgKeys, cfgPublishers)); + BEAST_EXPECT(trustedKeys->load({}, emptyCfgKeys, cfgPublishers)); auto const version = 1; auto const sequence = 1; using namespace std::chrono_literals; // Want to drop 1 sooner - NetClock::time_point const validUntil = env.timeKeeper().now() + - (i == 2 ? 120s - : i == 1 ? 60s - : 3600s); + NetClock::time_point const validUntil = env.timeKeeper().now() + (i == 2 ? 120s : i == 1 ? 60s : 3600s); if (i == 1) validUntil1 = validUntil; else if (i == 2) validUntil2 = validUntil; - std::vector localKeys{ - locals[i].first, locals[i].second}; - auto const blob = makeList( - localKeys, sequence, validUntil.time_since_epoch().count()); + std::vector localKeys{locals[i].first, locals[i].second}; + auto const blob = makeList(localKeys, sequence, validUntil.time_since_epoch().count()); auto const sig = signList(blob, pubSigningKeys); BEAST_EXPECT( ListDisposition::accepted == - trustedKeys - ->applyLists( - manifest, version, {{blob, sig, {}}}, siteUri) - .bestDisposition()); + trustedKeys->applyLists(manifest, version, {{blob, sig, {}}}, siteUri).bestDisposition()); }; // Apply multiple published lists @@ -1816,9 +1459,7 @@ private: env.app().overlay(), env.app().getHashRouter()); - BEAST_EXPECT( - trustedKeys->quorum() == - std::ceil((valKeys.size() - 3) * 0.8f)); + BEAST_EXPECT(trustedKeys->quorum() == std::ceil((valKeys.size() - 3) * 0.8f)); for (auto const& val : valKeys) BEAST_EXPECT(trustedKeys->listed(val.masterPublic)); @@ -1847,9 +1488,7 @@ private: env.app().overlay(), env.app().getHashRouter()); - BEAST_EXPECT( - trustedKeys->quorum() == - std::ceil((valKeys.size() - 6) * 0.8f)); + BEAST_EXPECT(trustedKeys->quorum() == std::ceil((valKeys.size() - 6) * 0.8f)); for (auto const& val : valKeys) BEAST_EXPECT(trustedKeys->listed(val.masterPublic)); @@ -1880,9 +1519,7 @@ private: env.app().overlay(), env.app().getHashRouter()); - BEAST_EXPECT( - trustedKeys->quorum() == - std::numeric_limits::max()); + BEAST_EXPECT(trustedKeys->quorum() == std::numeric_limits::max()); removed.clear(); for (std::size_t i = 0; i < maxKeys; ++i) @@ -1913,19 +1550,13 @@ private: jtx::Env env(*this); auto& app = env.app(); - auto toStr = [](PublicKey const& publicKey) { - return toBase58(TokenType::NodePublic, publicKey); - }; + auto toStr = [](PublicKey const& publicKey) { return toBase58(TokenType::NodePublic, publicKey); }; // Config listed keys { ManifestCache manifests; auto trustedKeys = std::make_unique( - manifests, - manifests, - env.timeKeeper(), - app.config().legacy("database_path"), - env.journal); + manifests, manifests, env.timeKeeper(), app.config().legacy("database_path"), env.journal); // Empty list has no expiration BEAST_EXPECT(trustedKeys->expires() == std::nullopt); @@ -1933,9 +1564,7 @@ private: // Config listed keys have maximum expiry PublicKey localCfgListed = randomNode(); trustedKeys->load({}, {toStr(localCfgListed)}, {}); - BEAST_EXPECT( - trustedKeys->expires() && - trustedKeys->expires().value() == NetClock::time_point::max()); + BEAST_EXPECT(trustedKeys->expires() && trustedKeys->expires().value() == NetClock::time_point::max()); BEAST_EXPECT(trustedKeys->listed(localCfgListed)); } @@ -1943,11 +1572,7 @@ private: { ManifestCache manifests; auto trustedKeys = std::make_unique( - manifests, - manifests, - env.app().timeKeeper(), - app.config().legacy("database_path"), - env.journal); + manifests, manifests, env.app().timeKeeper(), app.config().legacy("database_path"), env.journal); std::vector validators = {randomValidator()}; hash_set activeValidators; @@ -1966,31 +1591,20 @@ private: using namespace std::chrono_literals; auto addPublishedList = [this, &env, &trustedKeys, &validators]() { auto const publisherSecret = randomSecretKey(); - auto const publisherPublic = - derivePublicKey(KeyType::ed25519, publisherSecret); + auto const publisherPublic = derivePublicKey(KeyType::ed25519, publisherSecret); auto const pubSigningKeys = randomKeyPair(KeyType::secp256k1); auto const manifest = base64_encode(makeManifestString( - publisherPublic, - publisherSecret, - pubSigningKeys.first, - pubSigningKeys.second, - 1)); + publisherPublic, publisherSecret, pubSigningKeys.first, pubSigningKeys.second, 1)); - std::vector cfgPublishers( - {strHex(publisherPublic)}); + std::vector cfgPublishers({strHex(publisherPublic)}); std::vector emptyCfgKeys; - BEAST_EXPECT( - trustedKeys->load({}, emptyCfgKeys, cfgPublishers)); + BEAST_EXPECT(trustedKeys->load({}, emptyCfgKeys, cfgPublishers)); auto const version = 2; auto const sequence1 = 1; - NetClock::time_point const expiration1 = - env.timeKeeper().now() + 1800s; - auto const blob1 = makeList( - validators, - sequence1, - expiration1.time_since_epoch().count()); + NetClock::time_point const expiration1 = env.timeKeeper().now() + 1800s; + auto const blob1 = makeList(validators, sequence1, expiration1.time_since_epoch().count()); auto const sig1 = signList(blob1, pubSigningKeys); NetClock::time_point const effective2 = expiration1 - 300s; @@ -2021,8 +1635,7 @@ private: // Apply first list checkResult( - trustedKeys->applyLists( - prep1.manifest, prep1.version, prep1.blobs, siteUri), + trustedKeys->applyLists(prep1.manifest, prep1.version, prep1.blobs, siteUri), prep1.publisherPublic, ListDisposition::pending, ListDisposition::accepted); @@ -2033,15 +1646,12 @@ private: // Apply second list checkResult( - trustedKeys->applyLists( - prep2.manifest, prep2.version, prep2.blobs, siteUri), + trustedKeys->applyLists(prep2.manifest, prep2.version, prep2.blobs, siteUri), prep2.publisherPublic, ListDisposition::pending, ListDisposition::accepted); // We now have loaded both lists, so expiration is known - BEAST_EXPECT( - trustedKeys->expires() && - trustedKeys->expires().value() == prep1.expirations.back()); + BEAST_EXPECT(trustedKeys->expires() && trustedKeys->expires().value() == prep1.expirations.back()); // Advance past the first list's LAST validFrom date. It remains // the earliest validUntil, while rotating in the second list @@ -2053,9 +1663,7 @@ private: env.app().getOPs(), env.app().overlay(), env.app().getHashRouter()); - BEAST_EXPECT( - trustedKeys->expires() && - trustedKeys->expires().value() == prep1.expirations.back()); + BEAST_EXPECT(trustedKeys->expires() && trustedKeys->expires().value() == prep1.expirations.back()); BEAST_EXPECT(!changes.added.empty()); BEAST_EXPECT(changes.removed.empty()); } @@ -2070,9 +1678,7 @@ private: env.app().getOPs(), env.app().overlay(), env.app().getHashRouter()); - BEAST_EXPECT( - trustedKeys->expires() && - trustedKeys->expires().value() == prep1.expirations.back()); + BEAST_EXPECT(trustedKeys->expires() && trustedKeys->expires().value() == prep1.expirations.back()); BEAST_EXPECT(changes.added.empty()); BEAST_EXPECT(changes.removed.empty()); } @@ -2087,9 +1693,7 @@ private: ManifestCache manifests; auto createValidatorList = - [&](std::uint32_t vlSize, - std::optional minimumQuorum = {}) - -> std::shared_ptr { + [&](std::uint32_t vlSize, std::optional minimumQuorum = {}) -> std::shared_ptr { auto trustedKeys = std::make_shared( manifests, manifests, @@ -2116,8 +1720,7 @@ private: env.app().getOPs(), env.app().overlay(), env.app().getHashRouter()); - if (minimumQuorum == trustedKeys->quorum() || - trustedKeys->quorum() == std::ceil(cfgKeys.size() * 0.8f)) + if (minimumQuorum == trustedKeys->quorum() || trustedKeys->quorum() == std::ceil(cfgKeys.size() * 0.8f)) return trustedKeys; } return nullptr; @@ -2168,8 +1771,7 @@ private: env.app().getHashRouter()); BEAST_EXPECT( validators->quorum() == - static_cast(std::ceil( - std::max((us - nUnlSize) * 0.8f, us * 0.6f)))); + static_cast(std::ceil(std::max((us - nUnlSize) * 0.8f, us * 0.6f)))); } } } @@ -2187,8 +1789,7 @@ private: { //-- set == get, //-- check quorum, with nUNL size: 0, 30, 18, 12 - auto nUnlChange = [&](std::uint32_t nUnlSize, - std::uint32_t quorum) -> bool { + auto nUnlChange = [&](std::uint32_t nUnlSize, std::uint32_t quorum) -> bool { hash_set nUnl; auto it = unl.begin(); for (std::uint32_t i = 0; i < nUnlSize; ++i) @@ -2311,8 +1912,7 @@ private: BEAST_EXPECT(global != sha512Half(signature, blobVector, version)); { - std::map blobMap{ - {99, blobVector[0]}}; + std::map blobMap{{99, blobVector[0]}}; BEAST_EXPECT(global == sha512Half(manifest, blobMap, version)); BEAST_EXPECT(global != sha512Half(blob, blobMap, version)); } @@ -2348,8 +1948,7 @@ private: std::uint32_t const manifestCutoff = 7; auto extractHeader = [this](Message& message) { - auto const& buffer = - message.getBuffer(compression::Compressed::Off); + auto const& buffer = message.getBuffer(compression::Compressed::Off); boost::beast::multi_buffer buffers; @@ -2357,163 +1956,117 @@ private: auto start = buffer.begin(); auto end = buffer.end(); std::vector slice(start, end); - buffers.commit(boost::asio::buffer_copy( - buffers.prepare(slice.size()), boost::asio::buffer(slice))); + buffers.commit(boost::asio::buffer_copy(buffers.prepare(slice.size()), boost::asio::buffer(slice))); boost::system::error_code ec; - auto header = - detail::parseMessageHeader(ec, buffers.data(), buffers.size()); + auto header = detail::parseMessageHeader(ec, buffers.data(), buffers.size()); BEAST_EXPECT(!ec); return std::make_pair(header, buffers); }; - auto extractProtocolMessage1 = [this, - &extractHeader](Message& message) { + auto extractProtocolMessage1 = [this, &extractHeader](Message& message) { auto [header, buffers] = extractHeader(message); - if (BEAST_EXPECT(header) && - BEAST_EXPECT( - header->message_type == protocol::mtVALIDATOR_LIST)) + if (BEAST_EXPECT(header) && BEAST_EXPECT(header->message_type == protocol::mtVALIDATOR_LIST)) { - auto const msg = - detail::parseMessageContent( - *header, buffers.data()); + auto const msg = detail::parseMessageContent(*header, buffers.data()); BEAST_EXPECT(msg); return msg; } return std::shared_ptr(); }; - auto extractProtocolMessage2 = [this, - &extractHeader](Message& message) { + auto extractProtocolMessage2 = [this, &extractHeader](Message& message) { auto [header, buffers] = extractHeader(message); - if (BEAST_EXPECT(header) && - BEAST_EXPECT( - header->message_type == - protocol::mtVALIDATOR_LIST_COLLECTION)) + if (BEAST_EXPECT(header) && BEAST_EXPECT(header->message_type == protocol::mtVALIDATOR_LIST_COLLECTION)) { - auto const msg = detail::parseMessageContent< - protocol::TMValidatorListCollection>( - *header, buffers.data()); + auto const msg = + detail::parseMessageContent(*header, buffers.data()); BEAST_EXPECT(msg); return msg; } return std::shared_ptr(); }; - auto verifyMessage = - [this, - manifestCutoff, - &extractProtocolMessage1, - &extractProtocolMessage2]( - auto const version, - auto const& manifest, - auto const& blobInfos, - auto const& messages, - std::vector>> - expectedInfo) { - BEAST_EXPECT(messages.size() == expectedInfo.size()); - auto msgIter = expectedInfo.begin(); - for (auto const& messageWithHash : messages) + auto verifyMessage = [this, manifestCutoff, &extractProtocolMessage1, &extractProtocolMessage2]( + auto const version, + auto const& manifest, + auto const& blobInfos, + auto const& messages, + std::vector>> expectedInfo) { + BEAST_EXPECT(messages.size() == expectedInfo.size()); + auto msgIter = expectedInfo.begin(); + for (auto const& messageWithHash : messages) + { + if (!BEAST_EXPECT(msgIter != expectedInfo.end())) + break; + if (!BEAST_EXPECT(messageWithHash.message)) + continue; + auto const& expectedSeqs = msgIter->second; + auto seqIter = expectedSeqs.begin(); + auto const size = messageWithHash.message->getBuffer(compression::Compressed::Off).size(); + // This size is arbitrary, but shouldn't change + BEAST_EXPECT(size == msgIter->first); + if (expectedSeqs.size() == 1) { - if (!BEAST_EXPECT(msgIter != expectedInfo.end())) - break; - if (!BEAST_EXPECT(messageWithHash.message)) - continue; - auto const& expectedSeqs = msgIter->second; - auto seqIter = expectedSeqs.begin(); - auto const size = - messageWithHash.message - ->getBuffer(compression::Compressed::Off) - .size(); - // This size is arbitrary, but shouldn't change - BEAST_EXPECT(size == msgIter->first); - if (expectedSeqs.size() == 1) + auto const msg = extractProtocolMessage1(*messageWithHash.message); + auto const expectedVersion = 1; + if (BEAST_EXPECT(msg)) { - auto const msg = - extractProtocolMessage1(*messageWithHash.message); - auto const expectedVersion = 1; - if (BEAST_EXPECT(msg)) - { - BEAST_EXPECT(msg->version() == expectedVersion); - if (!BEAST_EXPECT(seqIter != expectedSeqs.end())) - continue; - auto const& expectedBlob = blobInfos.at(*seqIter); - BEAST_EXPECT( - (*seqIter < manifestCutoff) == - !!expectedBlob.manifest); - auto const expectedManifest = - *seqIter < manifestCutoff && - expectedBlob.manifest - ? *expectedBlob.manifest - : manifest; - BEAST_EXPECT(msg->manifest() == expectedManifest); - BEAST_EXPECT(msg->blob() == expectedBlob.blob); - BEAST_EXPECT( - msg->signature() == expectedBlob.signature); - ++seqIter; - BEAST_EXPECT(seqIter == expectedSeqs.end()); + BEAST_EXPECT(msg->version() == expectedVersion); + if (!BEAST_EXPECT(seqIter != expectedSeqs.end())) + continue; + auto const& expectedBlob = blobInfos.at(*seqIter); + BEAST_EXPECT((*seqIter < manifestCutoff) == !!expectedBlob.manifest); + auto const expectedManifest = + *seqIter < manifestCutoff && expectedBlob.manifest ? *expectedBlob.manifest : manifest; + BEAST_EXPECT(msg->manifest() == expectedManifest); + BEAST_EXPECT(msg->blob() == expectedBlob.blob); + BEAST_EXPECT(msg->signature() == expectedBlob.signature); + ++seqIter; + BEAST_EXPECT(seqIter == expectedSeqs.end()); - BEAST_EXPECT( - messageWithHash.hash == - sha512Half( - expectedManifest, - expectedBlob.blob, - expectedBlob.signature, - expectedVersion)); - } - } - else - { - std::vector hashingBlobs; - hashingBlobs.reserve(msgIter->second.size()); - - auto const msg = - extractProtocolMessage2(*messageWithHash.message); - if (BEAST_EXPECT(msg)) - { - BEAST_EXPECT(msg->version() == version); - BEAST_EXPECT(msg->manifest() == manifest); - for (auto const& blobInfo : msg->blobs()) - { - if (!BEAST_EXPECT( - seqIter != expectedSeqs.end())) - break; - auto const& expectedBlob = - blobInfos.at(*seqIter); - hashingBlobs.push_back(expectedBlob); - BEAST_EXPECT( - blobInfo.has_manifest() == - !!expectedBlob.manifest); - BEAST_EXPECT( - blobInfo.has_manifest() == - (*seqIter < manifestCutoff)); - - if (*seqIter < manifestCutoff) - BEAST_EXPECT( - blobInfo.manifest() == - *expectedBlob.manifest); - BEAST_EXPECT( - blobInfo.blob() == expectedBlob.blob); - BEAST_EXPECT( - blobInfo.signature() == - expectedBlob.signature); - ++seqIter; - } - BEAST_EXPECT(seqIter == expectedSeqs.end()); - } BEAST_EXPECT( messageWithHash.hash == - sha512Half(manifest, hashingBlobs, version)); + sha512Half(expectedManifest, expectedBlob.blob, expectedBlob.signature, expectedVersion)); } - ++msgIter; } - BEAST_EXPECT(msgIter == expectedInfo.end()); - }; - auto verifyBuildMessages = - [this]( - std::pair const& result, - std::size_t expectedSequence, - std::size_t expectedSize) { - BEAST_EXPECT(result.first == expectedSequence); - BEAST_EXPECT(result.second == expectedSize); - }; + else + { + std::vector hashingBlobs; + hashingBlobs.reserve(msgIter->second.size()); + + auto const msg = extractProtocolMessage2(*messageWithHash.message); + if (BEAST_EXPECT(msg)) + { + BEAST_EXPECT(msg->version() == version); + BEAST_EXPECT(msg->manifest() == manifest); + for (auto const& blobInfo : msg->blobs()) + { + if (!BEAST_EXPECT(seqIter != expectedSeqs.end())) + break; + auto const& expectedBlob = blobInfos.at(*seqIter); + hashingBlobs.push_back(expectedBlob); + BEAST_EXPECT(blobInfo.has_manifest() == !!expectedBlob.manifest); + BEAST_EXPECT(blobInfo.has_manifest() == (*seqIter < manifestCutoff)); + + if (*seqIter < manifestCutoff) + BEAST_EXPECT(blobInfo.manifest() == *expectedBlob.manifest); + BEAST_EXPECT(blobInfo.blob() == expectedBlob.blob); + BEAST_EXPECT(blobInfo.signature() == expectedBlob.signature); + ++seqIter; + } + BEAST_EXPECT(seqIter == expectedSeqs.end()); + } + BEAST_EXPECT(messageWithHash.hash == sha512Half(manifest, hashingBlobs, version)); + } + ++msgIter; + } + BEAST_EXPECT(msgIter == expectedInfo.end()); + }; + auto verifyBuildMessages = [this]( + std::pair const& result, + std::size_t expectedSequence, + std::size_t expectedSize) { + BEAST_EXPECT(result.first == expectedSequence); + BEAST_EXPECT(result.second == expectedSize); + }; std::string const manifest = "This is not a manifest"; std::uint32_t const version = 2; @@ -2549,10 +2102,7 @@ private: // This peer has a VL ahead of our "current" verifyBuildMessages( - ValidatorList::buildValidatorListMessages( - 1, 8, maxSequence, version, manifest, blobInfos, messages), - 0, - 0); + ValidatorList::buildValidatorListMessages(1, 8, maxSequence, version, manifest, blobInfos, messages), 0, 0); BEAST_EXPECT(messages.size() == 0); // Don't repeat the work if messages is populated, even though the @@ -2561,27 +2111,18 @@ private: // real code. messages.emplace_back(); verifyBuildMessages( - ValidatorList::buildValidatorListMessages( - 1, 3, maxSequence, version, manifest, blobInfos, messages), - 5, - 0); + ValidatorList::buildValidatorListMessages(1, 3, maxSequence, version, manifest, blobInfos, messages), 5, 0); BEAST_EXPECT(messages.size() == 1 && !messages.front().message); // Generate a version 1 message messages.clear(); verifyBuildMessages( - ValidatorList::buildValidatorListMessages( - 1, 3, maxSequence, version, manifest, blobInfos, messages), - 5, - 1); - if (BEAST_EXPECT(messages.size() == 1) && - BEAST_EXPECT(messages.front().message)) + ValidatorList::buildValidatorListMessages(1, 3, maxSequence, version, manifest, blobInfos, messages), 5, 1); + if (BEAST_EXPECT(messages.size() == 1) && BEAST_EXPECT(messages.front().message)) { auto const& messageWithHash = messages.front(); auto const msg = extractProtocolMessage1(*messageWithHash.message); - auto const size = - messageWithHash.message->getBuffer(compression::Compressed::Off) - .size(); + auto const size = messageWithHash.message->getBuffer(compression::Compressed::Off).size(); // This size is arbitrary, but shouldn't change BEAST_EXPECT(size == 108); auto const& expected = blobInfos.at(5); @@ -2592,10 +2133,7 @@ private: BEAST_EXPECT(msg->blob() == expected.blob); BEAST_EXPECT(msg->signature() == expected.signature); } - BEAST_EXPECT( - messageWithHash.hash == - sha512Half( - *expected.manifest, expected.blob, expected.signature, 1)); + BEAST_EXPECT(messageWithHash.hash == sha512Half(*expected.manifest, expected.blob, expected.signature, 1)); } // Version 2 @@ -2605,13 +2143,7 @@ private: // This peer has a VL ahead of us. verifyBuildMessages( ValidatorList::buildValidatorListMessages( - 2, - maxSequence * 2, - maxSequence, - version, - manifest, - blobInfos, - messages), + 2, maxSequence * 2, maxSequence, version, manifest, blobInfos, messages), 0, 0); BEAST_EXPECT(messages.size() == 0); @@ -2622,8 +2154,7 @@ private: // real code. messages.emplace_back(); verifyBuildMessages( - ValidatorList::buildValidatorListMessages( - 2, 3, maxSequence, version, manifest, blobInfos, messages), + ValidatorList::buildValidatorListMessages(2, 3, maxSequence, version, manifest, blobInfos, messages), maxSequence, 0); BEAST_EXPECT(messages.size() == 1 && !messages.front().message); @@ -2631,72 +2162,46 @@ private: // Generate a version 2 message. Don't send the current messages.clear(); verifyBuildMessages( - ValidatorList::buildValidatorListMessages( - 2, 5, maxSequence, version, manifest, blobInfos, messages), + ValidatorList::buildValidatorListMessages(2, 5, maxSequence, version, manifest, blobInfos, messages), maxSequence, 4); - verifyMessage( - version, manifest, blobInfos, messages, {{372, {6, 7, 10, 12}}}); + verifyMessage(version, manifest, blobInfos, messages, {{372, {6, 7, 10, 12}}}); // Test message splitting on size limits. // Set a limit that should give two messages messages.clear(); verifyBuildMessages( - ValidatorList::buildValidatorListMessages( - 2, 5, maxSequence, version, manifest, blobInfos, messages, 300), + ValidatorList::buildValidatorListMessages(2, 5, maxSequence, version, manifest, blobInfos, messages, 300), maxSequence, 4); - verifyMessage( - version, - manifest, - blobInfos, - messages, - {{212, {6, 7}}, {192, {10, 12}}}); + verifyMessage(version, manifest, blobInfos, messages, {{212, {6, 7}}, {192, {10, 12}}}); // Set a limit between the size of the two earlier messages so one // will split and the other won't messages.clear(); verifyBuildMessages( - ValidatorList::buildValidatorListMessages( - 2, 5, maxSequence, version, manifest, blobInfos, messages, 200), + ValidatorList::buildValidatorListMessages(2, 5, maxSequence, version, manifest, blobInfos, messages, 200), maxSequence, 4); - verifyMessage( - version, - manifest, - blobInfos, - messages, - {{108, {6}}, {108, {7}}, {192, {10, 12}}}); + verifyMessage(version, manifest, blobInfos, messages, {{108, {6}}, {108, {7}}, {192, {10, 12}}}); // Set a limit so that all the VLs are sent individually messages.clear(); verifyBuildMessages( - ValidatorList::buildValidatorListMessages( - 2, 5, maxSequence, version, manifest, blobInfos, messages, 150), + ValidatorList::buildValidatorListMessages(2, 5, maxSequence, version, manifest, blobInfos, messages, 150), maxSequence, 4); - verifyMessage( - version, - manifest, - blobInfos, - messages, - {{108, {6}}, {108, {7}}, {110, {10}}, {110, {12}}}); + verifyMessage(version, manifest, blobInfos, messages, {{108, {6}}, {108, {7}}, {110, {10}}, {110, {12}}}); // Set a limit smaller than some of the messages. Because single // messages send regardless, they will all still be sent messages.clear(); verifyBuildMessages( - ValidatorList::buildValidatorListMessages( - 2, 5, maxSequence, version, manifest, blobInfos, messages, 108), + ValidatorList::buildValidatorListMessages(2, 5, maxSequence, version, manifest, blobInfos, messages, 108), maxSequence, 4); - verifyMessage( - version, - manifest, - blobInfos, - messages, - {{108, {6}}, {108, {7}}, {110, {10}}, {110, {12}}}); + verifyMessage(version, manifest, blobInfos, messages, {{108, {6}}, {108, {7}}, {110, {10}}, {110, {12}}}); } void @@ -2738,76 +2243,48 @@ private: std::vector& publishers // out ) -> std::unique_ptr { auto result = std::make_unique( - valManifests, - pubManifests, - env.timeKeeper(), - app.config().legacy("database_path"), - env.journal); + valManifests, pubManifests, env.timeKeeper(), app.config().legacy("database_path"), env.journal); std::vector cfgPublishers; for (std::size_t i = 0; i < countTotal; ++i) { auto const publisherSecret = randomSecretKey(); - auto const publisherPublic = - derivePublicKey(KeyType::ed25519, publisherSecret); + auto const publisherPublic = derivePublicKey(KeyType::ed25519, publisherSecret); auto const pubSigningKeys = randomKeyPair(KeyType::secp256k1); cfgPublishers.push_back(strHex(publisherPublic)); - constexpr auto revoked = - std::numeric_limits::max(); + constexpr auto revoked = std::numeric_limits::max(); auto const manifest = base64_encode(makeManifestString( publisherPublic, publisherSecret, pubSigningKeys.first, pubSigningKeys.second, i < countRevoked ? revoked : 1)); - publishers.push_back(Publisher{ - i < countRevoked, - publisherPublic, - pubSigningKeys, - manifest}); + publishers.push_back(Publisher{i < countRevoked, publisherPublic, pubSigningKeys, manifest}); } std::vector const emptyCfgKeys; - auto threshold = - listThreshold > 0 ? std::optional(listThreshold) : std::nullopt; + auto threshold = listThreshold > 0 ? std::optional(listThreshold) : std::nullopt; if (self) { - valManifests.applyManifest( - *deserializeManifest(base64_decode(self->manifest))); - BEAST_EXPECT(result->load( - self->signingPublic, - emptyCfgKeys, - cfgPublishers, - threshold)); + valManifests.applyManifest(*deserializeManifest(base64_decode(self->manifest))); + BEAST_EXPECT(result->load(self->signingPublic, emptyCfgKeys, cfgPublishers, threshold)); } else { - BEAST_EXPECT( - result->load({}, emptyCfgKeys, cfgPublishers, threshold)); + BEAST_EXPECT(result->load({}, emptyCfgKeys, cfgPublishers, threshold)); } for (std::size_t i = 0; i < countTotal; ++i) { using namespace std::chrono_literals; - publishers[i].expiry = env.timeKeeper().now() + - (i == countTotal - 1 ? 60s : 3600s); - auto const blob = makeList( - valKeys, - 1, - publishers[i].expiry.time_since_epoch().count()); + publishers[i].expiry = env.timeKeeper().now() + (i == countTotal - 1 ? 60s : 3600s); + auto const blob = makeList(valKeys, 1, publishers[i].expiry.time_since_epoch().count()); auto const sig = signList(blob, publishers[i].signingKeys); BEAST_EXPECT( - result - ->applyLists( - publishers[i].manifest, - 1, - {{blob, sig, {}}}, - siteUri) - .bestDisposition() == - (publishers[i].revoked ? ListDisposition::untrusted - : ListDisposition::accepted)); + result->applyLists(publishers[i].manifest, 1, {{blob, sig, {}}}, siteUri).bestDisposition() == + (publishers[i].revoked ? ListDisposition::untrusted : ListDisposition::accepted)); } return result; @@ -2842,8 +2319,7 @@ private: env.app().overlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == std::ceil(keysTotal * 0.8f)); - BEAST_EXPECT( - trustedKeys->getTrustedMasterKeys().size() == keysTotal); + BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); hash_set added; added.insert(calcNodeID(self.masterPublic)); @@ -2902,8 +2378,7 @@ private: env.app().overlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == std::ceil(keysTotal * 0.8f)); - BEAST_EXPECT( - trustedKeys->getTrustedMasterKeys().size() == keysTotal); + BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); hash_set added; for (auto const& val : valKeys) @@ -2968,8 +2443,7 @@ private: env.app().overlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == std::ceil(keysTotal * 0.8f)); - BEAST_EXPECT( - trustedKeys->getTrustedMasterKeys().size() == keysTotal); + BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); hash_set added; for (auto const& val : valKeys) @@ -3038,8 +2512,7 @@ private: env.app().overlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == std::ceil(keysTotal * 0.8f)); - BEAST_EXPECT( - trustedKeys->getTrustedMasterKeys().size() == keysTotal); + BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); hash_set added; added.insert(calcNodeID(self.masterPublic)); @@ -3106,8 +2579,7 @@ private: env.app().overlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == std::ceil(keysTotal * 0.8f)); - BEAST_EXPECT( - trustedKeys->getTrustedMasterKeys().size() == keysTotal); + BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); hash_set added; for (auto const& val : valKeys) @@ -3174,8 +2646,7 @@ private: env.app().overlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == std::ceil(keysTotal * 0.8f)); - BEAST_EXPECT( - trustedKeys->getTrustedMasterKeys().size() == keysTotal); + BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); hash_set added; for (auto const& val : valKeys) @@ -3240,8 +2711,7 @@ private: env.app().overlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == std::ceil(keysTotal * 0.8f)); - BEAST_EXPECT( - trustedKeys->getTrustedMasterKeys().size() == keysTotal); + BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); hash_set added; added.insert(calcNodeID(self.masterPublic)); @@ -3262,8 +2732,7 @@ private: env.app().overlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == quorumDisabled); - BEAST_EXPECT( - trustedKeys->getTrustedMasterKeys().size() == keysTotal); + BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); BEAST_EXPECT(trustedKeys->trusted(self.masterPublic)); for (auto const& val : valKeys) @@ -3301,8 +2770,7 @@ private: env.app().overlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == std::ceil(keysTotal * 0.8f)); - BEAST_EXPECT( - trustedKeys->getTrustedMasterKeys().size() == keysTotal); + BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); hash_set added; added.insert(calcNodeID(self.masterPublic)); @@ -3323,8 +2791,7 @@ private: env.app().overlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == quorumDisabled); - BEAST_EXPECT( - trustedKeys->getTrustedMasterKeys().size() == keysTotal); + BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); BEAST_EXPECT(trustedKeys->trusted(self.masterPublic)); for (auto const& val : valKeys) @@ -3362,8 +2829,7 @@ private: env.app().overlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == std::ceil(keysTotal * 0.8f)); - BEAST_EXPECT( - trustedKeys->getTrustedMasterKeys().size() == keysTotal); + BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); hash_set added; for (auto const& val : valKeys) @@ -3383,8 +2849,7 @@ private: env.app().overlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == quorumDisabled); - BEAST_EXPECT( - trustedKeys->getTrustedMasterKeys().size() == keysTotal); + BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); BEAST_EXPECT(trustedKeys->trusted(self.masterPublic)); for (auto const& val : valKeys) @@ -3420,8 +2885,7 @@ private: env.app().overlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == std::ceil(keysTotal * 0.8f)); - BEAST_EXPECT( - trustedKeys->getTrustedMasterKeys().size() == keysTotal); + BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); hash_set added; for (auto const& val : valKeys) @@ -3441,8 +2905,7 @@ private: env.app().overlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == quorumDisabled); - BEAST_EXPECT( - trustedKeys->getTrustedMasterKeys().size() == keysTotal); + BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); for (auto const& val : valKeys) { @@ -3487,8 +2950,7 @@ private: env.app().overlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == quorumDisabled); - BEAST_EXPECT( - trustedKeys->getTrustedMasterKeys().size() == keysTotal); + BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); hash_set added; added.insert(calcNodeID(self.masterPublic)); @@ -3555,8 +3017,7 @@ private: env.app().overlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == quorumDisabled); - BEAST_EXPECT( - trustedKeys->getTrustedMasterKeys().size() == keysTotal); + BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); hash_set added; for (auto const& val : valKeys) @@ -3623,8 +3084,7 @@ private: env.app().overlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == quorumDisabled); - BEAST_EXPECT( - trustedKeys->getTrustedMasterKeys().size() == keysTotal); + BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); hash_set added; for (auto const& val : valKeys) @@ -3683,8 +3143,7 @@ private: env.app().overlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == std::ceil(keysTotal * 0.8f)); - BEAST_EXPECT( - trustedKeys->getTrustedMasterKeys().size() == keysTotal); + BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); hash_set added; added.insert(calcNodeID(self.masterPublic)); @@ -3745,8 +3204,7 @@ private: env.app().overlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == std::ceil(keysTotal * 0.8f)); - BEAST_EXPECT( - trustedKeys->getTrustedMasterKeys().size() == keysTotal); + BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); hash_set added; added.insert(calcNodeID(self.masterPublic)); @@ -3808,8 +3266,7 @@ private: env.app().overlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == std::ceil(keysTotal * 0.8f)); - BEAST_EXPECT( - trustedKeys->getTrustedMasterKeys().size() == keysTotal); + BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); hash_set added; for (auto const& val : valKeys) @@ -3870,8 +3327,7 @@ private: env.app().overlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == std::ceil(keysTotal * 0.8f)); - BEAST_EXPECT( - trustedKeys->getTrustedMasterKeys().size() == keysTotal); + BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); hash_set added; added.insert(calcNodeID(self.masterPublic)); @@ -3934,8 +3390,7 @@ private: env.app().overlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == std::ceil(keysTotal * 0.8f)); - BEAST_EXPECT( - trustedKeys->getTrustedMasterKeys().size() == keysTotal); + BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); hash_set added; for (auto const& val : valKeys) @@ -3973,8 +3428,7 @@ private: env.app().overlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == std::ceil(keysTotal * 0.8f)); - BEAST_EXPECT( - trustedKeys->getTrustedMasterKeys().size() == keysTotal); + BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); hash_set added; for (auto const& val : valKeys) @@ -4020,8 +3474,7 @@ private: env.app().overlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == std::ceil(keysTotal * 0.8f)); - BEAST_EXPECT( - trustedKeys->getTrustedMasterKeys().size() == keysTotal); + BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); hash_set added; added.insert(calcNodeID(self.masterPublic)); @@ -4090,8 +3543,7 @@ private: env.app().overlay(), env.app().getHashRouter()); BEAST_EXPECT(trustedKeys->quorum() == std::ceil(keysTotal * 0.8f)); - BEAST_EXPECT( - trustedKeys->getTrustedMasterKeys().size() == keysTotal); + BEAST_EXPECT(trustedKeys->getTrustedMasterKeys().size() == keysTotal); hash_set added; for (auto const& val : valKeys) diff --git a/src/test/app/ValidatorSite_test.cpp b/src/test/app/ValidatorSite_test.cpp index 1118818d7a..3b616ad5c9 100644 --- a/src/test/app/ValidatorSite_test.cpp +++ b/src/test/app/ValidatorSite_test.cpp @@ -50,8 +50,7 @@ private: using namespace jtx; Env env(*this, envconfig(), nullptr, beast::severities::kDisabled); - auto trustedSites = - std::make_unique(env.app(), env.journal); + auto trustedSites = std::make_unique(env.app(), env.journal); // load should accept empty sites list std::vector emptyCfgSites; @@ -118,25 +117,18 @@ private: bool failApply = false; int serverVersion = 1; std::chrono::seconds expiresFromNow = detail::default_expires; - std::chrono::seconds effectiveOverlap = - detail::default_effective_overlap; + std::chrono::seconds effectiveOverlap = detail::default_effective_overlap; int expectedRefreshMin = 0; }; void - testFetchList( - detail::DirGuard const& good, - std::vector const& paths) + testFetchList(detail::DirGuard const& good, std::vector const& paths) { testcase << "Fetch list - " << boost::algorithm::join( - paths | - boost::adaptors::transformed( - [](FetchListConfig const& cfg) { - return cfg.path + - (cfg.ssl ? " [https] v" : " [http] v") + - std::to_string(cfg.serverVersion) + - " " + cfg.msg; - }), + paths | boost::adaptors::transformed([](FetchListConfig const& cfg) { + return cfg.path + (cfg.ssl ? " [https] v" : " [http] v") + + std::to_string(cfg.serverVersion) + " " + cfg.msg; + }), ", "); using namespace jtx; @@ -179,19 +171,11 @@ private: while (item.list.size() < listSize) item.list.push_back(TrustedPublisherServer::randomValidator()); - NetClock::time_point const expires = - env.timeKeeper().now() + cfg.expiresFromNow; - NetClock::time_point const effective2 = - expires - cfg.effectiveOverlap; - NetClock::time_point const expires2 = - effective2 + cfg.expiresFromNow; + NetClock::time_point const expires = env.timeKeeper().now() + cfg.expiresFromNow; + NetClock::time_point const effective2 = expires - cfg.effectiveOverlap; + NetClock::time_point const expires2 = effective2 + cfg.expiresFromNow; item.server = make_TrustedPublisherServer( - env.app().getIOContext(), - item.list, - expires, - {{effective2, expires2}}, - cfg.ssl, - cfg.serverVersion); + env.app().getIOContext(), item.list, expires, {{effective2, expires2}}, cfg.ssl, cfg.serverVersion); std::string pubHex = strHex(item.server->publisherPublic()); cfgPublishers.push_back(pubHex); @@ -204,8 +188,7 @@ private: } std::stringstream uri; - uri << (cfg.ssl ? "https://" : "http://") - << item.server->local_endpoint() << cfg.path; + uri << (cfg.ssl ? "https://" : "http://") << item.server->local_endpoint() << cfg.path; item.uri = uri.str(); } @@ -231,10 +214,8 @@ private: { for (auto const& val : u.list) { - BEAST_EXPECT( - trustedKeys.listed(val.masterPublic) != u.cfg.failApply); - BEAST_EXPECT( - trustedKeys.listed(val.signingPublic) != u.cfg.failApply); + BEAST_EXPECT(trustedKeys.listed(val.masterPublic) != u.cfg.failApply); + BEAST_EXPECT(trustedKeys.listed(val.signingPublic) != u.cfg.failApply); } Json::Value myStatus; @@ -242,30 +223,24 @@ private: if (vs[jss::uri].asString().find(u.uri) != std::string::npos) myStatus = vs; BEAST_EXPECTS( - myStatus[jss::last_refresh_message].asString().empty() != - u.cfg.failFetch, + myStatus[jss::last_refresh_message].asString().empty() != u.cfg.failFetch, to_string(myStatus) + "\n" + sink.messages().str()); if (!u.cfg.msg.empty()) { - BEAST_EXPECTS( - sink.messages().str().find(u.cfg.msg) != std::string::npos, - sink.messages().str()); + BEAST_EXPECTS(sink.messages().str().find(u.cfg.msg) != std::string::npos, sink.messages().str()); } if (u.cfg.expectedRefreshMin) { BEAST_EXPECTS( - myStatus[jss::refresh_interval_min].asInt() == - u.cfg.expectedRefreshMin, - to_string(myStatus)); + myStatus[jss::refresh_interval_min].asInt() == u.cfg.expectedRefreshMin, to_string(myStatus)); } if (u.cfg.failFetch) { using namespace std::chrono; - std::stringstream nextRefreshStr{ - myStatus[jss::next_refresh_time].asString()}; + std::stringstream nextRefreshStr{myStatus[jss::next_refresh_time].asString()}; system_clock::time_point nextRefresh; date::from_stream(nextRefreshStr, "%Y-%b-%d %T", nextRefresh); BEAST_EXPECT(!nextRefreshStr.fail()); @@ -280,8 +255,7 @@ private: void testFileList(std::vector> const& paths) { - testcase << "File list - " << paths[0].first - << (paths.size() > 1 ? ", " + paths[1].first : ""); + testcase << "File list - " << paths[0].first << (paths.size() > 1 ? ", " + paths[1].first : ""); using namespace jtx; @@ -326,16 +300,10 @@ private: for (auto const& vs : jv[jss::validator_sites]) if (vs[jss::uri].asString().find(u.uri) != std::string::npos) myStatus = vs; - BEAST_EXPECTS( - myStatus[jss::last_refresh_message].asString().empty() != - u.shouldFail, - to_string(myStatus)); + BEAST_EXPECTS(myStatus[jss::last_refresh_message].asString().empty() != u.shouldFail, to_string(myStatus)); if (u.shouldFail) { - BEAST_EXPECTS( - sink.messages().str().find(u.expectMsg) != - std::string::npos, - sink.messages().str()); + BEAST_EXPECTS(sink.messages().str().find(u.expectMsg) != std::string::npos, sink.messages().str()); } } } @@ -351,27 +319,19 @@ private: }; { // Create a file with a real validator list - detail::FileDirGuard good( - *this, "test_val", "vl.txt", detail::realValidatorContents()); + detail::FileDirGuard good(*this, "test_val", "vl.txt", detail::realValidatorContents()); // Create a file with arbitrary content - detail::FileDirGuard hello( - *this, "test_val", "helloworld.txt", "Hello, world!"); + detail::FileDirGuard hello(*this, "test_val", "helloworld.txt", "Hello, world!"); // Create a file with malformed Json - detail::FileDirGuard json( - *this, - "test_val", - "json.txt", - R"json({ "version": 2, "extra" : "value" })json"); + detail::FileDirGuard json(*this, "test_val", "json.txt", R"json({ "version": 2, "extra" : "value" })json"); auto const goodPath = fullPath(good); auto const helloPath = fullPath(hello); auto const jsonPath = fullPath(json); auto const missingPath = jsonPath + ".bad"; testFileList({ {goodPath, ""}, - {helloPath, - "Unable to parse JSON response from file://" + helloPath}, - {jsonPath, - "Missing fields in JSON response from file://" + jsonPath}, + {helloPath, "Unable to parse JSON response from file://" + helloPath}, + {jsonPath, "Missing fields in JSON response from file://" + jsonPath}, {missingPath, "Problem retrieving from file://" + missingPath}, }); } @@ -390,179 +350,68 @@ public: testFetchList(good, {{"/validators", "", ssl}}); testFetchList(good, {{"/validators2", "", ssl}}); // fetch multiple sites - testFetchList( - good, {{"/validators", "", ssl}, {"/validators", "", ssl}}); - testFetchList( - good, {{"/validators", "", ssl}, {"/validators2", "", ssl}}); - testFetchList( - good, {{"/validators2", "", ssl}, {"/validators", "", ssl}}); - testFetchList( - good, {{"/validators2", "", ssl}, {"/validators2", "", ssl}}); + testFetchList(good, {{"/validators", "", ssl}, {"/validators", "", ssl}}); + testFetchList(good, {{"/validators", "", ssl}, {"/validators2", "", ssl}}); + testFetchList(good, {{"/validators2", "", ssl}, {"/validators", "", ssl}}); + testFetchList(good, {{"/validators2", "", ssl}, {"/validators2", "", ssl}}); // fetch single site with single redirects testFetchList(good, {{"/redirect_once/301", "", ssl}}); testFetchList(good, {{"/redirect_once/302", "", ssl}}); testFetchList(good, {{"/redirect_once/307", "", ssl}}); testFetchList(good, {{"/redirect_once/308", "", ssl}}); // one redirect, one not - testFetchList( - good, - {{"/validators", "", ssl}, {"/redirect_once/302", "", ssl}}); - testFetchList( - good, - {{"/validators2", "", ssl}, {"/redirect_once/302", "", ssl}}); + testFetchList(good, {{"/validators", "", ssl}, {"/redirect_once/302", "", ssl}}); + testFetchList(good, {{"/validators2", "", ssl}, {"/redirect_once/302", "", ssl}}); // UNLs with a "gap" between validUntil of one and validFrom of the // next testFetchList( - good, - {{"/validators2", - "", - ssl, - false, - false, - 1, - detail::default_expires, - std::chrono::seconds{-90}}}); + good, {{"/validators2", "", ssl, false, false, 1, detail::default_expires, std::chrono::seconds{-90}}}); // fetch single site with unending redirect (fails to load) - testFetchList( - good, - {{"/redirect_forever/301", - "Exceeded max redirects", - ssl, - true, - true}}); + testFetchList(good, {{"/redirect_forever/301", "Exceeded max redirects", ssl, true, true}}); // two that redirect forever testFetchList( good, - {{"/redirect_forever/307", - "Exceeded max redirects", - ssl, - true, - true}, - {"/redirect_forever/308", - "Exceeded max redirects", - ssl, - true, - true}}); + {{"/redirect_forever/307", "Exceeded max redirects", ssl, true, true}, + {"/redirect_forever/308", "Exceeded max redirects", ssl, true, true}}); + // one unending redirect, one not + testFetchList( + good, {{"/validators", "", ssl}, {"/redirect_forever/302", "Exceeded max redirects", ssl, true, true}}); // one unending redirect, one not testFetchList( good, - {{"/validators", "", ssl}, - {"/redirect_forever/302", - "Exceeded max redirects", - ssl, - true, - true}}); - // one unending redirect, one not - testFetchList( - good, - {{"/validators2", "", ssl}, - {"/redirect_forever/302", - "Exceeded max redirects", - ssl, - true, - true}}); + {{"/validators2", "", ssl}, {"/redirect_forever/302", "Exceeded max redirects", ssl, true, true}}); // invalid redir Location + testFetchList(good, {{"/redirect_to/ftp://invalid-url/302", "Invalid redirect location", ssl, true, true}}); testFetchList( - good, - {{"/redirect_to/ftp://invalid-url/302", - "Invalid redirect location", - ssl, - true, - true}}); - testFetchList( - good, - {{"/redirect_to/file://invalid-url/302", - "Invalid redirect location", - ssl, - true, - true}}); + good, {{"/redirect_to/file://invalid-url/302", "Invalid redirect location", ssl, true, true}}); // invalid json - testFetchList( - good, - {{"/validators/bad", - "Unable to parse JSON response", - ssl, - true, - true}}); - testFetchList( - good, - {{"/validators2/bad", - "Unable to parse JSON response", - ssl, - true, - true}}); + testFetchList(good, {{"/validators/bad", "Unable to parse JSON response", ssl, true, true}}); + testFetchList(good, {{"/validators2/bad", "Unable to parse JSON response", ssl, true, true}}); // error status returned - testFetchList( - good, - {{"/bad-resource", "returned bad status", ssl, true, true}}); + testFetchList(good, {{"/bad-resource", "returned bad status", ssl, true, true}}); // location field missing - testFetchList( - good, - {{"/redirect_nolo/308", - "returned a redirect with no Location", - ssl, - true, - true}}); + testFetchList(good, {{"/redirect_nolo/308", "returned a redirect with no Location", ssl, true, true}}); // json fields missing - testFetchList( - good, - {{"/validators/missing", - "Missing fields in JSON response", - ssl, - true, - true}}); - testFetchList( - good, - {{"/validators2/missing", - "Missing fields in JSON response", - ssl, - true, - true}}); + testFetchList(good, {{"/validators/missing", "Missing fields in JSON response", ssl, true, true}}); + testFetchList(good, {{"/validators2/missing", "Missing fields in JSON response", ssl, true, true}}); // timeout - testFetchList( - good, {{"/sleep/13", "took too long", ssl, true, true}}); + testFetchList(good, {{"/sleep/13", "took too long", ssl, true, true}}); // bad manifest format using known versions // * Retrieves a v1 formatted list claiming version 2 - testFetchList( - good, {{"/validators", "Missing fields", ssl, true, true, 2}}); + testFetchList(good, {{"/validators", "Missing fields", ssl, true, true, 2}}); // * Retrieves a v2 formatted list claiming version 1 - testFetchList( - good, {{"/validators2", "Missing fields", ssl, true, true, 0}}); + testFetchList(good, {{"/validators2", "Missing fields", ssl, true, true, 0}}); // bad manifest version // Because versions other than 1 are treated as v2, the v1 // list won't have the blobs_v2 fields, and thus will claim to have // missing fields - testFetchList( - good, {{"/validators", "Missing fields", ssl, true, true, 4}}); - testFetchList( - good, - {{"/validators2", - "1 unsupported version", - ssl, - false, - true, - 4}}); + testFetchList(good, {{"/validators", "Missing fields", ssl, true, true, 4}}); + testFetchList(good, {{"/validators2", "1 unsupported version", ssl, false, true, 4}}); using namespace std::chrono_literals; // get expired validator list + testFetchList(good, {{"/validators", "Applied 1 expired validator list(s)", ssl, false, false, 1, 0s}}); testFetchList( - good, - {{"/validators", - "Applied 1 expired validator list(s)", - ssl, - false, - false, - 1, - 0s}}); - testFetchList( - good, - {{"/validators2", - "Applied 1 expired validator list(s)", - ssl, - false, - false, - 1, - 0s, - -1s}}); + good, {{"/validators2", "Applied 1 expired validator list(s)", ssl, false, false, 1, 0s, -1s}}); // force an out-of-range validUntil value testFetchList( good, @@ -578,27 +427,13 @@ public: // returns the "best" result, so this looks like a success. testFetchList( good, - {{"/validators2", - "", - ssl, - false, - false, - 1, - std::chrono::seconds{Json::Value::maxInt - 300}, - 299s}}); + {{"/validators2", "", ssl, false, false, 1, std::chrono::seconds{Json::Value::maxInt - 300}, 299s}}); // force an out-of-range validFrom value // The first list is accepted. The second fails. The parser // returns the "best" result, so this looks like a success. testFetchList( good, - {{"/validators2", - "", - ssl, - false, - false, - 1, - std::chrono::seconds{Json::Value::maxInt - 300}, - 301s}}); + {{"/validators2", "", ssl, false, false, 1, std::chrono::seconds{Json::Value::maxInt - 300}, 301s}}); // force an out-of-range validUntil value on _both_ lists testFetchList( good, diff --git a/src/test/app/Vault_test.cpp b/src/test/app/Vault_test.cpp index 41a4fc2b3b..5d31c674c0 100644 --- a/src/test/app/Vault_test.cpp +++ b/src/test/app/Vault_test.cpp @@ -35,8 +35,7 @@ class Vault_test : public beast::unit_test::suite using PrettyAsset = xrpl::test::jtx::PrettyAsset; using PrettyAmount = xrpl::test::jtx::PrettyAmount; - static auto constexpr negativeAmount = - [](PrettyAsset const& asset) -> PrettyAmount { + static auto constexpr negativeAmount = [](PrettyAsset const& asset) -> PrettyAmount { return {STAmount{asset.raw(), 1ul, 0, true, STAmount::unchecked{}}, ""}; }; @@ -51,10 +50,7 @@ class Vault_test : public beast::unit_test::suite Account dave{"dave"}; auto const testSequence = [&, this]( - std::string const& prefix, - Env& env, - Vault& vault, - PrettyAsset const& asset) { + std::string const& prefix, Env& env, Vault& vault, PrettyAsset const& asset) { auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); tx[sfData] = "AFEED00E"; tx[sfAssetsMaximum] = asset(100).number(); @@ -64,26 +60,20 @@ class Vault_test : public beast::unit_test::suite std::uint64_t const scale = asset.raw().holds() ? 1 : 1e6; auto const [share, vaultAccount] = - [&env, - keylet = keylet, - asset, - this]() -> std::tuple { + [&env, keylet = keylet, asset, this]() -> std::tuple { auto const vault = env.le(keylet); BEAST_EXPECT(vault != nullptr); if (!asset.integral()) BEAST_EXPECT(vault->at(sfScale) == 6); else BEAST_EXPECT(vault->at(sfScale) == 0); - auto const shares = - env.le(keylet::mptIssuance(vault->at(sfShareMPTID))); + auto const shares = env.le(keylet::mptIssuance(vault->at(sfShareMPTID))); BEAST_EXPECT(shares != nullptr); if (!asset.integral()) BEAST_EXPECT(shares->at(sfAssetScale) == 6); else BEAST_EXPECT(shares->at(sfAssetScale) == 0); - return { - MPTIssue(vault->at(sfShareMPTID)), - Account("vault", vault->at(sfAccount))}; + return {MPTIssue(vault->at(sfShareMPTID)), Account("vault", vault->at(sfAccount))}; }(); auto const shares = share.raw().get(); env.memoize(vaultAccount); @@ -97,36 +87,25 @@ class Vault_test : public beast::unit_test::suite { testcase(prefix + " fail to deposit more than assets held"); - auto tx = vault.deposit( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(10000)}); + auto tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(10000)}); env(tx, ter(tecINSUFFICIENT_FUNDS)); env.close(); } { testcase(prefix + " deposit non-zero amount"); - auto tx = vault.deposit( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(50)}); + auto tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(50)}); env(tx); env.close(); - BEAST_EXPECT( - env.balance(depositor, shares) == share(50 * scale)); + BEAST_EXPECT(env.balance(depositor, shares) == share(50 * scale)); } { testcase(prefix + " deposit non-zero amount again"); - auto tx = vault.deposit( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(50)}); + auto tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(50)}); env(tx); env.close(); - BEAST_EXPECT( - env.balance(depositor, shares) == share(100 * scale)); + BEAST_EXPECT(env.balance(depositor, shares) == share(100 * scale)); } { @@ -145,8 +124,7 @@ class Vault_test : public beast::unit_test::suite } { - testcase( - prefix + " fail to set maximum lower than current amount"); + testcase(prefix + " fail to set maximum lower than current amount"); auto tx = vault.set({.owner = owner, .id = keylet.key}); tx[sfAssetsMaximum] = asset(50).number(); env(tx, ter(tecLIMIT_EXCEEDED)); @@ -187,10 +165,7 @@ class Vault_test : public beast::unit_test::suite { testcase(prefix + " fail to deposit more than maximum"); - auto tx = vault.deposit( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(100)}); + auto tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(100)}); env(tx, ter(tecLIMIT_EXCEEDED)); env.close(); } @@ -205,50 +180,36 @@ class Vault_test : public beast::unit_test::suite { testcase(prefix + " fail to withdraw more than assets held"); - auto tx = vault.withdraw( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(1000)}); + auto tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(1000)}); env(tx, ter(tecINSUFFICIENT_FUNDS)); env.close(); } { testcase(prefix + " deposit some more"); - auto tx = vault.deposit( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(100)}); + auto tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(100)}); env(tx); env.close(); - BEAST_EXPECT( - env.balance(depositor, shares) == share(200 * scale)); + BEAST_EXPECT(env.balance(depositor, shares) == share(200 * scale)); } { testcase(prefix + " clawback some"); - auto code = - asset.raw().native() ? ter(temMALFORMED) : ter(tesSUCCESS); - auto tx = vault.clawback( - {.issuer = issuer, - .id = keylet.key, - .holder = depositor, - .amount = asset(10)}); + auto code = asset.raw().native() ? ter(temMALFORMED) : ter(tesSUCCESS); + auto tx = + vault.clawback({.issuer = issuer, .id = keylet.key, .holder = depositor, .amount = asset(10)}); env(tx, code); env.close(); if (!asset.raw().native()) { - BEAST_EXPECT( - env.balance(depositor, shares) == share(190 * scale)); + BEAST_EXPECT(env.balance(depositor, shares) == share(190 * scale)); } } { testcase(prefix + " clawback all"); - auto code = asset.raw().native() ? ter(tecNO_PERMISSION) - : ter(tesSUCCESS); - auto tx = vault.clawback( - {.issuer = issuer, .id = keylet.key, .holder = depositor}); + auto code = asset.raw().native() ? ter(tecNO_PERMISSION) : ter(tesSUCCESS); + auto tx = vault.clawback({.issuer = issuer, .id = keylet.key, .holder = depositor}); env(tx, code); env.close(); if (!asset.raw().native()) @@ -257,19 +218,13 @@ class Vault_test : public beast::unit_test::suite { auto tx = vault.clawback( - {.issuer = issuer, - .id = keylet.key, - .holder = depositor, - .amount = asset(10)}); + {.issuer = issuer, .id = keylet.key, .holder = depositor, .amount = asset(10)}); env(tx, ter{tecPRECISION_LOSS}); env.close(); } { - auto tx = vault.withdraw( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(10)}); + auto tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(10)}); env(tx, ter{tecPRECISION_LOSS}); env.close(); } @@ -279,72 +234,46 @@ class Vault_test : public beast::unit_test::suite if (!asset.raw().native()) { testcase(prefix + " deposit again"); - auto tx = vault.deposit( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(200)}); + auto tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(200)}); env(tx); env.close(); - BEAST_EXPECT( - env.balance(depositor, shares) == share(200 * scale)); + BEAST_EXPECT(env.balance(depositor, shares) == share(200 * scale)); } else { testcase(prefix + " deposit/withdrawal same or less than fee"); auto const amount = env.current()->fees().base; - auto tx = vault.deposit( - {.depositor = depositor, - .id = keylet.key, - .amount = amount}); + auto tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = amount}); env(tx); env.close(); - tx = vault.withdraw( - {.depositor = depositor, - .id = keylet.key, - .amount = amount}); + tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = amount}); env(tx); env.close(); - tx = vault.deposit( - {.depositor = depositor, - .id = keylet.key, - .amount = amount}); + tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = amount}); env(tx); env.close(); // Withdraw to 3rd party - tx = vault.withdraw( - {.depositor = depositor, - .id = keylet.key, - .amount = amount}); + tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = amount}); tx[sfDestination] = charlie.human(); env(tx); env.close(); - tx = vault.deposit( - {.depositor = depositor, - .id = keylet.key, - .amount = amount - 1}); + tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = amount - 1}); env(tx); env.close(); - tx = vault.withdraw( - {.depositor = depositor, - .id = keylet.key, - .amount = amount - 1}); + tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = amount - 1}); env(tx); env.close(); } { - testcase( - prefix + " fail to withdraw to 3rd party lsfDepositAuth"); - auto tx = vault.withdraw( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(100)}); + testcase(prefix + " fail to withdraw to 3rd party lsfDepositAuth"); + auto tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(100)}); tx[sfDestination] = alice.human(); env(tx, ter{tecNO_PERMISSION}); env.close(); @@ -352,10 +281,7 @@ class Vault_test : public beast::unit_test::suite { testcase(prefix + " fail to withdraw to zero destination"); - auto tx = vault.withdraw( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(1000)}); + auto tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(1000)}); tx[sfDestination] = "0"; env(tx, ter(temMALFORMED)); env.close(); @@ -363,26 +289,16 @@ class Vault_test : public beast::unit_test::suite if (!asset.raw().native()) { - testcase( - prefix + " fail to withdraw to 3rd party no authorization"); - auto tx = vault.withdraw( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(100)}); + testcase(prefix + " fail to withdraw to 3rd party no authorization"); + auto tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(100)}); tx[sfDestination] = erin.human(); - env(tx, - ter{asset.raw().holds() ? tecNO_LINE : tecNO_AUTH}); + env(tx, ter{asset.raw().holds() ? tecNO_LINE : tecNO_AUTH}); env.close(); } { - testcase( - prefix + - " fail to withdraw to 3rd party lsfRequireDestTag"); - auto tx = vault.withdraw( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(100)}); + testcase(prefix + " fail to withdraw to 3rd party lsfRequireDestTag"); + auto tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(100)}); tx[sfDestination] = dave.human(); env(tx, ter{tecDST_TAG_NEEDED}); env.close(); @@ -390,10 +306,7 @@ class Vault_test : public beast::unit_test::suite { testcase(prefix + " withdraw to 3rd party lsfRequireDestTag"); - auto tx = vault.withdraw( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(50)}); + auto tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(50)}); tx[sfDestination] = dave.human(); tx[sfDestinationTag] = "0"; env(tx); @@ -402,24 +315,21 @@ class Vault_test : public beast::unit_test::suite { testcase(prefix + " deposit again"); - auto tx = vault.deposit( - {.depositor = dave, .id = keylet.key, .amount = asset(50)}); + auto tx = vault.deposit({.depositor = dave, .id = keylet.key, .amount = asset(50)}); env(tx); env.close(); } { testcase(prefix + " fail to withdraw lsfRequireDestTag"); - auto tx = vault.withdraw( - {.depositor = dave, .id = keylet.key, .amount = asset(50)}); + auto tx = vault.withdraw({.depositor = dave, .id = keylet.key, .amount = asset(50)}); env(tx, ter{tecDST_TAG_NEEDED}); env.close(); } { testcase(prefix + " withdraw with tag"); - auto tx = vault.withdraw( - {.depositor = dave, .id = keylet.key, .amount = asset(50)}); + auto tx = vault.withdraw({.depositor = dave, .id = keylet.key, .amount = asset(50)}); tx[sfDestinationTag] = "0"; env(tx); env.close(); @@ -427,46 +337,32 @@ class Vault_test : public beast::unit_test::suite { testcase(prefix + " withdraw to authorized 3rd party"); - auto tx = vault.withdraw( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(50)}); + auto tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(50)}); tx[sfDestination] = charlie.human(); env(tx); env.close(); - BEAST_EXPECT( - env.balance(depositor, shares) == share(100 * scale)); + BEAST_EXPECT(env.balance(depositor, shares) == share(100 * scale)); } { testcase(prefix + " withdraw to issuer"); - auto tx = vault.withdraw( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(50)}); + auto tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(50)}); tx[sfDestination] = issuer.human(); env(tx); env.close(); - BEAST_EXPECT( - env.balance(depositor, shares) == share(50 * scale)); + BEAST_EXPECT(env.balance(depositor, shares) == share(50 * scale)); } if (!asset.raw().native()) { testcase(prefix + " issuer deposits"); - auto tx = vault.deposit( - {.depositor = issuer, - .id = keylet.key, - .amount = asset(10)}); + auto tx = vault.deposit({.depositor = issuer, .id = keylet.key, .amount = asset(10)}); env(tx); env.close(); BEAST_EXPECT(env.balance(issuer, shares) == share(10 * scale)); testcase(prefix + " issuer withdraws"); - tx = vault.withdraw( - {.depositor = issuer, - .id = keylet.key, - .amount = share(10 * scale)}); + tx = vault.withdraw({.depositor = issuer, .id = keylet.key, .amount = share(10 * scale)}); env(tx); env.close(); BEAST_EXPECT(env.balance(issuer, shares) == share(0 * scale)); @@ -474,30 +370,21 @@ class Vault_test : public beast::unit_test::suite { testcase(prefix + " withdraw remaining assets"); - auto tx = vault.withdraw( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(50)}); + auto tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(50)}); env(tx); env.close(); BEAST_EXPECT(env.balance(depositor, shares) == share(0)); if (!asset.raw().native()) { - auto tx = vault.clawback( - {.issuer = issuer, - .id = keylet.key, - .holder = depositor, - .amount = asset(0)}); + auto tx = + vault.clawback({.issuer = issuer, .id = keylet.key, .holder = depositor, .amount = asset(0)}); env(tx, ter{tecPRECISION_LOSS}); env.close(); } { - auto tx = vault.withdraw( - {.depositor = depositor, - .id = keylet.key, - .amount = share(10)}); + auto tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = share(10)}); env(tx, ter{tecINSUFFICIENT_FUNDS}); env.close(); } @@ -511,8 +398,7 @@ class Vault_test : public beast::unit_test::suite env(pay(issuer, erin, asset(10))); // Erin deposits all in vault, then sends shares to depositor - auto tx = vault.deposit( - {.depositor = erin, .id = keylet.key, .amount = asset(10)}); + auto tx = vault.deposit({.depositor = erin, .id = keylet.key, .amount = asset(10)}); env(tx); env.close(); { @@ -523,10 +409,7 @@ class Vault_test : public beast::unit_test::suite env.close(); // depositor will gain MPToken for shares again - env(vault.deposit( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(1)})); + env(vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(1)})); env.close(); env(tx); @@ -535,10 +418,7 @@ class Vault_test : public beast::unit_test::suite testcase(prefix + " withdraw to authorized 3rd party"); // Depositor withdraws assets, destined to Erin - tx = vault.withdraw( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(10)}); + tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(10)}); tx[sfDestination] = erin.human(); env(tx); env.close(); @@ -556,10 +436,7 @@ class Vault_test : public beast::unit_test::suite env.close(); // Depositor withdraws remaining single asset - tx = vault.withdraw( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(1)}); + tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(1)}); env(tx); env.close(); } @@ -580,9 +457,7 @@ class Vault_test : public beast::unit_test::suite } }; - auto testCases = [&, this]( - std::string prefix, - std::function setup) { + auto testCases = [&, this](std::string prefix, std::function setup) { Env env{*this, testable_amendments() | featureSingleAssetVault}; Vault vault{env}; @@ -599,9 +474,7 @@ class Vault_test : public beast::unit_test::suite testSequence(prefix, env, vault, asset); }; - testCases("XRP", [&](Env& env) -> PrettyAsset { - return {xrpIssue(), 1'000'000}; - }); + testCases("XRP", [&](Env& env) -> PrettyAsset { return {xrpIssue(), 1'000'000}; }); testCases("IOU", [&](Env& env) -> Asset { PrettyAsset asset = issuer["IOU"]; @@ -620,8 +493,7 @@ class Vault_test : public beast::unit_test::suite testCases("MPT", [&](Env& env) -> Asset { MPTTester mptt{env, issuer, mptInitNoFund}; - mptt.create( - {.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock}); + mptt.create({.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock}); PrettyAsset asset = mptt.issuanceID(); mptt.authorize({.account = depositor}); mptt.authorize({.account = charlie}); @@ -639,49 +511,40 @@ class Vault_test : public beast::unit_test::suite struct CaseArgs { - FeatureBitset features = - testable_amendments() | featureSingleAssetVault; + FeatureBitset features = testable_amendments() | featureSingleAssetVault; }; - auto testCase = [&, this]( - std::function test, - CaseArgs args = {}) { - Env env{*this, args.features}; - Account issuer{"issuer"}; - Account owner{"owner"}; - Vault vault{env}; - env.fund(XRP(1000), issuer, owner); - env.close(); + auto testCase = + [&, this]( + std::function test, + CaseArgs args = {}) { + Env env{*this, args.features}; + Account issuer{"issuer"}; + Account owner{"owner"}; + Vault vault{env}; + env.fund(XRP(1000), issuer, owner); + env.close(); - env(fset(issuer, asfAllowTrustLineClawback)); - env(fset(issuer, asfRequireAuth)); - env.close(); + env(fset(issuer, asfAllowTrustLineClawback)); + env(fset(issuer, asfRequireAuth)); + env.close(); - PrettyAsset asset = issuer["IOU"]; - env(trust(owner, asset(1000))); - env(trust(issuer, asset(0), owner, tfSetfAuth)); - env(pay(issuer, owner, asset(1000))); - env.close(); + PrettyAsset asset = issuer["IOU"]; + env(trust(owner, asset(1000))); + env(trust(issuer, asset(0), owner, tfSetfAuth)); + env(pay(issuer, owner, asset(1000))); + env.close(); - test(env, issuer, owner, asset, vault); - }; + test(env, issuer, owner, asset, vault); + }; auto testDisabled = [&](TER resultAfterCreate = temDISABLED) { return [&, resultAfterCreate]( - Env& env, - Account const& issuer, - Account const& owner, - Asset const& asset, - Vault& vault) { + Env& env, Account const& issuer, Account const& owner, Asset const& asset, Vault& vault) { testcase("disabled single asset vault"); - auto [tx, keylet] = - vault.create({.owner = owner, .asset = asset}); + auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); env(tx, ter{temDISABLED}); { @@ -690,27 +553,18 @@ class Vault_test : public beast::unit_test::suite } { - auto tx = vault.deposit( - {.depositor = owner, - .id = keylet.key, - .amount = asset(10)}); + auto tx = vault.deposit({.depositor = owner, .id = keylet.key, .amount = asset(10)}); env(tx, ter{resultAfterCreate}); } { - auto tx = vault.withdraw( - {.depositor = owner, - .id = keylet.key, - .amount = asset(10)}); + auto tx = vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(10)}); env(tx, ter{resultAfterCreate}); } { - auto tx = vault.clawback( - {.issuer = issuer, - .id = keylet.key, - .holder = owner, - .amount = asset(10)}); + auto tx = + vault.clawback({.issuer = issuer, .id = keylet.key, .holder = owner, .amount = asset(10)}); env(tx, ter{resultAfterCreate}); } @@ -721,24 +575,15 @@ class Vault_test : public beast::unit_test::suite }; }; - testCase( - testDisabled(), - {.features = testable_amendments() - featureSingleAssetVault}); + testCase(testDisabled(), {.features = testable_amendments() - featureSingleAssetVault}); + + testCase(testDisabled(tecNO_ENTRY), {.features = testable_amendments() - featureMPTokensV1}); testCase( - testDisabled(tecNO_ENTRY), - {.features = testable_amendments() - featureMPTokensV1}); - - testCase( - [&](Env& env, - Account const& issuer, - Account const& owner, - Asset const& asset, - Vault& vault) { + [&](Env& env, Account const& issuer, Account const& owner, Asset const& asset, Vault& vault) { testcase("disabled permissioned domains"); - auto [tx, keylet] = - vault.create({.owner = owner, .asset = asset}); + auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); env(tx); tx[sfFlags] = tx[sfFlags].asUInt() | tfVaultPrivate; @@ -755,11 +600,7 @@ class Vault_test : public beast::unit_test::suite }, {.features = testable_amendments() - featurePermissionedDomains}); - testCase([&](Env& env, - Account const& issuer, - Account const& owner, - Asset const& asset, - Vault& vault) { + testCase([&](Env& env, Account const& issuer, Account const& owner, Asset const& asset, Vault& vault) { testcase("invalid flags"); auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); @@ -773,29 +614,19 @@ class Vault_test : public beast::unit_test::suite } { - auto tx = vault.deposit( - {.depositor = owner, - .id = keylet.key, - .amount = asset(10)}); + auto tx = vault.deposit({.depositor = owner, .id = keylet.key, .amount = asset(10)}); tx[sfFlags] = tfClearDeepFreeze; env(tx, ter{temINVALID_FLAG}); } { - auto tx = vault.withdraw( - {.depositor = owner, - .id = keylet.key, - .amount = asset(10)}); + auto tx = vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(10)}); tx[sfFlags] = tfClearDeepFreeze; env(tx, ter{temINVALID_FLAG}); } { - auto tx = vault.clawback( - {.issuer = issuer, - .id = keylet.key, - .holder = owner, - .amount = asset(10)}); + auto tx = vault.clawback({.issuer = issuer, .id = keylet.key, .holder = owner, .amount = asset(10)}); tx[sfFlags] = tfClearDeepFreeze; env(tx, ter{temINVALID_FLAG}); } @@ -807,11 +638,7 @@ class Vault_test : public beast::unit_test::suite } }); - testCase([&](Env& env, - Account const& issuer, - Account const& owner, - Asset const& asset, - Vault& vault) { + testCase([&](Env& env, Account const& issuer, Account const& owner, Asset const& asset, Vault& vault) { testcase("invalid fee"); auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); @@ -825,29 +652,19 @@ class Vault_test : public beast::unit_test::suite } { - auto tx = vault.deposit( - {.depositor = owner, - .id = keylet.key, - .amount = asset(10)}); + auto tx = vault.deposit({.depositor = owner, .id = keylet.key, .amount = asset(10)}); tx[jss::Fee] = "-1"; env(tx, ter{temBAD_FEE}); } { - auto tx = vault.withdraw( - {.depositor = owner, - .id = keylet.key, - .amount = asset(10)}); + auto tx = vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(10)}); tx[jss::Fee] = "-1"; env(tx, ter{temBAD_FEE}); } { - auto tx = vault.clawback( - {.issuer = issuer, - .id = keylet.key, - .holder = owner, - .amount = asset(10)}); + auto tx = vault.clawback({.issuer = issuer, .id = keylet.key, .holder = owner, .amount = asset(10)}); tx[jss::Fee] = "-1"; env(tx, ter{temBAD_FEE}); } @@ -860,15 +677,10 @@ class Vault_test : public beast::unit_test::suite }); testCase( - [&](Env& env, - Account const&, - Account const& owner, - Asset const&, - Vault& vault) { + [&](Env& env, Account const&, Account const& owner, Asset const&, Vault& vault) { testcase("disabled permissioned domain"); - auto [tx, keylet] = - vault.create({.owner = owner, .asset = xrpIssue()}); + auto [tx, keylet] = vault.create({.owner = owner, .asset = xrpIssue()}); tx[sfDomainID] = to_string(base_uint<256>(42ul)); env(tx, ter{temDISABLED}); @@ -884,18 +696,12 @@ class Vault_test : public beast::unit_test::suite env(tx, ter{temDISABLED}); } }, - {.features = (testable_amendments() | featureSingleAssetVault) - - featurePermissionedDomains}); + {.features = (testable_amendments() | featureSingleAssetVault) - featurePermissionedDomains}); - testCase([&](Env& env, - Account const& issuer, - Account const& owner, - Asset const& asset, - Vault& vault) { + testCase([&](Env& env, Account const& issuer, Account const& owner, Asset const& asset, Vault& vault) { testcase("use zero vault"); - auto [tx, keylet] = - vault.create({.owner = owner, .asset = xrpIssue()}); + auto [tx, keylet] = vault.create({.owner = owner, .asset = xrpIssue()}); { auto tx = vault.set({ @@ -906,27 +712,17 @@ class Vault_test : public beast::unit_test::suite } { - auto tx = vault.deposit( - {.depositor = owner, - .id = beast::zero, - .amount = asset(10)}); + auto tx = vault.deposit({.depositor = owner, .id = beast::zero, .amount = asset(10)}); env(tx, ter(temMALFORMED)); } { - auto tx = vault.withdraw( - {.depositor = owner, - .id = beast::zero, - .amount = asset(10)}); + auto tx = vault.withdraw({.depositor = owner, .id = beast::zero, .amount = asset(10)}); env(tx, ter{temMALFORMED}); } { - auto tx = vault.clawback( - {.issuer = issuer, - .id = beast::zero, - .holder = owner, - .amount = asset(10)}); + auto tx = vault.clawback({.issuer = issuer, .id = beast::zero, .holder = owner, .amount = asset(10)}); env(tx, ter{temMALFORMED}); } @@ -939,50 +735,36 @@ class Vault_test : public beast::unit_test::suite } }); - testCase([&](Env& env, - Account const&, - Account const& owner, - Asset const& asset, - Vault& vault) { + testCase([&](Env& env, Account const&, Account const& owner, Asset const& asset, Vault& vault) { testcase("withdraw to bad destination"); auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); { - auto tx = vault.withdraw( - {.depositor = owner, - .id = keylet.key, - .amount = asset(10)}); + auto tx = vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(10)}); tx[jss::Destination] = "0"; env(tx, ter{temMALFORMED}); } }); - testCase([&](Env& env, - Account const&, - Account const& owner, - Asset const& asset, - Vault& vault) { + testCase([&](Env& env, Account const&, Account const& owner, Asset const& asset, Vault& vault) { testcase("create with Scale"); { - auto [tx, keylet] = - vault.create({.owner = owner, .asset = asset}); + auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); tx[sfScale] = 255; env(tx, ter(temMALFORMED)); } { - auto [tx, keylet] = - vault.create({.owner = owner, .asset = asset}); + auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); tx[sfScale] = 19; env(tx, ter(temMALFORMED)); } // accepted range from 0 to 18 { - auto [tx, keylet] = - vault.create({.owner = owner, .asset = asset}); + auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); tx[sfScale] = 18; env(tx); env.close(); @@ -992,8 +774,7 @@ class Vault_test : public beast::unit_test::suite } { - auto [tx, keylet] = - vault.create({.owner = owner, .asset = asset}); + auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); tx[sfScale] = 0; env(tx); env.close(); @@ -1003,8 +784,7 @@ class Vault_test : public beast::unit_test::suite } { - auto [tx, keylet] = - vault.create({.owner = owner, .asset = asset}); + auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); env(tx); env.close(); auto const sleVault = env.le(keylet); @@ -1013,11 +793,7 @@ class Vault_test : public beast::unit_test::suite } }); - testCase([&](Env& env, - Account const&, - Account const& owner, - Asset const& asset, - Vault& vault) { + testCase([&](Env& env, Account const&, Account const& owner, Asset const& asset, Vault& vault) { testcase("create or set invalid data"); auto [tx1, keylet] = vault.create({.owner = owner, .asset = asset}); @@ -1049,11 +825,7 @@ class Vault_test : public beast::unit_test::suite } }); - testCase([&](Env& env, - Account const&, - Account const& owner, - Asset const& asset, - Vault& vault) { + testCase([&](Env& env, Account const&, Account const& owner, Asset const& asset, Vault& vault) { testcase("set nothing updated"); auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); @@ -1064,11 +836,7 @@ class Vault_test : public beast::unit_test::suite } }); - testCase([&](Env& env, - Account const&, - Account const& owner, - Asset const& asset, - Vault& vault) { + testCase([&](Env& env, Account const&, Account const& owner, Asset const& asset, Vault& vault) { testcase("create with invalid metadata"); auto [tx1, keylet] = vault.create({.owner = owner, .asset = asset}); @@ -1088,11 +856,7 @@ class Vault_test : public beast::unit_test::suite } }); - testCase([&](Env& env, - Account const&, - Account const& owner, - Asset const& asset, - Vault& vault) { + testCase([&](Env& env, Account const&, Account const& owner, Asset const& asset, Vault& vault) { testcase("set negative maximum"); auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); @@ -1104,35 +868,23 @@ class Vault_test : public beast::unit_test::suite } }); - testCase([&](Env& env, - Account const&, - Account const& owner, - Asset const& asset, - Vault& vault) { + testCase([&](Env& env, Account const&, Account const& owner, Asset const& asset, Vault& vault) { testcase("invalid deposit amount"); auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); { - auto tx = vault.deposit( - {.depositor = owner, - .id = keylet.key, - .amount = negativeAmount(asset)}); + auto tx = vault.deposit({.depositor = owner, .id = keylet.key, .amount = negativeAmount(asset)}); env(tx, ter(temBAD_AMOUNT)); } { - auto tx = vault.deposit( - {.depositor = owner, .id = keylet.key, .amount = asset(0)}); + auto tx = vault.deposit({.depositor = owner, .id = keylet.key, .amount = asset(0)}); env(tx, ter(temBAD_AMOUNT)); } }); - testCase([&](Env& env, - Account const&, - Account const& owner, - Asset const& asset, - Vault& vault) { + testCase([&](Env& env, Account const&, Account const& owner, Asset const& asset, Vault& vault) { testcase("invalid set immutable flag"); auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); @@ -1144,35 +896,23 @@ class Vault_test : public beast::unit_test::suite } }); - testCase([&](Env& env, - Account const&, - Account const& owner, - Asset const& asset, - Vault& vault) { + testCase([&](Env& env, Account const&, Account const& owner, Asset const& asset, Vault& vault) { testcase("invalid withdraw amount"); auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); { - auto tx = vault.withdraw( - {.depositor = owner, - .id = keylet.key, - .amount = negativeAmount(asset)}); + auto tx = vault.withdraw({.depositor = owner, .id = keylet.key, .amount = negativeAmount(asset)}); env(tx, ter(temBAD_AMOUNT)); } { - auto tx = vault.withdraw( - {.depositor = owner, .id = keylet.key, .amount = asset(0)}); + auto tx = vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(0)}); env(tx, ter(temBAD_AMOUNT)); } }); - testCase([&](Env& env, - Account const& issuer, - Account const& owner, - Asset const& asset, - Vault& vault) { + testCase([&](Env& env, Account const& issuer, Account const& owner, Asset const& asset, Vault& vault) { testcase("invalid clawback"); auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); @@ -1180,29 +920,18 @@ class Vault_test : public beast::unit_test::suite // Preclaim only checks for native assets. if (asset.native()) { - auto tx = vault.clawback( - {.issuer = issuer, - .id = keylet.key, - .holder = owner, - .amount = asset(50)}); + auto tx = vault.clawback({.issuer = issuer, .id = keylet.key, .holder = owner, .amount = asset(50)}); env(tx, ter(temMALFORMED)); } { auto tx = vault.clawback( - {.issuer = issuer, - .id = keylet.key, - .holder = owner, - .amount = negativeAmount(asset)}); + {.issuer = issuer, .id = keylet.key, .holder = owner, .amount = negativeAmount(asset)}); env(tx, ter(temBAD_AMOUNT)); } }); - testCase([&](Env& env, - Account const&, - Account const& owner, - Asset const& asset, - Vault& vault) { + testCase([&](Env& env, Account const&, Account const& owner, Asset const& asset, Vault& vault) { testcase("invalid create"); auto [tx1, keylet] = vault.create({.owner = owner, .asset = asset}); @@ -1280,10 +1009,7 @@ class Vault_test : public beast::unit_test::suite PrettyAsset const& asset, Vault& vault) { testcase("nothing to deposit to"); - auto tx = vault.deposit( - {.depositor = depositor, - .id = keylet::skip().key, - .amount = asset(10)}); + auto tx = vault.deposit({.depositor = depositor, .id = keylet::skip().key, .amount = asset(10)}); env(tx, ter(tecNO_ENTRY)); }); @@ -1295,10 +1021,7 @@ class Vault_test : public beast::unit_test::suite PrettyAsset const& asset, Vault& vault) { testcase("nothing to withdraw from"); - auto tx = vault.withdraw( - {.depositor = depositor, - .id = keylet::skip().key, - .amount = asset(10)}); + auto tx = vault.withdraw({.depositor = depositor, .id = keylet::skip().key, .amount = asset(10)}); env(tx, ter(tecNO_ENTRY)); }); @@ -1415,10 +1138,7 @@ class Vault_test : public beast::unit_test::suite { { testcase("IOU fail because MPT is disabled"); - Env env{ - *this, - (testable_amendments() - featureMPTokensV1) | - featureSingleAssetVault}; + Env env{*this, (testable_amendments() - featureMPTokensV1) | featureSingleAssetVault}; Account issuer{"issuer"}; Account owner{"owner"}; env.fund(XRP(1000), issuer, owner); @@ -1426,8 +1146,7 @@ class Vault_test : public beast::unit_test::suite Vault vault{env}; Asset asset = issuer["IOU"].asset(); - auto [tx, keylet] = - vault.create({.owner = owner, .asset = asset}); + auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); env(tx, ter(temDISABLED)); env.close(); @@ -1445,8 +1164,7 @@ class Vault_test : public beast::unit_test::suite Vault vault{env}; Asset asset = issuer["IOU"].asset(); - auto [tx, keylet] = - vault.create({.owner = owner, .asset = asset}); + auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); env(tx, ter(tecFROZEN)); env.close(); @@ -1464,8 +1182,7 @@ class Vault_test : public beast::unit_test::suite Vault vault{env}; Asset asset = issuer["IOU"].asset(); - auto [tx, keylet] = - vault.create({.owner = owner, .asset = asset}); + auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); env(tx, ter(terNO_RIPPLE)); env.close(); } @@ -1481,8 +1198,7 @@ class Vault_test : public beast::unit_test::suite Vault vault{env}; Asset asset = issuer["IOU"].asset(); { - auto [tx, keylet] = - vault.create({.owner = owner, .asset = asset}); + auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); env(tx, ter(terNO_ACCOUNT)); env.close(); } @@ -1497,8 +1213,7 @@ class Vault_test : public beast::unit_test::suite Account const carol("carol"); IOU const USD = gw["USD"]; - auto const [asset1, asset2] = - std::pair(XRP(10000), USD(10000)); + auto const [asset1, asset2] = std::pair(XRP(10000), USD(10000)); auto toFund = [&](STAmount const& a) -> STAmount { if (a.native()) { @@ -1523,15 +1238,13 @@ class Vault_test : public beast::unit_test::suite else if (asset2.native()) fund(env, gw, {alice, carol}, toFund2, {toFund1}, Fund::All); - AMM ammAlice( - env, alice, asset1, asset2, CreateArg{.log = false, .tfee = 0}); + AMM ammAlice(env, alice, asset1, asset2, CreateArg{.log = false, .tfee = 0}); Account const owner{"owner"}; env.fund(XRP(1000000), owner); Vault vault{env}; - auto [tx, k] = - vault.create({.owner = owner, .asset = ammAlice.lptIssue()}); + auto [tx, k] = vault.create({.owner = owner, .asset = ammAlice.lptIssue()}); env(tx, ter{tecWRONG_ASSET}); env.close(); } @@ -1630,14 +1343,10 @@ class Vault_test : public beast::unit_test::suite { testcase("nontransferable deposits"); - auto tx1 = vault.deposit( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(40)}); + auto tx1 = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(40)}); env(tx1); - auto tx2 = vault.deposit( - {.depositor = owner, .id = keylet.key, .amount = asset(60)}); + auto tx2 = vault.deposit({.depositor = owner, .id = keylet.key, .amount = asset(60)}); env(tx2); env.close(); } @@ -1646,17 +1355,11 @@ class Vault_test : public beast::unit_test::suite [&env, key = keylet.key, this]() -> AccountID { auto jvVault = env.rpc("vault_info", strHex(key)); - BEAST_EXPECT( - jvVault[jss::result][jss::vault][sfAssetsTotal] == "100"); - BEAST_EXPECT( - jvVault[jss::result][jss::vault][jss::shares] - [sfOutstandingAmount] == "100000000"); + BEAST_EXPECT(jvVault[jss::result][jss::vault][sfAssetsTotal] == "100"); + BEAST_EXPECT(jvVault[jss::result][jss::vault][jss::shares][sfOutstandingAmount] == "100000000"); // Vault pseudo-account - return parseBase58( - jvVault[jss::result][jss::vault][jss::Account] - .asString()) - .value(); + return parseBase58(jvVault[jss::result][jss::vault][jss::Account].asString()).value(); }(); auto const MptID = makeMptID(1, vaultAccount); @@ -1670,14 +1373,10 @@ class Vault_test : public beast::unit_test::suite { testcase("nontransferable shares can be used to withdraw"); - auto tx1 = vault.withdraw( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(20)}); + auto tx1 = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(20)}); env(tx1); - auto tx2 = vault.withdraw( - {.depositor = owner, .id = keylet.key, .amount = asset(30)}); + auto tx2 = vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(30)}); env(tx2); env.close(); } @@ -1685,23 +1384,16 @@ class Vault_test : public beast::unit_test::suite { testcase("nontransferable shares balance check"); auto jvVault = env.rpc("vault_info", strHex(keylet.key)); - BEAST_EXPECT( - jvVault[jss::result][jss::vault][sfAssetsTotal] == "50"); - BEAST_EXPECT( - jvVault[jss::result][jss::vault][jss::shares] - [sfOutstandingAmount] == "50000000"); + BEAST_EXPECT(jvVault[jss::result][jss::vault][sfAssetsTotal] == "50"); + BEAST_EXPECT(jvVault[jss::result][jss::vault][jss::shares][sfOutstandingAmount] == "50000000"); } { testcase("nontransferable shares withdraw rest"); - auto tx1 = vault.withdraw( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(20)}); + auto tx1 = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(20)}); env(tx1); - auto tx2 = vault.withdraw( - {.depositor = owner, .id = keylet.key, .amount = asset(30)}); + auto tx2 = vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(30)}); env(tx2); env.close(); } @@ -1747,8 +1439,7 @@ class Vault_test : public beast::unit_test::suite MPTTester mptt{env, issuer, mptInitNoFund}; auto const none = LedgerSpecificFlags(0); mptt.create( - {.flags = tfMPTCanTransfer | tfMPTCanLock | - (args.enableClawback ? tfMPTCanClawback : none) | + {.flags = tfMPTCanTransfer | tfMPTCanLock | (args.enableClawback ? tfMPTCanClawback : none) | (args.requireAuth ? tfMPTRequireAuth : none), .mutableFlags = tmfMPTCanMutateCanTransfer}); PrettyAsset asset = mptt.issuanceID(); @@ -1775,11 +1466,8 @@ class Vault_test : public beast::unit_test::suite Vault& vault, MPTTester& mptt) { testcase("MPT nothing to clawback from"); - auto tx = vault.clawback( - {.issuer = issuer, - .id = keylet::skip().key, - .holder = depositor, - .amount = asset(10)}); + auto tx = + vault.clawback({.issuer = issuer, .id = keylet::skip().key, .holder = depositor, .amount = asset(10)}); env(tx, ter(tecNO_ENTRY)); }); @@ -1813,10 +1501,7 @@ class Vault_test : public beast::unit_test::suite mptt.set({.account = issuer, .flags = tfMPTLock}); env.close(); - tx = vault.deposit( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(100)}); + tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(100)}); env(tx, ter{tecLOCKED}); env.close(); @@ -1837,10 +1522,7 @@ class Vault_test : public beast::unit_test::suite auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); env(tx); env.close(); - tx = vault.deposit( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(100)}); + tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(100)}); env(tx); env.close(); @@ -1857,21 +1539,14 @@ class Vault_test : public beast::unit_test::suite mptt.set({.account = issuer, .flags = tfMPTLock}); env.close(); - tx = vault.withdraw( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(100)}); + tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(100)}); env(tx, ter(tecLOCKED)); tx[sfDestination] = issuer.human(); env(tx, ter(tecLOCKED)); // Clawback is still permitted, even with global lock - tx = vault.clawback( - {.issuer = issuer, - .id = keylet.key, - .holder = depositor, - .amount = asset(0)}); + tx = vault.clawback({.issuer = issuer, .id = keylet.key, .holder = depositor, .amount = asset(0)}); env(tx); env.close(); @@ -1898,10 +1573,7 @@ class Vault_test : public beast::unit_test::suite env(tx); env.close(); - tx = vault.deposit( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(100)}); + tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(100)}); env(tx); env.close(); @@ -1935,33 +1607,24 @@ class Vault_test : public beast::unit_test::suite MPTTester& mptt) { testcase("MPT depositor without MPToken, auth required"); - auto [tx, keylet] = - vault.create({.owner = owner, .asset = asset}); + auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); env(tx); env.close(); - tx = vault.deposit( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(1000)}); + tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(1000)}); env(tx); env.close(); { // Remove depositor MPToken and it will not be re-created - mptt.authorize( - {.account = depositor, .flags = tfMPTUnauthorize}); + mptt.authorize({.account = depositor, .flags = tfMPTUnauthorize}); env.close(); - auto const mptoken = - keylet::mptoken(mptt.issuanceID(), depositor); + auto const mptoken = keylet::mptoken(mptt.issuanceID(), depositor); auto const sleMPT1 = env.le(mptoken); BEAST_EXPECT(sleMPT1 == nullptr); - tx = vault.withdraw( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(100)}); + tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(100)}); env(tx, ter{tecNO_AUTH}); env.close(); @@ -1975,10 +1638,7 @@ class Vault_test : public beast::unit_test::suite env.fund(XRP(1000), charlie); env.close(); - tx = vault.withdraw( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(100)}); + tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(100)}); tx[sfDestination] = charlie.human(); env(tx, ter(tecNO_AUTH)); } @@ -1996,35 +1656,27 @@ class Vault_test : public beast::unit_test::suite MPTTester& mptt) { testcase("MPT depositor without MPToken, no auth required"); - auto [tx, keylet] = - vault.create({.owner = owner, .asset = asset}); + auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); env(tx); env.close(); auto v = env.le(keylet); BEAST_EXPECT(v); tx = vault.deposit( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(1000)}); // all assets held by depositor + {.depositor = depositor, .id = keylet.key, .amount = asset(1000)}); // all assets held by depositor env(tx); env.close(); { // Remove depositor's MPToken and it will be re-created - mptt.authorize( - {.account = depositor, .flags = tfMPTUnauthorize}); + mptt.authorize({.account = depositor, .flags = tfMPTUnauthorize}); env.close(); - auto const mptoken = - keylet::mptoken(mptt.issuanceID(), depositor); + auto const mptoken = keylet::mptoken(mptt.issuanceID(), depositor); auto const sleMPT1 = env.le(mptoken); BEAST_EXPECT(sleMPT1 == nullptr); - tx = vault.withdraw( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(100)}); + tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(100)}); env(tx); env.close(); @@ -2035,19 +1687,14 @@ class Vault_test : public beast::unit_test::suite { // Remove 3rd party MPToken and it will not be re-created - mptt.authorize( - {.account = owner, .flags = tfMPTUnauthorize}); + mptt.authorize({.account = owner, .flags = tfMPTUnauthorize}); env.close(); - auto const mptoken = - keylet::mptoken(mptt.issuanceID(), owner); + auto const mptoken = keylet::mptoken(mptt.issuanceID(), owner); auto const sleMPT1 = env.le(mptoken); BEAST_EXPECT(sleMPT1 == nullptr); - tx = vault.withdraw( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(100)}); + tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(100)}); tx[sfDestination] = owner.human(); env(tx, ter(tecNO_AUTH)); env.close(); @@ -2061,10 +1708,8 @@ class Vault_test : public beast::unit_test::suite auto const [acctReserve, incReserve] = [this]() -> std::pair { Env env{*this, testable_amendments()}; return { - env.current()->fees().accountReserve(0).drops() / - DROPS_PER_XRP.drops(), - env.current()->fees().increment.drops() / - DROPS_PER_XRP.drops()}; + env.current()->fees().accountReserve(0).drops() / DROPS_PER_XRP.drops(), + env.current()->fees().increment.drops() / DROPS_PER_XRP.drops()}; }(); testCase( @@ -2078,8 +1723,7 @@ class Vault_test : public beast::unit_test::suite MPTTester& mptt) { testcase("MPT fail reserve to re-create MPToken"); - auto [tx, keylet] = - vault.create({.owner = owner, .asset = asset}); + auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); env(tx); env.close(); auto v = env.le(keylet); @@ -2089,20 +1733,16 @@ class Vault_test : public beast::unit_test::suite env.close(); tx = vault.deposit( - {.depositor = owner, - .id = keylet.key, - .amount = asset(1000)}); // all assets held by owner + {.depositor = owner, .id = keylet.key, .amount = asset(1000)}); // all assets held by owner env(tx); env.close(); { // Remove owners's MPToken and it will not be re-created - mptt.authorize( - {.account = owner, .flags = tfMPTUnauthorize}); + mptt.authorize({.account = owner, .flags = tfMPTUnauthorize}); env.close(); - auto const mptoken = - keylet::mptoken(mptt.issuanceID(), owner); + auto const mptoken = keylet::mptoken(mptt.issuanceID(), owner); auto const sleMPT = env.le(mptoken); BEAST_EXPECT(sleMPT == nullptr); @@ -2111,10 +1751,7 @@ class Vault_test : public beast::unit_test::suite env.close(); // No reserve to create MPToken for asset in VaultWithdraw - tx = vault.withdraw( - {.depositor = owner, - .id = keylet.key, - .amount = asset(100)}); + tx = vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(100)}); env(tx, ter{tecINSUFFICIENT_RESERVE}); env.close(); @@ -2126,8 +1763,7 @@ class Vault_test : public beast::unit_test::suite env.close(); } }, - {.requireAuth = false, - .initialXRP = acctReserve + incReserve * 4 + 1}); + {.requireAuth = false, .initialXRP = acctReserve + incReserve * 4 + 1}); testCase([this]( Env& env, @@ -2143,19 +1779,12 @@ class Vault_test : public beast::unit_test::suite env(tx); env.close(); - tx = vault.deposit( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(1000)}); + tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(1000)}); env(tx); env.close(); { - auto tx = vault.clawback( - {.issuer = issuer, - .id = keylet.key, - .holder = depositor, - .amount = asset(0)}); + auto tx = vault.clawback({.issuer = issuer, .id = keylet.key, .holder = depositor, .amount = asset(0)}); env(tx); } @@ -2163,33 +1792,22 @@ class Vault_test : public beast::unit_test::suite env.close(); { - auto [tx, keylet] = - vault.create({.owner = depositor, .asset = asset}); + auto [tx, keylet] = vault.create({.owner = depositor, .asset = asset}); env(tx, ter{tecOBJECT_NOT_FOUND}); } { - auto tx = vault.deposit( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(10)}); + auto tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(10)}); env(tx, ter{tecOBJECT_NOT_FOUND}); } { - auto tx = vault.withdraw( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(10)}); + auto tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(10)}); env(tx, ter{tecOBJECT_NOT_FOUND}); } { - auto tx = vault.clawback( - {.issuer = issuer, - .id = keylet.key, - .holder = depositor, - .amount = asset(0)}); + auto tx = vault.clawback({.issuer = issuer, .id = keylet.key, .holder = depositor, .amount = asset(0)}); env(tx, ter{tecOBJECT_NOT_FOUND}); } @@ -2210,10 +1828,7 @@ class Vault_test : public beast::unit_test::suite env(tx); env.close(); - tx = vault.deposit( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(1000)}); + tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(1000)}); env(tx); env.close(); @@ -2228,10 +1843,7 @@ class Vault_test : public beast::unit_test::suite env(pay(depositor, owner, shares(1))); env.close(); - tx = vault.withdraw( - {.depositor = owner, - .id = keylet.key, - .amount = shares(1)}); + tx = vault.withdraw({.depositor = owner, .id = keylet.key, .amount = shares(1)}); env(tx); env.close(); @@ -2239,11 +1851,7 @@ class Vault_test : public beast::unit_test::suite env(pay(depositor, owner, shares(1))); env.close(); - tx = vault.clawback( - {.issuer = issuer, - .id = keylet.key, - .holder = owner, - .amount = asset(0)}); + tx = vault.clawback({.issuer = issuer, .id = keylet.key, .holder = owner, .amount = asset(0)}); env(tx); env.close(); @@ -2272,11 +1880,7 @@ class Vault_test : public beast::unit_test::suite env.close(); // destroy all remaining shares, so we can delete vault - tx = vault.clawback( - {.issuer = issuer, - .id = keylet.key, - .holder = depositor, - .amount = asset(0)}); + tx = vault.clawback({.issuer = issuer, .id = keylet.key, .holder = depositor, .amount = asset(0)}); env(tx); env.close(); @@ -2297,24 +1901,17 @@ class Vault_test : public beast::unit_test::suite MPTTester& mptt) { testcase("MPT clawback disabled"); - auto [tx, keylet] = - vault.create({.owner = owner, .asset = asset}); + auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); env(tx); env.close(); - tx = vault.deposit( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(1000)}); + tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(1000)}); env(tx); env.close(); { - auto tx = vault.clawback( - {.issuer = issuer, - .id = keylet.key, - .holder = depositor, - .amount = asset(0)}); + auto tx = + vault.clawback({.issuer = issuer, .id = keylet.key, .holder = depositor, .amount = asset(0)}); env(tx, ter{tecNO_PERMISSION}); } }, @@ -2332,24 +1929,15 @@ class Vault_test : public beast::unit_test::suite auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); env(tx); env.close(); - tx = vault.deposit( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(1000)}); + tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(1000)}); env(tx); env.close(); - mptt.authorize( - {.account = issuer, - .holder = depositor, - .flags = tfMPTUnauthorize}); + mptt.authorize({.account = issuer, .holder = depositor, .flags = tfMPTUnauthorize}); env.close(); { - auto tx = vault.withdraw( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(100)}); + auto tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(100)}); env(tx, ter(tecNO_AUTH)); // Withdrawal to other (authorized) accounts works @@ -2364,28 +1952,17 @@ class Vault_test : public beast::unit_test::suite { // Cannot deposit some more - auto tx = vault.deposit( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(100)}); + auto tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(100)}); env(tx, ter(tecNO_AUTH)); } { // Cannot clawback if issuer is the holder - tx = vault.clawback( - {.issuer = issuer, - .id = keylet.key, - .holder = issuer, - .amount = asset(800)}); + tx = vault.clawback({.issuer = issuer, .id = keylet.key, .holder = issuer, .amount = asset(800)}); env(tx, ter(tecNO_PERMISSION)); } // Clawback works - tx = vault.clawback( - {.issuer = issuer, - .id = keylet.key, - .holder = depositor, - .amount = asset(800)}); + tx = vault.clawback({.issuer = issuer, .id = keylet.key, .holder = depositor, .amount = asset(800)}); env(tx); env.close(); @@ -2405,25 +1982,20 @@ class Vault_test : public beast::unit_test::suite env(tx); env.close(); - auto const vaultAccount = - [&env, keylet = keylet, this]() -> AccountID { + auto const vaultAccount = [&env, keylet = keylet, this]() -> AccountID { auto const vault = env.le(keylet); BEAST_EXPECT(vault != nullptr); return vault->at(sfAccount); }(); - tx = vault.deposit( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(100)}); + tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(100)}); env(tx); env.close(); tx = [&]() { Json::Value jv; jv[jss::Account] = issuer.human(); - jv[sfMPTokenIssuanceID] = - to_string(asset.get().getMptID()); + jv[sfMPTokenIssuanceID] = to_string(asset.get().getMptID()); jv[jss::Holder] = toBase58(vaultAccount); jv[jss::TransactionType] = jss::MPTokenIssuanceSet; jv[jss::Flags] = tfMPTLock; @@ -2432,24 +2004,14 @@ class Vault_test : public beast::unit_test::suite env(tx); env.close(); - tx = vault.deposit( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(100)}); + tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(100)}); env(tx, ter(tecLOCKED)); - tx = vault.withdraw( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(100)}); + tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(100)}); env(tx, ter(tecLOCKED)); // Clawback works, even when locked - tx = vault.clawback( - {.issuer = issuer, - .id = keylet.key, - .holder = depositor, - .amount = asset(100)}); + tx = vault.clawback({.issuer = issuer, .id = keylet.key, .holder = depositor, .amount = asset(100)}); env(tx); // Can delete an empty vault even when asset is locked. @@ -2468,9 +2030,7 @@ class Vault_test : public beast::unit_test::suite Vault vault{env}; MPTTester mptt{env, issuer, mptInitNoFund}; - mptt.create( - {.flags = tfMPTCanTransfer | tfMPTCanLock | lsfMPTCanClawback | - tfMPTRequireAuth}); + mptt.create({.flags = tfMPTCanTransfer | tfMPTCanLock | lsfMPTCanClawback | tfMPTRequireAuth}); mptt.authorize({.account = owner}); mptt.authorize({.account = issuer, .holder = owner}); PrettyAsset asset = mptt.issuanceID(); @@ -2504,10 +2064,7 @@ class Vault_test : public beast::unit_test::suite env(tx); env.close(); - tx = vault.deposit( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(100)}); + tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(100)}); env(tx); env.close(); @@ -2518,10 +2075,7 @@ class Vault_test : public beast::unit_test::suite env(tx, ter{tecNO_AUTH}); env.close(); - tx = vault.withdraw( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(100)}); + tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(100)}); env(tx, ter{tecNO_AUTH}); env.close(); @@ -2551,65 +2105,53 @@ class Vault_test : public beast::unit_test::suite bool charlieRipple = true; }; - auto testCase = - [&, this]( - std::function vaultAccount, - Vault& vault, - PrettyAsset const& asset, - std::function issuanceId)> test, - CaseArgs args = {}) { - Env env{*this, testable_amendments() | featureSingleAssetVault}; - Account const owner{"owner"}; - Account const issuer{"issuer"}; - Account const charlie{"charlie"}; - Vault vault{env}; - env.fund(XRP(args.initialXRP), issuer, owner, charlie); - env(fset(issuer, asfAllowTrustLineClawback)); - env.close(); + auto testCase = [&, this]( + std::function vaultAccount, + Vault& vault, + PrettyAsset const& asset, + std::function issuanceId)> test, + CaseArgs args = {}) { + Env env{*this, testable_amendments() | featureSingleAssetVault}; + Account const owner{"owner"}; + Account const issuer{"issuer"}; + Account const charlie{"charlie"}; + Vault vault{env}; + env.fund(XRP(args.initialXRP), issuer, owner, charlie); + env(fset(issuer, asfAllowTrustLineClawback)); + env.close(); - PrettyAsset const asset = issuer["IOU"]; - env.trust(asset(1000), owner); - env(pay(issuer, owner, asset(args.initialIOU))); + PrettyAsset const asset = issuer["IOU"]; + env.trust(asset(1000), owner); + env(pay(issuer, owner, asset(args.initialIOU))); + env.close(); + if (!args.charlieRipple) + { + env(fset(issuer, 0, asfDefaultRipple)); env.close(); - if (!args.charlieRipple) - { - env(fset(issuer, 0, asfDefaultRipple)); - env.close(); - env.trust(asset(1000), charlie); - env.close(); - env(pay(issuer, charlie, asset(args.initialIOU))); - env.close(); - env(fset(issuer, asfDefaultRipple)); - } - else - env.trust(asset(1000), charlie); + env.trust(asset(1000), charlie); env.close(); - env(rate(issuer, args.transferRate)); + env(pay(issuer, charlie, asset(args.initialIOU))); env.close(); + env(fset(issuer, asfDefaultRipple)); + } + else + env.trust(asset(1000), charlie); + env.close(); + env(rate(issuer, args.transferRate)); + env.close(); - auto const vaultAccount = - [&env](xrpl::Keylet keylet) -> Account { - return Account("vault", env.le(keylet)->at(sfAccount)); - }; - auto const issuanceId = [&env](xrpl::Keylet keylet) -> MPTID { - return env.le(keylet)->at(sfShareMPTID); - }; - - test( - env, - owner, - issuer, - charlie, - vaultAccount, - vault, - asset, - issuanceId); + auto const vaultAccount = [&env](xrpl::Keylet keylet) -> Account { + return Account("vault", env.le(keylet)->at(sfAccount)); }; + auto const issuanceId = [&env](xrpl::Keylet keylet) -> MPTID { return env.le(keylet)->at(sfShareMPTID); }; + + test(env, owner, issuer, charlie, vaultAccount, vault, asset, issuanceId); + }; testCase([&, this]( Env& env, @@ -2633,8 +2175,7 @@ class Vault_test : public beast::unit_test::suite Json::Value jv; jv[jss::Account] = issuer.human(); { - auto& ja = jv[jss::LimitAmount] = - foo(0).value().getJson(JsonOptions::none); + auto& ja = jv[jss::LimitAmount] = foo(0).value().getJson(JsonOptions::none); ja[jss::issuer] = toBase58(account); } jv[jss::TransactionType] = jss::TrustSet; @@ -2646,15 +2187,13 @@ class Vault_test : public beast::unit_test::suite } { - auto tx = vault.deposit( - {.depositor = issuer, .id = keylet.key, .amount = foo(20)}); + auto tx = vault.deposit({.depositor = issuer, .id = keylet.key, .amount = foo(20)}); env(tx, ter{tecWRONG_ASSET}); env.close(); } { - auto tx = vault.withdraw( - {.depositor = issuer, .id = keylet.key, .amount = foo(20)}); + auto tx = vault.withdraw({.depositor = issuer, .id = keylet.key, .amount = foo(20)}); env(tx, ter{tecWRONG_ASSET}); env.close(); } @@ -2678,8 +2217,7 @@ class Vault_test : public beast::unit_test::suite env(tx); env.close(); - env(vault.deposit( - {.depositor = owner, .id = keylet.key, .amount = asset(100)})); + env(vault.deposit({.depositor = owner, .id = keylet.key, .amount = asset(100)})); env.close(); Asset const share = Asset(issuanceId(keylet)); @@ -2689,8 +2227,7 @@ class Vault_test : public beast::unit_test::suite Json::Value jv; jv[jss::Account] = issuer.human(); { - auto& ja = jv[jss::LimitAmount] = - asset(0).value().getJson(JsonOptions::none); + auto& ja = jv[jss::LimitAmount] = asset(0).value().getJson(JsonOptions::none); ja[jss::issuer] = toBase58(account); } jv[jss::TransactionType] = jss::TrustSet; @@ -2705,18 +2242,12 @@ class Vault_test : public beast::unit_test::suite // is reported as "locked" state of the vault shares, because // this state is attached to shares by means of the transitive // isFrozen. - auto tx = vault.deposit( - {.depositor = owner, - .id = keylet.key, - .amount = asset(80)}); + auto tx = vault.deposit({.depositor = owner, .id = keylet.key, .amount = asset(80)}); env(tx, ter{tecLOCKED}); } { - auto tx = vault.withdraw( - {.depositor = owner, - .id = keylet.key, - .amount = asset(100)}); + auto tx = vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(100)}); env(tx, ter{tecLOCKED}); // also when trying to withdraw to a 3rd party @@ -2727,11 +2258,7 @@ class Vault_test : public beast::unit_test::suite { // Clawback works, even when locked - auto tx = vault.clawback( - {.issuer = issuer, - .id = keylet.key, - .holder = owner, - .amount = asset(50)}); + auto tx = vault.clawback({.issuer = issuer, .id = keylet.key, .holder = owner, .amount = asset(50)}); env(tx); env.close(); } @@ -2741,10 +2268,7 @@ class Vault_test : public beast::unit_test::suite env(trustSet); env.close(); - env(vault.withdraw( - {.depositor = owner, - .id = keylet.key, - .amount = share(50'000'000)})); + env(vault.withdraw({.depositor = owner, .id = keylet.key, .amount = share(50'000'000)})); env(vault.del({.owner = owner, .id = keylet.key})); env.close(); @@ -2762,15 +2286,11 @@ class Vault_test : public beast::unit_test::suite auto issuanceId) { testcase("IOU transfer fees not applied"); - auto [tx, keylet] = - vault.create({.owner = owner, .asset = asset}); + auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); env(tx); env.close(); - env(vault.deposit( - {.depositor = owner, - .id = keylet.key, - .amount = asset(100)})); + env(vault.deposit({.depositor = owner, .id = keylet.key, .amount = asset(100)})); env.close(); auto const issue = asset.raw().get(); @@ -2778,39 +2298,27 @@ class Vault_test : public beast::unit_test::suite // transfer fees ignored on deposit BEAST_EXPECT(env.balance(owner, issue) == asset(100)); - BEAST_EXPECT( - env.balance(vaultAccount(keylet), issue) == asset(100)); + BEAST_EXPECT(env.balance(vaultAccount(keylet), issue) == asset(100)); { - auto tx = vault.clawback( - {.issuer = issuer, - .id = keylet.key, - .holder = owner, - .amount = asset(50)}); + auto tx = + vault.clawback({.issuer = issuer, .id = keylet.key, .holder = owner, .amount = asset(50)}); env(tx); env.close(); } // transfer fees ignored on clawback BEAST_EXPECT(env.balance(owner, issue) == asset(100)); - BEAST_EXPECT( - env.balance(vaultAccount(keylet), issue) == asset(50)); + BEAST_EXPECT(env.balance(vaultAccount(keylet), issue) == asset(50)); - env(vault.withdraw( - {.depositor = owner, - .id = keylet.key, - .amount = share(20'000'000)})); + env(vault.withdraw({.depositor = owner, .id = keylet.key, .amount = share(20'000'000)})); // transfer fees ignored on withdraw BEAST_EXPECT(env.balance(owner, issue) == asset(120)); - BEAST_EXPECT( - env.balance(vaultAccount(keylet), issue) == asset(30)); + BEAST_EXPECT(env.balance(vaultAccount(keylet), issue) == asset(30)); { - auto tx = vault.withdraw( - {.depositor = owner, - .id = keylet.key, - .amount = share(30'000'000)}); + auto tx = vault.withdraw({.depositor = owner, .id = keylet.key, .amount = share(30'000'000)}); tx[sfDestination] = charlie.human(); env(tx); } @@ -2818,8 +2326,7 @@ class Vault_test : public beast::unit_test::suite // transfer fees ignored on withdraw to 3rd party BEAST_EXPECT(env.balance(owner, issue) == asset(120)); BEAST_EXPECT(env.balance(charlie, issue) == asset(30)); - BEAST_EXPECT( - env.balance(vaultAccount(keylet), issue) == asset(0)); + BEAST_EXPECT(env.balance(vaultAccount(keylet), issue) == asset(0)); env(vault.del({.owner = owner, .id = keylet.key})); env.close(); @@ -2841,16 +2348,12 @@ class Vault_test : public beast::unit_test::suite env(tx); env.close(); - env(vault.deposit( - {.depositor = owner, .id = keylet.key, .amount = asset(100)})); + env(vault.deposit({.depositor = owner, .id = keylet.key, .amount = asset(100)})); env.close(); // Withdraw to 3rd party works auto const withdrawToCharlie = [&](xrpl::Keylet keylet) { - auto tx = vault.withdraw( - {.depositor = owner, - .id = keylet.key, - .amount = asset(10)}); + auto tx = vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(10)}); tx[sfDestination] = charlie.human(); return tx; }(keylet); @@ -2861,8 +2364,7 @@ class Vault_test : public beast::unit_test::suite env.close(); // Cannot withdraw - auto const withdraw = vault.withdraw( - {.depositor = owner, .id = keylet.key, .amount = asset(10)}); + auto const withdraw = vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(10)}); env(withdraw, ter{tecFROZEN}); // Cannot withdraw to 3rd party @@ -2871,20 +2373,13 @@ class Vault_test : public beast::unit_test::suite { // Cannot deposit some more - auto tx = vault.deposit( - {.depositor = owner, - .id = keylet.key, - .amount = asset(10)}); + auto tx = vault.deposit({.depositor = owner, .id = keylet.key, .amount = asset(10)}); env(tx, ter{tecFROZEN}); } { // Clawback still works - auto tx = vault.clawback( - {.issuer = issuer, - .id = keylet.key, - .holder = owner, - .amount = asset(0)}); + auto tx = vault.clawback({.issuer = issuer, .id = keylet.key, .holder = owner, .amount = asset(0)}); env(tx); env.close(); } @@ -2908,8 +2403,7 @@ class Vault_test : public beast::unit_test::suite env(tx); env.close(); - env(vault.deposit( - {.depositor = owner, .id = keylet.key, .amount = asset(100)})); + env(vault.deposit({.depositor = owner, .id = keylet.key, .amount = asset(100)})); env.close(); Account const erin{"erin"}; @@ -2918,10 +2412,7 @@ class Vault_test : public beast::unit_test::suite // Withdraw to 3rd party without trust line auto const tx1 = [&](xrpl::Keylet keylet) { - auto tx = vault.withdraw( - {.depositor = owner, - .id = keylet.key, - .amount = asset(10)}); + auto tx = vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(10)}); tx[sfDestination] = erin.human(); return tx; }(keylet); @@ -2947,20 +2438,15 @@ class Vault_test : public beast::unit_test::suite env.trust(asset(0), owner); env.close(); - env(vault.deposit( - {.depositor = owner, .id = keylet.key, .amount = asset(200)})); + env(vault.deposit({.depositor = owner, .id = keylet.key, .amount = asset(200)})); env.close(); - auto trustline = - env.le(keylet::line(owner, asset.raw().get())); + auto trustline = env.le(keylet::line(owner, asset.raw().get())); BEAST_EXPECT(trustline == nullptr); // Withdraw without trust line, will succeed auto const tx1 = [&](xrpl::Keylet keylet) { - auto tx = vault.withdraw( - {.depositor = owner, - .id = keylet.key, - .amount = asset(10)}); + auto tx = vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(10)}); return tx; }(keylet); env(tx1); @@ -2978,41 +2464,30 @@ class Vault_test : public beast::unit_test::suite std::function issuanceId) { testcase("IOU non-transferable"); - auto [tx, keylet] = - vault.create({.owner = owner, .asset = asset}); + auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); tx[sfScale] = 0; env(tx); env.close(); // Turn on noripple on the pseudo account's trust line. // Charlie's is already set. - env(trust(issuer, vaultAccount(keylet)["IOU"], tfSetNoRipple), - THISLINE); + env(trust(issuer, vaultAccount(keylet)["IOU"], tfSetNoRipple), THISLINE); { // Charlie cannot deposit - auto tx = vault.deposit( - {.depositor = charlie, - .id = keylet.key, - .amount = asset(100)}); + auto tx = vault.deposit({.depositor = charlie, .id = keylet.key, .amount = asset(100)}); env(tx, ter{terNO_RIPPLE}, THISLINE); env.close(); } { PrettyAsset shares = issuanceId(keylet); - auto tx1 = vault.deposit( - {.depositor = owner, - .id = keylet.key, - .amount = asset(100)}); + auto tx1 = vault.deposit({.depositor = owner, .id = keylet.key, .amount = asset(100)}); env(tx1, THISLINE); env.close(); // Charlie cannot receive funds - auto tx2 = vault.withdraw( - {.depositor = owner, - .id = keylet.key, - .amount = shares(100)}); + auto tx2 = vault.withdraw({.depositor = owner, .id = keylet.key, .amount = shares(100)}); tx2[sfDestination] = charlie.human(); env(tx2, ter{terNO_RIPPLE}, THISLINE); env.close(); @@ -3021,8 +2496,7 @@ class Vault_test : public beast::unit_test::suite // Create MPToken for shares held by Charlie Json::Value tx{Json::objectValue}; tx[sfAccount] = charlie.human(); - tx[sfMPTokenIssuanceID] = - to_string(shares.raw().get().getMptID()); + tx[sfMPTokenIssuanceID] = to_string(shares.raw().get().getMptID()); tx[sfTransactionType] = jss::MPTokenAuthorize; env(tx); env.close(); @@ -3031,10 +2505,7 @@ class Vault_test : public beast::unit_test::suite env.close(); // Charlie cannot withdraw - auto tx3 = vault.withdraw( - {.depositor = charlie, - .id = keylet.key, - .amount = shares(100)}); + auto tx3 = vault.withdraw({.depositor = charlie, .id = keylet.key, .amount = shares(100)}); env(tx3, ter{terNO_RIPPLE}); env.close(); @@ -3042,10 +2513,7 @@ class Vault_test : public beast::unit_test::suite env.close(); } - tx = vault.withdraw( - {.depositor = owner, - .id = keylet.key, - .amount = asset(100)}); + tx = vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(100)}); env(tx, THISLINE); env.close(); @@ -3066,30 +2534,22 @@ class Vault_test : public beast::unit_test::suite auto&&...) { testcase("IOU calculation rounding"); - auto [tx, keylet] = - vault.create({.owner = owner, .asset = asset}); + auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); tx[sfScale] = 1; env(tx); env.close(); auto const startingOwnerBalance = env.balance(owner, asset); - BEAST_EXPECT( - (startingOwnerBalance.value() == - STAmount{asset, 11875, -2})); + BEAST_EXPECT((startingOwnerBalance.value() == STAmount{asset, 11875, -2})); // This operation (first deposit 100, then 3.75 x 5) is known to // have triggered calculation rounding errors in Number // (addition and division), causing the last deposit to be // blocked by Vault invariants. - env(vault.deposit( - {.depositor = owner, - .id = keylet.key, - .amount = asset(100)})); + env(vault.deposit({.depositor = owner, .id = keylet.key, .amount = asset(100)})); - auto const tx1 = vault.deposit( - {.depositor = owner, - .id = keylet.key, - .amount = asset(Number(375, -2))}); + auto const tx1 = + vault.deposit({.depositor = owner, .id = keylet.key, .amount = asset(Number(375, -2))}); for (auto i = 0; i < 5; ++i) { env(tx1); @@ -3098,11 +2558,8 @@ class Vault_test : public beast::unit_test::suite { STAmount const xfer{asset, 1185, -1}; - BEAST_EXPECT( - env.balance(owner, asset) == - startingOwnerBalance.value() - xfer); - BEAST_EXPECT( - env.balance(vaultAccount(keylet), asset) == xfer); + BEAST_EXPECT(env.balance(owner, asset) == startingOwnerBalance.value() - xfer); + BEAST_EXPECT(env.balance(vaultAccount(keylet), asset) == xfer); auto const vault = env.le(keylet); BEAST_EXPECT(vault->at(sfAssetsAvailable) == xfer); @@ -3112,18 +2569,11 @@ class Vault_test : public beast::unit_test::suite // Total vault balance should be 118.5 IOU. Withdraw and delete // the vault to verify this exact amount was deposited and the // owner has matching shares - env(vault.withdraw( - {.depositor = owner, - .id = keylet.key, - .amount = asset(Number(1000 + 37 * 5, -1))})); + env(vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(Number(1000 + 37 * 5, -1))})); { - BEAST_EXPECT( - env.balance(owner, asset) == - startingOwnerBalance.value()); - BEAST_EXPECT( - env.balance(vaultAccount(keylet), asset) == - beast::zero); + BEAST_EXPECT(env.balance(owner, asset) == startingOwnerBalance.value()); + BEAST_EXPECT(env.balance(vaultAccount(keylet), asset) == beast::zero); auto const vault = env.le(keylet); BEAST_EXPECT(vault->at(sfAssetsAvailable) == beast::zero); BEAST_EXPECT(vault->at(sfAssetsTotal) == beast::zero); @@ -3137,10 +2587,8 @@ class Vault_test : public beast::unit_test::suite auto const [acctReserve, incReserve] = [this]() -> std::pair { Env env{*this, testable_amendments()}; return { - env.current()->fees().accountReserve(0).drops() / - DROPS_PER_XRP.drops(), - env.current()->fees().increment.drops() / - DROPS_PER_XRP.drops()}; + env.current()->fees().accountReserve(0).drops() / DROPS_PER_XRP.drops(), + env.current()->fees().increment.drops() / DROPS_PER_XRP.drops()}; }(); testCase( @@ -3154,8 +2602,7 @@ class Vault_test : public beast::unit_test::suite PrettyAsset const& asset, auto&&...) { testcase("IOU no trust line to depositor no reserve"); - auto [tx, keylet] = - vault.create({.owner = owner, .asset = asset}); + auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); env(tx); env.close(); @@ -3164,24 +2611,17 @@ class Vault_test : public beast::unit_test::suite env.trust(asset(0), owner); env.close(); - env(vault.deposit( - {.depositor = owner, - .id = keylet.key, - .amount = asset(200)})); + env(vault.deposit({.depositor = owner, .id = keylet.key, .amount = asset(200)})); env.close(); - auto trustline = - env.le(keylet::line(owner, asset.raw().get())); + auto trustline = env.le(keylet::line(owner, asset.raw().get())); BEAST_EXPECT(trustline == nullptr); env(ticket::create(owner, 1)); env.close(); // Fail because not enough reserve to create trust line - tx = vault.withdraw( - {.depositor = owner, - .id = keylet.key, - .amount = asset(10)}); + tx = vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(10)}); env(tx, ter{tecNO_LINE_INSUF_RESERVE}); env.close(); @@ -3205,8 +2645,7 @@ class Vault_test : public beast::unit_test::suite PrettyAsset const& asset, auto&&...) { testcase("IOU no reserve for share MPToken"); - auto [tx, keylet] = - vault.create({.owner = owner, .asset = asset}); + auto [tx, keylet] = vault.create({.owner = owner, .asset = asset}); env(tx); env.close(); @@ -3217,10 +2656,7 @@ class Vault_test : public beast::unit_test::suite env.close(); // Fail because not enough reserve to create MPToken for shares - tx = vault.deposit( - {.depositor = charlie, - .id = keylet.key, - .amount = asset(100)}); + tx = vault.deposit({.depositor = charlie, .id = keylet.key, .amount = asset(100)}); env(tx, ter{tecINSUFFICIENT_RESERVE}); env.close(); @@ -3248,16 +2684,12 @@ class Vault_test : public beast::unit_test::suite env(tx); env.close(); - env(vault.deposit( - {.depositor = owner, .id = keylet.key, .amount = asset(100)})); + env(vault.deposit({.depositor = owner, .id = keylet.key, .amount = asset(100)})); env.close(); // Withdraw to 3rd party works auto const withdrawToCharlie = [&](xrpl::Keylet keylet) { - auto tx = vault.withdraw( - {.depositor = owner, - .id = keylet.key, - .amount = asset(10)}); + auto tx = vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(10)}); tx[sfDestination] = charlie.human(); return tx; }(keylet); @@ -3268,8 +2700,7 @@ class Vault_test : public beast::unit_test::suite env.close(); // Can withdraw - auto const withdraw = vault.withdraw( - {.depositor = owner, .id = keylet.key, .amount = asset(10)}); + auto const withdraw = vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(10)}); env(withdraw); env.close(); @@ -3277,11 +2708,7 @@ class Vault_test : public beast::unit_test::suite env(withdrawToCharlie, ter{tecFROZEN}); env.close(); - env(vault.clawback( - {.issuer = issuer, - .id = keylet.key, - .holder = owner, - .amount = asset(0)})); + env(vault.clawback({.issuer = issuer, .id = keylet.key, .holder = owner, .amount = asset(0)})); env.close(); env(vault.del({.owner = owner, .id = keylet.key})); @@ -3303,8 +2730,7 @@ class Vault_test : public beast::unit_test::suite env(tx); env.close(); - env(vault.deposit( - {.depositor = owner, .id = keylet.key, .amount = asset(100)})); + env(vault.deposit({.depositor = owner, .id = keylet.key, .amount = asset(100)})); env.close(); env(fset(issuer, asfGlobalFreeze)); @@ -3312,10 +2738,7 @@ class Vault_test : public beast::unit_test::suite { // Cannot withdraw - auto tx = vault.withdraw( - {.depositor = owner, - .id = keylet.key, - .amount = asset(10)}); + auto tx = vault.withdraw({.depositor = owner, .id = keylet.key, .amount = asset(10)}); env(tx, ter{tecFROZEN}); // Cannot withdraw to 3rd party @@ -3324,20 +2747,13 @@ class Vault_test : public beast::unit_test::suite env.close(); // Cannot deposit some more - tx = vault.deposit( - {.depositor = owner, - .id = keylet.key, - .amount = asset(10)}); + tx = vault.deposit({.depositor = owner, .id = keylet.key, .amount = asset(10)}); env(tx, ter{tecFROZEN}); } // Clawback is permitted - env(vault.clawback( - {.issuer = issuer, - .id = keylet.key, - .holder = owner, - .amount = asset(0)})); + env(vault.clawback({.issuer = issuer, .id = keylet.key, .holder = owner, .amount = asset(0)})); env.close(); env(vault.del({.owner = owner, .id = keylet.key})); @@ -3362,15 +2778,7 @@ class Vault_test : public beast::unit_test::suite Account credIssuer2{"credIssuer2"}; std::string const credType = "credential"; Vault vault{env}; - env.fund( - XRP(1000), - issuer, - owner, - depositor, - charlie, - pdOwner, - credIssuer1, - credIssuer2); + env.fund(XRP(1000), issuer, owner, depositor, charlie, pdOwner, credIssuer1, credIssuer2); env.close(); env(fset(issuer, asfAllowTrustLineClawback)); env.close(); @@ -3385,25 +2793,20 @@ class Vault_test : public beast::unit_test::suite env(pay(issuer, charlie, asset(5))); env.close(); - auto [tx, keylet] = vault.create( - {.owner = owner, .asset = asset, .flags = tfVaultPrivate}); + auto [tx, keylet] = vault.create({.owner = owner, .asset = asset, .flags = tfVaultPrivate}); env(tx); env.close(); BEAST_EXPECT(env.le(keylet)); { testcase("private vault owner can deposit"); - auto tx = vault.deposit( - {.depositor = owner, .id = keylet.key, .amount = asset(50)}); + auto tx = vault.deposit({.depositor = owner, .id = keylet.key, .amount = asset(50)}); env(tx); } { testcase("private vault depositor not authorized yet"); - auto tx = vault.deposit( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(50)}); + auto tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(50)}); env(tx, ter{tecNO_AUTH}); } @@ -3418,8 +2821,7 @@ class Vault_test : public beast::unit_test::suite testcase("private vault set domainId"); { - pdomain::Credentials const credentials1{ - {.issuer = credIssuer1, .credType = credType}}; + pdomain::Credentials const credentials1{{.issuer = credIssuer1, .credType = credType}}; env(pdomain::setTx(pdOwner, credentials1)); auto const domainId1 = [&]() { @@ -3439,8 +2841,7 @@ class Vault_test : public beast::unit_test::suite { pdomain::Credentials const credentials{ - {.issuer = credIssuer1, .credType = credType}, - {.issuer = credIssuer2, .credType = credType}}; + {.issuer = credIssuer1, .credType = credType}, {.issuer = credIssuer2, .credType = credType}}; env(pdomain::setTx(pdOwner, credentials)); auto const domainId = [&]() { @@ -3463,16 +2864,12 @@ class Vault_test : public beast::unit_test::suite { testcase("private vault depositor still not authorized"); - auto tx = vault.deposit( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(50)}); + auto tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(50)}); env(tx, ter{tecNO_AUTH}); env.close(); } - auto const credKeylet = - credentials::keylet(depositor, credIssuer1, credType); + auto const credKeylet = credentials::keylet(depositor, credIssuer1, credType); { testcase("private vault depositor now authorized"); env(credentials::create(depositor, credIssuer1, credType)); @@ -3483,33 +2880,24 @@ class Vault_test : public beast::unit_test::suite auto credSle = env.le(credKeylet); BEAST_EXPECT(credSle != nullptr); - auto tx = vault.deposit( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(50)}); + auto tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(50)}); env(tx); env.close(); - tx = vault.deposit( - {.depositor = charlie, .id = keylet.key, .amount = asset(50)}); + tx = vault.deposit({.depositor = charlie, .id = keylet.key, .amount = asset(50)}); env(tx, ter{tecNO_AUTH}); env.close(); } { testcase("private vault depositor lost authorization"); - env(credentials::deleteCred( - credIssuer1, depositor, credIssuer1, credType)); - env(credentials::deleteCred( - credIssuer1, charlie, credIssuer1, credType)); + env(credentials::deleteCred(credIssuer1, depositor, credIssuer1, credType)); + env(credentials::deleteCred(credIssuer1, charlie, credIssuer1, credType)); env.close(); auto credSle = env.le(credKeylet); BEAST_EXPECT(credSle == nullptr); - auto tx = vault.deposit( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(50)}); + auto tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(50)}); env(tx, ter{tecNO_AUTH}); env.close(); } @@ -3522,13 +2910,9 @@ class Vault_test : public beast::unit_test::suite { testcase("private vault expired authorization"); - uint32_t const closeTime = env.current() - ->header() - .parentCloseTime.time_since_epoch() - .count(); + uint32_t const closeTime = env.current()->header().parentCloseTime.time_since_epoch().count(); { - auto tx0 = - credentials::create(depositor, credIssuer2, credType); + auto tx0 = credentials::create(depositor, credIssuer2, credType); tx0[sfExpiration] = closeTime + 20; env(tx0); tx0 = credentials::create(charlie, credIssuer2, credType); @@ -3542,15 +2926,11 @@ class Vault_test : public beast::unit_test::suite } { - auto tx1 = vault.deposit( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(50)}); + auto tx1 = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(50)}); env(tx1); env.close(); - auto const tokenKeylet = keylet::mptoken( - shares.get().getMptID(), depositor.id()); + auto const tokenKeylet = keylet::mptoken(shares.get().getMptID(), depositor.id()); BEAST_EXPECT(env.le(tokenKeylet) != nullptr); } @@ -3560,14 +2940,10 @@ class Vault_test : public beast::unit_test::suite env.close(); env.close(); - auto const credsKeylet = - credentials::keylet(depositor, credIssuer2, credType); + auto const credsKeylet = credentials::keylet(depositor, credIssuer2, credType); BEAST_EXPECT(env.le(credsKeylet) != nullptr); - auto tx2 = vault.deposit( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(1)}); + auto tx2 = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(1)}); env(tx2, ter{tecEXPIRED}); env.close(); @@ -3575,17 +2951,12 @@ class Vault_test : public beast::unit_test::suite } { - auto const credsKeylet = - credentials::keylet(charlie, credIssuer2, credType); + auto const credsKeylet = credentials::keylet(charlie, credIssuer2, credType); BEAST_EXPECT(env.le(credsKeylet) != nullptr); - auto const tokenKeylet = keylet::mptoken( - shares.get().getMptID(), charlie.id()); + auto const tokenKeylet = keylet::mptoken(shares.get().getMptID(), charlie.id()); BEAST_EXPECT(env.le(tokenKeylet) == nullptr); - auto tx3 = vault.deposit( - {.depositor = charlie, - .id = keylet.key, - .amount = asset(2)}); + auto tx3 = vault.deposit({.depositor = charlie, .id = keylet.key, .amount = asset(2)}); env(tx3, ter{tecEXPIRED}); env.close(); @@ -3601,32 +2972,18 @@ class Vault_test : public beast::unit_test::suite env(tx); env.close(); - tx = vault.deposit( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(50)}); + tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(50)}); env(tx, ter{tecNO_AUTH}); env.close(); - tx = vault.withdraw( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(50)}); + tx = vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(50)}); env(tx); env.close(); - tx = vault.clawback( - {.issuer = issuer, - .id = keylet.key, - .holder = depositor, - .amount = asset(0)}); + tx = vault.clawback({.issuer = issuer, .id = keylet.key, .holder = depositor, .amount = asset(0)}); env(tx); - tx = vault.clawback( - {.issuer = issuer, - .id = keylet.key, - .holder = owner, - .amount = asset(0)}); + tx = vault.clawback({.issuer = issuer, .id = keylet.key, .holder = owner, .amount = asset(0)}); env(tx); env.close(); @@ -3655,13 +3012,11 @@ class Vault_test : public beast::unit_test::suite env.close(); PrettyAsset asset = xrpIssue(); - auto [tx, keylet] = vault.create( - {.owner = owner, .asset = asset, .flags = tfVaultPrivate}); + auto [tx, keylet] = vault.create({.owner = owner, .asset = asset, .flags = tfVaultPrivate}); env(tx); env.close(); - auto const [vaultAccount, issuanceId] = - [&env, keylet = keylet, this]() -> std::tuple { + auto const [vaultAccount, issuanceId] = [&env, keylet = keylet, this]() -> std::tuple { auto const vault = env.le(keylet); BEAST_EXPECT(vault != nullptr); return {vault->at(sfAccount), vault->at(sfShareMPTID)}; @@ -3672,8 +3027,7 @@ class Vault_test : public beast::unit_test::suite { testcase("private XRP vault owner can deposit"); - auto tx = vault.deposit( - {.depositor = owner, .id = keylet.key, .amount = asset(50)}); + auto tx = vault.deposit({.depositor = owner, .id = keylet.key, .amount = asset(50)}); env(tx); env.close(); } @@ -3685,17 +3039,13 @@ class Vault_test : public beast::unit_test::suite { testcase("private XRP vault depositor not authorized yet"); - auto tx = vault.deposit( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(50)}); + auto tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(50)}); env(tx, ter{tecNO_AUTH}); } { testcase("private XRP vault set DomainID"); - pdomain::Credentials const credentials{ - {.issuer = owner, .credType = credType}}; + pdomain::Credentials const credentials{{.issuer = owner, .credType = credType}}; env(pdomain::setTx(owner, credentials)); auto const domainId = [&]() { @@ -3717,10 +3067,7 @@ class Vault_test : public beast::unit_test::suite env.close(); BEAST_EXPECT(env.le(credKeylet)); - auto tx = vault.deposit( - {.depositor = depositor, - .id = keylet.key, - .amount = asset(50)}); + auto tx = vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(50)}); env(tx); env.close(); } @@ -3757,17 +3104,12 @@ class Vault_test : public beast::unit_test::suite auto const keylet = keylet::vault(owner.id(), env.seq(owner)); for (int i = 0; i < 256; ++i) { - AccountID const accountId = - xrpl::pseudoAccountAddress(*env.current(), keylet.key); + AccountID const accountId = xrpl::pseudoAccountAddress(*env.current(), keylet.key); - env(pay(env.master.id(), accountId, XRP(1000)), - seq(autofill), - fee(autofill), - sig(autofill)); + env(pay(env.master.id(), accountId, XRP(1000)), seq(autofill), fee(autofill), sig(autofill)); } - auto [tx, keylet1] = - vault.create({.owner = owner, .asset = xrpIssue()}); + auto [tx, keylet1] = vault.create({.owner = owner, .asset = xrpIssue()}); BEAST_EXPECT(keylet.key == keylet1.key); env(tx, ter{terADDRESS_COLLISION}); } @@ -3792,9 +3134,7 @@ class Vault_test : public beast::unit_test::suite std::function)> peek; }; - auto testCase = [&, this]( - std::uint8_t scale, - std::function test) { + auto testCase = [&, this](std::uint8_t scale, std::function test) { Env env{*this, testable_amendments() | featureSingleAssetVault}; Account const owner{"owner"}; Account const issuer{"issuer"}; @@ -3815,37 +3155,31 @@ class Vault_test : public beast::unit_test::suite tx[sfScale] = scale; env(tx); - auto const [vaultAccount, issuanceId] = - [&env](xrpl::Keylet keylet) -> std::tuple { + auto const [vaultAccount, issuanceId] = [&env](xrpl::Keylet keylet) -> std::tuple { auto const vault = env.le(keylet); - return { - Account("vault", vault->at(sfAccount)), - vault->at(sfShareMPTID)}; + return {Account("vault", vault->at(sfAccount)), vault->at(sfShareMPTID)}; }(keylet); MPTIssue shares(issuanceId); env.memoize(vaultAccount); - auto const peek = - [=, &env, this](std::function fn) -> bool { - return env.app().openLedger().modify( - [&](OpenView& view, beast::Journal j) -> bool { - Sandbox sb(&view, tapNONE); - auto vault = sb.peek(keylet::vault(keylet.key)); - if (!BEAST_EXPECT(vault != nullptr)) - return false; - auto shares = sb.peek( - keylet::mptIssuance(vault->at(sfShareMPTID))); - if (!BEAST_EXPECT(shares != nullptr)) - return false; - if (fn(*vault, *shares)) - { - sb.update(vault); - sb.update(shares); - sb.apply(view); - return true; - } + auto const peek = [=, &env, this](std::function fn) -> bool { + return env.app().openLedger().modify([&](OpenView& view, beast::Journal j) -> bool { + Sandbox sb(&view, tapNONE); + auto vault = sb.peek(keylet::vault(keylet.key)); + if (!BEAST_EXPECT(vault != nullptr)) return false; - }); + auto shares = sb.peek(keylet::mptIssuance(vault->at(sfShareMPTID))); + if (!BEAST_EXPECT(shares != nullptr)) + return false; + if (fn(*vault, *shares)) + { + sb.update(vault); + sb.update(shares); + sb.apply(view); + return true; + } + return false; + }); }; test( @@ -3865,10 +3199,7 @@ class Vault_test : public beast::unit_test::suite testCase(18, [&, this](Env& env, Data d) { testcase("Scale deposit overflow on first deposit"); - auto tx = d.vault.deposit( - {.depositor = d.depositor, - .id = d.keylet.key, - .amount = d.asset(10)}); + auto tx = d.vault.deposit({.depositor = d.depositor, .id = d.keylet.key, .amount = d.asset(10)}); env(tx, ter{tecPATH_DRY}); env.close(); }); @@ -3877,19 +3208,13 @@ class Vault_test : public beast::unit_test::suite testcase("Scale deposit overflow on second deposit"); { - auto tx = d.vault.deposit( - {.depositor = d.depositor, - .id = d.keylet.key, - .amount = d.asset(5)}); + auto tx = d.vault.deposit({.depositor = d.depositor, .id = d.keylet.key, .amount = d.asset(5)}); env(tx); env.close(); } { - auto tx = d.vault.deposit( - {.depositor = d.depositor, - .id = d.keylet.key, - .amount = d.asset(10)}); + auto tx = d.vault.deposit({.depositor = d.depositor, .id = d.keylet.key, .amount = d.asset(10)}); env(tx, ter{tecPATH_DRY}); env.close(); } @@ -3899,19 +3224,13 @@ class Vault_test : public beast::unit_test::suite testcase("Scale deposit overflow on total shares"); { - auto tx = d.vault.deposit( - {.depositor = d.depositor, - .id = d.keylet.key, - .amount = d.asset(5)}); + auto tx = d.vault.deposit({.depositor = d.depositor, .id = d.keylet.key, .amount = d.asset(5)}); env(tx); env.close(); } { - auto tx = d.vault.deposit( - {.depositor = d.depositor, - .id = d.keylet.key, - .amount = d.asset(5)}); + auto tx = d.vault.deposit({.depositor = d.depositor, .id = d.keylet.key, .amount = d.asset(5)}); env(tx, ter{tecPATH_DRY}); env.close(); } @@ -3921,25 +3240,18 @@ class Vault_test : public beast::unit_test::suite testcase("Scale deposit exact"); auto const start = env.balance(d.depositor, d.assets).number(); - auto tx = d.vault.deposit( - {.depositor = d.depositor, - .id = d.keylet.key, - .amount = d.asset(1)}); + auto tx = d.vault.deposit({.depositor = d.depositor, .id = d.keylet.key, .amount = d.asset(1)}); env(tx); env.close(); BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(10)); - BEAST_EXPECT( - env.balance(d.depositor, d.assets) == - STAmount(d.asset, start - 1)); + BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start - 1)); }); testCase(1, [&, this](Env& env, Data d) { testcase("Scale deposit insignificant amount"); auto tx = d.vault.deposit( - {.depositor = d.depositor, - .id = d.keylet.key, - .amount = STAmount(d.asset, Number(9, -2))}); + {.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.asset, Number(9, -2))}); env(tx, ter{tecPRECISION_LOSS}); }); @@ -3948,15 +3260,11 @@ class Vault_test : public beast::unit_test::suite auto const start = env.balance(d.depositor, d.assets).number(); auto tx = d.vault.deposit( - {.depositor = d.depositor, - .id = d.keylet.key, - .amount = STAmount(d.asset, Number(15, -1))}); + {.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.asset, Number(15, -1))}); env(tx); env.close(); BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(15)); - BEAST_EXPECT( - env.balance(d.depositor, d.assets) == - STAmount(d.asset, start - Number(15, -1))); + BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start - Number(15, -1))); }); testCase(1, [&, this](Env& env, Data d) { @@ -3967,41 +3275,29 @@ class Vault_test : public beast::unit_test::suite // vault and receive 12 shares in exchange { auto tx = d.vault.deposit( - {.depositor = d.depositor, - .id = d.keylet.key, - .amount = STAmount(d.asset, Number(125, -2))}); + {.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.asset, Number(125, -2))}); env(tx); env.close(); BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(12)); - BEAST_EXPECT( - env.balance(d.depositor, d.assets) == - STAmount(d.asset, start - Number(12, -1))); + BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start - Number(12, -1))); } { auto tx = d.vault.deposit( - {.depositor = d.depositor, - .id = d.keylet.key, - .amount = STAmount(d.asset, Number(1201, -3))}); + {.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.asset, Number(1201, -3))}); env(tx); env.close(); BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(24)); - BEAST_EXPECT( - env.balance(d.depositor, d.assets) == - STAmount(d.asset, start - Number(24, -1))); + BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start - Number(24, -1))); } { auto tx = d.vault.deposit( - {.depositor = d.depositor, - .id = d.keylet.key, - .amount = STAmount(d.asset, Number(1299, -3))}); + {.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.asset, Number(1299, -3))}); env(tx); env.close(); BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(36)); - BEAST_EXPECT( - env.balance(d.depositor, d.assets) == - STAmount(d.asset, start - Number(36, -1))); + BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start - Number(36, -1))); } }); @@ -4011,28 +3307,20 @@ class Vault_test : public beast::unit_test::suite auto const start = env.balance(d.depositor, d.assets).number(); // round to 12 auto tx = d.vault.deposit( - {.depositor = d.depositor, - .id = d.keylet.key, - .amount = STAmount(d.asset, Number(1201, -3))}); + {.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.asset, Number(1201, -3))}); env(tx); env.close(); BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(12)); - BEAST_EXPECT( - env.balance(d.depositor, d.assets) == - STAmount(d.asset, start - Number(12, -1))); + BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start - Number(12, -1))); { // round to 6 auto tx = d.vault.deposit( - {.depositor = d.depositor, - .id = d.keylet.key, - .amount = STAmount(d.asset, Number(69, -2))}); + {.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.asset, Number(69, -2))}); env(tx); env.close(); BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(18)); - BEAST_EXPECT( - env.balance(d.depositor, d.assets) == - STAmount(d.asset, start - Number(18, -1))); + BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start - Number(18, -1))); } }); @@ -4042,28 +3330,20 @@ class Vault_test : public beast::unit_test::suite auto const start = env.balance(d.depositor, d.assets).number(); // round to 12 auto tx = d.vault.deposit( - {.depositor = d.depositor, - .id = d.keylet.key, - .amount = STAmount(d.asset, Number(1299, -3))}); + {.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.asset, Number(1299, -3))}); env(tx); env.close(); BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(12)); - BEAST_EXPECT( - env.balance(d.depositor, d.assets) == - STAmount(d.asset, start - Number(12, -1))); + BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start - Number(12, -1))); { // round to 6 auto tx = d.vault.deposit( - {.depositor = d.depositor, - .id = d.keylet.key, - .amount = STAmount(d.asset, Number(62, -2))}); + {.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.asset, Number(62, -2))}); env(tx); env.close(); BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(18)); - BEAST_EXPECT( - env.balance(d.depositor, d.assets) == - STAmount(d.asset, start - Number(18, -1))); + BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start - Number(18, -1))); } }); @@ -4071,21 +3351,13 @@ class Vault_test : public beast::unit_test::suite // initial setup: deposit 100 IOU, receive 1000 shares auto const start = env.balance(d.depositor, d.assets).number(); auto tx = d.vault.deposit( - {.depositor = d.depositor, - .id = d.keylet.key, - .amount = STAmount(d.asset, Number(100, 0))}); + {.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.asset, Number(100, 0))}); env(tx); env.close(); BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(1000)); - BEAST_EXPECT( - env.balance(d.depositor, d.assets) == - STAmount(d.asset, start - Number(100, 0))); - BEAST_EXPECT( - env.balance(d.vaultAccount, d.assets) == - STAmount(d.asset, Number(100, 0))); - BEAST_EXPECT( - env.balance(d.vaultAccount, d.shares) == - STAmount(d.share, Number(-1000, 0))); + BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start - Number(100, 0))); + BEAST_EXPECT(env.balance(d.vaultAccount, d.assets) == STAmount(d.asset, Number(100, 0))); + BEAST_EXPECT(env.balance(d.vaultAccount, d.shares) == STAmount(d.share, Number(-1000, 0))); { testcase("Scale redeem exact"); @@ -4095,22 +3367,13 @@ class Vault_test : public beast::unit_test::suite auto const start = env.balance(d.depositor, d.assets).number(); auto tx = d.vault.withdraw( - {.depositor = d.depositor, - .id = d.keylet.key, - .amount = STAmount(d.share, Number(100, 0))}); + {.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.share, Number(100, 0))}); env(tx); env.close(); - BEAST_EXPECT( - env.balance(d.depositor, d.shares) == d.share(900)); - BEAST_EXPECT( - env.balance(d.depositor, d.assets) == - STAmount(d.asset, start + Number(10, 0))); - BEAST_EXPECT( - env.balance(d.vaultAccount, d.assets) == - STAmount(d.asset, Number(90, 0))); - BEAST_EXPECT( - env.balance(d.vaultAccount, d.shares) == - STAmount(d.share, Number(-900, 0))); + BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(900)); + BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start + Number(10, 0))); + BEAST_EXPECT(env.balance(d.vaultAccount, d.assets) == STAmount(d.asset, Number(90, 0))); + BEAST_EXPECT(env.balance(d.vaultAccount, d.shares) == STAmount(d.share, Number(-900, 0))); } { @@ -4130,22 +3393,13 @@ class Vault_test : public beast::unit_test::suite // closed (because a modification like above is not persistent), // which is why the checks below are expected to pass. auto tx = d.vault.withdraw( - {.depositor = d.depositor, - .id = d.keylet.key, - .amount = STAmount(d.share, Number(25, 0))}); + {.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.share, Number(25, 0))}); env(tx, ter{tecINSUFFICIENT_FUNDS}); env.close(); - BEAST_EXPECT( - env.balance(d.depositor, d.shares) == d.share(900 - 25)); - BEAST_EXPECT( - env.balance(d.depositor, d.assets) == - STAmount(d.asset, start + Number(25, -1))); - BEAST_EXPECT( - env.balance(d.vaultAccount, d.assets) == - STAmount(d.asset, Number(900 - 25, -1))); - BEAST_EXPECT( - env.balance(d.vaultAccount, d.shares) == - STAmount(d.share, -Number(900 - 25, 0))); + BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(900 - 25)); + BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start + Number(25, -1))); + BEAST_EXPECT(env.balance(d.vaultAccount, d.assets) == STAmount(d.asset, Number(900 - 25, -1))); + BEAST_EXPECT(env.balance(d.vaultAccount, d.shares) == STAmount(d.share, -Number(900 - 25, 0))); } { @@ -4157,39 +3411,26 @@ class Vault_test : public beast::unit_test::suite auto const start = env.balance(d.depositor, d.assets).number(); tx = d.vault.withdraw( - {.depositor = d.depositor, - .id = d.keylet.key, - .amount = STAmount(d.share, Number(21, 0))}); + {.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.share, Number(21, 0))}); env(tx); env.close(); - BEAST_EXPECT( - env.balance(d.depositor, d.shares) == d.share(875 - 21)); - BEAST_EXPECT( - env.balance(d.depositor, d.assets) == - STAmount(d.asset, start + Number(21, -1))); - BEAST_EXPECT( - env.balance(d.vaultAccount, d.assets) == - STAmount(d.asset, Number(875 - 21, -1))); - BEAST_EXPECT( - env.balance(d.vaultAccount, d.shares) == - STAmount(d.share, -Number(875 - 21, 0))); + BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(875 - 21)); + BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start + Number(21, -1))); + BEAST_EXPECT(env.balance(d.vaultAccount, d.assets) == STAmount(d.asset, Number(875 - 21, -1))); + BEAST_EXPECT(env.balance(d.vaultAccount, d.shares) == STAmount(d.share, -Number(875 - 21, 0))); } { testcase("Scale redeem rest"); auto const rest = env.balance(d.depositor, d.shares).number(); - tx = d.vault.withdraw( - {.depositor = d.depositor, - .id = d.keylet.key, - .amount = STAmount(d.share, rest)}); + tx = + d.vault.withdraw({.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.share, rest)}); env(tx); env.close(); BEAST_EXPECT(env.balance(d.depositor, d.shares).number() == 0); - BEAST_EXPECT( - env.balance(d.vaultAccount, d.assets).number() == 0); - BEAST_EXPECT( - env.balance(d.vaultAccount, d.shares).number() == 0); + BEAST_EXPECT(env.balance(d.vaultAccount, d.assets).number() == 0); + BEAST_EXPECT(env.balance(d.vaultAccount, d.shares).number() == 0); } }); @@ -4197,19 +3438,14 @@ class Vault_test : public beast::unit_test::suite testcase("Scale withdraw overflow"); { - auto tx = d.vault.deposit( - {.depositor = d.depositor, - .id = d.keylet.key, - .amount = d.asset(5)}); + auto tx = d.vault.deposit({.depositor = d.depositor, .id = d.keylet.key, .amount = d.asset(5)}); env(tx); env.close(); } { auto tx = d.vault.withdraw( - {.depositor = d.depositor, - .id = d.keylet.key, - .amount = STAmount(d.asset, Number(10, 0))}); + {.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.asset, Number(10, 0))}); env(tx, ter{tecPATH_DRY}); env.close(); } @@ -4219,21 +3455,13 @@ class Vault_test : public beast::unit_test::suite // initial setup: deposit 100 IOU, receive 1000 shares auto const start = env.balance(d.depositor, d.assets).number(); auto tx = d.vault.deposit( - {.depositor = d.depositor, - .id = d.keylet.key, - .amount = STAmount(d.asset, Number(100, 0))}); + {.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.asset, Number(100, 0))}); env(tx); env.close(); BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(1000)); - BEAST_EXPECT( - env.balance(d.depositor, d.assets) == - STAmount(d.asset, start - Number(100, 0))); - BEAST_EXPECT( - env.balance(d.vaultAccount, d.assets) == - STAmount(d.asset, Number(100, 0))); - BEAST_EXPECT( - env.balance(d.vaultAccount, d.shares) == - STAmount(d.share, Number(-1000, 0))); + BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start - Number(100, 0))); + BEAST_EXPECT(env.balance(d.vaultAccount, d.assets) == STAmount(d.asset, Number(100, 0))); + BEAST_EXPECT(env.balance(d.vaultAccount, d.shares) == STAmount(d.share, Number(-1000, 0))); { testcase("Scale withdraw exact"); @@ -4246,30 +3474,19 @@ class Vault_test : public beast::unit_test::suite auto const start = env.balance(d.depositor, d.assets).number(); auto tx = d.vault.withdraw( - {.depositor = d.depositor, - .id = d.keylet.key, - .amount = STAmount(d.asset, Number(10, 0))}); + {.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.asset, Number(10, 0))}); env(tx); env.close(); - BEAST_EXPECT( - env.balance(d.depositor, d.shares) == d.share(900)); - BEAST_EXPECT( - env.balance(d.depositor, d.assets) == - STAmount(d.asset, start + Number(10, 0))); - BEAST_EXPECT( - env.balance(d.vaultAccount, d.assets) == - STAmount(d.asset, Number(90, 0))); - BEAST_EXPECT( - env.balance(d.vaultAccount, d.shares) == - STAmount(d.share, Number(-900, 0))); + BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(900)); + BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start + Number(10, 0))); + BEAST_EXPECT(env.balance(d.vaultAccount, d.assets) == STAmount(d.asset, Number(90, 0))); + BEAST_EXPECT(env.balance(d.vaultAccount, d.shares) == STAmount(d.share, Number(-900, 0))); } { testcase("Scale withdraw insignificant amount"); auto tx = d.vault.withdraw( - {.depositor = d.depositor, - .id = d.keylet.key, - .amount = STAmount(d.asset, Number(4, -2))}); + {.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.asset, Number(4, -2))}); env(tx, ter{tecPRECISION_LOSS}); } @@ -4293,22 +3510,13 @@ class Vault_test : public beast::unit_test::suite // closed (because a modification like above is not persistent), // which is why the checks below are expected to pass. auto tx = d.vault.withdraw( - {.depositor = d.depositor, - .id = d.keylet.key, - .amount = STAmount(d.asset, Number(25, -1))}); + {.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.asset, Number(25, -1))}); env(tx, ter{tecINSUFFICIENT_FUNDS}); env.close(); - BEAST_EXPECT( - env.balance(d.depositor, d.shares) == d.share(900 - 25)); - BEAST_EXPECT( - env.balance(d.depositor, d.assets) == - STAmount(d.asset, start + Number(25, -1))); - BEAST_EXPECT( - env.balance(d.vaultAccount, d.assets) == - STAmount(d.asset, Number(900 - 25, -1))); - BEAST_EXPECT( - env.balance(d.vaultAccount, d.shares) == - STAmount(d.share, -Number(900 - 25, 0))); + BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(900 - 25)); + BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start + Number(25, -1))); + BEAST_EXPECT(env.balance(d.vaultAccount, d.assets) == STAmount(d.asset, Number(900 - 25, -1))); + BEAST_EXPECT(env.balance(d.vaultAccount, d.shares) == STAmount(d.share, -Number(900 - 25, 0))); } { @@ -4322,22 +3530,13 @@ class Vault_test : public beast::unit_test::suite auto const start = env.balance(d.depositor, d.assets).number(); auto tx = d.vault.withdraw( - {.depositor = d.depositor, - .id = d.keylet.key, - .amount = STAmount(d.asset, Number(375, -2))}); + {.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.asset, Number(375, -2))}); env(tx); env.close(); - BEAST_EXPECT( - env.balance(d.depositor, d.shares) == d.share(875 - 38)); - BEAST_EXPECT( - env.balance(d.depositor, d.assets) == - STAmount(d.asset, start + Number(38, -1))); - BEAST_EXPECT( - env.balance(d.vaultAccount, d.assets) == - STAmount(d.asset, Number(875 - 38, -1))); - BEAST_EXPECT( - env.balance(d.vaultAccount, d.shares) == - STAmount(d.share, -Number(875 - 38, 0))); + BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(875 - 38)); + BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start + Number(38, -1))); + BEAST_EXPECT(env.balance(d.vaultAccount, d.assets) == STAmount(d.asset, Number(875 - 38, -1))); + BEAST_EXPECT(env.balance(d.vaultAccount, d.shares) == STAmount(d.share, -Number(875 - 38, 0))); } { @@ -4351,22 +3550,13 @@ class Vault_test : public beast::unit_test::suite auto const start = env.balance(d.depositor, d.assets).number(); auto tx = d.vault.withdraw( - {.depositor = d.depositor, - .id = d.keylet.key, - .amount = STAmount(d.asset, Number(372, -2))}); + {.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.asset, Number(372, -2))}); env(tx); env.close(); - BEAST_EXPECT( - env.balance(d.depositor, d.shares) == d.share(837 - 37)); - BEAST_EXPECT( - env.balance(d.depositor, d.assets) == - STAmount(d.asset, start + Number(37, -1))); - BEAST_EXPECT( - env.balance(d.vaultAccount, d.assets) == - STAmount(d.asset, Number(837 - 37, -1))); - BEAST_EXPECT( - env.balance(d.vaultAccount, d.shares) == - STAmount(d.share, -Number(837 - 37, 0))); + BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(837 - 37)); + BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start + Number(37, -1))); + BEAST_EXPECT(env.balance(d.vaultAccount, d.assets) == STAmount(d.asset, Number(837 - 37, -1))); + BEAST_EXPECT(env.balance(d.vaultAccount, d.shares) == STAmount(d.share, -Number(837 - 37, 0))); } { @@ -4374,40 +3564,26 @@ class Vault_test : public beast::unit_test::suite auto const start = env.balance(d.depositor, d.assets).number(); auto tx = d.vault.withdraw( - {.depositor = d.depositor, - .id = d.keylet.key, - .amount = STAmount(d.asset, Number(9, -2))}); + {.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.asset, Number(9, -2))}); env(tx); env.close(); - BEAST_EXPECT( - env.balance(d.depositor, d.shares) == d.share(800 - 1)); - BEAST_EXPECT( - env.balance(d.depositor, d.assets) == - STAmount(d.asset, start + Number(1, -1))); - BEAST_EXPECT( - env.balance(d.vaultAccount, d.assets) == - STAmount(d.asset, Number(800 - 1, -1))); - BEAST_EXPECT( - env.balance(d.vaultAccount, d.shares) == - STAmount(d.share, -Number(800 - 1, 0))); + BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(800 - 1)); + BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start + Number(1, -1))); + BEAST_EXPECT(env.balance(d.vaultAccount, d.assets) == STAmount(d.asset, Number(800 - 1, -1))); + BEAST_EXPECT(env.balance(d.vaultAccount, d.shares) == STAmount(d.share, -Number(800 - 1, 0))); } { testcase("Scale withdraw rest"); - auto const rest = - env.balance(d.vaultAccount, d.assets).number(); + auto const rest = env.balance(d.vaultAccount, d.assets).number(); - tx = d.vault.withdraw( - {.depositor = d.depositor, - .id = d.keylet.key, - .amount = STAmount(d.asset, rest)}); + tx = + d.vault.withdraw({.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.asset, rest)}); env(tx); env.close(); BEAST_EXPECT(env.balance(d.depositor, d.shares).number() == 0); - BEAST_EXPECT( - env.balance(d.vaultAccount, d.assets).number() == 0); - BEAST_EXPECT( - env.balance(d.vaultAccount, d.shares).number() == 0); + BEAST_EXPECT(env.balance(d.vaultAccount, d.assets).number() == 0); + BEAST_EXPECT(env.balance(d.vaultAccount, d.shares).number() == 0); } }); @@ -4415,10 +3591,7 @@ class Vault_test : public beast::unit_test::suite testcase("Scale clawback overflow"); { - auto tx = d.vault.deposit( - {.depositor = d.depositor, - .id = d.keylet.key, - .amount = d.asset(5)}); + auto tx = d.vault.deposit({.depositor = d.depositor, .id = d.keylet.key, .amount = d.asset(5)}); env(tx); env.close(); } @@ -4438,21 +3611,13 @@ class Vault_test : public beast::unit_test::suite // initial setup: deposit 100 IOU, receive 1000 shares auto const start = env.balance(d.depositor, d.assets).number(); auto tx = d.vault.deposit( - {.depositor = d.depositor, - .id = d.keylet.key, - .amount = STAmount(d.asset, Number(100, 0))}); + {.depositor = d.depositor, .id = d.keylet.key, .amount = STAmount(d.asset, Number(100, 0))}); env(tx); env.close(); BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(1000)); - BEAST_EXPECT( - env.balance(d.depositor, d.assets) == - STAmount(d.asset, start - Number(100, 0))); - BEAST_EXPECT( - env.balance(d.vaultAccount, d.assets) == - STAmount(d.asset, Number(100, 0))); - BEAST_EXPECT( - env.balance(d.vaultAccount, d.shares) == - STAmount(d.share, -Number(1000, 0))); + BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start - Number(100, 0))); + BEAST_EXPECT(env.balance(d.vaultAccount, d.assets) == STAmount(d.asset, Number(100, 0))); + BEAST_EXPECT(env.balance(d.vaultAccount, d.shares) == STAmount(d.share, -Number(1000, 0))); { testcase("Scale clawback exact"); // assetsToSharesWithdraw: @@ -4470,17 +3635,10 @@ class Vault_test : public beast::unit_test::suite .amount = STAmount(d.asset, Number(10, 0))}); env(tx); env.close(); - BEAST_EXPECT( - env.balance(d.depositor, d.shares) == d.share(900)); - BEAST_EXPECT( - env.balance(d.depositor, d.assets) == - STAmount(d.asset, start)); - BEAST_EXPECT( - env.balance(d.vaultAccount, d.assets) == - STAmount(d.asset, Number(90, 0))); - BEAST_EXPECT( - env.balance(d.vaultAccount, d.shares) == - STAmount(d.share, -Number(900, 0))); + BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(900)); + BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start)); + BEAST_EXPECT(env.balance(d.vaultAccount, d.assets) == STAmount(d.asset, Number(90, 0))); + BEAST_EXPECT(env.balance(d.vaultAccount, d.shares) == STAmount(d.share, -Number(900, 0))); } { @@ -4510,17 +3668,10 @@ class Vault_test : public beast::unit_test::suite .amount = STAmount(d.asset, Number(25, -1))}); env(tx); env.close(); - BEAST_EXPECT( - env.balance(d.depositor, d.shares) == d.share(900 - 25)); - BEAST_EXPECT( - env.balance(d.depositor, d.assets) == - STAmount(d.asset, start)); - BEAST_EXPECT( - env.balance(d.vaultAccount, d.assets) == - STAmount(d.asset, Number(900 - 25, -1))); - BEAST_EXPECT( - env.balance(d.vaultAccount, d.shares) == - STAmount(d.share, -Number(900 - 25, 0))); + BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(900 - 25)); + BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start)); + BEAST_EXPECT(env.balance(d.vaultAccount, d.assets) == STAmount(d.asset, Number(900 - 25, -1))); + BEAST_EXPECT(env.balance(d.vaultAccount, d.shares) == STAmount(d.share, -Number(900 - 25, 0))); } { @@ -4540,17 +3691,10 @@ class Vault_test : public beast::unit_test::suite .amount = STAmount(d.asset, Number(375, -2))}); env(tx); env.close(); - BEAST_EXPECT( - env.balance(d.depositor, d.shares) == d.share(875 - 38)); - BEAST_EXPECT( - env.balance(d.depositor, d.assets) == - STAmount(d.asset, start)); - BEAST_EXPECT( - env.balance(d.vaultAccount, d.assets) == - STAmount(d.asset, Number(875 - 38, -1))); - BEAST_EXPECT( - env.balance(d.vaultAccount, d.shares) == - STAmount(d.share, -Number(875 - 38, 0))); + BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(875 - 38)); + BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start)); + BEAST_EXPECT(env.balance(d.vaultAccount, d.assets) == STAmount(d.asset, Number(875 - 38, -1))); + BEAST_EXPECT(env.balance(d.vaultAccount, d.shares) == STAmount(d.share, -Number(875 - 38, 0))); } { @@ -4570,17 +3714,10 @@ class Vault_test : public beast::unit_test::suite .amount = STAmount(d.asset, Number(372, -2))}); env(tx); env.close(); - BEAST_EXPECT( - env.balance(d.depositor, d.shares) == d.share(837 - 37)); - BEAST_EXPECT( - env.balance(d.depositor, d.assets) == - STAmount(d.asset, start)); - BEAST_EXPECT( - env.balance(d.vaultAccount, d.assets) == - STAmount(d.asset, Number(837 - 37, -1))); - BEAST_EXPECT( - env.balance(d.vaultAccount, d.shares) == - STAmount(d.share, -Number(837 - 37, 0))); + BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(837 - 37)); + BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start)); + BEAST_EXPECT(env.balance(d.vaultAccount, d.assets) == STAmount(d.asset, Number(837 - 37, -1))); + BEAST_EXPECT(env.balance(d.vaultAccount, d.shares) == STAmount(d.share, -Number(837 - 37, 0))); } { @@ -4594,23 +3731,15 @@ class Vault_test : public beast::unit_test::suite .amount = STAmount(d.asset, Number(9, -2))}); env(tx); env.close(); - BEAST_EXPECT( - env.balance(d.depositor, d.shares) == d.share(800 - 1)); - BEAST_EXPECT( - env.balance(d.depositor, d.assets) == - STAmount(d.asset, start)); - BEAST_EXPECT( - env.balance(d.vaultAccount, d.assets) == - STAmount(d.asset, Number(800 - 1, -1))); - BEAST_EXPECT( - env.balance(d.vaultAccount, d.shares) == - STAmount(d.share, -Number(800 - 1, 0))); + BEAST_EXPECT(env.balance(d.depositor, d.shares) == d.share(800 - 1)); + BEAST_EXPECT(env.balance(d.depositor, d.assets) == STAmount(d.asset, start)); + BEAST_EXPECT(env.balance(d.vaultAccount, d.assets) == STAmount(d.asset, Number(800 - 1, -1))); + BEAST_EXPECT(env.balance(d.vaultAccount, d.shares) == STAmount(d.share, -Number(800 - 1, 0))); } { testcase("Scale clawback rest"); - auto const rest = - env.balance(d.vaultAccount, d.assets).number(); + auto const rest = env.balance(d.vaultAccount, d.assets).number(); d.peek([](SLE& vault, auto&) -> bool { vault[sfAssetsAvailable] = Number(5); return true; @@ -4621,17 +3750,12 @@ class Vault_test : public beast::unit_test::suite // * when the ledger is closed with unmodified AssetsAvailable // because a modification like above is not persistent. tx = d.vault.clawback( - {.issuer = d.issuer, - .id = d.keylet.key, - .holder = d.depositor, - .amount = STAmount(d.asset, rest)}); + {.issuer = d.issuer, .id = d.keylet.key, .holder = d.depositor, .amount = STAmount(d.asset, rest)}); env(tx); env.close(); BEAST_EXPECT(env.balance(d.depositor, d.shares).number() == 0); - BEAST_EXPECT( - env.balance(d.vaultAccount, d.assets).number() == 0); - BEAST_EXPECT( - env.balance(d.vaultAccount, d.shares).number() == 0); + BEAST_EXPECT(env.balance(d.vaultAccount, d.assets).number() == 0); + BEAST_EXPECT(env.balance(d.vaultAccount, d.shares).number() == 0); } }); } @@ -4661,8 +3785,7 @@ class Vault_test : public beast::unit_test::suite // Set some fields { - auto tx1 = vault.deposit( - {.depositor = owner, .id = keylet.key, .amount = asset(50)}); + auto tx1 = vault.deposit({.depositor = owner, .id = keylet.key, .amount = asset(50)}); env(tx1); auto tx2 = vault.set({.owner = owner, .id = keylet.key}); @@ -4678,29 +3801,19 @@ class Vault_test : public beast::unit_test::suite }(); auto const check = [&, keylet = keylet, sle = sleVault, this]( - Json::Value const& vault, - Json::Value const& issuance = Json::nullValue) { + Json::Value const& vault, Json::Value const& issuance = Json::nullValue) { BEAST_EXPECT(vault.isObject()); - constexpr auto checkString = - [](auto& node, SField const& field, std::string v) -> bool { - return node.isMember(field.fieldName) && - node[field.fieldName].isString() && - node[field.fieldName] == v; + constexpr auto checkString = [](auto& node, SField const& field, std::string v) -> bool { + return node.isMember(field.fieldName) && node[field.fieldName].isString() && node[field.fieldName] == v; }; - constexpr auto checkObject = - [](auto& node, SField const& field, Json::Value v) -> bool { - return node.isMember(field.fieldName) && - node[field.fieldName].isObject() && - node[field.fieldName] == v; + constexpr auto checkObject = [](auto& node, SField const& field, Json::Value v) -> bool { + return node.isMember(field.fieldName) && node[field.fieldName].isObject() && node[field.fieldName] == v; }; - constexpr auto checkInt = - [](auto& node, SField const& field, int v) -> bool { + constexpr auto checkInt = [](auto& node, SField const& field, int v) -> bool { return node.isMember(field.fieldName) && - ((node[field.fieldName].isInt() && - node[field.fieldName] == Json::Int(v)) || - (node[field.fieldName].isUInt() && - node[field.fieldName] == Json::UInt(v))); + ((node[field.fieldName].isInt() && node[field.fieldName] == Json::Int(v)) || + (node[field.fieldName].isUInt() && node[field.fieldName] == Json::UInt(v))); }; BEAST_EXPECT(vault["LedgerEntryType"].asString() == "Vault"); @@ -4708,10 +3821,8 @@ class Vault_test : public beast::unit_test::suite BEAST_EXPECT(checkInt(vault, sfFlags, 0)); // Ignore all other standard fields, this test doesn't care - BEAST_EXPECT( - checkString(vault, sfAccount, toBase58(sle->at(sfAccount)))); - BEAST_EXPECT( - checkObject(vault, sfAsset, to_json(sle->at(sfAsset)))); + BEAST_EXPECT(checkString(vault, sfAccount, toBase58(sle->at(sfAccount)))); + BEAST_EXPECT(checkObject(vault, sfAsset, to_json(sle->at(sfAsset)))); BEAST_EXPECT(checkString(vault, sfAssetsAvailable, "50")); BEAST_EXPECT(checkString(vault, sfAssetsMaximum, "1000")); BEAST_EXPECT(checkString(vault, sfAssetsTotal, "50")); @@ -4721,23 +3832,15 @@ class Vault_test : public beast::unit_test::suite BEAST_EXPECT(checkString(vault, sfShareMPTID, strShareID)); BEAST_EXPECT(checkString(vault, sfOwner, toBase58(owner.id()))); BEAST_EXPECT(checkInt(vault, sfSequence, sequence)); - BEAST_EXPECT(checkInt( - vault, sfWithdrawalPolicy, vaultStrategyFirstComeFirstServe)); + BEAST_EXPECT(checkInt(vault, sfWithdrawalPolicy, vaultStrategyFirstComeFirstServe)); if (issuance.isObject()) { - BEAST_EXPECT( - issuance["LedgerEntryType"].asString() == - "MPTokenIssuance"); - BEAST_EXPECT( - issuance[jss::mpt_issuance_id].asString() == strShareID); + BEAST_EXPECT(issuance["LedgerEntryType"].asString() == "MPTokenIssuance"); + BEAST_EXPECT(issuance[jss::mpt_issuance_id].asString() == strShareID); BEAST_EXPECT(checkInt(issuance, sfSequence, 1)); - BEAST_EXPECT(checkInt( - issuance, - sfFlags, - int(lsfMPTCanEscrow | lsfMPTCanTrade | lsfMPTCanTransfer))); - BEAST_EXPECT( - checkString(issuance, sfOutstandingAmount, "50000000")); + BEAST_EXPECT(checkInt(issuance, sfFlags, int(lsfMPTCanEscrow | lsfMPTCanTrade | lsfMPTCanTransfer))); + BEAST_EXPECT(checkString(issuance, sfOutstandingAmount, "50000000")); } }; @@ -4772,8 +3875,7 @@ class Vault_test : public beast::unit_test::suite jvParams[jss::ledger_index] = jss::validated; jvParams[jss::vault] = to_string(uint256(42)); auto jvVault = env.rpc("json", "ledger_entry", to_string(jvParams)); - BEAST_EXPECT( - jvVault[jss::result][jss::error].asString() == "entryNotFound"); + BEAST_EXPECT(jvVault[jss::result][jss::error].asString() == "entryNotFound"); } { @@ -4783,8 +3885,7 @@ class Vault_test : public beast::unit_test::suite jvParams[jss::vault][jss::owner] = issuer.human(); jvParams[jss::vault][jss::seq] = 1'000'000; auto jvVault = env.rpc("json", "ledger_entry", to_string(jvParams)); - BEAST_EXPECT( - jvVault[jss::result][jss::error].asString() == "entryNotFound"); + BEAST_EXPECT(jvVault[jss::result][jss::error].asString() == "entryNotFound"); } { @@ -4793,9 +3894,7 @@ class Vault_test : public beast::unit_test::suite jvParams[jss::ledger_index] = jss::validated; jvParams[jss::vault] = 42; auto jvVault = env.rpc("json", "ledger_entry", to_string(jvParams)); - BEAST_EXPECT( - jvVault[jss::result][jss::error].asString() == - "malformedRequest"); + BEAST_EXPECT(jvVault[jss::result][jss::error].asString() == "malformedRequest"); } { @@ -4805,9 +3904,7 @@ class Vault_test : public beast::unit_test::suite jvParams[jss::vault][jss::owner] = 42; jvParams[jss::vault][jss::seq] = sequence; auto jvVault = env.rpc("json", "ledger_entry", to_string(jvParams)); - BEAST_EXPECT( - jvVault[jss::result][jss::error].asString() == - "malformedOwner"); + BEAST_EXPECT(jvVault[jss::result][jss::error].asString() == "malformedOwner"); } { @@ -4817,9 +3914,7 @@ class Vault_test : public beast::unit_test::suite jvParams[jss::vault][jss::owner] = issuer.human(); jvParams[jss::vault][jss::seq] = "foo"; auto jvVault = env.rpc("json", "ledger_entry", to_string(jvParams)); - BEAST_EXPECT( - jvVault[jss::result][jss::error].asString() == - "malformedRequest"); + BEAST_EXPECT(jvVault[jss::result][jss::error].asString() == "malformedRequest"); } { @@ -4829,9 +3924,7 @@ class Vault_test : public beast::unit_test::suite jvParams[jss::vault][jss::owner] = issuer.human(); jvParams[jss::vault][jss::seq] = -1; auto jvVault = env.rpc("json", "ledger_entry", to_string(jvParams)); - BEAST_EXPECT( - jvVault[jss::result][jss::error].asString() == - "malformedRequest"); + BEAST_EXPECT(jvVault[jss::result][jss::error].asString() == "malformedRequest"); } { @@ -4841,9 +3934,7 @@ class Vault_test : public beast::unit_test::suite jvParams[jss::vault][jss::owner] = issuer.human(); jvParams[jss::vault][jss::seq] = 1e20; auto jvVault = env.rpc("json", "ledger_entry", to_string(jvParams)); - BEAST_EXPECT( - jvVault[jss::result][jss::error].asString() == - "malformedRequest"); + BEAST_EXPECT(jvVault[jss::result][jss::error].asString() == "malformedRequest"); } { @@ -4853,9 +3944,7 @@ class Vault_test : public beast::unit_test::suite jvParams[jss::vault][jss::owner] = issuer.human(); jvParams[jss::vault][jss::seq] = true; auto jvVault = env.rpc("json", "ledger_entry", to_string(jvParams)); - BEAST_EXPECT( - jvVault[jss::result][jss::error].asString() == - "malformedRequest"); + BEAST_EXPECT(jvVault[jss::result][jss::error].asString() == "malformedRequest"); } { @@ -4864,8 +3953,7 @@ class Vault_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::account] = owner.human(); jvParams[jss::type] = jss::vault; - auto jv = env.rpc( - "json", "account_objects", to_string(jvParams))[jss::result]; + auto jv = env.rpc("json", "account_objects", to_string(jvParams))[jss::result]; BEAST_EXPECT(jv[jss::account_objects].size() == 1); check(jv[jss::account_objects][0u]); @@ -4878,22 +3966,18 @@ class Vault_test : public beast::unit_test::suite jvParams[jss::ledger_index] = jss::validated; jvParams[jss::binary] = false; jvParams[jss::type] = jss::vault; - Json::Value jv = - env.rpc("json", "ledger_data", to_string(jvParams)); + Json::Value jv = env.rpc("json", "ledger_data", to_string(jvParams)); BEAST_EXPECT(jv[jss::result][jss::state].size() == 1); check(jv[jss::result][jss::state][0u]); } { testcase("RPC vault_info command line"); - Json::Value jv = - env.rpc("vault_info", strHex(keylet.key), "validated"); + Json::Value jv = env.rpc("vault_info", strHex(keylet.key), "validated"); BEAST_EXPECT(!jv[jss::result].isMember(jss::error)); BEAST_EXPECT(jv[jss::result].isMember(jss::vault)); - check( - jv[jss::result][jss::vault], - jv[jss::result][jss::vault][jss::shares]); + check(jv[jss::result][jss::vault], jv[jss::result][jss::vault][jss::shares]); } { @@ -4905,9 +3989,7 @@ class Vault_test : public beast::unit_test::suite BEAST_EXPECT(!jv[jss::result].isMember(jss::error)); BEAST_EXPECT(jv[jss::result].isMember(jss::vault)); - check( - jv[jss::result][jss::vault], - jv[jss::result][jss::vault][jss::shares]); + check(jv[jss::result][jss::vault], jv[jss::result][jss::vault][jss::shares]); } { @@ -4916,8 +3998,7 @@ class Vault_test : public beast::unit_test::suite jvParams[jss::ledger_index] = jss::validated; jvParams[jss::vault_id] = "foobar"; auto jv = env.rpc("json", "vault_info", to_string(jvParams)); - BEAST_EXPECT( - jv[jss::result][jss::error].asString() == "malformedRequest"); + BEAST_EXPECT(jv[jss::result][jss::error].asString() == "malformedRequest"); } { @@ -4926,8 +4007,7 @@ class Vault_test : public beast::unit_test::suite jvParams[jss::ledger_index] = jss::validated; jvParams[jss::vault_id] = 0; auto jv = env.rpc("json", "vault_info", to_string(jvParams)); - BEAST_EXPECT( - jv[jss::result][jss::error].asString() == "malformedRequest"); + BEAST_EXPECT(jv[jss::result][jss::error].asString() == "malformedRequest"); } { @@ -4940,9 +4020,7 @@ class Vault_test : public beast::unit_test::suite BEAST_EXPECT(!jv[jss::result].isMember(jss::error)); BEAST_EXPECT(jv[jss::result].isMember(jss::vault)); - check( - jv[jss::result][jss::vault], - jv[jss::result][jss::vault][jss::shares]); + check(jv[jss::result][jss::vault], jv[jss::result][jss::vault][jss::shares]); } { @@ -4952,8 +4030,7 @@ class Vault_test : public beast::unit_test::suite jvParams[jss::owner] = owner.human(); jvParams[jss::seq] = "foobar"; auto jv = env.rpc("json", "vault_info", to_string(jvParams)); - BEAST_EXPECT( - jv[jss::result][jss::error].asString() == "malformedRequest"); + BEAST_EXPECT(jv[jss::result][jss::error].asString() == "malformedRequest"); } { @@ -4963,8 +4040,7 @@ class Vault_test : public beast::unit_test::suite jvParams[jss::owner] = owner.human(); jvParams[jss::seq] = 0; auto jv = env.rpc("json", "vault_info", to_string(jvParams)); - BEAST_EXPECT( - jv[jss::result][jss::error].asString() == "malformedRequest"); + BEAST_EXPECT(jv[jss::result][jss::error].asString() == "malformedRequest"); } { @@ -4974,8 +4050,7 @@ class Vault_test : public beast::unit_test::suite jvParams[jss::owner] = owner.human(); jvParams[jss::seq] = -1; auto jv = env.rpc("json", "vault_info", to_string(jvParams)); - BEAST_EXPECT( - jv[jss::result][jss::error].asString() == "malformedRequest"); + BEAST_EXPECT(jv[jss::result][jss::error].asString() == "malformedRequest"); } { @@ -4985,8 +4060,7 @@ class Vault_test : public beast::unit_test::suite jvParams[jss::owner] = owner.human(); jvParams[jss::seq] = 1e20; auto jv = env.rpc("json", "vault_info", to_string(jvParams)); - BEAST_EXPECT( - jv[jss::result][jss::error].asString() == "malformedRequest"); + BEAST_EXPECT(jv[jss::result][jss::error].asString() == "malformedRequest"); } { @@ -4996,8 +4070,7 @@ class Vault_test : public beast::unit_test::suite jvParams[jss::owner] = owner.human(); jvParams[jss::seq] = true; auto jv = env.rpc("json", "vault_info", to_string(jvParams)); - BEAST_EXPECT( - jv[jss::result][jss::error].asString() == "malformedRequest"); + BEAST_EXPECT(jv[jss::result][jss::error].asString() == "malformedRequest"); } { @@ -5007,8 +4080,7 @@ class Vault_test : public beast::unit_test::suite jvParams[jss::owner] = "foobar"; jvParams[jss::seq] = sequence; auto jv = env.rpc("json", "vault_info", to_string(jvParams)); - BEAST_EXPECT( - jv[jss::result][jss::error].asString() == "malformedRequest"); + BEAST_EXPECT(jv[jss::result][jss::error].asString() == "malformedRequest"); } { @@ -5017,8 +4089,7 @@ class Vault_test : public beast::unit_test::suite jvParams[jss::ledger_index] = jss::validated; jvParams[jss::owner] = owner.human(); auto jv = env.rpc("json", "vault_info", to_string(jvParams)); - BEAST_EXPECT( - jv[jss::result][jss::error].asString() == "malformedRequest"); + BEAST_EXPECT(jv[jss::result][jss::error].asString() == "malformedRequest"); } { @@ -5027,8 +4098,7 @@ class Vault_test : public beast::unit_test::suite jvParams[jss::ledger_index] = jss::validated; jvParams[jss::seq] = sequence; auto jv = env.rpc("json", "vault_info", to_string(jvParams)); - BEAST_EXPECT( - jv[jss::result][jss::error].asString() == "malformedRequest"); + BEAST_EXPECT(jv[jss::result][jss::error].asString() == "malformedRequest"); } { @@ -5038,8 +4108,7 @@ class Vault_test : public beast::unit_test::suite jvParams[jss::vault_id] = strHex(keylet.key); jvParams[jss::seq] = sequence; auto jv = env.rpc("json", "vault_info", to_string(jvParams)); - BEAST_EXPECT( - jv[jss::result][jss::error].asString() == "malformedRequest"); + BEAST_EXPECT(jv[jss::result][jss::error].asString() == "malformedRequest"); } { @@ -5049,8 +4118,7 @@ class Vault_test : public beast::unit_test::suite jvParams[jss::vault_id] = strHex(keylet.key); jvParams[jss::owner] = owner.human(); auto jv = env.rpc("json", "vault_info", to_string(jvParams)); - BEAST_EXPECT( - jv[jss::result][jss::error].asString() == "malformedRequest"); + BEAST_EXPECT(jv[jss::result][jss::error].asString() == "malformedRequest"); } { @@ -5063,8 +4131,7 @@ class Vault_test : public beast::unit_test::suite jvParams[jss::seq] = sequence; jvParams[jss::owner] = owner.human(); auto jv = env.rpc("json", "vault_info", to_string(jvParams)); - BEAST_EXPECT( - jv[jss::result][jss::error].asString() == "malformedRequest"); + BEAST_EXPECT(jv[jss::result][jss::error].asString() == "malformedRequest"); } { @@ -5072,8 +4139,7 @@ class Vault_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::ledger_index] = jss::validated; auto jv = env.rpc("json", "vault_info", to_string(jvParams)); - BEAST_EXPECT( - jv[jss::result][jss::error].asString() == "malformedRequest"); + BEAST_EXPECT(jv[jss::result][jss::error].asString() == "malformedRequest"); } { @@ -5085,23 +4151,19 @@ class Vault_test : public beast::unit_test::suite { testcase("RPC vault_info command line invalid index"); Json::Value jv = env.rpc("vault_info", "0", "validated"); - BEAST_EXPECT( - jv[jss::result][jss::error].asString() == "malformedRequest"); + BEAST_EXPECT(jv[jss::result][jss::error].asString() == "malformedRequest"); } { testcase("RPC vault_info command line invalid index"); - Json::Value jv = - env.rpc("vault_info", strHex(uint256(42)), "validated"); - BEAST_EXPECT( - jv[jss::result][jss::error].asString() == "entryNotFound"); + Json::Value jv = env.rpc("vault_info", strHex(uint256(42)), "validated"); + BEAST_EXPECT(jv[jss::result][jss::error].asString() == "entryNotFound"); } { testcase("RPC vault_info command line invalid ledger"); Json::Value jv = env.rpc("vault_info", strHex(keylet.key), "0"); - BEAST_EXPECT( - jv[jss::result][jss::error].asString() == "lgrNotFound"); + BEAST_EXPECT(jv[jss::result][jss::error].asString() == "lgrNotFound"); } } @@ -5120,9 +4182,7 @@ class Vault_test : public beast::unit_test::suite PrettyAsset asset = xrpIssue(); }; - auto const xrpBalance = - [this]( - Env const& env, Account const& account) -> std::optional { + auto const xrpBalance = [this](Env const& env, Account const& account) -> std::optional { auto sle = env.le(keylet::account(account.id())); if (BEAST_EXPECT(sle != nullptr)) return sle->getFieldAmount(sfBalance).xrp().drops(); @@ -5179,24 +4239,17 @@ class Vault_test : public beast::unit_test::suite if (!BEAST_EXPECT(startBalance.has_value())) return; - tx = vault.deposit( - {.depositor = carol, - .id = keylet.key, - .amount = asset(amount)}); + tx = vault.deposit({.depositor = carol, .id = keylet.key, .amount = asset(amount)}); env(tx, delegate::as(alice)); env.close(); BEAST_EXPECT(xrpBalance(env, carol) == *startBalance - amount); - tx = vault.withdraw( - {.depositor = carol, - .id = keylet.key, - .amount = asset(amount - 1)}); + tx = vault.withdraw({.depositor = carol, .id = keylet.key, .amount = asset(amount - 1)}); env(tx, delegate::as(alice)); env.close(); BEAST_EXPECT(xrpBalance(env, carol) == *startBalance - 1); - tx = vault.withdraw( - {.depositor = carol, .id = keylet.key, .amount = asset(1)}); + tx = vault.withdraw({.depositor = carol, .id = keylet.key, .amount = asset(1)}); env(tx); env.close(); BEAST_EXPECT(xrpBalance(env, carol) == *startBalance - baseFee); @@ -5215,27 +4268,17 @@ class Vault_test : public beast::unit_test::suite if (!BEAST_EXPECT(startBalance.has_value())) return; - tx = vault.deposit( - {.depositor = carol, - .id = keylet.key, - .amount = asset(amount)}); + tx = vault.deposit({.depositor = carol, .id = keylet.key, .amount = asset(amount)}); env(tx); env.close(); - BEAST_EXPECT( - xrpBalance(env, carol) == *startBalance - amount - baseFee); + BEAST_EXPECT(xrpBalance(env, carol) == *startBalance - amount - baseFee); - tx = vault.withdraw( - {.depositor = carol, - .id = keylet.key, - .amount = asset(baseFee)}); + tx = vault.withdraw({.depositor = carol, .id = keylet.key, .amount = asset(baseFee)}); env(tx, delegate::as(alice)); env.close(); BEAST_EXPECT(xrpBalance(env, carol) == *startBalance - amount); - tx = vault.withdraw( - {.depositor = carol, - .id = keylet.key, - .amount = asset(amount - baseFee)}); + tx = vault.withdraw({.depositor = carol, .id = keylet.key, .amount = asset(amount - baseFee)}); env(tx, delegate::as(alice)); env.close(); BEAST_EXPECT(xrpBalance(env, carol) == *startBalance - baseFee); @@ -5258,29 +4301,24 @@ class Vault_test : public beast::unit_test::suite auto const sleVault = env.le(vaultKeylet); BEAST_EXPECT(sleVault != nullptr); - return std::make_pair( - sleVault->at(sfAssetsAvailable), sleVault->at(sfAssetsTotal)); + return std::make_pair(sleVault->at(sfAssetsAvailable), sleVault->at(sfAssetsTotal)); }; auto const vaultShareBalance = [&](Keylet const& vaultKeylet) { auto const sleVault = env.le(vaultKeylet); BEAST_EXPECT(sleVault != nullptr); - auto const sleIssuance = - env.le(keylet::mptIssuance(sleVault->at(sfShareMPTID))); + auto const sleIssuance = env.le(keylet::mptIssuance(sleVault->at(sfShareMPTID))); BEAST_EXPECT(sleIssuance != nullptr); return sleIssuance->at(sfOutstandingAmount); }; auto const setupVault = - [&](PrettyAsset const& asset, - Account const& owner, - Account const& depositor) -> std::pair { + [&](PrettyAsset const& asset, Account const& owner, Account const& depositor) -> std::pair { Vault vault{env}; - auto const& [tx, vaultKeylet] = - vault.create({.owner = owner, .asset = asset}); + auto const& [tx, vaultKeylet] = vault.create({.owner = owner, .asset = asset}); env(tx, ter(tesSUCCESS), THISLINE); env.close(); @@ -5289,32 +4327,24 @@ class Vault_test : public beast::unit_test::suite Asset share = vaultSle->at(sfShareMPTID); - env(vault.deposit( - {.depositor = depositor, - .id = vaultKeylet.key, - .amount = asset(100)}), + env(vault.deposit({.depositor = depositor, .id = vaultKeylet.key, .amount = asset(100)}), ter(tesSUCCESS), THISLINE); env.close(); - auto const& [availablePreDefault, totalPreDefault] = - vaultAssetBalance(vaultKeylet); + auto const& [availablePreDefault, totalPreDefault] = vaultAssetBalance(vaultKeylet); BEAST_EXPECT(availablePreDefault == totalPreDefault); BEAST_EXPECT(availablePreDefault == asset(100).value()); // attempt to clawback shares while there are assets fails env(vault.clawback( - {.issuer = owner, - .id = vaultKeylet.key, - .holder = depositor, - .amount = share(0).value()}), + {.issuer = owner, .id = vaultKeylet.key, .holder = depositor, .amount = share(0).value()}), ter(tecNO_PERMISSION), THISLINE); env.close(); auto const& sharesAvailable = vaultShareBalance(vaultKeylet); - auto const& brokerKeylet = - keylet::loanbroker(owner.id(), env.seq(owner)); + auto const& brokerKeylet = keylet::loanbroker(owner.id(), env.seq(owner)); env(set(owner, vaultKeylet.key), THISLINE); env.close(); @@ -5336,22 +4366,16 @@ class Vault_test : public beast::unit_test::suite // attempt to clawback shares while there assetsAvailable == 0 and // assetsTotal > 0 fails env(vault.clawback( - {.issuer = owner, - .id = vaultKeylet.key, - .holder = depositor, - .amount = share(0).value()}), + {.issuer = owner, .id = vaultKeylet.key, .holder = depositor, .amount = share(0).value()}), ter(tecNO_PERMISSION), THISLINE); env.close(); env.close(std::chrono::seconds{120 + 60}); - env(manage(owner, loanKeylet.key, tfLoanDefault), - ter(tesSUCCESS), - THISLINE); + env(manage(owner, loanKeylet.key, tfLoanDefault), ter(tesSUCCESS), THISLINE); - auto const& [availablePostDefault, totalPostDefault] = - vaultAssetBalance(vaultKeylet); + auto const& [availablePostDefault, totalPostDefault] = vaultAssetBalance(vaultKeylet); BEAST_EXPECT(availablePostDefault == totalPostDefault); BEAST_EXPECT(availablePostDefault == asset(0).value()); @@ -5360,141 +4384,124 @@ class Vault_test : public beast::unit_test::suite return std::make_pair(vault, vaultKeylet); }; - auto const testCase = [&](PrettyAsset const& asset, - std::string const& prefix, - Account const& owner, - Account const& depositor) { - { - testcase( - "VaultClawback (share) - " + prefix + - " owner asset clawback fails"); - auto [vault, vaultKeylet] = setupVault(asset, owner, depositor); - env(vault.clawback({ - .issuer = owner, - .id = vaultKeylet.key, - .holder = depositor, - .amount = asset(100).value(), - }), - // when asset is XRP or owner is not issuer clawback fail - // when owner is issuer precision loss occurs as vault is - // empty - asset.native() ? ter(temMALFORMED) - : asset.raw().getIssuer() != owner.id() - ? ter(tecNO_PERMISSION) - : ter(tecPRECISION_LOSS), - THISLINE); - env.close(); - } + auto const testCase = + [&](PrettyAsset const& asset, std::string const& prefix, Account const& owner, Account const& depositor) { + { + testcase("VaultClawback (share) - " + prefix + " owner asset clawback fails"); + auto [vault, vaultKeylet] = setupVault(asset, owner, depositor); + env(vault.clawback({ + .issuer = owner, + .id = vaultKeylet.key, + .holder = depositor, + .amount = asset(100).value(), + }), + // when asset is XRP or owner is not issuer clawback fail + // when owner is issuer precision loss occurs as vault is + // empty + asset.native() ? ter(temMALFORMED) + : asset.raw().getIssuer() != owner.id() ? ter(tecNO_PERMISSION) + : ter(tecPRECISION_LOSS), + THISLINE); + env.close(); + } - { - testcase( - "VaultClawback (share) - " + prefix + - " owner incomplete share clawback fails"); - auto [vault, vaultKeylet] = setupVault(asset, owner, depositor); - auto const& vaultSle = env.le(vaultKeylet); - BEAST_EXPECT(vaultSle != nullptr); - if (!vaultSle) - return; - Asset share = vaultSle->at(sfShareMPTID); - env(vault.clawback({ - .issuer = owner, - .id = vaultKeylet.key, - .holder = depositor, - .amount = share(1).value(), - }), - ter(tecLIMIT_EXCEEDED), - THISLINE); - env.close(); - } + { + testcase("VaultClawback (share) - " + prefix + " owner incomplete share clawback fails"); + auto [vault, vaultKeylet] = setupVault(asset, owner, depositor); + auto const& vaultSle = env.le(vaultKeylet); + BEAST_EXPECT(vaultSle != nullptr); + if (!vaultSle) + return; + Asset share = vaultSle->at(sfShareMPTID); + env(vault.clawback({ + .issuer = owner, + .id = vaultKeylet.key, + .holder = depositor, + .amount = share(1).value(), + }), + ter(tecLIMIT_EXCEEDED), + THISLINE); + env.close(); + } - { - testcase( - "VaultClawback (share) - " + prefix + - " owner implicit complete share clawback"); - auto [vault, vaultKeylet] = setupVault(asset, owner, depositor); - env(vault.clawback({ - .issuer = owner, - .id = vaultKeylet.key, - .holder = depositor, - }), - // when owner is issuer implicit clawback fails - asset.native() || asset.raw().getIssuer() != owner.id() - ? ter(tesSUCCESS) - : ter(tecWRONG_ASSET), - THISLINE); - env.close(); - } + { + testcase("VaultClawback (share) - " + prefix + " owner implicit complete share clawback"); + auto [vault, vaultKeylet] = setupVault(asset, owner, depositor); + env(vault.clawback({ + .issuer = owner, + .id = vaultKeylet.key, + .holder = depositor, + }), + // when owner is issuer implicit clawback fails + asset.native() || asset.raw().getIssuer() != owner.id() ? ter(tesSUCCESS) : ter(tecWRONG_ASSET), + THISLINE); + env.close(); + } - { - testcase( - "VaultClawback (share) - " + prefix + - " owner explicit complete share clawback succeeds"); - auto [vault, vaultKeylet] = setupVault(asset, owner, depositor); - auto const& vaultSle = env.le(vaultKeylet); - BEAST_EXPECT(vaultSle != nullptr); - if (!vaultSle) - return; - Asset share = vaultSle->at(sfShareMPTID); - env(vault.clawback({ - .issuer = owner, - .id = vaultKeylet.key, - .holder = depositor, - .amount = share(vaultShareBalance(vaultKeylet)).value(), - }), - ter(tesSUCCESS), - THISLINE); - env.close(); - } - { - testcase( - "VaultClawback (share) - " + prefix + - " owner can clawback own shares"); - auto [vault, vaultKeylet] = setupVault(asset, owner, owner); - auto const& vaultSle = env.le(vaultKeylet); - BEAST_EXPECT(vaultSle != nullptr); - if (!vaultSle) - return; - Asset share = vaultSle->at(sfShareMPTID); - env(vault.clawback({ - .issuer = owner, - .id = vaultKeylet.key, - .holder = owner, - .amount = share(vaultShareBalance(vaultKeylet)).value(), - }), - ter(tesSUCCESS), - THISLINE); - env.close(); - } + { + testcase("VaultClawback (share) - " + prefix + " owner explicit complete share clawback succeeds"); + auto [vault, vaultKeylet] = setupVault(asset, owner, depositor); + auto const& vaultSle = env.le(vaultKeylet); + BEAST_EXPECT(vaultSle != nullptr); + if (!vaultSle) + return; + Asset share = vaultSle->at(sfShareMPTID); + env(vault.clawback({ + .issuer = owner, + .id = vaultKeylet.key, + .holder = depositor, + .amount = share(vaultShareBalance(vaultKeylet)).value(), + }), + ter(tesSUCCESS), + THISLINE); + env.close(); + } + { + testcase("VaultClawback (share) - " + prefix + " owner can clawback own shares"); + auto [vault, vaultKeylet] = setupVault(asset, owner, owner); + auto const& vaultSle = env.le(vaultKeylet); + BEAST_EXPECT(vaultSle != nullptr); + if (!vaultSle) + return; + Asset share = vaultSle->at(sfShareMPTID); + env(vault.clawback({ + .issuer = owner, + .id = vaultKeylet.key, + .holder = owner, + .amount = share(vaultShareBalance(vaultKeylet)).value(), + }), + ter(tesSUCCESS), + THISLINE); + env.close(); + } - { - testcase( - "VaultClawback (share) - " + prefix + - " empty vault share clawback fails"); - auto [vault, vaultKeylet] = setupVault(asset, owner, owner); - auto const& vaultSle = env.le(vaultKeylet); - if (BEAST_EXPECT(vaultSle != nullptr)) - return; - Asset share = vaultSle->at(sfShareMPTID); - env(vault.clawback({ - .issuer = owner, - .id = vaultKeylet.key, - .holder = owner, - .amount = share(vaultShareBalance(vaultKeylet)).value(), - }), - ter(tesSUCCESS), - THISLINE); + { + testcase("VaultClawback (share) - " + prefix + " empty vault share clawback fails"); + auto [vault, vaultKeylet] = setupVault(asset, owner, owner); + auto const& vaultSle = env.le(vaultKeylet); + if (BEAST_EXPECT(vaultSle != nullptr)) + return; + Asset share = vaultSle->at(sfShareMPTID); + env(vault.clawback({ + .issuer = owner, + .id = vaultKeylet.key, + .holder = owner, + .amount = share(vaultShareBalance(vaultKeylet)).value(), + }), + ter(tesSUCCESS), + THISLINE); - // Now the vault is empty, clawback again fails - env(vault.clawback({ - .issuer = owner, - .id = vaultKeylet.key, - .holder = owner, - }), - ter(tecNO_PERMISSION), - THISLINE); - env.close(); - } - }; + // Now the vault is empty, clawback again fails + env(vault.clawback({ + .issuer = owner, + .id = vaultKeylet.key, + .holder = owner, + }), + ter(tecNO_PERMISSION), + THISLINE); + env.close(); + } + }; Account owner{"alice"}; Account depositor{"bob"}; @@ -5523,8 +4530,7 @@ class Vault_test : public beast::unit_test::suite // Test MPT MPTTester mptt{env, issuer, mptInitNoFund}; - mptt.create( - {.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock}); + mptt.create({.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock}); PrettyAsset MPT = mptt.issuanceID(); mptt.authorize({.account = owner}); mptt.authorize({.account = depositor}); @@ -5543,24 +4549,19 @@ class Vault_test : public beast::unit_test::suite using namespace loan; Env env(*this); - auto const setupVault = - [&](PrettyAsset const& asset, - Account const& owner, - Account const& depositor, - Account const& issuer) -> std::pair { + auto const setupVault = [&](PrettyAsset const& asset, + Account const& owner, + Account const& depositor, + Account const& issuer) -> std::pair { Vault vault{env}; - auto const& [tx, vaultKeylet] = - vault.create({.owner = owner, .asset = asset}); + auto const& [tx, vaultKeylet] = vault.create({.owner = owner, .asset = asset}); env(tx, ter(tesSUCCESS), THISLINE); env.close(); auto const& vaultSle = env.le(vaultKeylet); BEAST_EXPECT(vaultSle != nullptr); - env(vault.deposit( - {.depositor = depositor, - .id = vaultKeylet.key, - .amount = asset(100)}), + env(vault.deposit({.depositor = depositor, .id = vaultKeylet.key, .amount = asset(100)}), ter(tesSUCCESS), THISLINE); env.close(); @@ -5575,12 +4576,9 @@ class Vault_test : public beast::unit_test::suite Account const& issuer) { if (asset.native()) { - testcase( - "VaultClawback (asset) - " + prefix + - " issuer XRP clawback fails"); - auto [vault, vaultKeylet] = - setupVault(asset, owner, depositor, issuer); - // If the asset is XRP, clawback with amount fails as malfored + testcase("VaultClawback (asset) - " + prefix + " issuer XRP clawback fails"); + auto [vault, vaultKeylet] = setupVault(asset, owner, depositor, issuer); + // If the asset is XRP, clawback with amount fails as malformed // when asset is specified. env(vault.clawback({ .issuer = issuer, @@ -5602,11 +4600,8 @@ class Vault_test : public beast::unit_test::suite } { - testcase( - "VaultClawback (asset) - " + prefix + - " clawback for different asset fails"); - auto [vault, vaultKeylet] = - setupVault(asset, owner, depositor, issuer); + testcase("VaultClawback (asset) - " + prefix + " clawback for different asset fails"); + auto [vault, vaultKeylet] = setupVault(asset, owner, depositor, issuer); Account issuer2{"issuer2"}; PrettyAsset asset2 = issuer2["FOO"]; @@ -5621,11 +4616,8 @@ class Vault_test : public beast::unit_test::suite } { - testcase( - "VaultClawback (asset) - " + prefix + - " ambiguous owner/issuer asset clawback fails"); - auto [vault, vaultKeylet] = - setupVault(asset, issuer, depositor, issuer); + testcase("VaultClawback (asset) - " + prefix + " ambiguous owner/issuer asset clawback fails"); + auto [vault, vaultKeylet] = setupVault(asset, issuer, depositor, issuer); env(vault.clawback({ .issuer = issuer, .id = vaultKeylet.key, @@ -5636,11 +4628,8 @@ class Vault_test : public beast::unit_test::suite } { - testcase( - "VaultClawback (asset) - " + prefix + - " non-issuer asset clawback fails"); - auto [vault, vaultKeylet] = - setupVault(asset, owner, depositor, issuer); + testcase("VaultClawback (asset) - " + prefix + " non-issuer asset clawback fails"); + auto [vault, vaultKeylet] = setupVault(asset, owner, depositor, issuer); env(vault.clawback({ .issuer = owner, @@ -5661,11 +4650,8 @@ class Vault_test : public beast::unit_test::suite } { - testcase( - "VaultClawback (asset) - " + prefix + - " issuer clawback from self fails"); - auto [vault, vaultKeylet] = - setupVault(asset, owner, issuer, issuer); + testcase("VaultClawback (asset) - " + prefix + " issuer clawback from self fails"); + auto [vault, vaultKeylet] = setupVault(asset, owner, issuer, issuer); env(vault.clawback({ .issuer = issuer, .id = vaultKeylet.key, @@ -5676,11 +4662,8 @@ class Vault_test : public beast::unit_test::suite } { - testcase( - "VaultClawback (asset) - " + prefix + - " issuer share clawback fails"); - auto [vault, vaultKeylet] = - setupVault(asset, owner, depositor, issuer); + testcase("VaultClawback (asset) - " + prefix + " issuer share clawback fails"); + auto [vault, vaultKeylet] = setupVault(asset, owner, depositor, issuer); auto const& vaultSle = env.le(vaultKeylet); BEAST_EXPECT(vaultSle != nullptr); if (!vaultSle) @@ -5698,11 +4681,8 @@ class Vault_test : public beast::unit_test::suite } { - testcase( - "VaultClawback (asset) - " + prefix + - " partial issuer asset clawback succeeds"); - auto [vault, vaultKeylet] = - setupVault(asset, owner, depositor, issuer); + testcase("VaultClawback (asset) - " + prefix + " partial issuer asset clawback succeeds"); + auto [vault, vaultKeylet] = setupVault(asset, owner, depositor, issuer); env(vault.clawback({ .issuer = issuer, @@ -5715,11 +4695,8 @@ class Vault_test : public beast::unit_test::suite } { - testcase( - "VaultClawback (asset) - " + prefix + - " full issuer asset clawback succeeds"); - auto [vault, vaultKeylet] = - setupVault(asset, owner, depositor, issuer); + testcase("VaultClawback (asset) - " + prefix + " full issuer asset clawback succeeds"); + auto [vault, vaultKeylet] = setupVault(asset, owner, depositor, issuer); env(vault.clawback({ .issuer = issuer, @@ -5732,11 +4709,8 @@ class Vault_test : public beast::unit_test::suite } { - testcase( - "VaultClawback (asset) - " + prefix + - " implicit full issuer asset clawback succeeds"); - auto [vault, vaultKeylet] = - setupVault(asset, owner, depositor, issuer); + testcase("VaultClawback (asset) - " + prefix + " implicit full issuer asset clawback succeeds"); + auto [vault, vaultKeylet] = setupVault(asset, owner, depositor, issuer); env(vault.clawback({ .issuer = issuer, @@ -5772,8 +4746,7 @@ class Vault_test : public beast::unit_test::suite // Test MPT MPTTester mptt{env, issuer, mptInitNoFund}; - mptt.create( - {.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock}); + mptt.create({.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock}); PrettyAsset MPT = mptt.issuanceID(); mptt.authorize({.account = owner}); mptt.authorize({.account = depositor}); @@ -5782,6 +4755,241 @@ class Vault_test : public beast::unit_test::suite testCase(MPT, "MPT", owner, depositor, issuer); } + void + testAssetsMaximum() + { + testcase("Assets Maximum"); + + using namespace test::jtx; + + Env env{*this, testable_amendments() | featureSingleAssetVault}; + Account const owner{"owner"}; + Account const issuer{"issuer"}; + + Vault vault{env}; + env.fund(XRP(1'000'000), issuer, owner); + env.close(); + + auto const maxInt64 = std::to_string(std::numeric_limits::max()); + BEAST_EXPECT(maxInt64 == "9223372036854775807"); + + // Naming things is hard + auto const maxInt64Plus1 = + std::to_string(static_cast(std::numeric_limits::max()) + 1); + BEAST_EXPECT(maxInt64Plus1 == "9223372036854775808"); + + auto const initialXRP = to_string(INITIAL_XRP); + BEAST_EXPECT(initialXRP == "100000000000000000"); + + auto const initialXRPPlus1 = to_string(INITIAL_XRP + 1); + BEAST_EXPECT(initialXRPPlus1 == "100000000000000001"); + + { + testcase("Assets Maximum: XRP"); + + PrettyAsset const xrpAsset = xrpIssue(); + + auto [tx, keylet] = vault.create({.owner = owner, .asset = xrpAsset}); + tx[sfData] = "4D65746144617461"; + + tx[sfAssetsMaximum] = maxInt64; + env(tx, ter(tefEXCEPTION), THISLINE); + env.close(); + + tx[sfAssetsMaximum] = initialXRPPlus1; + env(tx, ter(tefEXCEPTION), THISLINE); + env.close(); + + tx[sfAssetsMaximum] = initialXRP; + env(tx, THISLINE); + env.close(); + + tx[sfAssetsMaximum] = maxInt64Plus1; + env(tx, ter(tefEXCEPTION), THISLINE); + env.close(); + + // This value will be rounded + auto const insertAt = maxInt64Plus1.size() - 3; + auto const decimalTest = + maxInt64Plus1.substr(0, insertAt) + "." + maxInt64Plus1.substr(insertAt); // (max int64+1) / 1000 + BEAST_EXPECT(decimalTest == "9223372036854775.808"); + tx[sfAssetsMaximum] = decimalTest; + auto const newKeylet = keylet::vault(owner.id(), env.seq(owner)); + env(tx, THISLINE); + env.close(); + + auto const vaultSle = env.le(newKeylet); + if (!BEAST_EXPECT(vaultSle)) + return; + + BEAST_EXPECT(vaultSle->at(sfAssetsMaximum) == 9223372036854776); + } + + { + testcase("Assets Maximum: MPT"); + + PrettyAsset const mptAsset = [&]() { + MPTTester mptt{env, issuer, mptInitNoFund}; + mptt.create({.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock}); + env.close(); + PrettyAsset const mptAsset = mptt["MPT"]; + mptt.authorize({.account = owner}); + env.close(); + return mptAsset; + }(); + + env(pay(issuer, owner, mptAsset(100'000)), THISLINE); + env.close(); + + auto [tx, keylet] = vault.create({.owner = owner, .asset = mptAsset}); + tx[sfData] = "4D65746144617461"; + + tx[sfAssetsMaximum] = maxInt64; + env(tx, THISLINE); + env.close(); + + tx[sfAssetsMaximum] = initialXRPPlus1; + env(tx, THISLINE); + env.close(); + + tx[sfAssetsMaximum] = initialXRP; + env(tx, THISLINE); + env.close(); + + tx[sfAssetsMaximum] = maxInt64Plus1; + env(tx, ter(tefEXCEPTION), THISLINE); + env.close(); + + // This value will be rounded + auto const insertAt = maxInt64Plus1.size() - 1; + auto const decimalTest = + maxInt64Plus1.substr(0, insertAt) + "." + maxInt64Plus1.substr(insertAt); // (max int64+1) / 10 + BEAST_EXPECT(decimalTest == "922337203685477580.8"); + tx[sfAssetsMaximum] = decimalTest; + auto const newKeylet = keylet::vault(owner.id(), env.seq(owner)); + env(tx, THISLINE); + env.close(); + + auto const vaultSle = env.le(newKeylet); + if (!BEAST_EXPECT(vaultSle)) + return; + + BEAST_EXPECT(vaultSle->at(sfAssetsMaximum) == 922337203685477581); + } + + { + testcase("Assets Maximum: IOU"); + + // Almost anything goes with IOUs + PrettyAsset iouAsset = issuer["IOU"]; + env.trust(iouAsset(1000), owner); + env(pay(issuer, owner, iouAsset(200))); + env.close(); + + auto [tx, keylet] = vault.create({.owner = owner, .asset = iouAsset}); + tx[sfData] = "4D65746144617461"; + + tx[sfAssetsMaximum] = maxInt64; + env(tx, THISLINE); + env.close(); + + tx[sfAssetsMaximum] = initialXRPPlus1; + env(tx, THISLINE); + env.close(); + + tx[sfAssetsMaximum] = initialXRP; + env(tx, THISLINE); + env.close(); + + tx[sfAssetsMaximum] = maxInt64Plus1; + env(tx, THISLINE); + env.close(); + + tx[sfAssetsMaximum] = "1000000000000000e80"; + env.close(); + + tx[sfAssetsMaximum] = "1000000000000000e-96"; + env.close(); + + // These values will be rounded to 15 significant digits + { + auto const insertAt = maxInt64Plus1.size() - 1; + auto const decimalTest = + maxInt64Plus1.substr(0, insertAt) + "." + maxInt64Plus1.substr(insertAt); // (max int64+1) / 10 + BEAST_EXPECT(decimalTest == "922337203685477580.8"); + tx[sfAssetsMaximum] = decimalTest; + auto const newKeylet = keylet::vault(owner.id(), env.seq(owner)); + env(tx, THISLINE); + env.close(); + + auto const vaultSle = env.le(newKeylet); + if (!BEAST_EXPECT(vaultSle)) + return; + + BEAST_EXPECT((vaultSle->at(sfAssetsMaximum) == Number{9223372036854776, 2, Number::normalized{}})); + } + { + tx[sfAssetsMaximum] = "9223372036854775807e40"; // max int64 * 10^40 + auto const newKeylet = keylet::vault(owner.id(), env.seq(owner)); + env(tx, THISLINE); + env.close(); + + auto const vaultSle = env.le(newKeylet); + if (!BEAST_EXPECT(vaultSle)) + return; + + BEAST_EXPECT((vaultSle->at(sfAssetsMaximum) == Number{9223372036854776, 43, Number::normalized{}})); + } + { + tx[sfAssetsMaximum] = "9223372036854775807e-40"; // max int64 * 10^-40 + auto const newKeylet = keylet::vault(owner.id(), env.seq(owner)); + env(tx, THISLINE); + env.close(); + + auto const vaultSle = env.le(newKeylet); + if (!BEAST_EXPECT(vaultSle)) + return; + + BEAST_EXPECT((vaultSle->at(sfAssetsMaximum) == Number{9223372036854776, -37, Number::normalized{}})); + } + { + tx[sfAssetsMaximum] = "9223372036854775807e-100"; // max int64 * 10^-100 + auto const newKeylet = keylet::vault(owner.id(), env.seq(owner)); + env(tx, THISLINE); + env.close(); + + // Field 'AssetsMaximum' may not be explicitly set to default. + auto const vaultSle = env.le(newKeylet); + if (!BEAST_EXPECT(vaultSle)) + return; + + BEAST_EXPECT(vaultSle->at(sfAssetsMaximum) == numZero); + } + + // What _can't_ IOUs do? + // 1. Exceed maximum exponent / offset + tx[sfAssetsMaximum] = "1000000000000000e81"; + env(tx, ter(tefEXCEPTION), THISLINE); + env.close(); + + // 2. Mantissa larger than uint64 max + try + { + tx[sfAssetsMaximum] = "18446744073709551617e5"; // uint64 max + 1 + env(tx, THISLINE); + BEAST_EXPECT(false); + } + catch (parse_error const& e) + { + using namespace std::string_literals; + BEAST_EXPECT( + e.what() == + "invalidParamsField 'tx_json.AssetsMaximum' has invalid " + "data."s); + } + } + } + public: void run() override @@ -5802,6 +5010,7 @@ public: testDelegate(); testVaultClawbackBurnShares(); testVaultClawbackAssets(); + testAssetsMaximum(); } }; diff --git a/src/test/app/XChain_test.cpp b/src/test/app/XChain_test.cpp index 3b09845723..2921e10ae4 100644 --- a/src/test/app/XChain_test.cpp +++ b/src/test/app/XChain_test.cpp @@ -132,8 +132,7 @@ struct SEnv { STXChainBridge b(jvb); - auto tryGet = - [&](STXChainBridge::ChainType ct) -> std::shared_ptr { + auto tryGet = [&](STXChainBridge::ChainType ct) -> std::shared_ptr { if (auto r = env_.le(keylet::bridge(b, ct))) { if ((*r)[sfXChainBridge] == b) @@ -167,8 +166,7 @@ struct SEnv std::shared_ptr caClaimID(Json::Value const& jvb, std::uint64_t seq) { - return env_.le( - keylet::xChainCreateAccountClaimID(STXChainBridge(jvb), seq)); + return env_.le(keylet::xChainCreateAccountClaimID(STXChainBridge(jvb), seq)); } }; @@ -195,15 +193,7 @@ struct XEnv : public jtx::XChainBridgeObjects, public SEnv } else { - this->fund( - xrp_funds, - scDoor, - scAlice, - scBob, - scCarol, - scGw, - scAttester, - scReward); + this->fund(xrp_funds, scDoor, scAlice, scBob, scCarol, scGw, scAttester, scReward); for (auto& ra : payees) this->fund(xrp_funds, ra); @@ -280,14 +270,7 @@ struct BalanceTransfer jtx::Account const& payer, std::vector const& payees, bool withClaim) - : BalanceTransfer( - env, - from_acct, - to_acct, - payer, - &payees[0], - payees.size(), - withClaim) + : BalanceTransfer(env, from_acct, to_acct, payer, &payees[0], payees.size(), withClaim) { } @@ -295,28 +278,20 @@ struct BalanceTransfer payees_received(STAmount const& reward) const { return std::all_of( - reward_accounts.begin(), - reward_accounts.end(), - [&](balance const& b) { return b.diff() == reward; }); + reward_accounts.begin(), reward_accounts.end(), [&](balance const& b) { return b.diff() == reward; }); } bool check_most_balances(STAmount const& amt, STAmount const& reward) { - return from_.diff() == -amt && to_.diff() == amt && - payees_received(reward); + return from_.diff() == -amt && to_.diff() == amt && payees_received(reward); } bool - has_happened( - STAmount const& amt, - STAmount const& reward, - bool check_payer = true) + has_happened(STAmount const& amt, STAmount const& reward, bool check_payer = true) { - auto reward_cost = - multiply(reward, STAmount(reward_accounts.size()), reward.issue()); - return check_most_balances(amt, reward) && - (!check_payer || payer_.diff() == -(reward_cost + txFees_)); + auto reward_cost = multiply(reward, STAmount(reward_accounts.size()), reward.issue()); + return check_most_balances(amt, reward) && (!check_payer || payer_.diff() == -(reward_cost + txFees_)); } bool @@ -350,18 +325,13 @@ struct BridgeDef return {}; return minAccountCreate; }(); - mcEnv.tx(bridge_create(doorA, jvb, reward, optAccountCreate)) - .tx(jtx::signers(doorA, quorum, signers)) - .close(); + mcEnv.tx(bridge_create(doorA, jvb, reward, optAccountCreate)).tx(jtx::signers(doorA, quorum, signers)).close(); - scEnv.tx(bridge_create(doorB, jvb, reward, optAccountCreate)) - .tx(jtx::signers(doorB, quorum, signers)) - .close(); + scEnv.tx(bridge_create(doorB, jvb, reward, optAccountCreate)).tx(jtx::signers(doorB, quorum, signers)).close(); } }; -struct XChain_test : public beast::unit_test::suite, - public jtx::XChainBridgeObjects +struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObjects { XRPAmount reserve(std::uint32_t count) @@ -418,44 +388,31 @@ struct XChain_test : public beast::unit_test::suite, XEnv(*this).tx(create_bridge(mcDoor)).close(); // Bridge not owned by one of the door account. - XEnv(*this).tx( - create_bridge(mcBob), ter(temXCHAIN_BRIDGE_NONDOOR_OWNER)); + XEnv(*this).tx(create_bridge(mcBob), ter(temXCHAIN_BRIDGE_NONDOOR_OWNER)); // Create twice on the same account - XEnv(*this) - .tx(create_bridge(mcDoor)) - .close() - .tx(create_bridge(mcDoor), ter(tecDUPLICATE)); + XEnv(*this).tx(create_bridge(mcDoor)).close().tx(create_bridge(mcDoor), ter(tecDUPLICATE)); // Create USD bridge Alice -> Bob ... should succeed - XEnv(*this).tx( - create_bridge( - mcAlice, bridge(mcAlice, mcGw["USD"], mcBob, mcBob["USD"])), - ter(tesSUCCESS)); + XEnv(*this).tx(create_bridge(mcAlice, bridge(mcAlice, mcGw["USD"], mcBob, mcBob["USD"])), ter(tesSUCCESS)); // Create USD bridge, Alice is both the locking door and locking issue, // ... should fail. XEnv(*this).tx( - create_bridge( - mcAlice, bridge(mcAlice, mcAlice["USD"], mcBob, mcBob["USD"])), + create_bridge(mcAlice, bridge(mcAlice, mcAlice["USD"], mcBob, mcBob["USD"])), ter(temXCHAIN_BRIDGE_BAD_ISSUES)); // Bridge where the two door accounts are equal. XEnv(*this).tx( - create_bridge( - mcBob, bridge(mcBob, mcGw["USD"], mcBob, mcGw["USD"])), - ter(temXCHAIN_EQUAL_DOOR_ACCOUNTS)); + create_bridge(mcBob, bridge(mcBob, mcGw["USD"], mcBob, mcGw["USD"])), ter(temXCHAIN_EQUAL_DOOR_ACCOUNTS)); // Both door accounts are on the same chain. This is not allowed. // Although it doesn't violate any invariants, it's not a useful thing // to do and it complicates the "add claim" transactions. XEnv(*this) - .tx(create_bridge( - mcAlice, bridge(mcAlice, mcGw["USD"], mcBob, mcBob["USD"]))) + .tx(create_bridge(mcAlice, bridge(mcAlice, mcGw["USD"], mcBob, mcBob["USD"]))) .close() - .tx(create_bridge( - mcBob, bridge(mcAlice, mcGw["USD"], mcBob, mcBob["USD"])), - ter(tecDUPLICATE)) + .tx(create_bridge(mcBob, bridge(mcAlice, mcGw["USD"], mcBob, mcBob["USD"])), ter(tecDUPLICATE)) .close(); // Create a bridge on an account with exactly enough balance to @@ -473,36 +430,27 @@ struct XChain_test : public beast::unit_test::suite, .tx(create_bridge(mcuDoor, jvub), ter(tecINSUFFICIENT_RESERVE)); // Reward amount is non-xrp - XEnv(*this).tx( - create_bridge(mcDoor, jvb, mcUSD(1)), - ter(temXCHAIN_BRIDGE_BAD_REWARD_AMOUNT)); + XEnv(*this).tx(create_bridge(mcDoor, jvb, mcUSD(1)), ter(temXCHAIN_BRIDGE_BAD_REWARD_AMOUNT)); // Reward amount is XRP and negative - XEnv(*this).tx( - create_bridge(mcDoor, jvb, XRP(-1)), - ter(temXCHAIN_BRIDGE_BAD_REWARD_AMOUNT)); + XEnv(*this).tx(create_bridge(mcDoor, jvb, XRP(-1)), ter(temXCHAIN_BRIDGE_BAD_REWARD_AMOUNT)); // Reward amount is 1 xrp => should succeed XEnv(*this).tx(create_bridge(mcDoor, jvb, XRP(1)), ter(tesSUCCESS)); // Min create amount is 1 xrp, mincreate is 1 xrp => should succeed - XEnv(*this).tx( - create_bridge(mcDoor, jvb, XRP(1), XRP(1)), ter(tesSUCCESS)); + XEnv(*this).tx(create_bridge(mcDoor, jvb, XRP(1), XRP(1)), ter(tesSUCCESS)); // Min create amount is non-xrp XEnv(*this).tx( - create_bridge(mcDoor, jvb, XRP(1), mcUSD(100)), - ter(temXCHAIN_BRIDGE_BAD_MIN_ACCOUNT_CREATE_AMOUNT)); + create_bridge(mcDoor, jvb, XRP(1), mcUSD(100)), ter(temXCHAIN_BRIDGE_BAD_MIN_ACCOUNT_CREATE_AMOUNT)); // Min create amount is zero (should fail, currently succeeds) - XEnv(*this).tx( - create_bridge(mcDoor, jvb, XRP(1), XRP(0)), - ter(temXCHAIN_BRIDGE_BAD_MIN_ACCOUNT_CREATE_AMOUNT)); + XEnv(*this).tx(create_bridge(mcDoor, jvb, XRP(1), XRP(0)), ter(temXCHAIN_BRIDGE_BAD_MIN_ACCOUNT_CREATE_AMOUNT)); // Min create amount is negative XEnv(*this).tx( - create_bridge(mcDoor, jvb, XRP(1), XRP(-1)), - ter(temXCHAIN_BRIDGE_BAD_MIN_ACCOUNT_CREATE_AMOUNT)); + create_bridge(mcDoor, jvb, XRP(1), XRP(-1)), ter(temXCHAIN_BRIDGE_BAD_MIN_ACCOUNT_CREATE_AMOUNT)); // coverage test: BridgeCreate::preflight() - create bridge when feature // disabled. @@ -513,20 +461,13 @@ struct XChain_test : public beast::unit_test::suite, // coverage test: BridgeCreate::preclaim() returns tecNO_ISSUER. XEnv(*this).tx( - create_bridge( - mcAlice, bridge(mcAlice, mcuAlice["USD"], mcBob, mcBob["USD"])), - ter(tecNO_ISSUER)); + create_bridge(mcAlice, bridge(mcAlice, mcuAlice["USD"], mcBob, mcBob["USD"])), ter(tecNO_ISSUER)); // coverage test: create_bridge transaction with incorrect flag - XEnv(*this).tx( - create_bridge(mcAlice, jvb), - txflags(tfFillOrKill), - ter(temINVALID_FLAG)); + XEnv(*this).tx(create_bridge(mcAlice, jvb), txflags(tfFillOrKill), ter(temINVALID_FLAG)); // coverage test: create_bridge transaction with xchain feature disabled - XEnv(*this) - .disableFeature(featureXChainBridge) - .tx(create_bridge(mcAlice, jvb), ter(temDISABLED)); + XEnv(*this).disableFeature(featureXChainBridge).tx(create_bridge(mcAlice, jvb), ter(temDISABLED)); } void @@ -611,39 +552,28 @@ struct XChain_test : public beast::unit_test::suite, // Add the exact same bridge to two different accounts (one locking // account and one issuing) env.tx(create_bridge(a3, bridge(a3, GUSD, a4, a4["USD"]))).close(); - env.tx(create_bridge(a4, bridge(a3, GUSD, a4, a4["USD"])), - ter(tecDUPLICATE)) - .close(); + env.tx(create_bridge(a4, bridge(a3, GUSD, a4, a4["USD"])), ter(tecDUPLICATE)).close(); // Add the exact same bridge to two different accounts (one issuing // account and one locking - opposite order from the test above) env.tx(create_bridge(a5, bridge(a6, GUSD, a5, a5["USD"]))).close(); - env.tx(create_bridge(a6, bridge(a6, GUSD, a5, a5["USD"])), - ter(tecDUPLICATE)) - .close(); + env.tx(create_bridge(a6, bridge(a6, GUSD, a5, a5["USD"])), ter(tecDUPLICATE)).close(); // Test case 1 ~ 5, create bridges auto const goodBridge1 = bridge(A, GUSD, B, BUSD); auto const goodBridge2 = bridge(A, BUSD, C, CUSD); env.tx(create_bridge(B, goodBridge1)).close(); // Issuing asset is the same, this is a duplicate - env.tx(create_bridge(B, bridge(A, GEUR, B, BUSD)), ter(tecDUPLICATE)) - .close(); + env.tx(create_bridge(B, bridge(A, GEUR, B, BUSD)), ter(tecDUPLICATE)).close(); env.tx(create_bridge(A, goodBridge2), ter(tesSUCCESS)).close(); // Locking asset is the same - this is a duplicate - env.tx(create_bridge(A, bridge(A, BUSD, B, BEUR)), ter(tecDUPLICATE)) - .close(); + env.tx(create_bridge(A, bridge(A, BUSD, B, BEUR)), ter(tecDUPLICATE)).close(); // Locking asset is USD - this is a duplicate even tho it has a // different issuer - env.tx(create_bridge(A, bridge(A, CUSD, B, BEUR)), ter(tecDUPLICATE)) - .close(); + env.tx(create_bridge(A, bridge(A, CUSD, B, BEUR)), ter(tecDUPLICATE)).close(); // Test case 6 and 7, commits - env.tx(trust(C, BUSD(1000))) - .tx(trust(A, BUSD(1000))) - .close() - .tx(pay(B, C, BUSD(1000))) - .close(); + env.tx(trust(C, BUSD(1000))).tx(trust(A, BUSD(1000))).close().tx(pay(B, C, BUSD(1000))).close(); auto const aBalanceStart = env.balance(A, BUSD); auto const cBalanceStart = env.balance(C, BUSD); env.tx(xchain_commit(C, goodBridge1, 1, BUSD(50))).close(); @@ -853,14 +783,10 @@ struct XChain_test : public beast::unit_test::suite, auto const& expected = expected_result[test_result.size()]; - mcEnv.tx( - create_bridge(a, bridge(a, ia, b, ib)), - ter(TER::fromInt(expected.first))); + mcEnv.tx(create_bridge(a, bridge(a, ia, b, ib)), ter(TER::fromInt(expected.first))); TER mcTER = mcEnv.env_.ter(); - scEnv.tx( - create_bridge(b, bridge(a, ia, b, ib)), - ter(TER::fromInt(expected.second))); + scEnv.tx(create_bridge(b, bridge(a, ia, b, ib)), ter(TER::fromInt(expected.second))); TER scTER = scEnv.env_.ter(); bool pass = mcTER == tesSUCCESS && scTER == tesSUCCESS; @@ -869,8 +795,7 @@ struct XChain_test : public beast::unit_test::suite, }; auto apply_ics = [&](auto const& lc, auto const& ics) { - std::apply( - [&](auto const&... ic) { (testcase(lc, ic), ...); }, ics); + std::apply([&](auto const&... ic) { (testcase(lc, ic), ...); }, ics); }; std::apply([&](auto const&... lc) { (apply_ics(lc, ics), ...); }, lcs); @@ -883,8 +808,7 @@ struct XChain_test : public beast::unit_test::suite, std::cout << "Markdown output for matrix test: " << fname << "\n"; auto print_res = [](auto tup) -> std::string { - std::string status = std::string(transToken(std::get<0>(tup))) + - " / " + transToken(std::get<1>(tup)); + std::string status = std::string(transToken(std::get<0>(tup))) + " / " + transToken(std::get<1>(tup)); if (std::get<2>(tup)) return status; @@ -902,19 +826,11 @@ struct XChain_test : public beast::unit_test::suite, // first two header lines res += "| `issuing ->` | "; - std::apply( - [&](auto const&... ic) { - ((res += ic.first, res += " | "), ...); - }, - ics); + std::apply([&](auto const&... ic) { ((res += ic.first, res += " | "), ...); }, ics); res += "\n"; res += "| :--- | "; - std::apply( - [&](auto const&... ic) { - (((void)ic.first, res += ":---: | "), ...); - }, - ics); + std::apply([&](auto const&... ic) { (((void)ic.first, res += ":---: | "), ...); }, ics); res += "\n"; auto output = [&](auto const& lc, auto const& ic) { @@ -927,13 +843,11 @@ struct XChain_test : public beast::unit_test::suite, res += "| "; res += lc.first; res += " | "; - std::apply( - [&](auto const&... ic) { (output(lc, ic), ...); }, ics); + std::apply([&](auto const&... ic) { (output(lc, ic), ...); }, ics); res += "\n"; }; - std::apply( - [&](auto const&... lc) { (output_ics(lc, ics), ...); }, lcs); + std::apply([&](auto const&... lc) { (output_ics(lc, ics), ...); }, lcs); return res; }; @@ -946,8 +860,8 @@ struct XChain_test : public beast::unit_test::suite, std::ofstream ofs(ter_fname); for (auto& t : test_result) { - ofs << "{ " << std::string(transToken(std::get<0>(t))) << ", " - << std::string(transToken(std::get<1>(t))) << "}\n,"; + ofs << "{ " << std::string(transToken(std::get<0>(t))) << ", " << std::string(transToken(std::get<1>(t))) + << "}\n,"; } #endif } @@ -960,11 +874,7 @@ struct XChain_test : public beast::unit_test::suite, // Changing a non-existent bridge should fail XEnv(*this).tx( - bridge_modify( - mcAlice, - bridge(mcAlice, mcGw["USD"], mcBob, mcBob["USD"]), - XRP(2), - std::nullopt), + bridge_modify(mcAlice, bridge(mcAlice, mcGw["USD"], mcBob, mcBob["USD"]), XRP(2), std::nullopt), ter(tecNO_ENTRY)); // must change something @@ -980,29 +890,21 @@ struct XChain_test : public beast::unit_test::suite, .tx(bridge_modify(mcDoor, jvb, {}, {}), ter(temMALFORMED)); // Reward amount is non-xrp - XEnv(*this).tx( - bridge_modify(mcDoor, jvb, mcUSD(2), XRP(10)), - ter(temXCHAIN_BRIDGE_BAD_REWARD_AMOUNT)); + XEnv(*this).tx(bridge_modify(mcDoor, jvb, mcUSD(2), XRP(10)), ter(temXCHAIN_BRIDGE_BAD_REWARD_AMOUNT)); // Reward amount is XRP and negative - XEnv(*this).tx( - bridge_modify(mcDoor, jvb, XRP(-2), XRP(10)), - ter(temXCHAIN_BRIDGE_BAD_REWARD_AMOUNT)); + XEnv(*this).tx(bridge_modify(mcDoor, jvb, XRP(-2), XRP(10)), ter(temXCHAIN_BRIDGE_BAD_REWARD_AMOUNT)); // Min create amount is non-xrp XEnv(*this).tx( - bridge_modify(mcDoor, jvb, XRP(2), mcUSD(10)), - ter(temXCHAIN_BRIDGE_BAD_MIN_ACCOUNT_CREATE_AMOUNT)); + bridge_modify(mcDoor, jvb, XRP(2), mcUSD(10)), ter(temXCHAIN_BRIDGE_BAD_MIN_ACCOUNT_CREATE_AMOUNT)); // Min create amount is zero - XEnv(*this).tx( - bridge_modify(mcDoor, jvb, XRP(2), XRP(0)), - ter(temXCHAIN_BRIDGE_BAD_MIN_ACCOUNT_CREATE_AMOUNT)); + XEnv(*this).tx(bridge_modify(mcDoor, jvb, XRP(2), XRP(0)), ter(temXCHAIN_BRIDGE_BAD_MIN_ACCOUNT_CREATE_AMOUNT)); // Min create amount is negative XEnv(*this).tx( - bridge_modify(mcDoor, jvb, XRP(2), XRP(-10)), - ter(temXCHAIN_BRIDGE_BAD_MIN_ACCOUNT_CREATE_AMOUNT)); + bridge_modify(mcDoor, jvb, XRP(2), XRP(-10)), ter(temXCHAIN_BRIDGE_BAD_MIN_ACCOUNT_CREATE_AMOUNT)); // First check the regular claim process (without bridge_modify) for (auto withClaim : {false, true}) @@ -1024,25 +926,9 @@ struct XChain_test : public beast::unit_test::suite, mcEnv.tx(xchain_commit(mcAlice, jvb, claimID, amt, dst)).close(); BalanceTransfer transfer( - scEnv, - Account::master, - scBob, - scAlice, - &payees[0], - UT_XCHAIN_DEFAULT_QUORUM, - withClaim); + scEnv, Account::master, scBob, scAlice, &payees[0], UT_XCHAIN_DEFAULT_QUORUM, withClaim); - scEnv - .multiTx(claim_attestations( - scAttester, - jvb, - mcAlice, - amt, - payees, - true, - claimID, - dst, - signers)) + scEnv.multiTx(claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers)) .close(); if (withClaim) @@ -1050,8 +936,7 @@ struct XChain_test : public beast::unit_test::suite, BEAST_EXPECT(transfer.has_not_happened()); // need to submit a claim transactions - scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob)) - .close(); + scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob)).close(); } BEAST_EXPECT(transfer.has_happened(amt, split_reward_quorum)); @@ -1080,29 +965,12 @@ struct XChain_test : public beast::unit_test::suite, // Now modify the reward on the bridge mcEnv.tx(bridge_modify(mcDoor, jvb, XRP(2), XRP(10))).close(); - scEnv.tx(bridge_modify(Account::master, jvb, XRP(2), XRP(10))) - .close(); + scEnv.tx(bridge_modify(Account::master, jvb, XRP(2), XRP(10))).close(); BalanceTransfer transfer( - scEnv, - Account::master, - scBob, - scAlice, - &payees[0], - UT_XCHAIN_DEFAULT_QUORUM, - withClaim); + scEnv, Account::master, scBob, scAlice, &payees[0], UT_XCHAIN_DEFAULT_QUORUM, withClaim); - scEnv - .multiTx(claim_attestations( - scAttester, - jvb, - mcAlice, - amt, - payees, - true, - claimID, - dst, - signers)) + scEnv.multiTx(claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers)) .close(); if (withClaim) @@ -1110,8 +978,7 @@ struct XChain_test : public beast::unit_test::suite, BEAST_EXPECT(transfer.has_not_happened()); // need to submit a claim transactions - scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob)) - .close(); + scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob)).close(); } // make sure the reward accounts indeed received the original @@ -1143,40 +1010,21 @@ struct XChain_test : public beast::unit_test::suite, // change signers - claim should not be processed is the batch // is signed by original signers - scEnv.tx(jtx::signers(Account::master, quorum, alt_signers)) - .close(); + scEnv.tx(jtx::signers(Account::master, quorum, alt_signers)).close(); BalanceTransfer transfer( - scEnv, - Account::master, - scBob, - scAlice, - &payees[0], - UT_XCHAIN_DEFAULT_QUORUM, - withClaim); + scEnv, Account::master, scBob, scAlice, &payees[0], UT_XCHAIN_DEFAULT_QUORUM, withClaim); // submit claim using outdated signers - should fail scEnv .multiTx( - claim_attestations( - scAttester, - jvb, - mcAlice, - amt, - payees, - true, - claimID, - dst, - signers), + claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers), ter(tecNO_PERMISSION)) .close(); if (withClaim) { // need to submit a claim transactions - scEnv - .tx(xchain_claim(scAlice, jvb, claimID, amt, scBob), - ter(tecXCHAIN_CLAIM_NO_QUORUM)) - .close(); + scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob), ter(tecXCHAIN_CLAIM_NO_QUORUM)).close(); } // make sure transfer has not happened as we sent attestations @@ -1184,40 +1032,26 @@ struct XChain_test : public beast::unit_test::suite, BEAST_EXPECT(transfer.has_not_happened()); // submit claim using current signers - should succeed - scEnv - .multiTx(claim_attestations( - scAttester, - jvb, - mcAlice, - amt, - payees, - true, - claimID, - dst, - alt_signers)) + scEnv.multiTx(claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, alt_signers)) .close(); if (withClaim) { BEAST_EXPECT(transfer.has_not_happened()); // need to submit a claim transactions - scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob)) - .close(); + scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob)).close(); } // make sure the transfer went through as we sent attestations // using new signers - BEAST_EXPECT( - transfer.has_happened(amt, split_reward_quorum, false)); + BEAST_EXPECT(transfer.has_happened(amt, split_reward_quorum, false)); } // coverage test: bridge_modify transaction with incorrect flag XEnv(*this) .tx(create_bridge(mcDoor, jvb)) .close() - .tx(bridge_modify(mcDoor, jvb, XRP(1), XRP(2)), - txflags(tfFillOrKill), - ter(temINVALID_FLAG)); + .tx(bridge_modify(mcDoor, jvb, XRP(1), XRP(2)), txflags(tfFillOrKill), ter(temINVALID_FLAG)); // coverage test: bridge_modify transaction with xchain feature // disabled @@ -1231,8 +1065,7 @@ struct XChain_test : public beast::unit_test::suite, XEnv(*this) .tx(create_bridge(mcDoor, jvb)) .close() - .tx(bridge_modify(mcAlice, jvb, XRP(1), XRP(2)), - ter(temXCHAIN_BRIDGE_NONDOOR_OWNER)); + .tx(bridge_modify(mcAlice, jvb, XRP(1), XRP(2)), ter(temXCHAIN_BRIDGE_NONDOOR_OWNER)); /** * test tfClearAccountCreateAmount flag in BridgeModify tx @@ -1243,18 +1076,13 @@ struct XChain_test : public beast::unit_test::suite, XEnv(*this) .tx(create_bridge(mcDoor, jvb, XRP(1), XRP(20))) .close() - .tx(sidechain_xchain_account_create( - mcAlice, jvb, scuAlice, XRP(100), reward)) + .tx(sidechain_xchain_account_create(mcAlice, jvb, scuAlice, XRP(100), reward)) .close() - .tx(bridge_modify(mcDoor, jvb, {}, XRP(2)), - txflags(tfClearAccountCreateAmount), - ter(temMALFORMED)) + .tx(bridge_modify(mcDoor, jvb, {}, XRP(2)), txflags(tfClearAccountCreateAmount), ter(temMALFORMED)) .close() - .tx(bridge_modify(mcDoor, jvb, XRP(3), {}), - txflags(tfClearAccountCreateAmount)) + .tx(bridge_modify(mcDoor, jvb, XRP(3), {}), txflags(tfClearAccountCreateAmount)) .close() - .tx(sidechain_xchain_account_create( - mcAlice, jvb, scuBob, XRP(100), XRP(3)), + .tx(sidechain_xchain_account_create(mcAlice, jvb, scuBob, XRP(100), XRP(3)), ter(tecXCHAIN_CREATE_ACCOUNT_DISABLED)) .close(); } @@ -1292,11 +1120,7 @@ struct XChain_test : public beast::unit_test::suite, // Non-existent bridge XEnv(*this, true) - .tx(xchain_create_claim_id( - scAlice, - bridge(mcAlice, mcAlice["USD"], scBob, scBob["USD"]), - reward, - mcAlice), + .tx(xchain_create_claim_id(scAlice, bridge(mcAlice, mcAlice["USD"], scBob, scBob["USD"]), reward, mcAlice), ter(tecNO_ENTRY)) .close(); @@ -1305,8 +1129,7 @@ struct XChain_test : public beast::unit_test::suite, .tx(create_bridge(Account::master, jvb)) .fund(res1 - xrp_dust, scuAlice) // barely not enough .close() - .tx(xchain_create_claim_id(scuAlice, jvb, reward, mcAlice), - ter(tecINSUFFICIENT_RESERVE)) + .tx(xchain_create_claim_id(scuAlice, jvb, reward, mcAlice), ter(tecINSUFFICIENT_RESERVE)) .close(); // The specified reward doesn't match the reward on the bridge (test @@ -1315,17 +1138,14 @@ struct XChain_test : public beast::unit_test::suite, XEnv(*this, true) .tx(create_bridge(Account::master, jvb)) .close() - .tx(xchain_create_claim_id( - scAlice, jvb, split_reward_quorum, mcAlice), - ter(tecXCHAIN_REWARD_MISMATCH)) + .tx(xchain_create_claim_id(scAlice, jvb, split_reward_quorum, mcAlice), ter(tecXCHAIN_REWARD_MISMATCH)) .close(); // A reward amount that isn't XRP XEnv(*this, true) .tx(create_bridge(Account::master, jvb)) .close() - .tx(xchain_create_claim_id(scAlice, jvb, mcUSD(1), mcAlice), - ter(temXCHAIN_BRIDGE_BAD_REWARD_AMOUNT)) + .tx(xchain_create_claim_id(scAlice, jvb, mcUSD(1), mcAlice), ter(temXCHAIN_BRIDGE_BAD_REWARD_AMOUNT)) .close(); // coverage test: xchain_create_claim_id transaction with incorrect @@ -1333,9 +1153,7 @@ struct XChain_test : public beast::unit_test::suite, XEnv(*this, true) .tx(create_bridge(Account::master, jvb)) .close() - .tx(xchain_create_claim_id(scAlice, jvb, reward, mcAlice), - txflags(tfFillOrKill), - ter(temINVALID_FLAG)) + .tx(xchain_create_claim_id(scAlice, jvb, reward, mcAlice), txflags(tfFillOrKill), ter(temINVALID_FLAG)) .close(); // coverage test: xchain_create_claim_id transaction with xchain @@ -1344,8 +1162,7 @@ struct XChain_test : public beast::unit_test::suite, .tx(create_bridge(Account::master, jvb)) .disableFeature(featureXChainBridge) .close() - .tx(xchain_create_claim_id(scAlice, jvb, reward, mcAlice), - ter(temDISABLED)) + .tx(xchain_create_claim_id(scAlice, jvb, reward, mcAlice), ter(temDISABLED)) .close(); } @@ -1359,8 +1176,7 @@ struct XChain_test : public beast::unit_test::suite, testcase("Commit"); // Commit to a non-existent bridge - XEnv(*this).tx( - xchain_commit(mcAlice, jvb, 1, one_xrp, scBob), ter(tecNO_ENTRY)); + XEnv(*this).tx(xchain_commit(mcAlice, jvb, 1, one_xrp, scBob), ter(tecNO_ENTRY)); // check that reward not deducted when doing the commit { @@ -1369,10 +1185,7 @@ struct XChain_test : public beast::unit_test::suite, Balance alice_bal(xenv, mcAlice); auto const amt = XRP(1000); - xenv.tx(create_bridge(mcDoor, jvb)) - .close() - .tx(xchain_commit(mcAlice, jvb, 1, amt, scBob)) - .close(); + xenv.tx(create_bridge(mcDoor, jvb)).close().tx(xchain_commit(mcAlice, jvb, 1, amt, scBob)).close(); STAmount claim_cost = amt; BEAST_EXPECT(alice_bal.diff() == -(claim_cost + tx_fee)); @@ -1382,8 +1195,7 @@ struct XChain_test : public beast::unit_test::suite, XEnv(*this) .tx(create_bridge(mcDoor, jvb)) .close() - .tx(xchain_commit(mcAlice, jvb, 1, XRP(-1), scBob), - ter(temBAD_AMOUNT)); + .tx(xchain_commit(mcAlice, jvb, 1, XRP(-1), scBob), ter(temBAD_AMOUNT)); // Commit an amount whose issue that does not match the expected // issue on the bridge (either LockingChainIssue or @@ -1391,8 +1203,7 @@ struct XChain_test : public beast::unit_test::suite, XEnv(*this) .tx(create_bridge(mcDoor, jvb)) .close() - .tx(xchain_commit(mcAlice, jvb, 1, mcUSD(100), scBob), - ter(temBAD_ISSUER)); + .tx(xchain_commit(mcAlice, jvb, 1, mcUSD(100), scBob), ter(temBAD_ISSUER)); // Commit an amount that would put the sender below the required // reserve (if XRP) @@ -1400,8 +1211,7 @@ struct XChain_test : public beast::unit_test::suite, .tx(create_bridge(mcDoor, jvb)) .fund(res0 + one_xrp - xrp_dust, mcuAlice) // barely not enough .close() - .tx(xchain_commit(mcuAlice, jvb, 1, one_xrp, scBob), - ter(tecUNFUNDED_PAYMENT)); + .tx(xchain_commit(mcuAlice, jvb, 1, one_xrp, scBob), ter(tecUNFUNDED_PAYMENT)); XEnv(*this) .tx(create_bridge(mcDoor, jvb)) @@ -1417,8 +1227,7 @@ struct XChain_test : public beast::unit_test::suite, .tx(create_bridge(mcDoor, jvb)) .fund(res0, mcuAlice) // barely not enough .close() - .tx(xchain_commit(mcuAlice, jvb, 1, res0 + one_xrp, scBob), - ter(tecUNFUNDED_PAYMENT)); + .tx(xchain_commit(mcuAlice, jvb, 1, res0 + one_xrp, scBob), ter(tecUNFUNDED_PAYMENT)); auto jvb_USD = bridge(mcDoor, mcUSD, scGw, scUSD); @@ -1434,16 +1243,14 @@ struct XChain_test : public beast::unit_test::suite, .tx(trust(mcDoor, mcUSD(10000))) // door needs to have a trustline .tx(create_bridge(mcDoor, jvb_USD)) .close() - .tx(xchain_commit(mcDoor, jvb_USD, 1, mcUSD(1), scBob), - ter(tecXCHAIN_SELF_COMMIT)); + .tx(xchain_commit(mcDoor, jvb_USD, 1, mcUSD(1), scBob), ter(tecXCHAIN_SELF_COMMIT)); // commit sent from mcAlice which has no IOU balance => should fail XEnv(*this) .tx(trust(mcDoor, mcUSD(10000))) // door needs to have a trustline .tx(create_bridge(mcDoor, jvb_USD)) .close() - .tx(xchain_commit(mcAlice, jvb_USD, 1, mcUSD(1), scBob), - ter(terNO_LINE)); + .tx(xchain_commit(mcAlice, jvb_USD, 1, mcUSD(1), scBob), ter(terNO_LINE)); // commit sent from mcAlice which has no IOU balance => should fail // just changed the destination to scGw (which is the door account @@ -1452,8 +1259,7 @@ struct XChain_test : public beast::unit_test::suite, .tx(trust(mcDoor, mcUSD(10000))) // door needs to have a trustline .tx(create_bridge(mcDoor, jvb_USD)) .close() - .tx(xchain_commit(mcAlice, jvb_USD, 1, mcUSD(1), scGw), - ter(terNO_LINE)); + .tx(xchain_commit(mcAlice, jvb_USD, 1, mcUSD(1), scGw), ter(terNO_LINE)); // commit sent from mcAlice which has a IOU balance => should // succeed @@ -1471,9 +1277,7 @@ struct XChain_test : public beast::unit_test::suite, XEnv(*this) .tx(create_bridge(mcDoor)) .close() - .tx(xchain_commit(mcAlice, jvb, 1, one_xrp, scBob), - txflags(tfFillOrKill), - ter(temINVALID_FLAG)); + .tx(xchain_commit(mcAlice, jvb, 1, one_xrp, scBob), txflags(tfFillOrKill), ter(temINVALID_FLAG)); // coverage test: xchain_commit transaction with xchain feature // disabled @@ -1481,8 +1285,7 @@ struct XChain_test : public beast::unit_test::suite, .tx(create_bridge(mcDoor)) .disableFeature(featureXChainBridge) .close() - .tx(xchain_commit(mcAlice, jvb, 1, one_xrp, scBob), - ter(temDISABLED)); + .tx(xchain_commit(mcAlice, jvb, 1, one_xrp, scBob), ter(temDISABLED)); } void @@ -1494,9 +1297,7 @@ struct XChain_test : public beast::unit_test::suite, XRPAmount res0 = reserve(0); XRPAmount tx_fee = txFee(); - auto multiTtxFee = [&](std::uint32_t m) -> STAmount { - return multiply(tx_fee, STAmount(m), xrpIssue()); - }; + auto multiTtxFee = [&](std::uint32_t m) -> STAmount { return multiply(tx_fee, STAmount(m), xrpIssue()); }; // Add an attestation to a claim id that has already reached quorum. // This should succeed and share in the reward. @@ -1524,21 +1325,11 @@ struct XChain_test : public beast::unit_test::suite, auto const amt = XRP(1000); mcEnv.tx(xchain_commit(mcAlice, jvb, claimID, amt, dst)).close(); - BalanceTransfer transfer( - scEnv, Account::master, scBob, scAlice, payees, withClaim); + BalanceTransfer transfer(scEnv, Account::master, scBob, scAlice, payees, withClaim); scEnv .multiTx(claim_attestations( - scAttester, - jvb, - mcAlice, - amt, - payees, - true, - claimID, - dst, - signers, - UT_XCHAIN_DEFAULT_QUORUM)) + scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers, UT_XCHAIN_DEFAULT_QUORUM)) .close(); scEnv .tx(claim_attestation( @@ -1558,8 +1349,7 @@ struct XChain_test : public beast::unit_test::suite, BEAST_EXPECT(transfer.has_not_happened()); // need to submit a claim transactions - scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob)) - .close(); + scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob)).close(); BEAST_EXPECT(!scEnv.claimID(jvb, claimID)); // claim id deleted BEAST_EXPECT(scEnv.claimID(jvb) == claimID); } @@ -1609,27 +1399,9 @@ struct XChain_test : public beast::unit_test::suite, mcEnv.tx(xchain_commit(mcAlice, jvb, claimID, amt, dst)).close(); - BalanceTransfer transfer( - scEnv, - Account::master, - scBob, - scAlice, - &payees[0], - 3, - withClaim); + BalanceTransfer transfer(scEnv, Account::master, scBob, scAlice, &payees[0], 3, withClaim); - scEnv - .multiTx(claim_attestations( - scAttester, - jvb, - mcAlice, - amt, - payees, - true, - claimID, - dst, - signers_, - 3)) + scEnv.multiTx(claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers_, 3)) .close(); if (withClaim) @@ -1637,14 +1409,12 @@ struct XChain_test : public beast::unit_test::suite, BEAST_EXPECT(transfer.has_not_happened()); // need to submit a claim transactions - scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob)) - .close(); + scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob)).close(); } BEAST_EXPECT(!scEnv.claimID(jvb, 1)); // claim id deleted - BEAST_EXPECT(transfer.has_happened( - amt, divide(reward, STAmount(3), reward.issue()))); + BEAST_EXPECT(transfer.has_happened(amt, divide(reward, STAmount(3), reward.issue()))); } // 4,4 => should succeed @@ -1668,8 +1438,7 @@ struct XChain_test : public beast::unit_test::suite, } return result; }(); - STAmount const split_reward_ = - divide(reward, STAmount(signers_.size()), reward.issue()); + STAmount const split_reward_ = divide(reward, STAmount(signers_.size()), reward.issue()); mcEnv.tx(create_bridge(mcDoor, jvb)).close(); @@ -1686,28 +1455,9 @@ struct XChain_test : public beast::unit_test::suite, mcEnv.tx(xchain_commit(mcAlice, jvb, claimID, amt, dst)).close(); - BalanceTransfer transfer( - scEnv, - Account::master, - scBob, - scAlice, - &payees[2], - 2, - withClaim); + BalanceTransfer transfer(scEnv, Account::master, scBob, scAlice, &payees[2], 2, withClaim); - scEnv - .multiTx(claim_attestations( - scAttester, - jvb, - mcAlice, - amt, - payees, - true, - claimID, - dst, - signers_, - 2, - 2)) + scEnv.multiTx(claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers_, 2, 2)) .close(); if (withClaim) @@ -1715,14 +1465,12 @@ struct XChain_test : public beast::unit_test::suite, BEAST_EXPECT(transfer.has_not_happened()); // need to submit a claim transactions - scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob)) - .close(); + scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob)).close(); } BEAST_EXPECT(!scEnv.claimID(jvb, claimID)); // claim id deleted - BEAST_EXPECT(transfer.has_happened( - amt, divide(reward, STAmount(2), reward.issue()))); + BEAST_EXPECT(transfer.has_happened(amt, divide(reward, STAmount(2), reward.issue()))); } // 1,2 => should fail @@ -1762,41 +1510,19 @@ struct XChain_test : public beast::unit_test::suite, auto const amt = XRP(1000); mcEnv.tx(xchain_commit(mcAlice, jvb, claimID, amt, dst)).close(); - BalanceTransfer transfer( - scEnv, - Account::master, - scBob, - scAlice, - &payees[0], - 2, - withClaim); + BalanceTransfer transfer(scEnv, Account::master, scBob, scAlice, &payees[0], 2, withClaim); - scEnv - .multiTx(claim_attestations( - scAttester, - jvb, - mcAlice, - amt, - payees, - true, - claimID, - dst, - signers_, - 2)) + scEnv.multiTx(claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers_, 2)) .close(); if (withClaim) { BEAST_EXPECT(transfer.has_not_happened()); // need to submit a claim transactions - scEnv - .tx(xchain_claim(scAlice, jvb, claimID, amt, scBob), - ter(tecXCHAIN_CLAIM_NO_QUORUM)) - .close(); + scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob), ter(tecXCHAIN_CLAIM_NO_QUORUM)).close(); } - BEAST_EXPECT( - !!scEnv.claimID(jvb, claimID)); // claim id still present + BEAST_EXPECT(!!scEnv.claimID(jvb, claimID)); // claim id still present BEAST_EXPECT(transfer.has_not_happened()); } @@ -1838,28 +1564,9 @@ struct XChain_test : public beast::unit_test::suite, mcEnv.tx(xchain_commit(mcAlice, jvb, claimID, amt, dst)).close(); - BalanceTransfer transfer( - scEnv, - Account::master, - scBob, - scAlice, - &payees[1], - 2, - withClaim); + BalanceTransfer transfer(scEnv, Account::master, scBob, scAlice, &payees[1], 2, withClaim); - scEnv - .multiTx(claim_attestations( - scAttester, - jvb, - mcAlice, - amt, - payees, - true, - claimID, - dst, - signers_, - 2, - 1)) + scEnv.multiTx(claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers_, 2, 1)) .close(); if (withClaim) @@ -1867,14 +1574,10 @@ struct XChain_test : public beast::unit_test::suite, BEAST_EXPECT(transfer.has_not_happened()); // need to submit a claim transactions - scEnv - .tx(xchain_claim(scAlice, jvb, claimID, amt, scBob), - ter(tecXCHAIN_CLAIM_NO_QUORUM)) - .close(); + scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob), ter(tecXCHAIN_CLAIM_NO_QUORUM)).close(); } - BEAST_EXPECT( - !!scEnv.claimID(jvb, claimID)); // claim id still present + BEAST_EXPECT(!!scEnv.claimID(jvb, claimID)); // claim id still present BEAST_EXPECT(transfer.has_not_happened()); } @@ -1894,18 +1597,12 @@ struct XChain_test : public beast::unit_test::suite, mcEnv.tx(create_bridge(mcDoor, jvb, reward, XRP(20))) .close() - .tx(sidechain_xchain_account_create( - mcAlice, jvb, scuAlice, amt, reward)) - .tx(sidechain_xchain_account_create( - mcBob, jvb, scuBob, amt, reward)) - .tx(sidechain_xchain_account_create( - mcCarol, jvb, scuCarol, amt, reward)) + .tx(sidechain_xchain_account_create(mcAlice, jvb, scuAlice, amt, reward)) + .tx(sidechain_xchain_account_create(mcBob, jvb, scuBob, amt, reward)) + .tx(sidechain_xchain_account_create(mcCarol, jvb, scuCarol, amt, reward)) .close(); - BEAST_EXPECT( - door.diff() == - (multiply(amt_plus_reward, STAmount(3), xrpIssue()) - - tx_fee)); + BEAST_EXPECT(door.diff() == (multiply(amt_plus_reward, STAmount(3), xrpIssue()) - tx_fee)); BEAST_EXPECT(carol.diff() == -(amt + reward + tx_fee)); } @@ -1928,11 +1625,10 @@ struct XChain_test : public beast::unit_test::suite, // att_create_acct_vec return vectors of size 2, so 2*3 txns BEAST_EXPECT(attester.diff() == -multiTtxFee(6)); - BEAST_EXPECT(!!scEnv.caClaimID(jvb, 1)); // ca claim id present - BEAST_EXPECT(!!scEnv.caClaimID(jvb, 2)); // ca claim id present - BEAST_EXPECT(!!scEnv.caClaimID(jvb, 3)); // ca claim id present - BEAST_EXPECT( - scEnv.claimCount(jvb) == 0); // claim count still 0 + BEAST_EXPECT(!!scEnv.caClaimID(jvb, 1)); // ca claim id present + BEAST_EXPECT(!!scEnv.caClaimID(jvb, 2)); // ca claim id present + BEAST_EXPECT(!!scEnv.caClaimID(jvb, 3)); // ca claim id present + BEAST_EXPECT(scEnv.claimCount(jvb) == 0); // claim count still 0 } { @@ -1941,16 +1637,14 @@ struct XChain_test : public beast::unit_test::suite, Balance attester(scEnv, scAttester); Balance door(scEnv, Account::master); - scEnv.multiTx(att_create_acct_vec(2, amt, scuBob, 3, 2)) - .close(); + scEnv.multiTx(att_create_acct_vec(2, amt, scuBob, 3, 2)).close(); BEAST_EXPECT(door.diff() == STAmount(0)); // att_create_acct_vec return vectors of size 3, so 3 txns BEAST_EXPECT(attester.diff() == -multiTtxFee(3)); - BEAST_EXPECT(!!scEnv.caClaimID(jvb, 2)); // ca claim id present - BEAST_EXPECT( - scEnv.claimCount(jvb) == 0); // claim count still 0 + BEAST_EXPECT(!!scEnv.caClaimID(jvb, 2)); // ca claim id present + BEAST_EXPECT(scEnv.claimCount(jvb) == 0); // claim count still 0 } { @@ -1959,16 +1653,14 @@ struct XChain_test : public beast::unit_test::suite, Balance attester(scEnv, scAttester); Balance door(scEnv, Account::master); - scEnv.multiTx(att_create_acct_vec(3, amt, scuCarol, 3, 2)) - .close(); + scEnv.multiTx(att_create_acct_vec(3, amt, scuCarol, 3, 2)).close(); BEAST_EXPECT(door.diff() == STAmount(0)); // att_create_acct_vec return vectors of size 3, so 3 txns BEAST_EXPECT(attester.diff() == -multiTtxFee(3)); - BEAST_EXPECT(!!scEnv.caClaimID(jvb, 3)); // ca claim id present - BEAST_EXPECT( - scEnv.claimCount(jvb) == 0); // claim count still 0 + BEAST_EXPECT(!!scEnv.caClaimID(jvb, 3)); // ca claim id present + BEAST_EXPECT(scEnv.claimCount(jvb) == 0); // claim count still 0 } { @@ -1977,8 +1669,7 @@ struct XChain_test : public beast::unit_test::suite, Balance attester(scEnv, scAttester); Balance door(scEnv, Account::master); - scEnv.multiTx(att_create_acct_vec(1, amt, scuAlice, 3, 1)) - .close(); + scEnv.multiTx(att_create_acct_vec(1, amt, scuAlice, 3, 1)).close(); BEAST_EXPECT(door.diff() == -amt_plus_reward); // att_create_acct_vec return vectors of size 3, so 3 txns @@ -1997,17 +1688,15 @@ struct XChain_test : public beast::unit_test::suite, Balance attester(scEnv, scAttester); Balance door(scEnv, Account::master); - scEnv.multiTx(att_create_acct_vec(3, amt, scuCarol, 3, 2)) - .close(); + scEnv.multiTx(att_create_acct_vec(3, amt, scuCarol, 3, 2)).close(); BEAST_EXPECT(door.diff() == STAmount(0)); // att_create_acct_vec return vectors of size 3, so 3 txns BEAST_EXPECT(attester.diff() == -multiTtxFee(3)); - BEAST_EXPECT(!!scEnv.caClaimID(jvb, 2)); // claim id 2 present - BEAST_EXPECT(!!scEnv.caClaimID(jvb, 3)); // claim id 3 present - BEAST_EXPECT( - scEnv.claimCount(jvb) == 1); // claim count still 1 + BEAST_EXPECT(!!scEnv.caClaimID(jvb, 2)); // claim id 2 present + BEAST_EXPECT(!!scEnv.caClaimID(jvb, 3)); // claim id 3 present + BEAST_EXPECT(scEnv.claimCount(jvb) == 1); // claim count still 1 } { @@ -2058,10 +1747,7 @@ struct XChain_test : public beast::unit_test::suite, Balance door(mcEnv, mcDoor); Balance carol(mcEnv, mcCarol); - mcEnv - .tx(sidechain_xchain_account_create( - mcCarol, jvb, scuAlice, amt, reward)) - .close(); + mcEnv.tx(sidechain_xchain_account_create(mcCarol, jvb, scuAlice, amt, reward)).close(); BEAST_EXPECT(door.diff() == amt_plus_reward); BEAST_EXPECT(carol.diff() == -(amt_plus_reward + tx_fee)); @@ -2075,14 +1761,12 @@ struct XChain_test : public beast::unit_test::suite, Balance door(scEnv, Account::master); scEnv.multiTx(att_create_acct_vec(1, amt, scuAlice, 2)).close(); - BEAST_EXPECT(!!scEnv.caClaimID(jvb, 1)); // claim id present - BEAST_EXPECT( - scEnv.claimCount(jvb) == 0); // claim count is one less + BEAST_EXPECT(!!scEnv.caClaimID(jvb, 1)); // claim id present + BEAST_EXPECT(scEnv.claimCount(jvb) == 0); // claim count is one less scEnv.multiTx(att_create_acct_vec(1, amt, scuAlice, 2, 2)).close(); - BEAST_EXPECT(!scEnv.caClaimID(jvb, 1)); // claim id deleted - BEAST_EXPECT( - scEnv.claimCount(jvb) == 1); // claim count was incremented + BEAST_EXPECT(!scEnv.caClaimID(jvb, 1)); // claim id deleted + BEAST_EXPECT(scEnv.claimCount(jvb) == 1); // claim count was incremented BEAST_EXPECT(attester.diff() == -multiTtxFee(4)); BEAST_EXPECT(door.diff() == -reward); @@ -2104,10 +1788,7 @@ struct XChain_test : public beast::unit_test::suite, Balance door(mcEnv, mcDoor); Balance carol(mcEnv, mcCarol); - mcEnv - .tx(sidechain_xchain_account_create( - mcCarol, jvb, scAlice, amt, reward)) - .close(); + mcEnv.tx(sidechain_xchain_account_create(mcCarol, jvb, scAlice, amt, reward)).close(); BEAST_EXPECT(door.diff() == amt_plus_reward); BEAST_EXPECT(carol.diff() == -(amt_plus_reward + tx_fee)); @@ -2122,14 +1803,12 @@ struct XChain_test : public beast::unit_test::suite, Balance alice(scEnv, scAlice); scEnv.multiTx(att_create_acct_vec(1, amt, scAlice, 2)).close(); - BEAST_EXPECT(!!scEnv.caClaimID(jvb, 1)); // claim id present - BEAST_EXPECT( - scEnv.claimCount(jvb) == 0); // claim count is one less + BEAST_EXPECT(!!scEnv.caClaimID(jvb, 1)); // claim id present + BEAST_EXPECT(scEnv.claimCount(jvb) == 0); // claim count is one less scEnv.multiTx(att_create_acct_vec(1, amt, scAlice, 2, 2)).close(); - BEAST_EXPECT(!scEnv.caClaimID(jvb, 1)); // claim id deleted - BEAST_EXPECT( - scEnv.claimCount(jvb) == 1); // claim count was incremented + BEAST_EXPECT(!scEnv.caClaimID(jvb, 1)); // claim id deleted + BEAST_EXPECT(scEnv.claimCount(jvb) == 1); // claim count was incremented BEAST_EXPECT(door.diff() == -amt_plus_reward); BEAST_EXPECT(attester.diff() == -multiTtxFee(4)); @@ -2151,10 +1830,7 @@ struct XChain_test : public beast::unit_test::suite, Balance door(mcEnv, mcDoor); Balance carol(mcEnv, mcCarol); - mcEnv - .tx(sidechain_xchain_account_create( - mcCarol, jvb, scAlice, amt, reward)) - .close(); + mcEnv.tx(sidechain_xchain_account_create(mcCarol, jvb, scAlice, amt, reward)).close(); BEAST_EXPECT(door.diff() == amt_plus_reward); BEAST_EXPECT(carol.diff() == -(amt_plus_reward + tx_fee)); @@ -2170,14 +1846,12 @@ struct XChain_test : public beast::unit_test::suite, Balance alice(scEnv, scAlice); scEnv.multiTx(att_create_acct_vec(1, amt, scAlice, 2)).close(); - BEAST_EXPECT(!!scEnv.caClaimID(jvb, 1)); // claim id present - BEAST_EXPECT( - scEnv.claimCount(jvb) == 0); // claim count is one less + BEAST_EXPECT(!!scEnv.caClaimID(jvb, 1)); // claim id present + BEAST_EXPECT(scEnv.claimCount(jvb) == 0); // claim count is one less scEnv.multiTx(att_create_acct_vec(1, amt, scAlice, 2, 2)).close(); - BEAST_EXPECT(!scEnv.caClaimID(jvb, 1)); // claim id deleted - BEAST_EXPECT( - scEnv.claimCount(jvb) == 1); // claim count was incremented + BEAST_EXPECT(!scEnv.caClaimID(jvb, 1)); // claim id deleted + BEAST_EXPECT(scEnv.claimCount(jvb) == 1); // claim count was incremented BEAST_EXPECT(door.diff() == -reward); BEAST_EXPECT(attester.diff() == -multiTtxFee(4)); @@ -2201,20 +1875,14 @@ struct XChain_test : public beast::unit_test::suite, mcEnv.tx(create_bridge(mcDoor, jvb, reward, XRP(20))) .close() - .tx(sidechain_xchain_account_create( - mcAlice, jvb, scuAlice, amt, reward)) + .tx(sidechain_xchain_account_create(mcAlice, jvb, scuAlice, amt, reward)) .close() // make sure Alice gets claim #1 - .tx(sidechain_xchain_account_create( - mcBob, jvb, scuBob, amt, reward)) + .tx(sidechain_xchain_account_create(mcBob, jvb, scuBob, amt, reward)) .close() // make sure Bob gets claim #2 - .tx(sidechain_xchain_account_create( - mcCarol, jvb, scuCarol, amt, reward)) + .tx(sidechain_xchain_account_create(mcCarol, jvb, scuCarol, amt, reward)) .close(); // and Carol will get claim #3 - BEAST_EXPECT( - door.diff() == - (multiply(amt_plus_reward, STAmount(3), xrpIssue()) - - tx_fee)); + BEAST_EXPECT(door.diff() == (multiply(amt_plus_reward, STAmount(3), xrpIssue()) - tx_fee)); BEAST_EXPECT(carol.diff() == -(amt + reward + tx_fee)); } @@ -2251,58 +1919,42 @@ struct XChain_test : public beast::unit_test::suite, .close(); txCount += 3; - BEAST_EXPECTS( - !!scEnv.caClaimID(jvb, 1), "claim id 1 still there"); - BEAST_EXPECTS( - !!scEnv.caClaimID(jvb, 2), "claim id 2 still there"); - BEAST_EXPECTS( - !!scEnv.caClaimID(jvb, 3), "claim id 3 still there"); - BEAST_EXPECTS( - scEnv.claimCount(jvb) == 0, "No account created yet"); + BEAST_EXPECTS(!!scEnv.caClaimID(jvb, 1), "claim id 1 still there"); + BEAST_EXPECTS(!!scEnv.caClaimID(jvb, 2), "claim id 2 still there"); + BEAST_EXPECTS(!!scEnv.caClaimID(jvb, 3), "claim id 3 still there"); + BEAST_EXPECTS(scEnv.claimCount(jvb) == 0, "No account created yet"); - scEnv.multiTx(att_create_acct_vec(3, amt, scuCarol, 1, 1)) - .close(); + scEnv.multiTx(att_create_acct_vec(3, amt, scuCarol, 1, 1)).close(); txCount += 1; - BEAST_EXPECTS( - !!scEnv.caClaimID(jvb, 3), "claim id 3 still there"); - BEAST_EXPECTS( - scEnv.claimCount(jvb) == 0, "No account created yet"); + BEAST_EXPECTS(!!scEnv.caClaimID(jvb, 3), "claim id 3 still there"); + BEAST_EXPECTS(scEnv.claimCount(jvb) == 0, "No account created yet"); - scEnv.multiTx(att_create_acct_vec(1, amt, scuAlice, 1, 2)) - .close(); + scEnv.multiTx(att_create_acct_vec(1, amt, scuAlice, 1, 2)).close(); txCount += 1; BEAST_EXPECTS(!scEnv.caClaimID(jvb, 1), "claim id 1 deleted"); BEAST_EXPECTS(scEnv.claimCount(jvb) == 1, "scuAlice created"); scEnv.multiTx(att_create_acct_vec(2, amt, scuBob, 1, 3)) - .multiTx( - att_create_acct_vec(1, amt, scuAlice, 1, 3), - ter(tecXCHAIN_ACCOUNT_CREATE_PAST)) + .multiTx(att_create_acct_vec(1, amt, scuAlice, 1, 3), ter(tecXCHAIN_ACCOUNT_CREATE_PAST)) .close(); txCount += 2; BEAST_EXPECTS(!scEnv.caClaimID(jvb, 2), "claim id 2 deleted"); BEAST_EXPECTS(!scEnv.caClaimID(jvb, 1), "claim id 1 not added"); - BEAST_EXPECTS( - scEnv.claimCount(jvb) == 2, "scuAlice & scuBob created"); + BEAST_EXPECTS(scEnv.claimCount(jvb) == 2, "scuAlice & scuBob created"); - scEnv.multiTx(att_create_acct_vec(3, amt, scuCarol, 1, 0)) - .close(); + scEnv.multiTx(att_create_acct_vec(3, amt, scuCarol, 1, 0)).close(); txCount += 1; BEAST_EXPECTS(!scEnv.caClaimID(jvb, 3), "claim id 3 deleted"); - BEAST_EXPECTS( - scEnv.claimCount(jvb) == 3, "All 3 accounts created"); + BEAST_EXPECTS(scEnv.claimCount(jvb) == 3, "All 3 accounts created"); // because of the division of the rewards among attesters, // sometimes a couple drops are left over unspent in the // door account (here 2 drops) - BEAST_EXPECT( - multiply(amt_plus_reward, STAmount(3), xrpIssue()) + - door.diff() < - drops(3)); + BEAST_EXPECT(multiply(amt_plus_reward, STAmount(3), xrpIssue()) + door.diff() < drops(3)); BEAST_EXPECT(attester.diff() == -multiTtxFee(txCount)); BEAST_EXPECT(scEnv.balance(scuAlice) == amt); BEAST_EXPECT(scEnv.balance(scuBob) == amt); @@ -2320,16 +1972,7 @@ struct XChain_test : public beast::unit_test::suite, scEnv.tx(create_bridge(Account::master, jvb)) .tx(jtx::signers(Account::master, quorum, signers)) .close() - .tx(claim_attestation( - scAttester, - jvb, - mcAlice, - XRP(1000), - payees[0], - true, - 1, - {}, - signers[0]), + .tx(claim_attestation(scAttester, jvb, mcAlice, XRP(1000), payees[0], true, 1, {}, signers[0]), txflags(tfFillOrKill), ter(temINVALID_FLAG)) .close(); @@ -2343,16 +1986,7 @@ struct XChain_test : public beast::unit_test::suite, .tx(jtx::signers(Account::master, quorum, signers)) .disableFeature(featureXChainBridge) .close() - .tx(claim_attestation( - scAttester, - jvb, - mcAlice, - XRP(1000), - payees[0], - true, - 1, - {}, - signers[0]), + .tx(claim_attestation(scAttester, jvb, mcAlice, XRP(1000), payees[0], true, 1, {}, signers[0]), ter(temDISABLED)) .close(); } @@ -2388,19 +2022,10 @@ struct XChain_test : public beast::unit_test::suite, for (int i = 0; i < signers.size(); ++i) { - auto const att = claim_attestation( - scAttester, - jvb, - mcAlice, - amt, - payees[i], - true, - claimID, - dst, - signers[i]); + auto const att = + claim_attestation(scAttester, jvb, mcAlice, amt, payees[i], true, claimID, dst, signers[i]); - TER const expectedTER = - i < quorum ? tesSUCCESS : TER{tecXCHAIN_NO_CLAIM_ID}; + TER const expectedTER = i < quorum ? tesSUCCESS : TER{tecXCHAIN_NO_CLAIM_ID}; if (i + 1 == quorum) scEnv.tx(att, ter(expectedTER)).close(); else @@ -2409,8 +2034,7 @@ struct XChain_test : public beast::unit_test::suite, if (i + 1 < quorum) BEAST_EXPECT(dstStartBalance == scEnv.env_.balance(dst)); else - BEAST_EXPECT( - dstStartBalance + amt == scEnv.env_.balance(dst)); + BEAST_EXPECT(dstStartBalance + amt == scEnv.env_.balance(dst)); } BEAST_EXPECT(dstStartBalance + amt == scEnv.env_.balance(dst)); } @@ -2454,47 +2078,25 @@ struct XChain_test : public beast::unit_test::suite, { // G1: master key - auto att = claim_attestation( - scAttester, - jvb, - mcAlice, - amt, - payees[0], - true, - claimID, - dst, - alt_signers[0]); + auto att = + claim_attestation(scAttester, jvb, mcAlice, amt, payees[0], true, claimID, dst, alt_signers[0]); scEnv.tx(att).close(); } { // G2: regular key // alt_signers[0] is the regular key of alt_signers[1] // There should be 2 attestations after the transaction - scEnv - .tx(jtx::regkey( - alt_signers[1].account, alt_signers[0].account)) - .close(); - auto att = claim_attestation( - scAttester, - jvb, - mcAlice, - amt, - payees[1], - true, - claimID, - dst, - alt_signers[0]); - att[sfAttestationSignerAccount.getJsonName()] = - alt_signers[1].account.human(); + scEnv.tx(jtx::regkey(alt_signers[1].account, alt_signers[0].account)).close(); + auto att = + claim_attestation(scAttester, jvb, mcAlice, amt, payees[1], true, claimID, dst, alt_signers[0]); + att[sfAttestationSignerAccount.getJsonName()] = alt_signers[1].account.human(); scEnv.tx(att).close(); } { // B3: public key and non-exist (unfunded) account mismatch // G3: public key and non-exist (unfunded) account match - auto const unfundedSigner1 = - alt_signers[UT_XCHAIN_DEFAULT_NUM_SIGNERS - 1]; - auto const unfundedSigner2 = - alt_signers[UT_XCHAIN_DEFAULT_NUM_SIGNERS - 2]; + auto const unfundedSigner1 = alt_signers[UT_XCHAIN_DEFAULT_NUM_SIGNERS - 1]; + auto const unfundedSigner2 = alt_signers[UT_XCHAIN_DEFAULT_NUM_SIGNERS - 2]; auto att = claim_attestation( scAttester, jvb, @@ -2505,83 +2107,41 @@ struct XChain_test : public beast::unit_test::suite, claimID, dst, unfundedSigner1); - att[sfAttestationSignerAccount.getJsonName()] = - unfundedSigner2.account.human(); - scEnv.tx(att, ter(tecXCHAIN_BAD_PUBLIC_KEY_ACCOUNT_PAIR)) - .close(); - att[sfAttestationSignerAccount.getJsonName()] = - unfundedSigner1.account.human(); + att[sfAttestationSignerAccount.getJsonName()] = unfundedSigner2.account.human(); + scEnv.tx(att, ter(tecXCHAIN_BAD_PUBLIC_KEY_ACCOUNT_PAIR)).close(); + att[sfAttestationSignerAccount.getJsonName()] = unfundedSigner1.account.human(); scEnv.tx(att).close(); } { // B2: single item signer list std::vector tempSignerList = {signers[0]}; - scEnv.tx( - jtx::signers(alt_signers[2].account, 1, tempSignerList)); + scEnv.tx(jtx::signers(alt_signers[2].account, 1, tempSignerList)); auto att = claim_attestation( - scAttester, - jvb, - mcAlice, - amt, - payees[2], - true, - claimID, - dst, - tempSignerList.front()); - att[sfAttestationSignerAccount.getJsonName()] = - alt_signers[2].account.human(); - scEnv.tx(att, ter(tecXCHAIN_BAD_PUBLIC_KEY_ACCOUNT_PAIR)) - .close(); + scAttester, jvb, mcAlice, amt, payees[2], true, claimID, dst, tempSignerList.front()); + att[sfAttestationSignerAccount.getJsonName()] = alt_signers[2].account.human(); + scEnv.tx(att, ter(tecXCHAIN_BAD_PUBLIC_KEY_ACCOUNT_PAIR)).close(); } { // B1: disabled master key - scEnv.tx(fset(alt_signers[2].account, asfDisableMaster, 0)) - .close(); - auto att = claim_attestation( - scAttester, - jvb, - mcAlice, - amt, - payees[2], - true, - claimID, - dst, - alt_signers[2]); - scEnv.tx(att, ter(tecXCHAIN_BAD_PUBLIC_KEY_ACCOUNT_PAIR)) - .close(); + scEnv.tx(fset(alt_signers[2].account, asfDisableMaster, 0)).close(); + auto att = + claim_attestation(scAttester, jvb, mcAlice, amt, payees[2], true, claimID, dst, alt_signers[2]); + scEnv.tx(att, ter(tecXCHAIN_BAD_PUBLIC_KEY_ACCOUNT_PAIR)).close(); } { // --B4: not on signer list - auto att = claim_attestation( - scAttester, - jvb, - mcAlice, - amt, - payees[0], - true, - claimID, - dst, - signers[0]); + auto att = claim_attestation(scAttester, jvb, mcAlice, amt, payees[0], true, claimID, dst, signers[0]); scEnv.tx(att, ter(tecNO_PERMISSION)).close(); } { // --B5: missing sfAttestationSignerAccount field // Then submit the one with the field. Should reach quorum. - auto att = claim_attestation( - scAttester, - jvb, - mcAlice, - amt, - payees[3], - true, - claimID, - dst, - alt_signers[3]); + auto att = + claim_attestation(scAttester, jvb, mcAlice, amt, payees[3], true, claimID, dst, alt_signers[3]); att.removeMember(sfAttestationSignerAccount.getJsonName()); scEnv.tx(att, ter(temMALFORMED)).close(); BEAST_EXPECT(dstStartBalance == scEnv.env_.balance(dst)); - att[sfAttestationSignerAccount.getJsonName()] = - alt_signers[3].account.human(); + att[sfAttestationSignerAccount.getJsonName()] = alt_signers[3].account.human(); scEnv.tx(att).close(); BEAST_EXPECT(dstStartBalance + amt == scEnv.env_.balance(dst)); } @@ -2589,7 +2149,7 @@ struct XChain_test : public beast::unit_test::suite, } void - testXChainAddAccountCreateNonBatchAttestation() + testXChainAddAccountCreateNonBatchAttestation() // cspell: disable-line { using namespace jtx; @@ -2628,10 +2188,7 @@ struct XChain_test : public beast::unit_test::suite, Balance bal_doorA(mcEnv, doorA); Balance bal_a(mcEnv, a); - mcEnv - .tx(sidechain_xchain_account_create( - a, xrp_b.jvb, ua, amt, xrp_b.reward)) - .close(); + mcEnv.tx(sidechain_xchain_account_create(a, xrp_b.jvb, ua, amt, xrp_b.reward)).close(); BEAST_EXPECT(bal_doorA.diff() == amt_plus_reward); BEAST_EXPECT(bal_a.diff() == -(amt_plus_reward + tx_fee)); @@ -2640,19 +2197,8 @@ struct XChain_test : public beast::unit_test::suite, for (int i = 0; i < signers.size(); ++i) { auto const att = create_account_attestation( - signers[0].account, - xrp_b.jvb, - a, - amt, - xrp_b.reward, - signers[i].account, - true, - 1, - ua, - signers[i]); - TER const expectedTER = i < xrp_b.quorum - ? tesSUCCESS - : TER{tecXCHAIN_ACCOUNT_CREATE_PAST}; + signers[0].account, xrp_b.jvb, a, amt, xrp_b.reward, signers[i].account, true, 1, ua, signers[i]); + TER const expectedTER = i < xrp_b.quorum ? tesSUCCESS : TER{tecXCHAIN_ACCOUNT_CREATE_PAST}; scEnv.tx(att, ter(expectedTER)).close(); if (i + 1 < xrp_b.quorum) @@ -2696,33 +2242,16 @@ struct XChain_test : public beast::unit_test::suite, mcEnv.tx(xchain_commit(mcAlice, jvb, claimID, amt, dst)).close(); BalanceTransfer transfer( - scEnv, - Account::master, - scBob, - scAlice, - &payees[0], - UT_XCHAIN_DEFAULT_QUORUM, - withClaim); + scEnv, Account::master, scBob, scAlice, &payees[0], UT_XCHAIN_DEFAULT_QUORUM, withClaim); - scEnv - .multiTx(claim_attestations( - scAttester, - jvb, - mcAlice, - amt, - payees, - true, - claimID, - dst, - signers)) + scEnv.multiTx(claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers)) .close(); if (withClaim) { BEAST_EXPECT(transfer.has_not_happened()); // need to submit a claim transactions - scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob)) - .close(); + scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob)).close(); } BEAST_EXPECT(transfer.has_happened(amt, split_reward_quorum)); @@ -2750,27 +2279,11 @@ struct XChain_test : public beast::unit_test::suite, std::uint32_t const claimID = 1; mcEnv.tx(xchain_commit(mcAlice, jvb, claimID, amt, dst)).close(); - BalanceTransfer transfer( - scEnv, - Account::master, - scBob, - scAlice, - &payees[0], - 1, - withClaim); + BalanceTransfer transfer(scEnv, Account::master, scBob, scAlice, &payees[0], 1, withClaim); jtx::signer master_signer(Account::master); scEnv - .tx(claim_attestation( - scAttester, - jvb, - mcAlice, - amt, - payees[0], - true, - claimID, - dst, - master_signer), + .tx(claim_attestation(scAttester, jvb, mcAlice, amt, payees[0], true, claimID, dst, master_signer), ter(tecXCHAIN_NO_SIGNERS_LIST)) .close(); @@ -2801,27 +2314,11 @@ struct XChain_test : public beast::unit_test::suite, std::uint32_t const claimID = 1; mcEnv.tx(xchain_commit(mcAlice, jvb, claimID, amt, dst)).close(); - BalanceTransfer transfer( - scEnv, - Account::master, - scBob, - scAlice, - &payees[0], - 1, - withClaim); + BalanceTransfer transfer(scEnv, Account::master, scBob, scAlice, &payees[0], 1, withClaim); jtx::signer master_signer(payees[0]); scEnv - .tx(claim_attestation( - scAttester, - jvb, - mcAlice, - amt, - payees[0], - true, - claimID, - dst, - master_signer), + .tx(claim_attestation(scAttester, jvb, mcAlice, amt, payees[0], true, claimID, dst, master_signer), ter(tecXCHAIN_NO_SIGNERS_LIST)) .close(); @@ -2837,38 +2334,22 @@ struct XChain_test : public beast::unit_test::suite, mcEnv.tx(create_bridge(mcDoor, jvb)).close(); - auto jvb_unknown = - bridge(mcBob, xrpIssue(), Account::master, xrpIssue()); + auto jvb_unknown = bridge(mcBob, xrpIssue(), Account::master, xrpIssue()); scEnv.tx(create_bridge(Account::master, jvb)) .tx(jtx::signers(Account::master, quorum, signers)) .close() - .tx(xchain_create_claim_id( - scAlice, jvb_unknown, reward, mcAlice), - ter(tecNO_ENTRY)) + .tx(xchain_create_claim_id(scAlice, jvb_unknown, reward, mcAlice), ter(tecNO_ENTRY)) .close(); auto dst(withClaim ? std::nullopt : std::optional{scBob}); auto const amt = XRP(1000); std::uint32_t const claimID = 1; - mcEnv - .tx(xchain_commit(mcAlice, jvb_unknown, claimID, amt, dst), - ter(tecNO_ENTRY)) - .close(); + mcEnv.tx(xchain_commit(mcAlice, jvb_unknown, claimID, amt, dst), ter(tecNO_ENTRY)).close(); - BalanceTransfer transfer( - scEnv, Account::master, scBob, scAlice, payees, withClaim); + BalanceTransfer transfer(scEnv, Account::master, scBob, scAlice, payees, withClaim); scEnv - .tx(claim_attestation( - scAttester, - jvb_unknown, - mcAlice, - amt, - payees[0], - true, - claimID, - dst, - signers[0]), + .tx(claim_attestation(scAttester, jvb_unknown, mcAlice, amt, payees[0], true, claimID, dst, signers[0]), ter(tecNO_ENTRY)) .close(); @@ -2877,10 +2358,7 @@ struct XChain_test : public beast::unit_test::suite, BEAST_EXPECT(transfer.has_not_happened()); // need to submit a claim transactions - scEnv - .tx(xchain_claim(scAlice, jvb_unknown, claimID, amt, scBob), - ter(tecNO_ENTRY)) - .close(); + scEnv.tx(xchain_claim(scAlice, jvb_unknown, claimID, amt, scBob), ter(tecNO_ENTRY)).close(); } BEAST_EXPECT(transfer.has_not_happened()); @@ -2906,21 +2384,11 @@ struct XChain_test : public beast::unit_test::suite, std::uint32_t const claimID = 1; mcEnv.tx(xchain_commit(mcAlice, jvb, claimID, amt, dst)).close(); - BalanceTransfer transfer( - scEnv, Account::master, scBob, scAlice, payees, withClaim); + BalanceTransfer transfer(scEnv, Account::master, scBob, scAlice, payees, withClaim); // attest using non-existent claim id scEnv - .tx(claim_attestation( - scAttester, - jvb, - mcAlice, - amt, - payees[0], - true, - 999, - dst, - signers[0]), + .tx(claim_attestation(scAttester, jvb, mcAlice, amt, payees[0], true, 999, dst, signers[0]), ter(tecXCHAIN_NO_CLAIM_ID)) .close(); if (withClaim) @@ -2928,10 +2396,7 @@ struct XChain_test : public beast::unit_test::suite, BEAST_EXPECT(transfer.has_not_happened()); // claim using non-existent claim id - scEnv - .tx(xchain_claim(scAlice, jvb, 999, amt, scBob), - ter(tecXCHAIN_NO_CLAIM_ID)) - .close(); + scEnv.tx(xchain_claim(scAlice, jvb, 999, amt, scBob), ter(tecXCHAIN_NO_CLAIM_ID)).close(); } BEAST_EXPECT(transfer.has_not_happened()); @@ -2958,25 +2423,9 @@ struct XChain_test : public beast::unit_test::suite, mcEnv.tx(xchain_commit(mcAlice, jvb, claimID, amt, dst)).close(); BalanceTransfer transfer( - scEnv, - Account::master, - scBob, - scAlice, - &payees[0], - UT_XCHAIN_DEFAULT_QUORUM, - withClaim); + scEnv, Account::master, scBob, scAlice, &payees[0], UT_XCHAIN_DEFAULT_QUORUM, withClaim); - scEnv - .multiTx(claim_attestations( - scAttester, - jvb, - mcAlice, - amt, - payees, - true, - claimID, - dst, - signers)) + scEnv.multiTx(claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers)) .close(); if (withClaim) { @@ -2984,10 +2433,7 @@ struct XChain_test : public beast::unit_test::suite, // submit a claim transaction with the wrong account (scGw // instead of scAlice) - scEnv - .tx(xchain_claim(scGw, jvb, claimID, amt, scBob), - ter(tecXCHAIN_BAD_CLAIM_ID)) - .close(); + scEnv.tx(xchain_claim(scGw, jvb, claimID, amt, scBob), ter(tecXCHAIN_BAD_CLAIM_ID)).close(); BEAST_EXPECT(transfer.has_not_happened()); } else @@ -3016,8 +2462,7 @@ struct XChain_test : public beast::unit_test::suite, std::uint32_t const claimID = 1; mcEnv.tx(xchain_commit(mcAlice, jvb, claimID, amt, dst)).close(); - BalanceTransfer transfer( - scEnv, Account::master, scBob, scAlice, payees, withClaim); + BalanceTransfer transfer(scEnv, Account::master, scBob, scAlice, payees, withClaim); // don't send any attestations @@ -3026,10 +2471,7 @@ struct XChain_test : public beast::unit_test::suite, BEAST_EXPECT(transfer.has_not_happened()); // need to submit a claim transactions - scEnv - .tx(xchain_claim(scAlice, jvb, claimID, amt, scBob), - ter(tecXCHAIN_CLAIM_NO_QUORUM)) - .close(); + scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob), ter(tecXCHAIN_CLAIM_NO_QUORUM)).close(); } BEAST_EXPECT(transfer.has_not_happened()); @@ -3056,32 +2498,18 @@ struct XChain_test : public beast::unit_test::suite, std::uint32_t const claimID = 1; mcEnv.tx(xchain_commit(mcAlice, jvb, claimID, amt, dst)).close(); - BalanceTransfer transfer( - scEnv, Account::master, scBob, scAlice, payees, withClaim); + BalanceTransfer transfer(scEnv, Account::master, scBob, scAlice, payees, withClaim); auto tooFew = quorum - 1; scEnv - .multiTx(claim_attestations( - scAttester, - jvb, - mcAlice, - amt, - payees, - true, - claimID, - dst, - signers, - tooFew)) + .multiTx(claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers, tooFew)) .close(); if (withClaim) { BEAST_EXPECT(transfer.has_not_happened()); // need to submit a claim transactions - scEnv - .tx(xchain_claim(scAlice, jvb, claimID, amt, scBob), - ter(tecXCHAIN_CLAIM_NO_QUORUM)) - .close(); + scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob), ter(tecXCHAIN_CLAIM_NO_QUORUM)).close(); } BEAST_EXPECT(transfer.has_not_happened()); @@ -3107,21 +2535,11 @@ struct XChain_test : public beast::unit_test::suite, std::uint32_t const claimID = 1; mcEnv.tx(xchain_commit(mcAlice, jvb, claimID, amt, dst)).close(); - BalanceTransfer transfer( - scEnv, Account::master, scBob, scAlice, payees, withClaim); + BalanceTransfer transfer(scEnv, Account::master, scBob, scAlice, payees, withClaim); scEnv .multiTx( - claim_attestations( - scAttester, - jvb, - mcAlice, - amt, - payees, - true, - 0, - dst, - signers), + claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, 0, dst, signers), ter(tecXCHAIN_NO_CLAIM_ID)) .close(); if (withClaim) @@ -3129,10 +2547,7 @@ struct XChain_test : public beast::unit_test::suite, BEAST_EXPECT(transfer.has_not_happened()); // need to submit a claim transactions - scEnv - .tx(xchain_claim(scAlice, jvb, 0, amt, scBob), - ter(tecXCHAIN_NO_CLAIM_ID)) - .close(); + scEnv.tx(xchain_claim(scAlice, jvb, 0, amt, scBob), ter(tecXCHAIN_NO_CLAIM_ID)).close(); } BEAST_EXPECT(transfer.has_not_happened()); @@ -3162,25 +2577,9 @@ struct XChain_test : public beast::unit_test::suite, mcEnv.tx(xchain_commit(mcAlice, jvb, claimID, amt, dst)).close(); BalanceTransfer transfer( - scEnv, - Account::master, - scBob, - scAlice, - &payees[0], - UT_XCHAIN_DEFAULT_QUORUM, - withClaim); + scEnv, Account::master, scBob, scAlice, &payees[0], UT_XCHAIN_DEFAULT_QUORUM, withClaim); - scEnv - .multiTx(claim_attestations( - scAttester, - jvb, - mcAlice, - amt, - payees, - true, - claimID, - dst, - signers)) + scEnv.multiTx(claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers)) .close(); if (withClaim) @@ -3188,10 +2587,7 @@ struct XChain_test : public beast::unit_test::suite, BEAST_EXPECT(transfer.has_not_happened()); // need to submit a claim transactions - scEnv - .tx(xchain_claim(scAlice, jvb, claimID, scUSD(1000), scBob), - ter(temBAD_AMOUNT)) - .close(); + scEnv.tx(xchain_claim(scAlice, jvb, claimID, scUSD(1000), scBob), ter(temBAD_AMOUNT)).close(); } BEAST_EXPECT(transfer.has_not_happened()); @@ -3218,35 +2614,16 @@ struct XChain_test : public beast::unit_test::suite, mcEnv.tx(xchain_commit(mcAlice, jvb, claimID, amt, dst)).close(); BalanceTransfer transfer( - scEnv, - Account::master, - scBob, - scAlice, - &payees[0], - UT_XCHAIN_DEFAULT_QUORUM, - withClaim); + scEnv, Account::master, scBob, scAlice, &payees[0], UT_XCHAIN_DEFAULT_QUORUM, withClaim); - scEnv - .multiTx(claim_attestations( - scAttester, - jvb, - mcAlice, - amt, - payees, - true, - claimID, - dst, - signers)) + scEnv.multiTx(claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers)) .close(); if (withClaim) { BEAST_EXPECT(transfer.has_not_happened()); // need to submit a claim transactions - scEnv - .tx(xchain_claim(scAlice, jvb, claimID, amt, scuBob), - ter(tecNO_DST)) - .close(); + scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scuBob), ter(tecNO_DST)).close(); } BEAST_EXPECT(transfer.has_not_happened()); @@ -3276,48 +2653,20 @@ struct XChain_test : public beast::unit_test::suite, mcEnv.tx(xchain_commit(mcAlice, jvb, claimID, amt, dst)).close(); BalanceTransfer transfer( - scEnv, - Account::master, - scBob, - scAlice, - &payees[0], - UT_XCHAIN_DEFAULT_QUORUM, - withClaim); + scEnv, Account::master, scBob, scAlice, &payees[0], UT_XCHAIN_DEFAULT_QUORUM, withClaim); if (withClaim) { - scEnv - .multiTx(claim_attestations( - scAttester, - jvb, - mcAlice, - amt, - payees, - true, - claimID, - dst, - signers)) + scEnv.multiTx(claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers)) .close(); BEAST_EXPECT(transfer.has_not_happened()); // need to submit a claim transactions - scEnv - .tx(xchain_claim(scAlice, jvb, claimID, amt, scBob), - ter(tecUNFUNDED_PAYMENT)) - .close(); + scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob), ter(tecUNFUNDED_PAYMENT)).close(); } else { - auto txns = claim_attestations( - scAttester, - jvb, - mcAlice, - amt, - payees, - true, - claimID, - dst, - signers); + auto txns = claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers); for (int i = 0; i < UT_XCHAIN_DEFAULT_QUORUM - 1; ++i) { scEnv.tx(txns[i]).close(); @@ -3327,10 +2676,7 @@ struct XChain_test : public beast::unit_test::suite, // The attestation should succeed, because it adds an // attestation, but the claim should fail with insufficient // funds - scEnv - .tx(xchain_claim(scAlice, jvb, claimID, amt, scBob), - ter(tecUNFUNDED_PAYMENT)) - .close(); + scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob), ter(tecUNFUNDED_PAYMENT)).close(); } BEAST_EXPECT(transfer.has_not_happened()); @@ -3352,8 +2698,7 @@ struct XChain_test : public beast::unit_test::suite, res0 + reward, scuAlice) // just not enough because of fees .close() - .tx(xchain_create_claim_id(scuAlice, jvb, reward, mcAlice), - ter(tecINSUFFICIENT_RESERVE)) + .tx(xchain_create_claim_id(scuAlice, jvb, reward, mcAlice), ter(tecINSUFFICIENT_RESERVE)) .close(); auto dst(withClaim ? std::nullopt : std::optional{scBob}); @@ -3361,20 +2706,10 @@ struct XChain_test : public beast::unit_test::suite, std::uint32_t const claimID = 1; mcEnv.tx(xchain_commit(mcAlice, jvb, claimID, amt, dst)).close(); - BalanceTransfer transfer( - scEnv, Account::master, scBob, scuAlice, payees, withClaim); + BalanceTransfer transfer(scEnv, Account::master, scBob, scuAlice, payees, withClaim); scEnv - .tx(claim_attestation( - scAttester, - jvb, - mcAlice, - amt, - payees[0], - true, - claimID, - dst, - signers[0]), + .tx(claim_attestation(scAttester, jvb, mcAlice, amt, payees[0], true, claimID, dst, signers[0]), ter(tecXCHAIN_NO_CLAIM_ID)) .close(); if (withClaim) @@ -3382,10 +2717,7 @@ struct XChain_test : public beast::unit_test::suite, BEAST_EXPECT(transfer.has_not_happened()); // need to submit a claim transactions - scEnv - .tx(xchain_claim(scuAlice, jvb, claimID, amt, scBob), - ter(tecXCHAIN_NO_CLAIM_ID)) - .close(); + scEnv.tx(xchain_claim(scuAlice, jvb, claimID, amt, scBob), ter(tecXCHAIN_NO_CLAIM_ID)).close(); } BEAST_EXPECT(transfer.has_not_happened()); @@ -3413,23 +2745,8 @@ struct XChain_test : public beast::unit_test::suite, mcEnv.tx(xchain_commit(mcAlice, jvb, claimID, amt, dst)).close(); BalanceTransfer transfer( - scEnv, - Account::master, - scBob, - scAlice, - &payees[0], - UT_XCHAIN_DEFAULT_QUORUM, - withClaim); - auto txns = claim_attestations( - scAttester, - jvb, - mcAlice, - amt, - payees, - true, - claimID, - dst, - signers); + scEnv, Account::master, scBob, scAlice, &payees[0], UT_XCHAIN_DEFAULT_QUORUM, withClaim); + auto txns = claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers); for (int i = 0; i < UT_XCHAIN_DEFAULT_QUORUM - 1; ++i) { scEnv.tx(txns[i]).close(); @@ -3441,26 +2758,19 @@ struct XChain_test : public beast::unit_test::suite, BEAST_EXPECT(transfer.has_not_happened()); // need to submit a claim transactions - scEnv - .tx(xchain_claim(scAlice, jvb, claimID, amt, scBob), - ter(tecNO_PERMISSION)) - .close(); + scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob), ter(tecNO_PERMISSION)).close(); // the transfer failed, but check that we can still use the // claimID with a different account Balance scCarol_bal(scEnv, scCarol); - scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scCarol)) - .close(); + scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scCarol)).close(); BEAST_EXPECT(scCarol_bal.diff() == amt); } else { scEnv.tx(txns.back()).close(); - scEnv - .tx(xchain_claim(scAlice, jvb, claimID, amt, scBob), - ter(tecNO_PERMISSION)) - .close(); + scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob), ter(tecNO_PERMISSION)).close(); // A way would be to remove deposit auth and resubmit the // attestations (even though the witness servers won't do // it) @@ -3496,23 +2806,8 @@ struct XChain_test : public beast::unit_test::suite, mcEnv.tx(xchain_commit(mcAlice, jvb, claimID, amt, dst)).close(); BalanceTransfer transfer( - scEnv, - Account::master, - scBob, - scAlice, - &payees[0], - UT_XCHAIN_DEFAULT_QUORUM, - withClaim); - auto txns = claim_attestations( - scAttester, - jvb, - mcAlice, - amt, - payees, - true, - claimID, - dst, - signers); + scEnv, Account::master, scBob, scAlice, &payees[0], UT_XCHAIN_DEFAULT_QUORUM, withClaim); + auto txns = claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers); for (int i = 0; i < UT_XCHAIN_DEFAULT_QUORUM - 1; ++i) { scEnv.tx(txns[i]).close(); @@ -3523,26 +2818,19 @@ struct XChain_test : public beast::unit_test::suite, BEAST_EXPECT(transfer.has_not_happened()); // need to submit a claim transactions - scEnv - .tx(xchain_claim(scAlice, jvb, claimID, amt, scBob), - ter(tecDST_TAG_NEEDED)) - .close(); + scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob), ter(tecDST_TAG_NEEDED)).close(); // the transfer failed, but check that we can still use the // claimID with a different account Balance scCarol_bal(scEnv, scCarol); - scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scCarol)) - .close(); + scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scCarol)).close(); BEAST_EXPECT(scCarol_bal.diff() == amt); } else { scEnv.tx(txns.back()).close(); - scEnv - .tx(xchain_claim(scAlice, jvb, claimID, amt, scBob), - ter(tecDST_TAG_NEEDED)) - .close(); + scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob), ter(tecDST_TAG_NEEDED)).close(); // A way would be to remove the destination tag requirement // and resubmit the attestations (even though the witness // servers won't do it) @@ -3583,16 +2871,7 @@ struct XChain_test : public beast::unit_test::suite, // should not occur because dest account has deposit auth set Balance scBob_bal(scEnv, scBob); - scEnv.multiTx(claim_attestations( - scAttester, - jvb, - mcAlice, - amt, - payees, - true, - claimID, - dst, - signers)); + scEnv.multiTx(claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers)); BEAST_EXPECT(scBob_bal.diff() == STAmount(0)); // Check that check that we still can use the claimID to transfer @@ -3624,32 +2903,14 @@ struct XChain_test : public beast::unit_test::suite, mcEnv.tx(xchain_commit(mcAlice, jvb, claimID, amt, dst)).close(); BalanceTransfer transfer( - scEnv, - Account::master, - scBob, - scAlice, - &payees[0], - UT_XCHAIN_DEFAULT_QUORUM, - withClaim); - scEnv.multiTx(claim_attestations( - scAttester, - jvb, - mcAlice, - amt, - payees, - true, - claimID, - dst, - signers)); + scEnv, Account::master, scBob, scAlice, &payees[0], UT_XCHAIN_DEFAULT_QUORUM, withClaim); + scEnv.multiTx(claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers)); if (withClaim) { BEAST_EXPECT(transfer.has_not_happened()); // claim wrong amount - scEnv - .tx(xchain_claim(scAlice, jvb, claimID, one_xrp, scBob), - ter(tecXCHAIN_CLAIM_NO_QUORUM)) - .close(); + scEnv.tx(xchain_claim(scAlice, jvb, claimID, one_xrp, scBob), ter(tecXCHAIN_CLAIM_NO_QUORUM)).close(); } BEAST_EXPECT(transfer.has_not_happened()); @@ -3677,24 +2938,9 @@ struct XChain_test : public beast::unit_test::suite, mcEnv.tx(xchain_commit(mcAlice, jvb, claimID, amt, dst)).close(); BalanceTransfer transfer( - scEnv, - Account::master, - scBob, - scAlice, - &payees[0], - UT_XCHAIN_DEFAULT_QUORUM, - withClaim); + scEnv, Account::master, scBob, scAlice, &payees[0], UT_XCHAIN_DEFAULT_QUORUM, withClaim); Balance scAlice_bal(scEnv, scAlice); - scEnv.multiTx(claim_attestations( - scAttester, - jvb, - mcAlice, - amt, - payees, - true, - claimID, - dst, - signers)); + scEnv.multiTx(claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers)); STAmount claim_cost = reward; @@ -3703,14 +2949,12 @@ struct XChain_test : public beast::unit_test::suite, BEAST_EXPECT(transfer.has_not_happened()); // need to submit a claim transactions - scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob)) - .close(); + scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob)).close(); claim_cost += tx_fee; } BEAST_EXPECT(transfer.has_happened(amt, split_reward_quorum)); - BEAST_EXPECT( - scAlice_bal.diff() == -claim_cost); // because reward % 4 == 0 + BEAST_EXPECT(scAlice_bal.diff() == -claim_cost); // because reward % 4 == 0 } // Verify that if a reward is not evenly divisible among the reward @@ -3735,24 +2979,9 @@ struct XChain_test : public beast::unit_test::suite, mcEnv.tx(xchain_commit(mcAlice, jvb, claimID, amt, dst)).close(); BalanceTransfer transfer( - scEnv, - Account::master, - scBob, - scAlice, - &payees[0], - UT_XCHAIN_DEFAULT_QUORUM, - withClaim); + scEnv, Account::master, scBob, scAlice, &payees[0], UT_XCHAIN_DEFAULT_QUORUM, withClaim); Balance scAlice_bal(scEnv, scAlice); - scEnv.multiTx(claim_attestations( - scAttester, - jvb, - mcAlice, - amt, - payees, - true, - claimID, - dst, - signers)); + scEnv.multiTx(claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers)); STAmount claim_cost = tiny_reward; if (withClaim) @@ -3760,14 +2989,12 @@ struct XChain_test : public beast::unit_test::suite, BEAST_EXPECT(transfer.has_not_happened()); // need to submit a claim transactions - scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob)) - .close(); + scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob)).close(); claim_cost += tx_fee; } BEAST_EXPECT(transfer.has_happened(amt, tiny_reward_split)); - BEAST_EXPECT( - scAlice_bal.diff() == -(claim_cost - tiny_reward_remainder)); + BEAST_EXPECT(scAlice_bal.diff() == -(claim_cost - tiny_reward_remainder)); } // If a reward distribution fails for one of the reward accounts @@ -3797,31 +3024,15 @@ struct XChain_test : public beast::unit_test::suite, mcEnv.tx(xchain_commit(mcAlice, jvb, claimID, amt, dst)).close(); BalanceTransfer transfer( - scEnv, - Account::master, - scBob, - scAlice, - &payees[0], - UT_XCHAIN_DEFAULT_QUORUM - 1, - withClaim); - scEnv.multiTx(claim_attestations( - scAttester, - jvb, - mcAlice, - amt, - alt_payees, - true, - claimID, - dst, - signers)); + scEnv, Account::master, scBob, scAlice, &payees[0], UT_XCHAIN_DEFAULT_QUORUM - 1, withClaim); + scEnv.multiTx(claim_attestations(scAttester, jvb, mcAlice, amt, alt_payees, true, claimID, dst, signers)); if (withClaim) { BEAST_EXPECT(transfer.has_not_happened()); // need to submit a claim transactions - scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob)) - .close(); + scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob)).close(); } // this also checks that only 3 * split_reward was deducted from @@ -3856,31 +3067,15 @@ struct XChain_test : public beast::unit_test::suite, // split_reward BalanceTransfer transfer( - scEnv, - Account::master, - scBob, - scAlice, - &payees[0], - UT_XCHAIN_DEFAULT_QUORUM - 1, - withClaim); - scEnv.multiTx(claim_attestations( - scAttester, - jvb, - mcAlice, - amt, - payees, - true, - claimID, - dst, - signers)); + scEnv, Account::master, scBob, scAlice, &payees[0], UT_XCHAIN_DEFAULT_QUORUM - 1, withClaim); + scEnv.multiTx(claim_attestations(scAttester, jvb, mcAlice, amt, payees, true, claimID, dst, signers)); if (withClaim) { BEAST_EXPECT(transfer.has_not_happened()); // need to submit a claim transactions - scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob)) - .close(); + scEnv.tx(xchain_claim(scAlice, jvb, claimID, amt, scBob)).close(); } // this also checks that only 3 * split_reward was deducted from @@ -3896,9 +3091,7 @@ struct XChain_test : public beast::unit_test::suite, XEnv(*this, true) .tx(create_bridge(Account::master, jvb)) .close() - .tx(xchain_claim(scAlice, jvb, 1, XRP(1000), scBob), - txflags(tfFillOrKill), - ter(temINVALID_FLAG)) + .tx(xchain_claim(scAlice, jvb, 1, XRP(1000), scBob), txflags(tfFillOrKill), ter(temINVALID_FLAG)) .close(); // coverage test: xchain_claim transaction with xchain feature @@ -3907,16 +3100,14 @@ struct XChain_test : public beast::unit_test::suite, .tx(create_bridge(Account::master, jvb)) .disableFeature(featureXChainBridge) .close() - .tx(xchain_claim(scAlice, jvb, 1, XRP(1000), scBob), - ter(temDISABLED)) + .tx(xchain_claim(scAlice, jvb, 1, XRP(1000), scBob), ter(temDISABLED)) .close(); // coverage test: XChainClaim::preclaim - isLockingChain = true; XEnv(*this) .tx(create_bridge(mcDoor, jvb)) .close() - .tx(xchain_claim(mcAlice, jvb, 1, XRP(1000), mcBob), - ter(tecXCHAIN_NO_CLAIM_ID)); + .tx(xchain_claim(mcAlice, jvb, 1, XRP(1000), mcBob), ter(tecXCHAIN_NO_CLAIM_ID)); } void @@ -3934,27 +3125,21 @@ struct XChain_test : public beast::unit_test::suite, auto const amt = XRP(111); auto const amt_plus_reward = amt + reward; - scEnv.tx(create_bridge(Account::master, jvb)) - .tx(jtx::signers(Account::master, quorum, signers)) - .close(); + scEnv.tx(create_bridge(Account::master, jvb)).tx(jtx::signers(Account::master, quorum, signers)).close(); Balance door(scEnv, Account::master); // scEnv.tx(att_create_acct_batch1(1, amt, // Account::master)).close(); - scEnv.multiTx(att_create_acct_vec(1, amt, Account::master, 2)) - .close(); - BEAST_EXPECT(!!scEnv.caClaimID(jvb, 1)); // claim id present - BEAST_EXPECT( - scEnv.claimCount(jvb) == 0); // claim count is one less + scEnv.multiTx(att_create_acct_vec(1, amt, Account::master, 2)).close(); + BEAST_EXPECT(!!scEnv.caClaimID(jvb, 1)); // claim id present + BEAST_EXPECT(scEnv.claimCount(jvb) == 0); // claim count is one less // scEnv.tx(att_create_acct_batch2(1, amt, // Account::master)).close(); - scEnv.multiTx(att_create_acct_vec(1, amt, Account::master, 2, 2)) - .close(); - BEAST_EXPECT(!scEnv.caClaimID(jvb, 1)); // claim id deleted - BEAST_EXPECT( - scEnv.claimCount(jvb) == 1); // claim count was incremented + scEnv.multiTx(att_create_acct_vec(1, amt, Account::master, 2, 2)).close(); + BEAST_EXPECT(!scEnv.caClaimID(jvb, 1)); // claim id deleted + BEAST_EXPECT(scEnv.claimCount(jvb) == 1); // claim count was incremented BEAST_EXPECT(door.diff() == -reward); } @@ -3970,8 +3155,7 @@ struct XChain_test : public beast::unit_test::suite, Balance carol(mcEnv, mcCarol); mcEnv - .tx(sidechain_xchain_account_create( - mcCarol, jvb, scuAlice, XRP(19), reward), + .tx(sidechain_xchain_account_create(mcCarol, jvb, scuAlice, XRP(19), reward), ter(tecXCHAIN_INSUFF_CREATE_AMOUNT)) .close(); @@ -3988,8 +3172,7 @@ struct XChain_test : public beast::unit_test::suite, Balance door(mcEnv, mcDoor); mcEnv - .tx(sidechain_xchain_account_create( - mcCarol, jvb, scuAlice, XRP(20), reward), + .tx(sidechain_xchain_account_create(mcCarol, jvb, scuAlice, XRP(20), reward), txflags(tfFillOrKill), ter(temINVALID_FLAG)) .close(); @@ -4007,9 +3190,7 @@ struct XChain_test : public beast::unit_test::suite, Balance door(mcEnv, mcDoor); mcEnv.disableFeature(featureXChainBridge) - .tx(sidechain_xchain_account_create( - mcCarol, jvb, scuAlice, XRP(20), reward), - ter(temDISABLED)) + .tx(sidechain_xchain_account_create(mcCarol, jvb, scuAlice, XRP(20), reward), ter(temDISABLED)) .close(); BEAST_EXPECT(door.diff() == STAmount(0)); @@ -4023,10 +3204,7 @@ struct XChain_test : public beast::unit_test::suite, Balance door(mcEnv, mcDoor); - mcEnv - .tx(sidechain_xchain_account_create( - mcCarol, jvb, scuAlice, XRP(-20), reward), - ter(temBAD_AMOUNT)) + mcEnv.tx(sidechain_xchain_account_create(mcCarol, jvb, scuAlice, XRP(-20), reward), ter(temBAD_AMOUNT)) .close(); BEAST_EXPECT(door.diff() == STAmount(0)); @@ -4040,10 +3218,7 @@ struct XChain_test : public beast::unit_test::suite, Balance door(mcEnv, mcDoor); - mcEnv - .tx(sidechain_xchain_account_create( - mcCarol, jvb, scuAlice, XRP(20), XRP(-1)), - ter(temBAD_AMOUNT)) + mcEnv.tx(sidechain_xchain_account_create(mcCarol, jvb, scuAlice, XRP(20), XRP(-1)), ter(temBAD_AMOUNT)) .close(); BEAST_EXPECT(door.diff() == STAmount(0)); @@ -4058,9 +3233,7 @@ struct XChain_test : public beast::unit_test::suite, Balance door(mcEnv, mcDoor); mcEnv - .tx(sidechain_xchain_account_create( - mcDoor, jvb, scuAlice, XRP(20), XRP(1)), - ter(tecXCHAIN_SELF_COMMIT)) + .tx(sidechain_xchain_account_create(mcDoor, jvb, scuAlice, XRP(20), XRP(1)), ter(tecXCHAIN_SELF_COMMIT)) .close(); BEAST_EXPECT(door.diff() == -tx_fee); @@ -4075,8 +3248,7 @@ struct XChain_test : public beast::unit_test::suite, Balance door(mcEnv, mcDoor); mcEnv - .tx(sidechain_xchain_account_create( - mcCarol, jvb, scuAlice, XRP(20), XRP(2)), + .tx(sidechain_xchain_account_create(mcCarol, jvb, scuAlice, XRP(20), XRP(2)), ter(tecXCHAIN_REWARD_MISMATCH)) .close(); @@ -4098,8 +3270,7 @@ struct XChain_test : public beast::unit_test::suite, .tx(create_bridge(mcDoor, jvb)) .fund(res0 + one_xrp + tx_fee - drops(1), mcuAlice) .close() - .tx(xchain_commit(mcuAlice, jvb, 1, one_xrp, scBob), - ter(tesSUCCESS)); + .tx(xchain_commit(mcuAlice, jvb, 1, one_xrp, scBob), ter(tesSUCCESS)); // commit where the commit amount drips into the reserve, this should // fail @@ -4107,8 +3278,7 @@ struct XChain_test : public beast::unit_test::suite, .tx(create_bridge(mcDoor, jvb)) .fund(res0 + one_xrp - drops(1), mcuAlice) .close() - .tx(xchain_commit(mcuAlice, jvb, 1, one_xrp, scBob), - ter(tecUNFUNDED_PAYMENT)); + .tx(xchain_commit(mcuAlice, jvb, 1, one_xrp, scBob), ter(tecUNFUNDED_PAYMENT)); auto const minAccountCreate = XRP(20); @@ -4116,12 +3286,9 @@ struct XChain_test : public beast::unit_test::suite, // this should succeed XEnv(*this) .tx(create_bridge(mcDoor, jvb, reward, minAccountCreate)) - .fund( - res0 + tx_fee + minAccountCreate + reward - drops(1), mcuAlice) + .fund(res0 + tx_fee + minAccountCreate + reward - drops(1), mcuAlice) .close() - .tx(sidechain_xchain_account_create( - mcuAlice, jvb, scuAlice, minAccountCreate, reward), - ter(tesSUCCESS)); + .tx(sidechain_xchain_account_create(mcuAlice, jvb, scuAlice, minAccountCreate, reward), ter(tesSUCCESS)); // account create commit where the commit dips into the reserve, // this should fail @@ -4129,8 +3296,7 @@ struct XChain_test : public beast::unit_test::suite, .tx(create_bridge(mcDoor, jvb, reward, minAccountCreate)) .fund(res0 + minAccountCreate + reward - drops(1), mcuAlice) .close() - .tx(sidechain_xchain_account_create( - mcuAlice, jvb, scuAlice, minAccountCreate, reward), + .tx(sidechain_xchain_account_create(mcuAlice, jvb, scuAlice, minAccountCreate, reward), ter(tecUNFUNDED_PAYMENT)); } @@ -4141,8 +3307,7 @@ struct XChain_test : public beast::unit_test::suite, testcase("Bridge Delete Door Account"); - auto const acctDelFee{ - drops(XEnv(*this).env_.current()->fees().increment)}; + auto const acctDelFee{drops(XEnv(*this).env_.current()->fees().increment)}; // Deleting an account that owns bridge should fail { @@ -4156,10 +3321,7 @@ struct XChain_test : public beast::unit_test::suite, mcEnv.close(); // try to delete mcDoor, send funds to mcAlice - mcEnv.tx( - acctdelete(mcDoor, mcAlice), - fee(acctDelFee), - ter(tecHAS_OBLIGATIONS)); + mcEnv.tx(acctdelete(mcDoor, mcAlice), fee(acctDelFee), ter(tecHAS_OBLIGATIONS)); } // Deleting an account that owns a claim id should fail @@ -4177,10 +3339,7 @@ struct XChain_test : public beast::unit_test::suite, scEnv.close(); // try to delete scAlice, send funds to scBob - scEnv.tx( - acctdelete(scAlice, scBob), - fee(acctDelFee), - ter(tecHAS_OBLIGATIONS)); + scEnv.tx(acctdelete(scAlice, scBob), fee(acctDelFee), ter(tecHAS_OBLIGATIONS)); } } @@ -4196,11 +3355,8 @@ struct XChain_test : public beast::unit_test::suite, std::uint32_t const claimID = 1; std::optional dst{scBob}; auto const amt = XRP(1000); - scEnv.tx(create_bridge(Account::master, jvb)) - .tx(jtx::signers(Account::master, quorum, signers)) - .close(); - scEnv.tx(xchain_create_claim_id(scAlice, jvb, reward, mcAlice)) - .close(); + scEnv.tx(create_bridge(Account::master, jvb)).tx(jtx::signers(Account::master, quorum, signers)).close(); + scEnv.tx(xchain_create_claim_id(scAlice, jvb, reward, mcAlice)).close(); auto jvAtt = claim_attestation( scAttester, jvb, @@ -4227,9 +3383,7 @@ struct XChain_test : public beast::unit_test::suite, Account dst{scBob}; auto const amt = XRP(1000); auto const rewardAmt = XRP(1); - scEnv.tx(create_bridge(Account::master, jvb)) - .tx(jtx::signers(Account::master, quorum, signers)) - .close(); + scEnv.tx(create_bridge(Account::master, jvb)).tx(jtx::signers(Account::master, quorum, signers)).close(); auto jvAtt = create_account_attestation( scAttester, jvb, @@ -4263,7 +3417,7 @@ struct XChain_test : public beast::unit_test::suite, testXChainCommit(); testXChainAddAttestation(); testXChainAddClaimNonBatchAttestation(); - testXChainAddAccountCreateNonBatchAttestation(); + testXChainAddAccountCreateNonBatchAttestation(); // cspell: disable-line testXChainClaim(); testXChainCreateAccount(); testFeeDipsIntoReserve(); @@ -4274,8 +3428,7 @@ struct XChain_test : public beast::unit_test::suite, // ----------------------------------------------------------- // ----------------------------------------------------------- -struct XChainSim_test : public beast::unit_test::suite, - public jtx::XChainBridgeObjects +struct XChainSim_test : public beast::unit_test::suite, public jtx::XChainBridgeObjects { private: static constexpr size_t num_signers = 5; @@ -4338,8 +3491,7 @@ private: using CreateClaimVec = jtx::JValueVec; using CreateClaimMap = std::map; - ChainStateTrack(ENV& env) - : env(env), tx_fee(env.env_.current()->fees().base) + ChainStateTrack(ENV& env) : env(env), tx_fee(env.env_.current()->fees().base) { } @@ -4355,10 +3507,7 @@ private: } uint32_t - sendCreateAttestations( - size_t signer_idx, - BridgeID bridge, - CreateClaimVec& claims) + sendCreateAttestations(size_t signer_idx, BridgeID bridge, CreateClaimVec& claims) { size_t num_successful = 0; for (auto const& c : claims) @@ -4386,6 +3535,7 @@ private: do { callback_called = false; + // cspell: ignore attns for (size_t i = 0; i < signers_attns.size(); ++i) { for (auto& [bridge, claims] : signers_attns[i]) @@ -4393,13 +3543,11 @@ private: sendAttestations(i, bridge, claims.xfer_claims); auto& c = counters[bridge]; - auto& create_claims = - claims.create_claims[c.claim_count]; + auto& create_claims = claims.create_claims[c.claim_count]; auto num_attns = create_claims.size(); if (num_attns) { - c.num_create_attn_sent += sendCreateAttestations( - i, bridge, create_claims); + c.num_create_attn_sent += sendCreateAttestations(i, bridge, create_claims); } assert(claims.create_claims[c.claim_count].empty()); } @@ -4425,10 +3573,7 @@ private: } void - receive( - jtx::Account const& acct, - STAmount amt, - std::uint64_t divisor = 1) + receive(jtx::Account const& acct, STAmount amt, std::uint64_t divisor = 1) { if (amt.issue() != xrpIssue()) return; @@ -4441,11 +3586,7 @@ private: else { it->second.expectedDiff += - (divisor == 1 ? amt - : divide( - amt, - STAmount(amt.issue(), divisor), - amt.issue())); + (divisor == 1 ? amt : divide(amt, STAmount(amt.issue(), divisor), amt.issue())); } } @@ -4454,12 +3595,7 @@ private: { if (amt.issue() != xrpIssue()) return; - receive( - acct, - times == 1 - ? -amt - : -multiply( - amt, STAmount(amt.issue(), times), amt.issue())); + receive(acct, times == 1 ? -amt : -multiply(amt, STAmount(amt.issue(), times), amt.issue())); } void @@ -4486,14 +3622,12 @@ private: struct BridgeCounters { - using complete_cb = - std::function const& signers)>; + using complete_cb = std::function const& signers)>; uint32_t claim_id{0}; uint32_t create_count{0}; // for account create. First should be 1 - uint32_t claim_count{ - 0}; // for account create. Increments after quorum for - // current create_count (starts at 1) is reached. + uint32_t claim_count{0}; // for account create. Increments after quorum for + // current create_count (starts at 1) is reached. uint32_t num_create_attn_sent{0}; // for current claim_count std::vector signers; @@ -4562,9 +3696,7 @@ private: class SmBase { public: - SmBase( - std::shared_ptr const& chainstate, - BridgeDef const& bridge) + SmBase(std::shared_ptr const& chainstate, BridgeDef const& bridge) : bridge_(bridge), st_(chainstate) { } @@ -4608,9 +3740,7 @@ private: std::shared_ptr const& chainstate, BridgeDef const& bridge, AccountCreate create) - : Base(chainstate, bridge) - , sm_state(st_initial) - , cr(std::move(create)) + : Base(chainstate, bridge), sm_state(st_initial), cr(std::move(create)) { } @@ -4626,9 +3756,7 @@ private: ChainStateTrack& st = srcState(); jtx::Account const& srcdoor = srcDoor(); - st.env - .tx(sidechain_xchain_account_create( - cr.from, bridge_.jvb, cr.to, cr.amt, cr.reward)) + st.env.tx(sidechain_xchain_account_create(cr.from, bridge_.jvb, cr.to, cr.amt, cr.reward)) .close(); // needed for claim_id sequence to be correct' st.spendFee(cr.from); st.transfer(cr.from, srcdoor, cr.amt); @@ -4653,9 +3781,8 @@ private: // enqueue one attestation for this signer cr.attested[signer_idx] = true; - st.signers_attns[signer_idx][&bridge_] - .create_claims[cr.claim_id - 1] - .emplace_back(create_account_attestation( + st.signers_attns[signer_idx][&bridge_].create_claims[cr.claim_id - 1].emplace_back( + create_account_attestation( bridge_.signers[signer_idx].account, bridge_.jvb, cr.from, @@ -4680,9 +3807,7 @@ private: auto complete_cb = [&](std::vector const& signers) { auto num_attestors = signers.size(); st.env.close(); - assert( - num_attestors <= - std::count(cr.attested.begin(), cr.attested.end(), true)); + assert(num_attestors <= std::count(cr.attested.begin(), cr.attested.end(), true)); assert(num_attestors >= bridge_.quorum); assert(cr.claim_id - 1 == counters.claim_count); @@ -4736,13 +3861,8 @@ private: public: using Base = SmBase; - SmTransfer( - std::shared_ptr const& chainstate, - BridgeDef const& bridge, - Transfer xfer) - : Base(chainstate, bridge) - , xfer(std::move(xfer)) - , sm_state(st_initial) + SmTransfer(std::shared_ptr const& chainstate, BridgeDef const& bridge, Transfer xfer) + : Base(chainstate, bridge), xfer(std::move(xfer)), sm_state(st_initial) { } @@ -4757,9 +3877,7 @@ private: { ChainStateTrack& st = destState(); - st.env - .tx(xchain_create_claim_id( - xfer.to, bridge_.jvb, bridge_.reward, xfer.from)) + st.env.tx(xchain_create_claim_id(xfer.to, bridge_.jvb, bridge_.reward, xfer.from)) .close(); // needed for claim_id sequence to be // correct' st.spendFee(xfer.to); @@ -4782,9 +3900,7 @@ private: bridge_.jvb, xfer.claim_id, xfer.amt, - xfer.with_claim == WithClaim::yes - ? std::nullopt - : std::optional(xfer.finaldest))); + xfer.with_claim == WithClaim::yes ? std::nullopt : std::optional(xfer.finaldest))); st.spendFee(xfer.from); st.transfer(xfer.from, srcdoor, xfer.amt); } @@ -4817,27 +3933,22 @@ private: // enqueue one attestation for this signer xfer.attested[signer_idx] = true; - st.signers_attns[signer_idx][&bridge_] - .xfer_claims.emplace_back(claim_attestation( - bridge_.signers[signer_idx].account, - bridge_.jvb, - xfer.from, - xfer.amt, - bridge_.signers[signer_idx].account, - xfer.a2b, - xfer.claim_id, - xfer.with_claim == WithClaim::yes - ? std::nullopt - : std::optional(xfer.finaldest), - bridge_.signers[signer_idx])); + st.signers_attns[signer_idx][&bridge_].xfer_claims.emplace_back(claim_attestation( + bridge_.signers[signer_idx].account, + bridge_.jvb, + xfer.from, + xfer.amt, + bridge_.signers[signer_idx].account, + xfer.a2b, + xfer.claim_id, + xfer.with_claim == WithClaim::yes ? std::nullopt : std::optional(xfer.finaldest), + bridge_.signers[signer_idx])); break; } } // return true if quorum was reached, false otherwise - bool quorum = - std::count(xfer.attested.begin(), xfer.attested.end(), true) >= - bridge_.quorum; + bool quorum = std::count(xfer.attested.begin(), xfer.attested.end(), true) >= bridge_.quorum; if (quorum && xfer.with_claim == WithClaim::no) { distribute_reward(st); @@ -4850,8 +3961,7 @@ private: claim() { ChainStateTrack& st = destState(); - st.env.tx(xchain_claim( - xfer.to, bridge_.jvb, xfer.claim_id, xfer.amt, xfer.finaldest)); + st.env.tx(xchain_claim(xfer.to, bridge_.jvb, xfer.claim_id, xfer.amt, xfer.finaldest)); distribute_reward(st); st.transfer(dstDoor(), xfer.finaldest, xfer.amt); st.spendFee(xfer.to); @@ -4873,10 +3983,8 @@ private: break; case st_attesting: - sm_state = attest(time, rnd) - ? (xfer.with_claim == WithClaim::yes ? st_attested - : st_completed) - : st_attesting; + sm_state = attest(time, rnd) ? (xfer.with_claim == WithClaim::yes ? st_attested : st_completed) + : st_attesting; break; case st_attested: @@ -4911,25 +4019,18 @@ private: BridgeDef const& bridge, Transfer transfer) { - sm_.emplace_back( - time, SmTransfer(chainstate, bridge, std::move(transfer))); + sm_.emplace_back(time, SmTransfer(chainstate, bridge, std::move(transfer))); } void - ac(uint64_t time, - std::shared_ptr const& chainstate, - BridgeDef const& bridge, - AccountCreate ac) + ac(uint64_t time, std::shared_ptr const& chainstate, BridgeDef const& bridge, AccountCreate ac) { - sm_.emplace_back( - time, SmCreateAccount(chainstate, bridge, std::move(ac))); + sm_.emplace_back(time, SmCreateAccount(chainstate, bridge, std::move(ac))); } public: void - runSimulation( - std::shared_ptr const& st, - bool verify_balances = true) + runSimulation(std::shared_ptr const& st, bool verify_balances = true) { using namespace jtx; uint64_t time = 0; @@ -4980,8 +4081,7 @@ public: // create 10 accounts + door funded on both chains, and store // in ChainStateTracker the initial amount of these accounts - Account doorXRPLocking("doorXRPLocking"), - doorUSDLocking("doorUSDLocking"), doorUSDIssuing("doorUSDIssuing"); + Account doorXRPLocking("doorXRPLocking"), doorUSDLocking("doorUSDLocking"), doorUSDIssuing("doorUSDIssuing"); constexpr size_t num_acct = 10; auto a = [&doorXRPLocking, &doorUSDLocking, &doorUSDIssuing]() { @@ -4989,9 +4089,7 @@ public: std::vector result; result.reserve(num_acct); for (int i = 0; i < num_acct; ++i) - result.emplace_back( - "a"s + std::to_string(i), - (i % 2) ? KeyType::ed25519 : KeyType::secp256k1); + result.emplace_back("a"s + std::to_string(i), (i % 2) ? KeyType::ed25519 : KeyType::secp256k1); result.emplace_back("doorXRPLocking"); doorXRPLocking = result.back(); result.emplace_back("doorUSDLocking"); @@ -5040,9 +4138,7 @@ public: std::vector result; result.reserve(num_ua); for (int i = 0; i < num_ua; ++i) - result.emplace_back( - "ua"s + std::to_string(i), - (i % 2) ? KeyType::ed25519 : KeyType::secp256k1); + result.emplace_back("ua"s + std::to_string(i), (i % 2) ? KeyType::ed25519 : KeyType::secp256k1); return result; }(); @@ -5056,30 +4152,14 @@ public: // create XRP -> XRP bridge // ------------------------ BridgeDef xrp_b{ - doorXRPLocking, - xrpIssue(), - Account::master, - xrpIssue(), - XRP(1), - XRP(20), - quorum, - signers, - Json::nullValue}; + doorXRPLocking, xrpIssue(), Account::master, xrpIssue(), XRP(1), XRP(20), quorum, signers, Json::nullValue}; initBridge(xrp_b); // create USD -> USD bridge // ------------------------ BridgeDef usd_b{ - doorUSDLocking, - usdLocking, - doorUSDIssuing, - usdIssuing, - XRP(1), - XRP(20), - quorum, - signers, - Json::nullValue}; + doorUSDLocking, usdLocking, doorUSDIssuing, usdIssuing, XRP(1), XRP(20), quorum, signers, Json::nullValue}; initBridge(usd_b); diff --git a/src/test/app/tx/apply_test.cpp b/src/test/app/tx/apply_test.cpp index 6f9473ce69..fada168112 100644 --- a/src/test/app/tx/apply_test.cpp +++ b/src/test/app/tx/apply_test.cpp @@ -36,8 +36,7 @@ public: STTx const tx = *std::make_shared(std::ref(sitTrans)); { - test::jtx::Env fully_canonical( - *this, test::jtx::testable_amendments()); + test::jtx::Env fully_canonical(*this, test::jtx::testable_amendments()); Validity valid = checkValidity( fully_canonical.app().getHashRouter(), diff --git a/src/test/basics/Buffer_test.cpp b/src/test/basics/Buffer_test.cpp index cb3c48484b..908650982c 100644 --- a/src/test/basics/Buffer_test.cpp +++ b/src/test/basics/Buffer_test.cpp @@ -21,10 +21,9 @@ struct Buffer_test : beast::unit_test::suite void run() override { - std::uint8_t const data[] = { - 0xa8, 0xa1, 0x38, 0x45, 0x23, 0xec, 0xe4, 0x23, 0x71, 0x6d, 0x2a, - 0x18, 0xb4, 0x70, 0xcb, 0xf5, 0xac, 0x2d, 0x89, 0x4d, 0x19, 0x9c, - 0xf0, 0x2c, 0x15, 0xd1, 0xf9, 0x9b, 0x66, 0xd2, 0x30, 0xd3}; + std::uint8_t const data[] = {0xa8, 0xa1, 0x38, 0x45, 0x23, 0xec, 0xe4, 0x23, 0x71, 0x6d, 0x2a, + 0x18, 0xb4, 0x70, 0xcb, 0xf5, 0xac, 0x2d, 0x89, 0x4d, 0x19, 0x9c, + 0xf0, 0x2c, 0x15, 0xd1, 0xf9, 0x9b, 0x66, 0xd2, 0x30, 0xd3}; Buffer b0; BEAST_EXPECT(sane(b0)); @@ -100,8 +99,7 @@ struct Buffer_test : beast::unit_test::suite { testcase("Move Construction / Assignment"); - static_assert( - std::is_nothrow_move_constructible::value, ""); + static_assert(std::is_nothrow_move_constructible::value, ""); static_assert(std::is_nothrow_move_assignable::value, ""); { // Move-construct from empty buf diff --git a/src/test/basics/Expected_test.cpp b/src/test/basics/Expected_test.cpp index 010a6fbb8e..186e34d2e0 100644 --- a/src/test/basics/Expected_test.cpp +++ b/src/test/basics/Expected_test.cpp @@ -18,9 +18,7 @@ struct Expected_test : beast::unit_test::suite { // Test non-error const construction. { - auto const expected = []() -> Expected { - return "Valid value"; - }(); + auto const expected = []() -> Expected { return "Valid value"; }(); BEAST_EXPECT(expected); BEAST_EXPECT(expected.has_value()); BEAST_EXPECT(expected.value() == "Valid value"); @@ -42,9 +40,7 @@ struct Expected_test : beast::unit_test::suite } // Test non-error non-const construction. { - auto expected = []() -> Expected { - return "Valid value"; - }(); + auto expected = []() -> Expected { return "Valid value"; }(); BEAST_EXPECT(expected); BEAST_EXPECT(expected.has_value()); BEAST_EXPECT(expected.value() == "Valid value"); @@ -68,9 +64,7 @@ struct Expected_test : beast::unit_test::suite } // Test non-error overlapping type construction. { - auto expected = []() -> Expected { - return 1; - }(); + auto expected = []() -> Expected { return 1; }(); BEAST_EXPECT(expected); BEAST_EXPECT(expected.has_value()); BEAST_EXPECT(expected.value() == 1); @@ -91,9 +85,7 @@ struct Expected_test : beast::unit_test::suite } // Test error construction from rvalue. { - auto const expected = []() -> Expected { - return Unexpected(telLOCAL_ERROR); - }(); + auto const expected = []() -> Expected { return Unexpected(telLOCAL_ERROR); }(); BEAST_EXPECT(!expected); BEAST_EXPECT(!expected.has_value()); BEAST_EXPECT(expected.error() == telLOCAL_ERROR); @@ -114,9 +106,7 @@ struct Expected_test : beast::unit_test::suite // Test error construction from lvalue. { auto const err(telLOCAL_ERROR); - auto expected = [&err]() -> Expected { - return Unexpected(err); - }(); + auto expected = [&err]() -> Expected { return Unexpected(err); }(); BEAST_EXPECT(!expected); BEAST_EXPECT(!expected.has_value()); BEAST_EXPECT(expected.error() == telLOCAL_ERROR); @@ -136,19 +126,14 @@ struct Expected_test : beast::unit_test::suite } // Test error construction from const char*. { - auto const expected = []() -> Expected { - return Unexpected("Not what is expected!"); - }(); + auto const expected = []() -> Expected { return Unexpected("Not what is expected!"); }(); BEAST_EXPECT(!expected); BEAST_EXPECT(!expected.has_value()); - BEAST_EXPECT( - expected.error() == std::string("Not what is expected!")); + BEAST_EXPECT(expected.error() == std::string("Not what is expected!")); } // Test error construction of string from const char*. { - auto expected = []() -> Expected { - return Unexpected("Not what is expected!"); - }(); + auto expected = []() -> Expected { return Unexpected("Not what is expected!"); }(); BEAST_EXPECT(!expected); BEAST_EXPECT(!expected.has_value()); BEAST_EXPECT(expected.error() == "Not what is expected!"); @@ -157,9 +142,7 @@ struct Expected_test : beast::unit_test::suite } // Test non-error const construction of Expected. { - auto const expected = []() -> Expected { - return {}; - }(); + auto const expected = []() -> Expected { return {}; }(); BEAST_EXPECT(expected); bool throwOccurred = false; try @@ -176,9 +159,7 @@ struct Expected_test : beast::unit_test::suite } // Test non-error non-const construction of Expected. { - auto expected = []() -> Expected { - return {}; - }(); + auto expected = []() -> Expected { return {}; }(); BEAST_EXPECT(expected); bool throwOccurred = false; try @@ -195,17 +176,13 @@ struct Expected_test : beast::unit_test::suite } // Test error const construction of Expected. { - auto const expected = []() -> Expected { - return Unexpected("Not what is expected!"); - }(); + auto const expected = []() -> Expected { return Unexpected("Not what is expected!"); }(); BEAST_EXPECT(!expected); BEAST_EXPECT(expected.error() == "Not what is expected!"); } // Test error non-const construction of Expected. { - auto expected = []() -> Expected { - return Unexpected("Not what is expected!"); - }(); + auto expected = []() -> Expected { return Unexpected("Not what is expected!"); }(); BEAST_EXPECT(!expected); BEAST_EXPECT(expected.error() == "Not what is expected!"); std::string const s(std::move(expected.error())); diff --git a/src/test/basics/FileUtilities_test.cpp b/src/test/basics/FileUtilities_test.cpp index c655e4d1bc..d8664448d6 100644 --- a/src/test/basics/FileUtilities_test.cpp +++ b/src/test/basics/FileUtilities_test.cpp @@ -15,14 +15,9 @@ public: using namespace xrpl::detail; using namespace boost::system; - constexpr char const* expectedContents = - "This file is very short. That's all we need."; + constexpr char const* expectedContents = "This file is very short. That's all we need."; - FileDirGuard file( - *this, - "test_file", - "test.txt", - "This is temporary text that should get overwritten"); + FileDirGuard file(*this, "test_file", "test.txt", "This is temporary text that should get overwritten"); error_code ec; auto const path = file.file(); @@ -47,8 +42,7 @@ public: { // Test with small max auto const bad = getFileContents(ec, path, 16); - BEAST_EXPECT( - ec && ec.value() == boost::system::errc::file_too_large); + BEAST_EXPECT(ec && ec.value() == boost::system::errc::file_too_large); BEAST_EXPECT(bad.empty()); } } diff --git a/src/test/basics/IOUAmount_test.cpp b/src/test/basics/IOUAmount_test.cpp index d299f439d4..73ab0343cd 100644 --- a/src/test/basics/IOUAmount_test.cpp +++ b/src/test/basics/IOUAmount_test.cpp @@ -148,8 +148,7 @@ public: BEAST_EXPECTS(result == expected, ss.str()); }; - for (auto const mantissaSize : - {MantissaRange::small, MantissaRange::large}) + for (auto const mantissaSize : {MantissaRange::small, MantissaRange::large}) { NumberMantissaScaleGuard mg(mantissaSize); @@ -203,19 +202,16 @@ public: BEAST_EXPECT(tiny == mulRatio(tiny, maxUInt - 1, maxUInt, true)); // rounding down should be zero BEAST_EXPECT(beast::zero == mulRatio(tiny, 1, maxUInt, false)); - BEAST_EXPECT( - beast::zero == mulRatio(tiny, maxUInt - 1, maxUInt, false)); + BEAST_EXPECT(beast::zero == mulRatio(tiny, maxUInt - 1, maxUInt, false)); // tiny negative numbers IOUAmount tinyNeg(-minMantissa, minExponent); // Round up should give zero BEAST_EXPECT(beast::zero == mulRatio(tinyNeg, 1, maxUInt, true)); - BEAST_EXPECT( - beast::zero == mulRatio(tinyNeg, maxUInt - 1, maxUInt, true)); + BEAST_EXPECT(beast::zero == mulRatio(tinyNeg, maxUInt - 1, maxUInt, true)); // rounding down should be tiny BEAST_EXPECT(tinyNeg == mulRatio(tinyNeg, 1, maxUInt, false)); - BEAST_EXPECT( - tinyNeg == mulRatio(tinyNeg, maxUInt - 1, maxUInt, false)); + BEAST_EXPECT(tinyNeg == mulRatio(tinyNeg, maxUInt - 1, maxUInt, false)); } { // rounding @@ -235,8 +231,7 @@ public: { IOUAmount negOne(-1, 0); auto const rup = mulRatio(negOne, maxUInt - 1, maxUInt, true); - auto const rdown = - mulRatio(negOne, maxUInt - 1, maxUInt, false); + auto const rdown = mulRatio(negOne, maxUInt - 1, maxUInt, false); BEAST_EXPECT(rup.mantissa() - rdown.mantissa() == 1); } } diff --git a/src/test/basics/IntrusiveShared_test.cpp b/src/test/basics/IntrusiveShared_test.cpp index 500b6e7e39..d0aa4c75e9 100644 --- a/src/test/basics/IntrusiveShared_test.cpp +++ b/src/test/basics/IntrusiveShared_test.cpp @@ -96,13 +96,11 @@ public: { for (int i = 0; i < maxStates; ++i) { - state[i].store( - TrackedState::uninitialized, std::memory_order_release); + state[i].store(TrackedState::uninitialized, std::memory_order_release); } nextId.store(0, std::memory_order_release); if (resetCallback) - TIBase::tracingCallback_ = [](TrackedState, - std::optional) {}; + TIBase::tracingCallback_ = [](TrackedState, std::optional) {}; } struct ResetStatesGuard @@ -129,8 +127,7 @@ public: using enum TrackedState; assert(state.size() > id_); - tracingCallback_( - state[id_].load(std::memory_order_relaxed), deletedStarted); + tracingCallback_(state[id_].load(std::memory_order_relaxed), deletedStarted); assert(state.size() > id_); // Use relaxed memory order to try to avoid atomic operations from @@ -152,9 +149,7 @@ public: using enum TrackedState; assert(state.size() > id_); - tracingCallback_( - state[id_].load(std::memory_order_relaxed), - partiallyDeletedStarted); + tracingCallback_(state[id_].load(std::memory_order_relaxed), partiallyDeletedStarted); assert(state.size() > id_); state[id_].store(partiallyDeletedStarted, std::memory_order_relaxed); @@ -167,8 +162,7 @@ public: tracingCallback_(partiallyDeleted, std::nullopt); } - static std::function)> - tracingCallback_; + static std::function)> tracingCallback_; int id_; @@ -183,8 +177,8 @@ private: std::array, TIBase::maxStates> TIBase::state; std::atomic TIBase::nextId{0}; -std::function)> - TIBase::tracingCallback_ = [](TrackedState, std::optional) {}; +std::function)> TIBase::tracingCallback_ = + [](TrackedState, std::optional) {}; } // namespace @@ -387,8 +381,7 @@ public: bool destructorRan = false; bool partialDeleteRan = false; std::latch partialDeleteStartedSyncPoint{2}; - strong->tracingCallback_ = [&](TrackedState cur, - std::optional next) { + strong->tracingCallback_ = [&](TrackedState cur, std::optional next) { using enum TrackedState; if (next == deletedStarted) { @@ -455,8 +448,7 @@ public: bool destructorRan = false; bool partialDeleteRan = false; std::latch weakResetSyncPoint{2}; - strong->tracingCallback_ = [&](TrackedState cur, - std::optional next) { + strong->tracingCallback_ = [&](TrackedState cur, std::optional next) { using enum TrackedState; if (next == partiallyDeleted) { @@ -502,14 +494,9 @@ public: int s = destructionState.load(std::memory_order_relaxed); return {(s & 1) != 0, (s & 2) != 0}; }; - auto setDestructorRan = [&]() -> void { - destructionState.fetch_or(1, std::memory_order_acq_rel); - }; - auto setPartialDeleteRan = [&]() -> void { - destructionState.fetch_or(2, std::memory_order_acq_rel); - }; - auto tracingCallback = [&](TrackedState cur, - std::optional next) { + auto setDestructorRan = [&]() -> void { destructionState.fetch_or(1, std::memory_order_acq_rel); }; + auto setPartialDeleteRan = [&]() -> void { destructionState.fetch_or(2, std::memory_order_acq_rel); }; + auto tracingCallback = [&](TrackedState cur, std::optional next) { using enum TrackedState; auto [destructorRan, partialDeleteRan] = getDestructorState(); if (next == partiallyDeleted) @@ -523,13 +510,9 @@ public: setDestructorRan(); } }; - auto createVecOfPointers = [&](auto const& toClone, - std::default_random_engine& eng) - -> std::vector< - std::variant, WeakIntrusive>> { - std::vector< - std::variant, WeakIntrusive>> - result; + auto createVecOfPointers = [&](auto const& toClone, std::default_random_engine& eng) + -> std::vector, WeakIntrusive>> { + std::vector, WeakIntrusive>> result; std::uniform_int_distribution<> toCreateDist(4, 64); std::uniform_int_distribution<> isStrongDist(0, 1); auto numToCreate = toCreateDist(eng); @@ -581,8 +564,7 @@ public: // clear the temporary variables. rsg.emplace(false); - auto [destructorRan, partialDeleteRan] = - getDestructorState(); + auto [destructorRan, partialDeleteRan] = getDestructorState(); BEAST_EXPECT(!i || destructorRan); destructionState.store(0, std::memory_order_release); @@ -596,8 +578,7 @@ public: // ------ Sync Point ------ postCreateToCloneSyncPoint.arrive_and_wait(); - auto v = - createVecOfPointers(toClone[threadId], engines[threadId]); + auto v = createVecOfPointers(toClone[threadId], engines[threadId]); toClone[threadId].reset(); // ------ Sync Point ------ @@ -642,14 +623,9 @@ public: int s = destructionState.load(std::memory_order_relaxed); return {(s & 1) != 0, (s & 2) != 0}; }; - auto setDestructorRan = [&]() -> void { - destructionState.fetch_or(1, std::memory_order_acq_rel); - }; - auto setPartialDeleteRan = [&]() -> void { - destructionState.fetch_or(2, std::memory_order_acq_rel); - }; - auto tracingCallback = [&](TrackedState cur, - std::optional next) { + auto setDestructorRan = [&]() -> void { destructionState.fetch_or(1, std::memory_order_acq_rel); }; + auto setPartialDeleteRan = [&]() -> void { destructionState.fetch_or(2, std::memory_order_acq_rel); }; + auto tracingCallback = [&](TrackedState cur, std::optional next) { using enum TrackedState; auto [destructorRan, partialDeleteRan] = getDestructorState(); if (next == partiallyDeleted) @@ -664,8 +640,7 @@ public: } }; auto createVecOfPointers = [&](auto const& toClone, - std::default_random_engine& eng) - -> std::vector> { + std::default_random_engine& eng) -> std::vector> { std::vector> result; std::uniform_int_distribution<> toCreateDist(4, 64); auto numToCreate = toCreateDist(eng); @@ -710,8 +685,7 @@ public: // thread will also check that the destructor ran and // clear the temporary variables. rsg.emplace(false); - auto [destructorRan, partialDeleteRan] = - getDestructorState(); + auto [destructorRan, partialDeleteRan] = getDestructorState(); BEAST_EXPECT(!i || destructorRan); destructionState.store(0, std::memory_order_release); @@ -725,8 +699,7 @@ public: // ------ Sync Point ------ postCreateToCloneSyncPoint.arrive_and_wait(); - auto v = - createVecOfPointers(toClone[threadId], engines[threadId]); + auto v = createVecOfPointers(toClone[threadId], engines[threadId]); toClone[threadId].reset(); // ------ Sync Point ------ @@ -785,14 +758,9 @@ public: int s = destructionState.load(std::memory_order_relaxed); return {(s & 1) != 0, (s & 2) != 0}; }; - auto setDestructorRan = [&]() -> void { - destructionState.fetch_or(1, std::memory_order_acq_rel); - }; - auto setPartialDeleteRan = [&]() -> void { - destructionState.fetch_or(2, std::memory_order_acq_rel); - }; - auto tracingCallback = [&](TrackedState cur, - std::optional next) { + auto setDestructorRan = [&]() -> void { destructionState.fetch_or(1, std::memory_order_acq_rel); }; + auto setPartialDeleteRan = [&]() -> void { destructionState.fetch_or(2, std::memory_order_acq_rel); }; + auto tracingCallback = [&](TrackedState cur, std::optional next) { using enum TrackedState; auto [destructorRan, partialDeleteRan] = getDestructorState(); if (next == partiallyDeleted) @@ -833,8 +801,7 @@ public: // thread will also check that the destructor ran and // clear the temporary variables. rsg.emplace(false); - auto [destructorRan, partialDeleteRan] = - getDestructorState(); + auto [destructorRan, partialDeleteRan] = getDestructorState(); BEAST_EXPECT(!i || destructorRan); destructionState.store(0, std::memory_order_release); diff --git a/src/test/basics/Number_test.cpp b/src/test/basics/Number_test.cpp index 1fa5ae6e8f..13b2d72412 100644 --- a/src/test/basics/Number_test.cpp +++ b/src/test/basics/Number_test.cpp @@ -37,8 +37,7 @@ public: auto const minMantissa = Number::minMantissa(); try { - Number x = - Number{false, minMantissa * 10, 32768, Number::normalized{}}; + Number x = Number{false, minMantissa * 10, 32768, Number::normalized{}}; } catch (std::overflow_error const&) { @@ -57,10 +56,7 @@ public: Number{false, minMantissa * 10, 32767, Number::normalized{}}, Number{false, minMantissa, 32768, Number::normalized{}}, __LINE__); - test( - Number{false, minMantissa, -32769, Number::normalized{}}, - Number{}, - __LINE__); + test(Number{false, minMantissa, -32769, Number::normalized{}}, Number{}, __LINE__); test( Number{false, minMantissa, 32000, Number::normalized{}} * 1'000 + Number{false, 1'500, 32000, Number::normalized{}}, @@ -70,29 +66,24 @@ public: test( Number{std::numeric_limits::min()}, - scale == MantissaRange::small - ? Number{-9'223'372'036'854'776, 3} - : Number{true, 9'223'372'036'854'775'808ULL, 0, Number::normalized{}}, + scale == MantissaRange::small ? Number{-9'223'372'036'854'776, 3} + : Number{true, 9'223'372'036'854'775'808ULL, 0, Number::normalized{}}, __LINE__); test( Number{std::numeric_limits::min() + 1}, - scale == MantissaRange::small ? Number{-9'223'372'036'854'776, 3} - : Number{-9'223'372'036'854'775'807}, + scale == MantissaRange::small ? Number{-9'223'372'036'854'776, 3} : Number{-9'223'372'036'854'775'807}, __LINE__); test( Number{std::numeric_limits::max()}, Number{ - scale == MantissaRange::small - ? 9'223'372'036'854'776 - : std::numeric_limits::max(), + scale == MantissaRange::small ? 9'223'372'036'854'776 : std::numeric_limits::max(), 18 - Number::mantissaLog()}, __LINE__); caught = false; try { [[maybe_unused]] - Number q = - Number{false, minMantissa, 32767, Number::normalized{}} * 100; + Number q = Number{false, minMantissa, 32767, Number::normalized{}} * 100; } catch (std::overflow_error const&) { @@ -123,9 +114,7 @@ public: Number{9'999'999'999'999'344, -16}}, {Number{}, Number{5}, Number{5}}, {Number{5}, Number{}, Number{5}}, - {Number{5'555'555'555'555'555, -32768}, - Number{-5'555'555'555'555'554, -32768}, - Number{0}}, + {Number{5'555'555'555'555'555, -32768}, Number{-5'555'555'555'555'554, -32768}, Number{0}}, {Number{-9'999'999'999'999'999, -31}, Number{1'000'000'000'000'000, -15}, Number{9'999'999'999'999'990, -16}}}); @@ -142,23 +131,13 @@ public: Number{-1'000'000'000'000'065'556, -18}}, {Number{-1'000'000'000'000'000, -15}, Number{6'555'555'555'555'555, -29}, - Number{ - true, - 9'999'999'999'999'344'444ULL, - -19, - Number::normalized{}}}, + Number{true, 9'999'999'999'999'344'444ULL, -19, Number::normalized{}}}, {Number{-6'555'555'555'555'555, -29}, Number{1'000'000'000'000'000, -15}, - Number{ - false, - 9'999'999'999'999'344'444ULL, - -19, - Number::normalized{}}}, + Number{false, 9'999'999'999'999'344'444ULL, -19, Number::normalized{}}}, {Number{}, Number{5}, Number{5}}, {Number{5}, Number{}, Number{5}}, - {Number{5'555'555'555'555'555'000, -32768}, - Number{-5'555'555'555'555'554'000, -32768}, - Number{0}}, + {Number{5'555'555'555'555'555'000, -32768}, Number{-5'555'555'555'555'554'000, -32768}, Number{0}}, {Number{-9'999'999'999'999'999, -31}, Number{1'000'000'000'000'000, -15}, Number{9'999'999'999'999'990, -16}}, @@ -171,53 +150,23 @@ public: Number{-1'000'000'000'000'000'066, -18}}, {Number{-1'000'000'000'000'000'000, -18}, Number{6'555'555'555'555'555'555, -35}, - Number{ - true, - 9'999'999'999'999'999'344ULL, - -19, - Number::normalized{}}}, + Number{true, 9'999'999'999'999'999'344ULL, -19, Number::normalized{}}}, {Number{-6'555'555'555'555'555'555, -35}, Number{1'000'000'000'000'000'000, -18}, - Number{ - false, - 9'999'999'999'999'999'344ULL, - -19, - Number::normalized{}}}, + Number{false, 9'999'999'999'999'999'344ULL, -19, Number::normalized{}}}, {Number{}, Number{5}, Number{5}}, - {Number{5'555'555'555'555'555'555, -32768}, - Number{-5'555'555'555'555'555'554, -32768}, - Number{0}}, - {Number{ - true, - 9'999'999'999'999'999'999ULL, - -37, - Number::normalized{}}, + {Number{5'555'555'555'555'555'555, -32768}, Number{-5'555'555'555'555'555'554, -32768}, Number{0}}, + {Number{true, 9'999'999'999'999'999'999ULL, -37, Number::normalized{}}, Number{1'000'000'000'000'000'000, -18}, - Number{ - false, - 9'999'999'999'999'999'990ULL, - -19, - Number::normalized{}}}, - {Number{Number::maxRep}, - Number{6, -1}, - Number{Number::maxRep / 10, 1}}, - {Number{Number::maxRep - 1}, - Number{1, 0}, - Number{Number::maxRep}}, + Number{false, 9'999'999'999'999'999'990ULL, -19, Number::normalized{}}}, + {Number{Number::maxRep}, Number{6, -1}, Number{Number::maxRep / 10, 1}}, + {Number{Number::maxRep - 1}, Number{1, 0}, Number{Number::maxRep}}, // Test extremes { // Each Number operand rounds up, so the actual mantissa is // minMantissa - Number{ - false, - 9'999'999'999'999'999'999ULL, - 0, - Number::normalized{}}, - Number{ - false, - 9'999'999'999'999'999'999ULL, - 0, - Number::normalized{}}, + Number{false, 9'999'999'999'999'999'999ULL, 0, Number::normalized{}}, + Number{false, 9'999'999'999'999'999'999ULL, 0, Number::normalized{}}, Number{2, 19}, }, { @@ -226,21 +175,9 @@ public: // With addition using uint128_t, there's no problem. After // normalizing, the resulting mantissa ends up less than // maxRep. - Number{ - false, - 9'999'999'999'999'999'990ULL, - 0, - Number::normalized{}}, - Number{ - false, - 9'999'999'999'999'999'990ULL, - 0, - Number::normalized{}}, - Number{ - false, - 1'999'999'999'999'999'998ULL, - 1, - Number::normalized{}}, + Number{false, 9'999'999'999'999'999'990ULL, 0, Number::normalized{}}, + Number{false, 9'999'999'999'999'999'990ULL, 0, Number::normalized{}}, + Number{false, 1'999'999'999'999'999'998ULL, 1, Number::normalized{}}, }, }); auto test = [this](auto const& c) { @@ -260,14 +197,8 @@ public: bool caught = false; try { - Number{ - false, Number::maxMantissa(), 32768, Number::normalized{}} + - Number{ - false, - Number::minMantissa(), - 32767, - Number::normalized{}} * - 5; + Number{false, Number::maxMantissa(), 32768, Number::normalized{}} + + Number{false, Number::minMantissa(), 32767, Number::normalized{}} * 5; } catch (std::overflow_error const&) { @@ -291,9 +222,7 @@ public: {Number{6'555'555'555'555'555, -29}, Number{1'000'000'000'000'000, -15}, Number{-9'999'999'999'999'344, -16}}, - {Number{1'000'000'000'000'000, -15}, - Number{1'000'000'000'000'000, -15}, - Number{0}}, + {Number{1'000'000'000'000'000, -15}, Number{1'000'000'000'000'000, -15}, Number{0}}, {Number{1'000'000'000'000'000, -15}, Number{1'000'000'000'000'001, -15}, Number{-1'000'000'000'000'000, -30}}, @@ -307,21 +236,11 @@ public: { {Number{1'000'000'000'000'000, -15}, Number{6'555'555'555'555'555, -29}, - Number{ - false, - 9'999'999'999'999'344'444ULL, - -19, - Number::normalized{}}}, + Number{false, 9'999'999'999'999'344'444ULL, -19, Number::normalized{}}}, {Number{6'555'555'555'555'555, -29}, Number{1'000'000'000'000'000, -15}, - Number{ - true, - 9'999'999'999'999'344'444ULL, - -19, - Number::normalized{}}}, - {Number{1'000'000'000'000'000, -15}, - Number{1'000'000'000'000'000, -15}, - Number{0}}, + Number{true, 9'999'999'999'999'344'444ULL, -19, Number::normalized{}}}, + {Number{1'000'000'000'000'000, -15}, Number{1'000'000'000'000'000, -15}, Number{0}}, {Number{1'000'000'000'000'000, -15}, Number{1'000'000'000'000'001, -15}, Number{-1'000'000'000'000'000, -30}}, @@ -331,36 +250,22 @@ public: // Items from cSmall expanded for the larger mantissa {Number{1'000'000'000'000'000'000, -18}, Number{6'555'555'555'555'555'555, -32}, - Number{ - false, - 9'999'999'999'999'344'444ULL, - -19, - Number::normalized{}}}, + Number{false, 9'999'999'999'999'344'444ULL, -19, Number::normalized{}}}, {Number{6'555'555'555'555'555'555, -32}, Number{1'000'000'000'000'000'000, -18}, - Number{ - true, - 9'999'999'999'999'344'444ULL, - -19, - Number::normalized{}}}, - {Number{1'000'000'000'000'000'000, -18}, - Number{1'000'000'000'000'000'000, -18}, - Number{0}}, + Number{true, 9'999'999'999'999'344'444ULL, -19, Number::normalized{}}}, + {Number{1'000'000'000'000'000'000, -18}, Number{1'000'000'000'000'000'000, -18}, Number{0}}, {Number{1'000'000'000'000'000'000, -18}, Number{1'000'000'000'000'000'001, -18}, Number{-1'000'000'000'000'000'000, -36}}, {Number{1'000'000'000'000'000'001, -18}, Number{1'000'000'000'000'000'000, -18}, Number{1'000'000'000'000'000'000, -36}}, - {Number{Number::maxRep}, - Number{6, -1}, - Number{Number::maxRep - 1}}, + {Number{Number::maxRep}, Number{6, -1}, Number{Number::maxRep - 1}}, {Number{false, Number::maxRep + 1, 0, Number::normalized{}}, Number{1, 0}, Number{Number::maxRep / 10 + 1, 1}}, - {Number{false, Number::maxRep + 1, 0, Number::normalized{}}, - Number{3, 0}, - Number{Number::maxRep}}, + {Number{false, Number::maxRep + 1, 0, Number::normalized{}}, Number{3, 0}, Number{Number::maxRep}}, {power(2, 63), Number{3, 0}, Number{Number::maxRep}}, }); auto test = [this](auto const& c) { @@ -406,274 +311,157 @@ public: { auto const cSmall = std::to_array({ {Number{7}, Number{8}, Number{56}}, - {Number{1414213562373095, -15}, - Number{1414213562373095, -15}, - Number{2000000000000000, -15}}, - {Number{-1414213562373095, -15}, - Number{1414213562373095, -15}, - Number{-2000000000000000, -15}}, - {Number{-1414213562373095, -15}, - Number{-1414213562373095, -15}, - Number{2000000000000000, -15}}, - {Number{3214285714285706, -15}, - Number{3111111111111119, -15}, - Number{1000000000000000, -14}}, - {Number{1000000000000000, -32768}, - Number{1000000000000000, -32768}, - Number{0}}, + {Number{1414213562373095, -15}, Number{1414213562373095, -15}, Number{2000000000000000, -15}}, + {Number{-1414213562373095, -15}, Number{1414213562373095, -15}, Number{-2000000000000000, -15}}, + {Number{-1414213562373095, -15}, Number{-1414213562373095, -15}, Number{2000000000000000, -15}}, + {Number{3214285714285706, -15}, Number{3111111111111119, -15}, Number{1000000000000000, -14}}, + {Number{1000000000000000, -32768}, Number{1000000000000000, -32768}, Number{0}}, // Maximum mantissa range - {Number{9'999'999'999'999'999, 0}, - Number{9'999'999'999'999'999, 0}, - Number{9'999'999'999'999'998, 16}}, + {Number{9'999'999'999'999'999, 0}, Number{9'999'999'999'999'999, 0}, Number{9'999'999'999'999'998, 16}}, }); auto const cLarge = std::to_array({ // Note that items with extremely large mantissas need to be // calculated, because otherwise they overflow uint64. Items // from C with larger mantissa {Number{7}, Number{8}, Number{56}}, - {Number{1414213562373095, -15}, - Number{1414213562373095, -15}, - Number{1999999999999999862, -18}}, - {Number{-1414213562373095, -15}, - Number{1414213562373095, -15}, - Number{-1999999999999999862, -18}}, - {Number{-1414213562373095, -15}, - Number{-1414213562373095, -15}, - Number{1999999999999999862, -18}}, + {Number{1414213562373095, -15}, Number{1414213562373095, -15}, Number{1999999999999999862, -18}}, + {Number{-1414213562373095, -15}, Number{1414213562373095, -15}, Number{-1999999999999999862, -18}}, + {Number{-1414213562373095, -15}, Number{-1414213562373095, -15}, Number{1999999999999999862, -18}}, {Number{3214285714285706, -15}, Number{3111111111111119, -15}, - Number{ - false, - 9'999'999'999'999'999'579ULL, - -18, - Number::normalized{}}}, - {Number{1000000000000000000, -32768}, - Number{1000000000000000000, -32768}, - Number{0}}, + Number{false, 9'999'999'999'999'999'579ULL, -18, Number::normalized{}}}, + {Number{1000000000000000000, -32768}, Number{1000000000000000000, -32768}, Number{0}}, // Items from cSmall expanded for the larger mantissa, // except duplicates. Sadly, it looks like sqrt(2)^2 != 2 // with higher precision - {Number{1414213562373095049, -18}, - Number{1414213562373095049, -18}, - Number{2000000000000000001, -18}}, + {Number{1414213562373095049, -18}, Number{1414213562373095049, -18}, Number{2000000000000000001, -18}}, {Number{-1414213562373095048, -18}, Number{1414213562373095048, -18}, Number{-1999999999999999998, -18}}, {Number{-1414213562373095048, -18}, Number{-1414213562373095049, -18}, Number{1999999999999999999, -18}}, - {Number{3214285714285714278, -18}, - Number{3111111111111111119, -18}, - Number{10, 0}}, + {Number{3214285714285714278, -18}, Number{3111111111111111119, -18}, Number{10, 0}}, // Maximum mantissa range - rounds up to 1e19 {Number{false, maxMantissa, 0, Number::normalized{}}, Number{false, maxMantissa, 0, Number::normalized{}}, Number{1, 38}}, // Maximum int64 range - {Number{Number::maxRep, 0}, - Number{Number::maxRep, 0}, - Number{85'070'591'730'234'615'85, 19}}, + {Number{Number::maxRep, 0}, Number{Number::maxRep, 0}, Number{85'070'591'730'234'615'85, 19}}, }); tests(cSmall, cLarge); } Number::setround(Number::towards_zero); - testcase << "test_mul " << to_string(Number::getMantissaScale()) - << " towards_zero"; + testcase << "test_mul " << to_string(Number::getMantissaScale()) << " towards_zero"; { auto const cSmall = std::to_array( {{Number{7}, Number{8}, Number{56}}, - {Number{1414213562373095, -15}, - Number{1414213562373095, -15}, - Number{1999999999999999, -15}}, - {Number{-1414213562373095, -15}, - Number{1414213562373095, -15}, - Number{-1999999999999999, -15}}, - {Number{-1414213562373095, -15}, - Number{-1414213562373095, -15}, - Number{1999999999999999, -15}}, - {Number{3214285714285706, -15}, - Number{3111111111111119, -15}, - Number{9999999999999999, -15}}, - {Number{1000000000000000, -32768}, - Number{1000000000000000, -32768}, - Number{0}}}); + {Number{1414213562373095, -15}, Number{1414213562373095, -15}, Number{1999999999999999, -15}}, + {Number{-1414213562373095, -15}, Number{1414213562373095, -15}, Number{-1999999999999999, -15}}, + {Number{-1414213562373095, -15}, Number{-1414213562373095, -15}, Number{1999999999999999, -15}}, + {Number{3214285714285706, -15}, Number{3111111111111119, -15}, Number{9999999999999999, -15}}, + {Number{1000000000000000, -32768}, Number{1000000000000000, -32768}, Number{0}}}); auto const cLarge = std::to_array( // Note that items with extremely large mantissas need to be // calculated, because otherwise they overflow uint64. Items // from C with larger mantissa { {Number{7}, Number{8}, Number{56}}, - {Number{1414213562373095, -15}, - Number{1414213562373095, -15}, - Number{1999999999999999861, -18}}, - {Number{-1414213562373095, -15}, - Number{1414213562373095, -15}, - Number{-1999999999999999861, -18}}, - {Number{-1414213562373095, -15}, - Number{-1414213562373095, -15}, - Number{1999999999999999861, -18}}, + {Number{1414213562373095, -15}, Number{1414213562373095, -15}, Number{1999999999999999861, -18}}, + {Number{-1414213562373095, -15}, Number{1414213562373095, -15}, Number{-1999999999999999861, -18}}, + {Number{-1414213562373095, -15}, Number{-1414213562373095, -15}, Number{1999999999999999861, -18}}, {Number{3214285714285706, -15}, Number{3111111111111119, -15}, - Number{ - false, - 9999999999999999579ULL, - -18, - Number::normalized{}}}, - {Number{1000000000000000000, -32768}, - Number{1000000000000000000, -32768}, - Number{0}}, + Number{false, 9999999999999999579ULL, -18, Number::normalized{}}}, + {Number{1000000000000000000, -32768}, Number{1000000000000000000, -32768}, Number{0}}, // Items from cSmall expanded for the larger mantissa, // except duplicates. Sadly, it looks like sqrt(2)^2 != 2 // with higher precision - {Number{1414213562373095049, -18}, - Number{1414213562373095049, -18}, - Number{2, 0}}, + {Number{1414213562373095049, -18}, Number{1414213562373095049, -18}, Number{2, 0}}, {Number{-1414213562373095048, -18}, Number{1414213562373095048, -18}, Number{-1999999999999999997, -18}}, {Number{-1414213562373095048, -18}, Number{-1414213562373095049, -18}, Number{1999999999999999999, -18}}, - {Number{3214285714285714278, -18}, - Number{3111111111111111119, -18}, - Number{10, 0}}, + {Number{3214285714285714278, -18}, Number{3111111111111111119, -18}, Number{10, 0}}, // Maximum mantissa range - rounds down to maxMantissa/10e1 // 99'999'999'999'999'999'800'000'000'000'000'000'100 {Number{false, maxMantissa, 0, Number::normalized{}}, Number{false, maxMantissa, 0, Number::normalized{}}, - Number{ - false, - maxMantissa / 10 - 1, - 20, - Number::normalized{}}}, + Number{false, maxMantissa / 10 - 1, 20, Number::normalized{}}}, // Maximum int64 range // 85'070'591'730'234'615'847'396'907'784'232'501'249 - {Number{Number::maxRep, 0}, - Number{Number::maxRep, 0}, - Number{85'070'591'730'234'615'84, 19}}, + {Number{Number::maxRep, 0}, Number{Number::maxRep, 0}, Number{85'070'591'730'234'615'84, 19}}, }); tests(cSmall, cLarge); } Number::setround(Number::downward); - testcase << "test_mul " << to_string(Number::getMantissaScale()) - << " downward"; + testcase << "test_mul " << to_string(Number::getMantissaScale()) << " downward"; { auto const cSmall = std::to_array( {{Number{7}, Number{8}, Number{56}}, - {Number{1414213562373095, -15}, - Number{1414213562373095, -15}, - Number{1999999999999999, -15}}, - {Number{-1414213562373095, -15}, - Number{1414213562373095, -15}, - Number{-2000000000000000, -15}}, - {Number{-1414213562373095, -15}, - Number{-1414213562373095, -15}, - Number{1999999999999999, -15}}, - {Number{3214285714285706, -15}, - Number{3111111111111119, -15}, - Number{9999999999999999, -15}}, - {Number{1000000000000000, -32768}, - Number{1000000000000000, -32768}, - Number{0}}}); + {Number{1414213562373095, -15}, Number{1414213562373095, -15}, Number{1999999999999999, -15}}, + {Number{-1414213562373095, -15}, Number{1414213562373095, -15}, Number{-2000000000000000, -15}}, + {Number{-1414213562373095, -15}, Number{-1414213562373095, -15}, Number{1999999999999999, -15}}, + {Number{3214285714285706, -15}, Number{3111111111111119, -15}, Number{9999999999999999, -15}}, + {Number{1000000000000000, -32768}, Number{1000000000000000, -32768}, Number{0}}}); auto const cLarge = std::to_array( // Note that items with extremely large mantissas need to be // calculated, because otherwise they overflow uint64. Items // from C with larger mantissa { {Number{7}, Number{8}, Number{56}}, - {Number{1414213562373095, -15}, - Number{1414213562373095, -15}, - Number{1999999999999999861, -18}}, - {Number{-1414213562373095, -15}, - Number{1414213562373095, -15}, - Number{-1999999999999999862, -18}}, - {Number{-1414213562373095, -15}, - Number{-1414213562373095, -15}, - Number{1999999999999999861, -18}}, + {Number{1414213562373095, -15}, Number{1414213562373095, -15}, Number{1999999999999999861, -18}}, + {Number{-1414213562373095, -15}, Number{1414213562373095, -15}, Number{-1999999999999999862, -18}}, + {Number{-1414213562373095, -15}, Number{-1414213562373095, -15}, Number{1999999999999999861, -18}}, {Number{3214285714285706, -15}, Number{3111111111111119, -15}, - Number{ - false, - 9'999'999'999'999'999'579ULL, - -18, - Number::normalized{}}}, - {Number{1000000000000000000, -32768}, - Number{1000000000000000000, -32768}, - Number{0}}, + Number{false, 9'999'999'999'999'999'579ULL, -18, Number::normalized{}}}, + {Number{1000000000000000000, -32768}, Number{1000000000000000000, -32768}, Number{0}}, // Items from cSmall expanded for the larger mantissa, // except duplicates. Sadly, it looks like sqrt(2)^2 != 2 // with higher precision - {Number{1414213562373095049, -18}, - Number{1414213562373095049, -18}, - Number{2, 0}}, + {Number{1414213562373095049, -18}, Number{1414213562373095049, -18}, Number{2, 0}}, {Number{-1414213562373095048, -18}, Number{1414213562373095048, -18}, Number{-1999999999999999998, -18}}, {Number{-1414213562373095048, -18}, Number{-1414213562373095049, -18}, Number{1999999999999999999, -18}}, - {Number{3214285714285714278, -18}, - Number{3111111111111111119, -18}, - Number{10, 0}}, + {Number{3214285714285714278, -18}, Number{3111111111111111119, -18}, Number{10, 0}}, // Maximum mantissa range - rounds down to maxMantissa/10e1 // 99'999'999'999'999'999'800'000'000'000'000'000'100 {Number{false, maxMantissa, 0, Number::normalized{}}, Number{false, maxMantissa, 0, Number::normalized{}}, - Number{ - false, - maxMantissa / 10 - 1, - 20, - Number::normalized{}}}, + Number{false, maxMantissa / 10 - 1, 20, Number::normalized{}}}, // Maximum int64 range // 85'070'591'730'234'615'847'396'907'784'232'501'249 - {Number{Number::maxRep, 0}, - Number{Number::maxRep, 0}, - Number{85'070'591'730'234'615'84, 19}}, + {Number{Number::maxRep, 0}, Number{Number::maxRep, 0}, Number{85'070'591'730'234'615'84, 19}}, }); tests(cSmall, cLarge); } Number::setround(Number::upward); - testcase << "test_mul " << to_string(Number::getMantissaScale()) - << " upward"; + testcase << "test_mul " << to_string(Number::getMantissaScale()) << " upward"; { auto const cSmall = std::to_array( {{Number{7}, Number{8}, Number{56}}, - {Number{1414213562373095, -15}, - Number{1414213562373095, -15}, - Number{2000000000000000, -15}}, - {Number{-1414213562373095, -15}, - Number{1414213562373095, -15}, - Number{-1999999999999999, -15}}, - {Number{-1414213562373095, -15}, - Number{-1414213562373095, -15}, - Number{2000000000000000, -15}}, - {Number{3214285714285706, -15}, - Number{3111111111111119, -15}, - Number{1000000000000000, -14}}, - {Number{1000000000000000, -32768}, - Number{1000000000000000, -32768}, - Number{0}}}); + {Number{1414213562373095, -15}, Number{1414213562373095, -15}, Number{2000000000000000, -15}}, + {Number{-1414213562373095, -15}, Number{1414213562373095, -15}, Number{-1999999999999999, -15}}, + {Number{-1414213562373095, -15}, Number{-1414213562373095, -15}, Number{2000000000000000, -15}}, + {Number{3214285714285706, -15}, Number{3111111111111119, -15}, Number{1000000000000000, -14}}, + {Number{1000000000000000, -32768}, Number{1000000000000000, -32768}, Number{0}}}); auto const cLarge = std::to_array( // Note that items with extremely large mantissas need to be // calculated, because otherwise they overflow uint64. Items // from C with larger mantissa { {Number{7}, Number{8}, Number{56}}, - {Number{1414213562373095, -15}, - Number{1414213562373095, -15}, - Number{1999999999999999862, -18}}, - {Number{-1414213562373095, -15}, - Number{1414213562373095, -15}, - Number{-1999999999999999861, -18}}, - {Number{-1414213562373095, -15}, - Number{-1414213562373095, -15}, - Number{1999999999999999862, -18}}, - {Number{3214285714285706, -15}, - Number{3111111111111119, -15}, - Number{999999999999999958, -17}}, - {Number{1000000000000000000, -32768}, - Number{1000000000000000000, -32768}, - Number{0}}, + {Number{1414213562373095, -15}, Number{1414213562373095, -15}, Number{1999999999999999862, -18}}, + {Number{-1414213562373095, -15}, Number{1414213562373095, -15}, Number{-1999999999999999861, -18}}, + {Number{-1414213562373095, -15}, Number{-1414213562373095, -15}, Number{1999999999999999862, -18}}, + {Number{3214285714285706, -15}, Number{3111111111111119, -15}, Number{999999999999999958, -17}}, + {Number{1000000000000000000, -32768}, Number{1000000000000000000, -32768}, Number{0}}, // Items from cSmall expanded for the larger mantissa, // except duplicates. Sadly, it looks like sqrt(2)^2 != 2 // with higher precision @@ -683,9 +471,7 @@ public: {Number{-1414213562373095048, -18}, Number{1414213562373095048, -18}, Number{-1999999999999999997, -18}}, - {Number{-1414213562373095048, -18}, - Number{-1414213562373095049, -18}, - Number{2, 0}}, + {Number{-1414213562373095048, -18}, Number{-1414213562373095049, -18}, Number{2, 0}}, {Number{3214285714285714278, -18}, Number{3111111111111111119, -18}, Number{1000000000000000001, -17}}, @@ -696,24 +482,17 @@ public: Number{1, 38}}, // Maximum int64 range // 85'070'591'730'234'615'847'396'907'784'232'501'249 - {Number{Number::maxRep, 0}, - Number{Number::maxRep, 0}, - Number{85'070'591'730'234'615'85, 19}}, + {Number{Number::maxRep, 0}, Number{Number::maxRep, 0}, Number{85'070'591'730'234'615'85, 19}}, }); tests(cSmall, cLarge); } - testcase << "test_mul " << to_string(Number::getMantissaScale()) - << " overflow"; + testcase << "test_mul " << to_string(Number::getMantissaScale()) << " overflow"; { bool caught = false; try { Number{false, maxMantissa, 32768, Number::normalized{}} * - Number{ - false, - Number::minMantissa() * 5, - 32767, - Number::normalized{}}; + Number{false, Number::minMantissa() * 5, 32767, Number::normalized{}}; } catch (std::overflow_error const&) { @@ -753,12 +532,8 @@ public: {Number{1}, Number{10}, Number{1, -1}}, {Number{1}, Number{-10}, Number{-1, -1}}, {Number{0}, Number{100}, Number{0}}, - {Number{1414213562373095, -10}, - Number{1414213562373095, -10}, - Number{1}}, - {Number{9'999'999'999'999'999}, - Number{1'000'000'000'000'000}, - Number{9'999'999'999'999'999, -15}}, + {Number{1414213562373095, -10}, Number{1414213562373095, -10}, Number{1}}, + {Number{9'999'999'999'999'999}, Number{1'000'000'000'000'000}, Number{9'999'999'999'999'999, -15}}, {Number{2}, Number{3}, Number{6'666'666'666'666'667, -16}}, {Number{-2}, Number{3}, Number{-6'666'666'666'666'667, -16}}, {Number{1}, Number{7}, Number{1'428'571'428'571'428, -16}}}); @@ -770,29 +545,20 @@ public: {Number{1}, Number{10}, Number{1, -1}}, {Number{1}, Number{-10}, Number{-1, -1}}, {Number{0}, Number{100}, Number{0}}, - {Number{1414213562373095, -10}, - Number{1414213562373095, -10}, - Number{1}}, - {Number{9'999'999'999'999'999}, - Number{1'000'000'000'000'000}, - Number{9'999'999'999'999'999, -15}}, + {Number{1414213562373095, -10}, Number{1414213562373095, -10}, Number{1}}, + {Number{9'999'999'999'999'999}, Number{1'000'000'000'000'000}, Number{9'999'999'999'999'999, -15}}, {Number{2}, Number{3}, Number{6'666'666'666'666'666'667, -19}}, - {Number{-2}, - Number{3}, - Number{-6'666'666'666'666'666'667, -19}}, + {Number{-2}, Number{3}, Number{-6'666'666'666'666'666'667, -19}}, {Number{1}, Number{7}, Number{1'428'571'428'571'428'571, -19}}, // Items from cSmall expanded for the larger mantissa, except // duplicates. - {Number{1414213562373095049, -13}, - Number{1414213562373095049, -13}, - Number{1}}, + {Number{1414213562373095049, -13}, Number{1414213562373095049, -13}, Number{1}}, {Number{false, maxMantissa, 0, Number::normalized{}}, Number{1'000'000'000'000'000'000}, Number{false, maxMantissa, -18, Number::normalized{}}}}); tests(cSmall, cLarge); } - testcase << "test_div " << to_string(Number::getMantissaScale()) - << " towards_zero"; + testcase << "test_div " << to_string(Number::getMantissaScale()) << " towards_zero"; Number::setround(Number::towards_zero); { auto const cSmall = std::to_array( @@ -800,12 +566,8 @@ public: {Number{1}, Number{10}, Number{1, -1}}, {Number{1}, Number{-10}, Number{-1, -1}}, {Number{0}, Number{100}, Number{0}}, - {Number{1414213562373095, -10}, - Number{1414213562373095, -10}, - Number{1}}, - {Number{9'999'999'999'999'999}, - Number{1'000'000'000'000'000}, - Number{9'999'999'999'999'999, -15}}, + {Number{1414213562373095, -10}, Number{1414213562373095, -10}, Number{1}}, + {Number{9'999'999'999'999'999}, Number{1'000'000'000'000'000}, Number{9'999'999'999'999'999, -15}}, {Number{2}, Number{3}, Number{6'666'666'666'666'666, -16}}, {Number{-2}, Number{3}, Number{-6'666'666'666'666'666, -16}}, {Number{1}, Number{7}, Number{1'428'571'428'571'428, -16}}}); @@ -817,29 +579,20 @@ public: {Number{1}, Number{10}, Number{1, -1}}, {Number{1}, Number{-10}, Number{-1, -1}}, {Number{0}, Number{100}, Number{0}}, - {Number{1414213562373095, -10}, - Number{1414213562373095, -10}, - Number{1}}, - {Number{9'999'999'999'999'999}, - Number{1'000'000'000'000'000}, - Number{9'999'999'999'999'999, -15}}, + {Number{1414213562373095, -10}, Number{1414213562373095, -10}, Number{1}}, + {Number{9'999'999'999'999'999}, Number{1'000'000'000'000'000}, Number{9'999'999'999'999'999, -15}}, {Number{2}, Number{3}, Number{6'666'666'666'666'666'666, -19}}, - {Number{-2}, - Number{3}, - Number{-6'666'666'666'666'666'666, -19}}, + {Number{-2}, Number{3}, Number{-6'666'666'666'666'666'666, -19}}, {Number{1}, Number{7}, Number{1'428'571'428'571'428'571, -19}}, // Items from cSmall expanded for the larger mantissa, except // duplicates. - {Number{1414213562373095049, -13}, - Number{1414213562373095049, -13}, - Number{1}}, + {Number{1414213562373095049, -13}, Number{1414213562373095049, -13}, Number{1}}, {Number{false, maxMantissa, 0, Number::normalized{}}, Number{1'000'000'000'000'000'000}, Number{false, maxMantissa, -18, Number::normalized{}}}}); tests(cSmall, cLarge); } - testcase << "test_div " << to_string(Number::getMantissaScale()) - << " downward"; + testcase << "test_div " << to_string(Number::getMantissaScale()) << " downward"; Number::setround(Number::downward); { auto const cSmall = std::to_array( @@ -847,12 +600,8 @@ public: {Number{1}, Number{10}, Number{1, -1}}, {Number{1}, Number{-10}, Number{-1, -1}}, {Number{0}, Number{100}, Number{0}}, - {Number{1414213562373095, -10}, - Number{1414213562373095, -10}, - Number{1}}, - {Number{9'999'999'999'999'999}, - Number{1'000'000'000'000'000}, - Number{9'999'999'999'999'999, -15}}, + {Number{1414213562373095, -10}, Number{1414213562373095, -10}, Number{1}}, + {Number{9'999'999'999'999'999}, Number{1'000'000'000'000'000}, Number{9'999'999'999'999'999, -15}}, {Number{2}, Number{3}, Number{6'666'666'666'666'666, -16}}, {Number{-2}, Number{3}, Number{-6'666'666'666'666'667, -16}}, {Number{1}, Number{7}, Number{1'428'571'428'571'428, -16}}}); @@ -864,29 +613,20 @@ public: {Number{1}, Number{10}, Number{1, -1}}, {Number{1}, Number{-10}, Number{-1, -1}}, {Number{0}, Number{100}, Number{0}}, - {Number{1414213562373095, -10}, - Number{1414213562373095, -10}, - Number{1}}, - {Number{9'999'999'999'999'999}, - Number{1'000'000'000'000'000}, - Number{9'999'999'999'999'999, -15}}, + {Number{1414213562373095, -10}, Number{1414213562373095, -10}, Number{1}}, + {Number{9'999'999'999'999'999}, Number{1'000'000'000'000'000}, Number{9'999'999'999'999'999, -15}}, {Number{2}, Number{3}, Number{6'666'666'666'666'666'666, -19}}, - {Number{-2}, - Number{3}, - Number{-6'666'666'666'666'666'667, -19}}, + {Number{-2}, Number{3}, Number{-6'666'666'666'666'666'667, -19}}, {Number{1}, Number{7}, Number{1'428'571'428'571'428'571, -19}}, // Items from cSmall expanded for the larger mantissa, except // duplicates. - {Number{1414213562373095049, -13}, - Number{1414213562373095049, -13}, - Number{1}}, + {Number{1414213562373095049, -13}, Number{1414213562373095049, -13}, Number{1}}, {Number{false, maxMantissa, 0, Number::normalized{}}, Number{1'000'000'000'000'000'000}, Number{false, maxMantissa, -18, Number::normalized{}}}}); tests(cSmall, cLarge); } - testcase << "test_div " << to_string(Number::getMantissaScale()) - << " upward"; + testcase << "test_div " << to_string(Number::getMantissaScale()) << " upward"; Number::setround(Number::upward); { auto const cSmall = std::to_array( @@ -894,12 +634,8 @@ public: {Number{1}, Number{10}, Number{1, -1}}, {Number{1}, Number{-10}, Number{-1, -1}}, {Number{0}, Number{100}, Number{0}}, - {Number{1414213562373095, -10}, - Number{1414213562373095, -10}, - Number{1}}, - {Number{9'999'999'999'999'999}, - Number{1'000'000'000'000'000}, - Number{9'999'999'999'999'999, -15}}, + {Number{1414213562373095, -10}, Number{1414213562373095, -10}, Number{1}}, + {Number{9'999'999'999'999'999}, Number{1'000'000'000'000'000}, Number{9'999'999'999'999'999, -15}}, {Number{2}, Number{3}, Number{6'666'666'666'666'667, -16}}, {Number{-2}, Number{3}, Number{-6'666'666'666'666'666, -16}}, {Number{1}, Number{7}, Number{1'428'571'428'571'429, -16}}}); @@ -911,29 +647,20 @@ public: {Number{1}, Number{10}, Number{1, -1}}, {Number{1}, Number{-10}, Number{-1, -1}}, {Number{0}, Number{100}, Number{0}}, - {Number{1414213562373095, -10}, - Number{1414213562373095, -10}, - Number{1}}, - {Number{9'999'999'999'999'999}, - Number{1'000'000'000'000'000}, - Number{9'999'999'999'999'999, -15}}, + {Number{1414213562373095, -10}, Number{1414213562373095, -10}, Number{1}}, + {Number{9'999'999'999'999'999}, Number{1'000'000'000'000'000}, Number{9'999'999'999'999'999, -15}}, {Number{2}, Number{3}, Number{6'666'666'666'666'666'667, -19}}, - {Number{-2}, - Number{3}, - Number{-6'666'666'666'666'666'666, -19}}, + {Number{-2}, Number{3}, Number{-6'666'666'666'666'666'666, -19}}, {Number{1}, Number{7}, Number{1'428'571'428'571'428'572, -19}}, // Items from cSmall expanded for the larger mantissa, except // duplicates. - {Number{1414213562373095049, -13}, - Number{1414213562373095049, -13}, - Number{1}}, + {Number{1414213562373095049, -13}, Number{1414213562373095049, -13}, Number{1}}, {Number{false, maxMantissa, 0, Number::normalized{}}, Number{1'000'000'000'000'000'000}, Number{false, maxMantissa, -18, Number::normalized{}}}}); tests(cSmall, cLarge); } - testcase << "test_div " << to_string(Number::getMantissaScale()) - << " overflow"; + testcase << "test_div " << to_string(Number::getMantissaScale()) << " overflow"; bool caught = false; try { @@ -958,8 +685,7 @@ public: { auto const result = root(x, y); std::stringstream ss; - ss << "root(" << x << ", " << y << ") = " << result - << ". Expected: " << z; + ss << "root(" << x << ", " << y << ") = " << result << ". Expected: " << z; BEAST_EXPECTS(result == z, ss.str()); } }; @@ -987,14 +713,9 @@ public: Number{false, 999'999'999'999'999'999, -9, Number::normalized{}}}, {Number{false, Number::maxMantissa() - 9, 0, Number::normalized{}}, 2, - Number{ - false, 3'162'277'660'168'379'330, -9, Number::normalized{}}}, - {Number{Number::maxRep}, - 2, - Number{false, 3'037'000'499'976049692, -9, Number::normalized{}}}, - {Number{Number::maxRep}, - 4, - Number{false, 55'108'98747006743627, -14, Number::normalized{}}}, + Number{false, 3'162'277'660'168'379'330, -9, Number::normalized{}}}, + {Number{Number::maxRep}, 2, Number{false, 3'037'000'499'976049692, -9, Number::normalized{}}}, + {Number{Number::maxRep}, 4, Number{false, 55'108'98747006743627, -14, Number::normalized{}}}, }); test(cSmall); if (Number::getMantissaScale() != MantissaRange::small) @@ -1036,8 +757,7 @@ public: auto const expected = root(x, 2); auto const result = root2(x); std::stringstream ss; - ss << "root2(" << x << ") = " << result - << ". Expected: " << expected; + ss << "root2(" << x << ") = " << result << ". Expected: " << expected; BEAST_EXPECTS(result == expected, ss.str()); } }; @@ -1078,12 +798,8 @@ public: {Number{-64}, 2, Number{4096}}, {Number{64}, 3, Number{262144}}, {Number{-64}, 3, Number{-262144}}, - {Number{64}, - 11, - Number{false, 7378697629483820646ULL, 1, Number::normalized{}}}, - {Number{-64}, - 11, - Number{true, 7378697629483820646ULL, 1, Number::normalized{}}}}; + {Number{64}, 11, Number{false, 7378697629483820646ULL, 1, Number::normalized{}}}, + {Number{-64}, 11, Number{true, 7378697629483820646ULL, 1, Number::normalized{}}}}; for (auto const& [x, y, z] : c) BEAST_EXPECT((power(x, y) == z)); } @@ -1384,34 +1100,14 @@ public: auto const maxMantissa = Number::maxMantissa(); BEAST_EXPECT(maxMantissa == 9'999'999'999'999'999); - test( - Number{ - false, - maxMantissa * 1000 + 999, - -3, - Number::normalized()}, - "9999999999999999"); - test( - Number{ - true, - maxMantissa * 1000 + 999, - -3, - Number::normalized()}, - "-9999999999999999"); + test(Number{false, maxMantissa * 1000 + 999, -3, Number::normalized()}, "9999999999999999"); + test(Number{true, maxMantissa * 1000 + 999, -3, Number::normalized()}, "-9999999999999999"); - test( - Number{std::numeric_limits::max(), -3}, - "9223372036854775"); - test( - -(Number{std::numeric_limits::max(), -3}), - "-9223372036854775"); + test(Number{std::numeric_limits::max(), -3}, "9223372036854775"); + test(-(Number{std::numeric_limits::max(), -3}), "-9223372036854775"); - test( - Number{std::numeric_limits::min(), 0}, - "-9223372036854775e3"); - test( - -(Number{std::numeric_limits::min(), 0}), - "9223372036854775e3"); + test(Number{std::numeric_limits::min(), 0}, "-9223372036854775e3"); + test(-(Number{std::numeric_limits::min(), 0}), "9223372036854775e3"); } break; case MantissaRange::large: @@ -1425,37 +1121,21 @@ public: auto const maxMantissa = Number::maxMantissa(); BEAST_EXPECT(maxMantissa == 9'999'999'999'999'999'999ULL); - test( - Number{false, maxMantissa, 0, Number::normalized{}}, - "9999999999999999990"); - test( - Number{true, maxMantissa, 0, Number::normalized{}}, - "-9999999999999999990"); + test(Number{false, maxMantissa, 0, Number::normalized{}}, "9999999999999999990"); + test(Number{true, maxMantissa, 0, Number::normalized{}}, "-9999999999999999990"); - test( - Number{std::numeric_limits::max(), 0}, - "9223372036854775807"); - test( - -(Number{std::numeric_limits::max(), 0}), - "-9223372036854775807"); + test(Number{std::numeric_limits::max(), 0}, "9223372036854775807"); + test(-(Number{std::numeric_limits::max(), 0}), "-9223372036854775807"); // Because the absolute value of min is larger than max, it // will be scaled down to fit under max. Since we're // rounding towards zero, the 8 at the end is dropped. - test( - Number{std::numeric_limits::min(), 0}, - "-9223372036854775800"); - test( - -(Number{std::numeric_limits::min(), 0}), - "9223372036854775800"); + test(Number{std::numeric_limits::min(), 0}, "-9223372036854775800"); + test(-(Number{std::numeric_limits::min(), 0}), "9223372036854775800"); } - test( - Number{std::numeric_limits::max(), 0} + 1, - "9223372036854775810"); - test( - -(Number{std::numeric_limits::max(), 0} + 1), - "-9223372036854775810"); + test(Number{std::numeric_limits::max(), 0} + 1, "9223372036854775810"); + test(-(Number{std::numeric_limits::max(), 0} + 1), "-9223372036854775810"); break; default: BEAST_EXPECT(false); @@ -1465,8 +1145,7 @@ public: void test_relationals() { - testcase << "test_relationals " - << to_string(Number::getMantissaScale()); + testcase << "test_relationals " << to_string(Number::getMantissaScale()); BEAST_EXPECT(!(Number{100} < Number{10})); BEAST_EXPECT(Number{100} > Number{10}); BEAST_EXPECT(Number{100} >= Number{10}); @@ -1554,87 +1233,39 @@ public: std::map const expected{ // Positive numbers {Number{13, -1}, - {{Number::to_nearest, 1}, - {Number::towards_zero, 1}, - {Number::downward, 1}, - {Number::upward, 2}}}, + {{Number::to_nearest, 1}, {Number::towards_zero, 1}, {Number::downward, 1}, {Number::upward, 2}}}, {Number{23, -1}, - {{Number::to_nearest, 2}, - {Number::towards_zero, 2}, - {Number::downward, 2}, - {Number::upward, 3}}}, + {{Number::to_nearest, 2}, {Number::towards_zero, 2}, {Number::downward, 2}, {Number::upward, 3}}}, {Number{15, -1}, - {{Number::to_nearest, 2}, - {Number::towards_zero, 1}, - {Number::downward, 1}, - {Number::upward, 2}}}, + {{Number::to_nearest, 2}, {Number::towards_zero, 1}, {Number::downward, 1}, {Number::upward, 2}}}, {Number{25, -1}, - {{Number::to_nearest, 2}, - {Number::towards_zero, 2}, - {Number::downward, 2}, - {Number::upward, 3}}}, + {{Number::to_nearest, 2}, {Number::towards_zero, 2}, {Number::downward, 2}, {Number::upward, 3}}}, {Number{152, -2}, - {{Number::to_nearest, 2}, - {Number::towards_zero, 1}, - {Number::downward, 1}, - {Number::upward, 2}}}, + {{Number::to_nearest, 2}, {Number::towards_zero, 1}, {Number::downward, 1}, {Number::upward, 2}}}, {Number{252, -2}, - {{Number::to_nearest, 3}, - {Number::towards_zero, 2}, - {Number::downward, 2}, - {Number::upward, 3}}}, + {{Number::to_nearest, 3}, {Number::towards_zero, 2}, {Number::downward, 2}, {Number::upward, 3}}}, {Number{17, -1}, - {{Number::to_nearest, 2}, - {Number::towards_zero, 1}, - {Number::downward, 1}, - {Number::upward, 2}}}, + {{Number::to_nearest, 2}, {Number::towards_zero, 1}, {Number::downward, 1}, {Number::upward, 2}}}, {Number{27, -1}, - {{Number::to_nearest, 3}, - {Number::towards_zero, 2}, - {Number::downward, 2}, - {Number::upward, 3}}}, + {{Number::to_nearest, 3}, {Number::towards_zero, 2}, {Number::downward, 2}, {Number::upward, 3}}}, // Negative numbers {Number{-13, -1}, - {{Number::to_nearest, -1}, - {Number::towards_zero, -1}, - {Number::downward, -2}, - {Number::upward, -1}}}, + {{Number::to_nearest, -1}, {Number::towards_zero, -1}, {Number::downward, -2}, {Number::upward, -1}}}, {Number{-23, -1}, - {{Number::to_nearest, -2}, - {Number::towards_zero, -2}, - {Number::downward, -3}, - {Number::upward, -2}}}, + {{Number::to_nearest, -2}, {Number::towards_zero, -2}, {Number::downward, -3}, {Number::upward, -2}}}, {Number{-15, -1}, - {{Number::to_nearest, -2}, - {Number::towards_zero, -1}, - {Number::downward, -2}, - {Number::upward, -1}}}, + {{Number::to_nearest, -2}, {Number::towards_zero, -1}, {Number::downward, -2}, {Number::upward, -1}}}, {Number{-25, -1}, - {{Number::to_nearest, -2}, - {Number::towards_zero, -2}, - {Number::downward, -3}, - {Number::upward, -2}}}, + {{Number::to_nearest, -2}, {Number::towards_zero, -2}, {Number::downward, -3}, {Number::upward, -2}}}, {Number{-152, -2}, - {{Number::to_nearest, -2}, - {Number::towards_zero, -1}, - {Number::downward, -2}, - {Number::upward, -1}}}, + {{Number::to_nearest, -2}, {Number::towards_zero, -1}, {Number::downward, -2}, {Number::upward, -1}}}, {Number{-252, -2}, - {{Number::to_nearest, -3}, - {Number::towards_zero, -2}, - {Number::downward, -3}, - {Number::upward, -2}}}, + {{Number::to_nearest, -3}, {Number::towards_zero, -2}, {Number::downward, -3}, {Number::upward, -2}}}, {Number{-17, -1}, - {{Number::to_nearest, -2}, - {Number::towards_zero, -1}, - {Number::downward, -2}, - {Number::upward, -1}}}, + {{Number::to_nearest, -2}, {Number::towards_zero, -1}, {Number::downward, -2}, {Number::upward, -1}}}, {Number{-27, -1}, - {{Number::to_nearest, -3}, - {Number::towards_zero, -2}, - {Number::downward, -3}, - {Number::upward, -2}}}, + {{Number::to_nearest, -3}, {Number::towards_zero, -2}, {Number::downward, -3}, {Number::upward, -2}}}, }; for (auto const& [num, roundings] : expected) @@ -1645,9 +1276,8 @@ public: auto const res = static_cast(num); BEAST_EXPECTS( res == val, - to_string(num) + " with mode " + std::to_string(mode) + - " expected " + std::to_string(val) + " got " + - std::to_string(res)); + to_string(num) + " with mode " + std::to_string(mode) + " expected " + std::to_string(val) + + " got " + std::to_string(res)); } } } @@ -1665,8 +1295,7 @@ public: if (scale == MantissaRange::small) { - BEAST_EXPECT( - std::numeric_limits::max() > INITIAL_XRP.drops()); + BEAST_EXPECT(std::numeric_limits::max() > INITIAL_XRP.drops()); BEAST_EXPECT(Number::maxMantissa() < INITIAL_XRP.drops()); Number const initalXrp{INITIAL_XRP}; BEAST_EXPECT(initalXrp.exponent() > 0); @@ -1674,19 +1303,16 @@ public: Number const maxInt64{Number::maxRep}; BEAST_EXPECT(maxInt64.exponent() > 0); // 85'070'591'730'234'615'865'843'651'857'942'052'864 - 38 digits - BEAST_EXPECT( - (power(maxInt64, 2) == Number{85'070'591'730'234'62, 22})); + BEAST_EXPECT((power(maxInt64, 2) == Number{85'070'591'730'234'62, 22})); - Number const max = - Number{false, Number::maxMantissa(), 0, Number::normalized{}}; + Number const max = Number{false, Number::maxMantissa(), 0, Number::normalized{}}; BEAST_EXPECT(max.exponent() <= 0); // 99'999'999'999'999'980'000'000'000'000'001 - 32 digits BEAST_EXPECT((power(max, 2) == Number{99'999'999'999'999'98, 16})); } else { - BEAST_EXPECT( - std::numeric_limits::max() > INITIAL_XRP.drops()); + BEAST_EXPECT(std::numeric_limits::max() > INITIAL_XRP.drops()); BEAST_EXPECT(Number::maxMantissa() > INITIAL_XRP.drops()); Number const initalXrp{INITIAL_XRP}; BEAST_EXPECT(initalXrp.exponent() <= 0); @@ -1694,21 +1320,17 @@ public: Number const maxInt64{Number::maxRep}; BEAST_EXPECT(maxInt64.exponent() <= 0); // 85'070'591'730'234'615'847'396'907'784'232'501'249 - 38 digits - BEAST_EXPECT( - (power(maxInt64, 2) == Number{85'070'591'730'234'615'85, 19})); + BEAST_EXPECT((power(maxInt64, 2) == Number{85'070'591'730'234'615'85, 19})); NumberRoundModeGuard mg(Number::towards_zero); auto const maxMantissa = Number::maxMantissa(); - Number const max = - Number{false, maxMantissa, 0, Number::normalized{}}; + Number const max = Number{false, maxMantissa, 0, Number::normalized{}}; BEAST_EXPECT(max.mantissa() == maxMantissa / 10); BEAST_EXPECT(max.exponent() == 1); // 99'999'999'999'999'999'800'000'000'000'000'000'100 - also 38 // digits - BEAST_EXPECT(( - power(max, 2) == - Number{false, maxMantissa / 10 - 1, 20, Number::normalized{}})); + BEAST_EXPECT((power(max, 2) == Number{false, maxMantissa / 10 - 1, 20, Number::normalized{}})); } } diff --git a/src/test/basics/PerfLog_test.cpp b/src/test/basics/PerfLog_test.cpp index 06944bb5ce..57eed2aed9 100644 --- a/src/test/basics/PerfLog_test.cpp +++ b/src/test/basics/PerfLog_test.cpp @@ -28,11 +28,7 @@ class PerfLog_test : public beast::unit_test::suite // We're only using Env for its Journal. That Journal gives better // coverage in unit tests. - test::jtx::Env env_{ - *this, - test::jtx::envconfig(), - nullptr, - beast::severities::kDisabled}; + test::jtx::Env env_{*this, test::jtx::envconfig(), nullptr, beast::severities::kDisabled}; beast::Journal j_{env_.app().journal("PerfLog_test")}; struct Fixture @@ -89,10 +85,8 @@ class PerfLog_test : public beast::unit_test::suite std::unique_ptr perfLog(WithFile withFile) { - perf::PerfLog::Setup const setup{ - withFile == WithFile::no ? "" : logFile(), logInterval()}; - return perf::make_PerfLog( - setup, app_, j_, [this]() { return signalStop(); }); + perf::PerfLog::Setup const setup{withFile == WithFile::no ? "" : logFile(), logInterval()}; + return perf::make_PerfLog(setup, app_, j_, [this]() { return signalStop(); }); } // Block until the log file has grown in size, indicating that the @@ -156,20 +150,16 @@ class PerfLog_test : public beast::unit_test::suite { currents.emplace_back( jsonToUint64(cur[jss::duration_us]), - cur.isMember(jss::job) ? cur[jss::job].asString() - : cur[jss::method].asString()); + cur.isMember(jss::job) ? cur[jss::job].asString() : cur[jss::method].asString()); } // Note that the longest durations should be at the front of the // vector since they were started first. - std::sort( - currents.begin(), - currents.end(), - [](Cur const& lhs, Cur const& rhs) { - if (lhs.dur != rhs.dur) - return (rhs.dur < lhs.dur); - return (lhs.name < rhs.name); - }); + std::sort(currents.begin(), currents.end(), [](Cur const& lhs, Cur const& rhs) { + if (lhs.dur != rhs.dur) + return (rhs.dur < lhs.dur); + return (lhs.name < rhs.name); + }); return currents; } @@ -200,8 +190,7 @@ public: { // Make a file that prevents PerfLog from creating its file. std::ofstream nastyFile; - nastyFile.open( - fixture.logDir().c_str(), std::ios::out | std::ios::app); + nastyFile.open(fixture.logDir().c_str(), std::ios::out | std::ios::app); if (!BEAST_EXPECT(nastyFile)) return; nastyFile.close(); @@ -239,24 +228,20 @@ public: return; auto fileWriteable = [](boost::filesystem::path const& p) -> bool { - return std::ofstream{p.c_str(), std::ios::out | std::ios::app} - .is_open(); + return std::ofstream{p.c_str(), std::ios::out | std::ios::app}.is_open(); }; if (!BEAST_EXPECT(fileWriteable(fixture.logFile()))) return; boost::filesystem::permissions( - fixture.logFile(), - perms::remove_perms | perms::owner_write | perms::others_write | - perms::group_write); + fixture.logFile(), perms::remove_perms | perms::owner_write | perms::others_write | perms::group_write); // If the test is running as root, then the write protect may have // no effect. Make sure write protect worked before proceeding. if (fileWriteable(fixture.logFile())) { - log << "Unable to write protect file. Test skipped." - << std::endl; + log << "Unable to write protect file. Test skipped." << std::endl; return; } @@ -275,9 +260,7 @@ public: // Fix file permissions so the file can be cleaned up. boost::filesystem::permissions( - fixture.logFile(), - perms::add_perms | perms::owner_write | perms::others_write | - perms::group_write); + fixture.logFile(), perms::add_perms | perms::owner_write | perms::others_write | perms::group_write); } } @@ -292,8 +275,7 @@ public: // Get the all the labels we can use for RPC interfaces without // causing an assert. - std::vector labels = - test::jtx::make_vector(xrpl::RPC::getHandlerNames()); + std::vector labels = test::jtx::make_vector(xrpl::RPC::getHandlerNames()); std::shuffle(labels.begin(), labels.end(), default_prng()); // Get two IDs to associate with each label. Errors tend to happen at @@ -302,15 +284,11 @@ public: std::vector ids; ids.reserve(labels.size() * 2); std::generate_n( - std::back_inserter(ids), - labels.size(), - [i = std::numeric_limits::min()]() mutable { + std::back_inserter(ids), labels.size(), [i = std::numeric_limits::min()]() mutable { return i++; }); std::generate_n( - std::back_inserter(ids), - labels.size(), - [i = std::numeric_limits::max()]() mutable { + std::back_inserter(ids), labels.size(), [i = std::numeric_limits::max()]() mutable { return i--; }); std::shuffle(ids.begin(), ids.end(), default_prng()); @@ -322,8 +300,7 @@ public: for (int idIndex = 0; idIndex < 2; ++idIndex) { std::this_thread::sleep_for(std::chrono::microseconds(10)); - perfLog->rpcStart( - labels[labelIndex], ids[(labelIndex * 2) + idIndex]); + perfLog->rpcStart(labels[labelIndex], ids[(labelIndex * 2) + idIndex]); } } { @@ -350,8 +327,7 @@ public: // Verify that every entry in labels appears twice in currents. // If we sort by duration_us they should be in the order the // rpcStart() call was made. - std::vector const currents{ - getSortedCurrent(perfLog->currentJson()[jss::methods])}; + std::vector const currents{getSortedCurrent(perfLog->currentJson()[jss::methods])}; BEAST_EXPECT(currents.size() == labels.size() * 2); std::uint64_t prevDur = std::numeric_limits::max(); @@ -376,8 +352,7 @@ public: perfLog->rpcFinish(labels[0], ids[0 + 1]); // Note that label[0] id[0] is intentionally left unfinished. - auto validateFinalCounters = [this, &labels]( - Json::Value const& countersJson) { + auto validateFinalCounters = [this, &labels](Json::Value const& countersJson) { { Json::Value const& jobQueue = countersJson[jss::job_queue]; BEAST_EXPECT(jobQueue.isObject()); @@ -404,8 +379,7 @@ public: for (int i = 1; i < labels.size(); ++i) { Json::Value const& counter{rpc[labels[i]]}; - std::uint64_t const dur{ - jsonToUint64(counter[jss::duration_us])}; + std::uint64_t const dur{jsonToUint64(counter[jss::duration_us])}; BEAST_EXPECT(dur != 0 && dur < prevDur); prevDur = dur; BEAST_EXPECT(counter[jss::errored] == "1"); @@ -416,15 +390,12 @@ public: // Check "total" Json::Value const& total{rpc[jss::total]}; BEAST_EXPECT(total[jss::duration_us] != "0"); - BEAST_EXPECT( - jsonToUint64(total[jss::errored]) == labels.size() - 1); + BEAST_EXPECT(jsonToUint64(total[jss::errored]) == labels.size() - 1); BEAST_EXPECT(jsonToUint64(total[jss::finished]) == labels.size()); - BEAST_EXPECT( - jsonToUint64(total[jss::started]) == labels.size() * 2); + BEAST_EXPECT(jsonToUint64(total[jss::started]) == labels.size() * 2); }; - auto validateFinalCurrent = [this, - &labels](Json::Value const& currentJson) { + auto validateFinalCurrent = [this, &labels](Json::Value const& currentJson) { { Json::Value const& job_queue = currentJson[jss::jobs]; BEAST_EXPECT(job_queue.isArray()); @@ -503,8 +474,7 @@ public: JobType type; std::string typeName; - JobName(JobType t, std::string name) - : type(t), typeName(std::move(name)) + JobName(JobType t, std::string name) : type(t), typeName(std::move(name)) { } }; @@ -525,8 +495,7 @@ public: for (int i = 0; i < jobs.size(); ++i) { perfLog->jobQueue(jobs[i].type); - Json::Value const jq_counters{ - perfLog->countersJson()[jss::job_queue]}; + Json::Value const jq_counters{perfLog->countersJson()[jss::job_queue]}; BEAST_EXPECT(jq_counters.size() == i + 2); for (int j = 0; j <= i; ++j) @@ -573,18 +542,15 @@ public: // be half as many queued as started... for (int i = 0; i < jobs.size(); ++i) { - perfLog->jobStart( - jobs[i].type, microseconds{i + 1}, steady_clock::now(), i * 2); + perfLog->jobStart(jobs[i].type, microseconds{i + 1}, steady_clock::now(), i * 2); std::this_thread::sleep_for(microseconds(10)); // Check each jobType counter entry. - Json::Value const jq_counters{ - perfLog->countersJson()[jss::job_queue]}; + Json::Value const jq_counters{perfLog->countersJson()[jss::job_queue]}; for (int j = 0; j < jobs.size(); ++j) { Json::Value const& counter{jq_counters[jobs[j].typeName]}; - std::uint64_t const queued_dur_us{ - jsonToUint64(counter[jss::queued_duration_us])}; + std::uint64_t const queued_dur_us{jsonToUint64(counter[jss::queued_duration_us])}; if (j < i) { BEAST_EXPECT(counter[jss::started] == "2"); @@ -613,24 +579,17 @@ public: BEAST_EXPECT(total[jss::finished] == "0"); // Total queued duration is triangle number of (i + 1). - BEAST_EXPECT( - jsonToUint64(total[jss::queued_duration_us]) == - (((i * i) + 3 * i + 2) / 2)); + BEAST_EXPECT(jsonToUint64(total[jss::queued_duration_us]) == (((i * i) + 3 * i + 2) / 2)); BEAST_EXPECT(total[jss::running_duration_us] == "0"); } - perfLog->jobStart( - jobs[i].type, - microseconds{0}, - steady_clock::now(), - (i * 2) + 1); + perfLog->jobStart(jobs[i].type, microseconds{0}, steady_clock::now(), (i * 2) + 1); std::this_thread::sleep_for(microseconds{10}); // Verify that every entry in jobs appears twice in currents. // If we sort by duration_us they should be in the order the // rpcStart() call was made. - std::vector const currents{ - getSortedCurrent(perfLog->currentJson()[jss::jobs])}; + std::vector const currents{getSortedCurrent(perfLog->currentJson()[jss::jobs])}; BEAST_EXPECT(currents.size() == (i + 1) * 2); std::uint64_t prevDur = std::numeric_limits::max(); @@ -652,17 +611,14 @@ public: // A number of the computations in this loop care about the // number of jobs that have finished. Make that available. int const finished = ((jobs.size() - i) * 2) - 1; - perfLog->jobFinish( - jobs[i].type, microseconds(finished), (i * 2) + 1); + perfLog->jobFinish(jobs[i].type, microseconds(finished), (i * 2) + 1); std::this_thread::sleep_for(microseconds(10)); - Json::Value const jq_counters{ - perfLog->countersJson()[jss::job_queue]}; + Json::Value const jq_counters{perfLog->countersJson()[jss::job_queue]}; for (int j = 0; j < jobs.size(); ++j) { Json::Value const& counter{jq_counters[jobs[j].typeName]}; - std::uint64_t const running_dur_us{ - jsonToUint64(counter[jss::running_duration_us])}; + std::uint64_t const running_dur_us{jsonToUint64(counter[jss::running_duration_us])}; if (j < i) { BEAST_EXPECT(counter[jss::finished] == "0"); @@ -679,8 +635,7 @@ public: BEAST_EXPECT(running_dur_us == ((jobs.size() - j) * 4) - 1); } - std::uint64_t const queued_dur_us{ - jsonToUint64(counter[jss::queued_duration_us])}; + std::uint64_t const queued_dur_us{jsonToUint64(counter[jss::queued_duration_us])}; BEAST_EXPECT(queued_dur_us == j + 1); BEAST_EXPECT(counter[jss::queued] == "1"); BEAST_EXPECT(counter[jss::started] == "2"); @@ -689,31 +644,25 @@ public: // Verify values in jss::total are what we expect. Json::Value const& total{jq_counters[jss::total]}; BEAST_EXPECT(jsonToUint64(total[jss::queued]) == jobs.size()); - BEAST_EXPECT( - jsonToUint64(total[jss::started]) == jobs.size() * 2); + BEAST_EXPECT(jsonToUint64(total[jss::started]) == jobs.size() * 2); BEAST_EXPECT(jsonToUint64(total[jss::finished]) == finished); // Total queued duration should be triangle number of // jobs.size(). int const queuedDur = ((jobs.size() * (jobs.size() + 1)) / 2); - BEAST_EXPECT( - jsonToUint64(total[jss::queued_duration_us]) == queuedDur); + BEAST_EXPECT(jsonToUint64(total[jss::queued_duration_us]) == queuedDur); // Total running duration should be triangle number of finished. int const runningDur = ((finished * (finished + 1)) / 2); - BEAST_EXPECT( - jsonToUint64(total[jss::running_duration_us]) == - runningDur); + BEAST_EXPECT(jsonToUint64(total[jss::running_duration_us]) == runningDur); } - perfLog->jobFinish( - jobs[i].type, microseconds(finished + 1), (i * 2)); + perfLog->jobFinish(jobs[i].type, microseconds(finished + 1), (i * 2)); std::this_thread::sleep_for(microseconds(10)); // Verify that the two jobs we just finished no longer appear in // currents. - std::vector const currents{ - getSortedCurrent(perfLog->currentJson()[jss::jobs])}; + std::vector const currents{getSortedCurrent(perfLog->currentJson()[jss::jobs])}; BEAST_EXPECT(currents.size() == i * 2); std::uint64_t prevDur = std::numeric_limits::max(); @@ -730,8 +679,7 @@ public: } // Validate the final results. - auto validateFinalCounters = [this, - &jobs](Json::Value const& countersJson) { + auto validateFinalCounters = [this, &jobs](Json::Value const& countersJson) { { Json::Value const& rpc = countersJson[jss::rpc]; BEAST_EXPECT(rpc.isObject()); @@ -742,12 +690,10 @@ public: for (int i = jobs.size() - 1; i >= 0; --i) { Json::Value const& counter{jobQueue[jobs[i].typeName]}; - std::uint64_t const running_dur_us{ - jsonToUint64(counter[jss::running_duration_us])}; + std::uint64_t const running_dur_us{jsonToUint64(counter[jss::running_duration_us])}; BEAST_EXPECT(running_dur_us == ((jobs.size() - i) * 4) - 1); - std::uint64_t const queued_dur_us{ - jsonToUint64(counter[jss::queued_duration_us])}; + std::uint64_t const queued_dur_us{jsonToUint64(counter[jss::queued_duration_us])}; BEAST_EXPECT(queued_dur_us == i + 1); BEAST_EXPECT(counter[jss::queued] == "1"); @@ -765,13 +711,11 @@ public: // Total queued duration should be triangle number of // jobs.size(). int const queuedDur = ((jobs.size() * (jobs.size() + 1)) / 2); - BEAST_EXPECT( - jsonToUint64(total[jss::queued_duration_us]) == queuedDur); + BEAST_EXPECT(jsonToUint64(total[jss::queued_duration_us]) == queuedDur); // Total running duration should be triangle number of finished. int const runningDur = ((finished * (finished + 1)) / 2); - BEAST_EXPECT( - jsonToUint64(total[jss::running_duration_us]) == runningDur); + BEAST_EXPECT(jsonToUint64(total[jss::running_duration_us]) == runningDur); }; auto validateFinalCurrent = [this](Json::Value const& currentJson) { @@ -861,37 +805,31 @@ public: perfLog->resizeJobs(1); // Lambda to validate countersJson for this test. - auto verifyCounters = [this, jobTypeName]( - Json::Value const& countersJson, - int started, - int finished, - int queued_us, - int running_us) { - BEAST_EXPECT(countersJson.isObject()); - BEAST_EXPECT(countersJson.size() == 2); + auto verifyCounters = + [this, jobTypeName]( + Json::Value const& countersJson, int started, int finished, int queued_us, int running_us) { + BEAST_EXPECT(countersJson.isObject()); + BEAST_EXPECT(countersJson.size() == 2); - BEAST_EXPECT(countersJson.isMember(jss::rpc)); - BEAST_EXPECT(countersJson[jss::rpc].isObject()); - BEAST_EXPECT(countersJson[jss::rpc].size() == 0); + BEAST_EXPECT(countersJson.isMember(jss::rpc)); + BEAST_EXPECT(countersJson[jss::rpc].isObject()); + BEAST_EXPECT(countersJson[jss::rpc].size() == 0); - BEAST_EXPECT(countersJson.isMember(jss::job_queue)); - BEAST_EXPECT(countersJson[jss::job_queue].isObject()); - BEAST_EXPECT(countersJson[jss::job_queue].size() == 1); - { - Json::Value const& job{ - countersJson[jss::job_queue][jobTypeName]}; + BEAST_EXPECT(countersJson.isMember(jss::job_queue)); + BEAST_EXPECT(countersJson[jss::job_queue].isObject()); + BEAST_EXPECT(countersJson[jss::job_queue].size() == 1); + { + Json::Value const& job{countersJson[jss::job_queue][jobTypeName]}; - BEAST_EXPECT(job.isObject()); - BEAST_EXPECT(jsonToUint64(job[jss::queued]) == 0); - BEAST_EXPECT(jsonToUint64(job[jss::started]) == started); - BEAST_EXPECT(jsonToUint64(job[jss::finished]) == finished); + BEAST_EXPECT(job.isObject()); + BEAST_EXPECT(jsonToUint64(job[jss::queued]) == 0); + BEAST_EXPECT(jsonToUint64(job[jss::started]) == started); + BEAST_EXPECT(jsonToUint64(job[jss::finished]) == finished); - BEAST_EXPECT( - jsonToUint64(job[jss::queued_duration_us]) == queued_us); - BEAST_EXPECT( - jsonToUint64(job[jss::running_duration_us]) == running_us); - } - }; + BEAST_EXPECT(jsonToUint64(job[jss::queued_duration_us]) == queued_us); + BEAST_EXPECT(jsonToUint64(job[jss::running_duration_us]) == running_us); + } + }; // Lambda to validate currentJson (always empty) for this test. auto verifyEmptyCurrent = [this](Json::Value const& currentJson) { diff --git a/src/test/basics/StringUtilities_test.cpp b/src/test/basics/StringUtilities_test.cpp index ec993b20c3..65134da8e5 100644 --- a/src/test/basics/StringUtilities_test.cpp +++ b/src/test/basics/StringUtilities_test.cpp @@ -120,8 +120,7 @@ public: { parsedURL pUrl; - BEAST_EXPECT( - parseUrl(pUrl, "scheme://user:pass@domain:123/abc:321")); + BEAST_EXPECT(parseUrl(pUrl, "scheme://user:pass@domain:123/abc:321")); BEAST_EXPECT(pUrl.scheme == "scheme"); BEAST_EXPECT(pUrl.username == "user"); BEAST_EXPECT(pUrl.password == "pass"); @@ -220,8 +219,7 @@ public: { parsedURL pUrl; - BEAST_EXPECT( - parseUrl(pUrl, "scheme://user:pass@domain/path/with/an@sign")); + BEAST_EXPECT(parseUrl(pUrl, "scheme://user:pass@domain/path/with/an@sign")); BEAST_EXPECT(pUrl.scheme == "scheme"); BEAST_EXPECT(pUrl.username == "user"); BEAST_EXPECT(pUrl.password == "pass"); @@ -270,8 +268,7 @@ public: BEAST_EXPECT(!parseUrl(pUrl, "nonsense")); BEAST_EXPECT(!parseUrl(pUrl, "://")); BEAST_EXPECT(!parseUrl(pUrl, ":///")); - BEAST_EXPECT( - !parseUrl(pUrl, "scheme://user:pass@domain:65536/abc:321")); + BEAST_EXPECT(!parseUrl(pUrl, "scheme://user:pass@domain:65536/abc:321")); BEAST_EXPECT(!parseUrl(pUrl, "UPPER://domain:23498765/")); BEAST_EXPECT(!parseUrl(pUrl, "UPPER://domain:0/")); BEAST_EXPECT(!parseUrl(pUrl, "UPPER://domain:+7/")); diff --git a/src/test/basics/Units_test.cpp b/src/test/basics/Units_test.cpp index d0193320bf..9094730870 100644 --- a/src/test/basics/Units_test.cpp +++ b/src/test/basics/Units_test.cpp @@ -16,17 +16,14 @@ private: { XRPAmount x{100}; BEAST_EXPECT(x.drops() == 100); - BEAST_EXPECT( - (std::is_same_v)); + BEAST_EXPECT((std::is_same_v)); auto y = 4u * x; BEAST_EXPECT(y.value() == 400); - BEAST_EXPECT( - (std::is_same_v)); + BEAST_EXPECT((std::is_same_v)); auto z = 4 * y; BEAST_EXPECT(z.value() == 1600); - BEAST_EXPECT( - (std::is_same_v)); + BEAST_EXPECT((std::is_same_v)); FeeLevel32 f{10}; FeeLevel32 baseFee{100}; @@ -35,23 +32,17 @@ private: BEAST_EXPECT(drops); BEAST_EXPECT(drops.value() == 1000); - BEAST_EXPECT((std::is_same_v< - std::remove_reference_t::unit_type, - unit::dropTag>)); + BEAST_EXPECT((std::is_same_v::unit_type, unit::dropTag>)); - BEAST_EXPECT((std::is_same_v< - std::remove_reference_t, - XRPAmount>)); + BEAST_EXPECT((std::is_same_v, XRPAmount>)); } { XRPAmount x{100}; BEAST_EXPECT(x.value() == 100); - BEAST_EXPECT( - (std::is_same_v)); + BEAST_EXPECT((std::is_same_v)); auto y = 4u * x; BEAST_EXPECT(y.value() == 400); - BEAST_EXPECT( - (std::is_same_v)); + BEAST_EXPECT((std::is_same_v)); FeeLevel64 f{10}; FeeLevel64 baseFee{100}; @@ -60,23 +51,17 @@ private: BEAST_EXPECT(drops); BEAST_EXPECT(drops.value() == 1000); - BEAST_EXPECT((std::is_same_v< - std::remove_reference_t::unit_type, - unit::dropTag>)); - BEAST_EXPECT((std::is_same_v< - std::remove_reference_t, - XRPAmount>)); + BEAST_EXPECT((std::is_same_v::unit_type, unit::dropTag>)); + BEAST_EXPECT((std::is_same_v, XRPAmount>)); } { FeeLevel64 x{1024}; BEAST_EXPECT(x.value() == 1024); - BEAST_EXPECT( - (std::is_same_v)); + BEAST_EXPECT((std::is_same_v)); std::uint64_t m = 4; auto y = m * x; BEAST_EXPECT(y.value() == 4096); - BEAST_EXPECT( - (std::is_same_v)); + BEAST_EXPECT((std::is_same_v)); XRPAmount basefee{10}; FeeLevel64 referencefee{256}; @@ -85,12 +70,8 @@ private: BEAST_EXPECT(drops); BEAST_EXPECT(drops.value() == 40); - BEAST_EXPECT((std::is_same_v< - std::remove_reference_t::unit_type, - unit::dropTag>)); - BEAST_EXPECT((std::is_same_v< - std::remove_reference_t, - XRPAmount>)); + BEAST_EXPECT((std::is_same_v::unit_type, unit::dropTag>)); + BEAST_EXPECT((std::is_same_v, XRPAmount>)); } } @@ -118,8 +99,7 @@ private: FeeLevel64 x{std::numeric_limits::max()}; auto y = x.jsonClipped(); BEAST_EXPECT(y.type() == Json::uintValue); - BEAST_EXPECT( - y == Json::Value{std::numeric_limits::max()}); + BEAST_EXPECT(y == Json::Value{std::numeric_limits::max()}); } { @@ -147,16 +127,14 @@ private: XRPAmount x{std::numeric_limits::max()}; auto y = x.jsonClipped(); BEAST_EXPECT(y.type() == Json::intValue); - BEAST_EXPECT( - y == Json::Value{std::numeric_limits::max()}); + BEAST_EXPECT(y == Json::Value{std::numeric_limits::max()}); } { XRPAmount x{std::numeric_limits::min()}; auto y = x.jsonClipped(); BEAST_EXPECT(y.type() == Json::intValue); - BEAST_EXPECT( - y == Json::Value{std::numeric_limits::min()}); + BEAST_EXPECT(y == Json::Value{std::numeric_limits::min()}); } } @@ -169,9 +147,7 @@ private: { auto make = [&](auto x) -> FeeLevel64 { return x; }; - auto explicitmake = [&](auto x) -> FeeLevel64 { - return FeeLevel64{x}; - }; + auto explicitmake = [&](auto x) -> FeeLevel64 { return FeeLevel64{x}; }; [[maybe_unused]] FeeLevel64 defaulted; @@ -256,9 +232,7 @@ private: } { auto make = [&](auto x) -> FeeLevelDouble { return x; }; - auto explicitmake = [&](auto x) -> FeeLevelDouble { - return FeeLevelDouble{x}; - }; + auto explicitmake = [&](auto x) -> FeeLevelDouble { return FeeLevelDouble{x}; }; [[maybe_unused]] FeeLevelDouble defaulted; diff --git a/src/test/basics/XRPAmount_test.cpp b/src/test/basics/XRPAmount_test.cpp index 3f4e68de6e..391917e678 100644 --- a/src/test/basics/XRPAmount_test.cpp +++ b/src/test/basics/XRPAmount_test.cpp @@ -203,10 +203,8 @@ public: testcase("mulRatio"); constexpr auto maxUInt32 = std::numeric_limits::max(); - constexpr auto maxXRP = - std::numeric_limits::max(); - constexpr auto minXRP = - std::numeric_limits::min(); + constexpr auto maxXRP = std::numeric_limits::max(); + constexpr auto minXRP = std::numeric_limits::min(); { // multiply by a number that would overflow then divide by the same @@ -219,10 +217,8 @@ public: // multiply and divide by values that would overflow if done // naively, and check that it gives the correct answer big -= 0xf; // Subtract a little so it's divisible by 4 - BEAST_EXPECT( - mulRatio(big, 3, 4, false).value() == (big.value() / 4) * 3); - BEAST_EXPECT( - mulRatio(big, 3, 4, true).value() == (big.value() / 4) * 3); + BEAST_EXPECT(mulRatio(big, 3, 4, false).value() == (big.value() / 4) * 3); + BEAST_EXPECT(mulRatio(big, 3, 4, true).value() == (big.value() / 4) * 3); BEAST_EXPECT((big.value() * 3) / 4 != (big.value() / 4) * 3); } @@ -235,10 +231,8 @@ public: // multiply and divide by values that would overflow if done // naively, and check that it gives the correct answer - BEAST_EXPECT( - mulRatio(big, 3, 4, false).value() == (big.value() / 4) * 3); - BEAST_EXPECT( - mulRatio(big, 3, 4, true).value() == (big.value() / 4) * 3); + BEAST_EXPECT(mulRatio(big, 3, 4, false).value() == (big.value() / 4) * 3); + BEAST_EXPECT(mulRatio(big, 3, 4, true).value() == (big.value() / 4) * 3); BEAST_EXPECT((big.value() * 3) / 4 != (big.value() / 4) * 3); } @@ -249,44 +243,36 @@ public: BEAST_EXPECT(tiny == mulRatio(tiny, 1, maxUInt32, true)); // rounding down should be zero BEAST_EXPECT(beast::zero == mulRatio(tiny, 1, maxUInt32, false)); - BEAST_EXPECT( - beast::zero == mulRatio(tiny, maxUInt32 - 1, maxUInt32, false)); + BEAST_EXPECT(beast::zero == mulRatio(tiny, maxUInt32 - 1, maxUInt32, false)); // tiny negative numbers XRPAmount tinyNeg(-1); // Round up should give zero BEAST_EXPECT(beast::zero == mulRatio(tinyNeg, 1, maxUInt32, true)); - BEAST_EXPECT( - beast::zero == - mulRatio(tinyNeg, maxUInt32 - 1, maxUInt32, true)); + BEAST_EXPECT(beast::zero == mulRatio(tinyNeg, maxUInt32 - 1, maxUInt32, true)); // rounding down should be tiny - BEAST_EXPECT( - tinyNeg == mulRatio(tinyNeg, maxUInt32 - 1, maxUInt32, false)); + BEAST_EXPECT(tinyNeg == mulRatio(tinyNeg, maxUInt32 - 1, maxUInt32, false)); } { // rounding { XRPAmount one(1); auto const rup = mulRatio(one, maxUInt32 - 1, maxUInt32, true); - auto const rdown = - mulRatio(one, maxUInt32 - 1, maxUInt32, false); + auto const rdown = mulRatio(one, maxUInt32 - 1, maxUInt32, false); BEAST_EXPECT(rup.drops() - rdown.drops() == 1); } { XRPAmount big(maxXRP); auto const rup = mulRatio(big, maxUInt32 - 1, maxUInt32, true); - auto const rdown = - mulRatio(big, maxUInt32 - 1, maxUInt32, false); + auto const rdown = mulRatio(big, maxUInt32 - 1, maxUInt32, false); BEAST_EXPECT(rup.drops() - rdown.drops() == 1); } { XRPAmount negOne(-1); - auto const rup = - mulRatio(negOne, maxUInt32 - 1, maxUInt32, true); - auto const rdown = - mulRatio(negOne, maxUInt32 - 1, maxUInt32, false); + auto const rup = mulRatio(negOne, maxUInt32 - 1, maxUInt32, true); + auto const rdown = mulRatio(negOne, maxUInt32 - 1, maxUInt32, false); BEAST_EXPECT(rup.drops() - rdown.drops() == 1); } } diff --git a/src/test/basics/base58_test.cpp b/src/test/basics/base58_test.cpp index 16307bdb0f..5da22d533e 100644 --- a/src/test/basics/base58_test.cpp +++ b/src/test/basics/base58_test.cpp @@ -73,8 +73,7 @@ randomTokenTypeAndSize() -> std::tuple // Return the token type and subspan of `d` to use as test data. [[nodiscard]] inline auto -randomB256TestData(std::span d) - -> std::tuple> +randomB256TestData(std::span d) -> std::tuple> { auto& rng = randEngine(); std::uniform_int_distribution dist(0, 255); @@ -165,14 +164,14 @@ class base58_test : public beast::unit_test::suite if (!d) continue; auto bigInt = multiprecision_utils::randomBigInt(); - auto const boostBigInt = multiprecision_utils::toBoostMP( - std::span(bigInt.data(), bigInt.size())); + auto const boostBigInt = + multiprecision_utils::toBoostMP(std::span(bigInt.data(), bigInt.size())); auto const refDiv = boostBigInt / d; auto const refMod = boostBigInt % d; - auto const mod = b58_fast::detail::inplace_bigint_div_rem( - std::span(bigInt.data(), bigInt.size()), d); + auto const mod = + b58_fast::detail::inplace_bigint_div_rem(std::span(bigInt.data(), bigInt.size()), d); auto const foundDiv = multiprecision_utils::toBoostMP(bigInt); BEAST_EXPECT(refMod.convert_to() == mod); BEAST_EXPECT(foundDiv == refDiv); @@ -181,18 +180,17 @@ class base58_test : public beast::unit_test::suite { std::uint64_t const d = dist(eng); auto bigInt = multiprecision_utils::randomBigInt(/*minSize*/ 2); - if (bigInt[bigInt.size() - 1] == - std::numeric_limits::max()) + if (bigInt[bigInt.size() - 1] == std::numeric_limits::max()) { bigInt[bigInt.size() - 1] -= 1; // Prevent overflow } - auto const boostBigInt = multiprecision_utils::toBoostMP( - std::span(bigInt.data(), bigInt.size())); + auto const boostBigInt = + multiprecision_utils::toBoostMP(std::span(bigInt.data(), bigInt.size())); auto const refAdd = boostBigInt + d; - auto const result = b58_fast::detail::inplace_bigint_add( - std::span(bigInt.data(), bigInt.size()), d); + auto const result = + b58_fast::detail::inplace_bigint_add(std::span(bigInt.data(), bigInt.size()), d); BEAST_EXPECT(result == TokenCodecErrc::success); auto const foundAdd = multiprecision_utils::toBoostMP(bigInt); BEAST_EXPECT(refAdd == foundAdd); @@ -201,16 +199,15 @@ class base58_test : public beast::unit_test::suite { std::uint64_t const d = dist1(eng); // Force overflow - std::vector bigInt( - 5, std::numeric_limits::max()); + std::vector bigInt(5, std::numeric_limits::max()); - auto const boostBigInt = multiprecision_utils::toBoostMP( - std::span(bigInt.data(), bigInt.size())); + auto const boostBigInt = + multiprecision_utils::toBoostMP(std::span(bigInt.data(), bigInt.size())); auto const refAdd = boostBigInt + d; - auto const result = b58_fast::detail::inplace_bigint_add( - std::span(bigInt.data(), bigInt.size()), d); + auto const result = + b58_fast::detail::inplace_bigint_add(std::span(bigInt.data(), bigInt.size()), d); BEAST_EXPECT(result == TokenCodecErrc::overflowAdd); auto const foundAdd = multiprecision_utils::toBoostMP(bigInt); BEAST_EXPECT(refAdd != foundAdd); @@ -222,13 +219,13 @@ class base58_test : public beast::unit_test::suite // inplace mul requires the most significant coeff to be zero to // hold the result. bigInt[bigInt.size() - 1] = 0; - auto const boostBigInt = multiprecision_utils::toBoostMP( - std::span(bigInt.data(), bigInt.size())); + auto const boostBigInt = + multiprecision_utils::toBoostMP(std::span(bigInt.data(), bigInt.size())); auto const refMul = boostBigInt * d; - auto const result = b58_fast::detail::inplace_bigint_mul( - std::span(bigInt.data(), bigInt.size()), d); + auto const result = + b58_fast::detail::inplace_bigint_mul(std::span(bigInt.data(), bigInt.size()), d); BEAST_EXPECT(result == TokenCodecErrc::success); auto const foundMul = multiprecision_utils::toBoostMP(bigInt); BEAST_EXPECT(refMul == foundMul); @@ -237,15 +234,14 @@ class base58_test : public beast::unit_test::suite { std::uint64_t const d = dist1(eng); // Force overflow - std::vector bigInt( - 5, std::numeric_limits::max()); - auto const boostBigInt = multiprecision_utils::toBoostMP( - std::span(bigInt.data(), bigInt.size())); + std::vector bigInt(5, std::numeric_limits::max()); + auto const boostBigInt = + multiprecision_utils::toBoostMP(std::span(bigInt.data(), bigInt.size())); auto const refMul = boostBigInt * d; - auto const result = b58_fast::detail::inplace_bigint_mul( - std::span(bigInt.data(), bigInt.size()), d); + auto const result = + b58_fast::detail::inplace_bigint_mul(std::span(bigInt.data(), bigInt.size()), d); BEAST_EXPECT(result == TokenCodecErrc::inputTooLarge); auto const foundMul = multiprecision_utils::toBoostMP(bigInt); BEAST_EXPECT(refMul != foundMul); @@ -267,8 +263,7 @@ class base58_test : public beast::unit_test::suite std::span const outBuf{b58ResultBuf[i]}; if (i == 0) { - auto const r = xrpl::b58_fast::detail::b256_to_b58_be( - b256Data, outBuf); + auto const r = xrpl::b58_fast::detail::b256_to_b58_be(b256Data, outBuf); BEAST_EXPECT(r); b58Result[i] = r.value(); } @@ -276,10 +271,7 @@ class base58_test : public beast::unit_test::suite { std::array tmpBuf; std::string const s = xrpl::b58_ref::detail::encodeBase58( - b256Data.data(), - b256Data.size(), - tmpBuf.data(), - tmpBuf.size()); + b256Data.data(), b256Data.size(), tmpBuf.data(), tmpBuf.size()); BEAST_EXPECT(s.size()); b58Result[i] = outBuf.subspan(0, s.size()); std::copy(s.begin(), s.end(), b58Result[i].begin()); @@ -287,11 +279,7 @@ class base58_test : public beast::unit_test::suite } if (BEAST_EXPECT(b58Result[0].size() == b58Result[1].size())) { - if (!BEAST_EXPECT( - memcmp( - b58Result[0].data(), - b58Result[1].data(), - b58Result[0].size()) == 0)) + if (!BEAST_EXPECT(memcmp(b58Result[0].data(), b58Result[1].data(), b58Result[0].size()) == 0)) { printAsChar(b58Result[0], b58Result[1]); } @@ -299,24 +287,18 @@ class base58_test : public beast::unit_test::suite for (int i = 0; i < 2; ++i) { - std::span const outBuf{ - b256ResultBuf[i].data(), b256ResultBuf[i].size()}; + std::span const outBuf{b256ResultBuf[i].data(), b256ResultBuf[i].size()}; if (i == 0) { - std::string const in( - b58Result[i].data(), - b58Result[i].data() + b58Result[i].size()); - auto const r = - xrpl::b58_fast::detail::b58_to_b256_be(in, outBuf); + std::string const in(b58Result[i].data(), b58Result[i].data() + b58Result[i].size()); + auto const r = xrpl::b58_fast::detail::b58_to_b256_be(in, outBuf); BEAST_EXPECT(r); b256Result[i] = r.value(); } else { - std::string const st( - b58Result[i].begin(), b58Result[i].end()); - std::string const s = - xrpl::b58_ref::detail::decodeBase58(st); + std::string const st(b58Result[i].begin(), b58Result[i].end()); + std::string const s = xrpl::b58_ref::detail::decodeBase58(st); BEAST_EXPECT(s.size()); b256Result[i] = outBuf.subspan(0, s.size()); std::copy(s.begin(), s.end(), b256Result[i].begin()); @@ -325,19 +307,14 @@ class base58_test : public beast::unit_test::suite if (BEAST_EXPECT(b256Result[0].size() == b256Result[1].size())) { - if (!BEAST_EXPECT( - memcmp( - b256Result[0].data(), - b256Result[1].data(), - b256Result[0].size()) == 0)) + if (!BEAST_EXPECT(memcmp(b256Result[0].data(), b256Result[1].data(), b256Result[0].size()) == 0)) { printAsInt(b256Result[0], b256Result[1]); } } }; - auto testTokenEncode = [&](xrpl::TokenType const tokType, - std::span const& b256Data) { + auto testTokenEncode = [&](xrpl::TokenType const tokType, std::span const& b256Data) { std::array b58ResultBuf[2]; std::array, 2> b58Result; @@ -345,19 +322,16 @@ class base58_test : public beast::unit_test::suite std::array, 2> b256Result; for (int i = 0; i < 2; ++i) { - std::span const outBuf{ - b58ResultBuf[i].data(), b58ResultBuf[i].size()}; + std::span const outBuf{b58ResultBuf[i].data(), b58ResultBuf[i].size()}; if (i == 0) { - auto const r = xrpl::b58_fast::encodeBase58Token( - tokType, b256Data, outBuf); + auto const r = xrpl::b58_fast::encodeBase58Token(tokType, b256Data, outBuf); BEAST_EXPECT(r); b58Result[i] = r.value(); } else { - std::string const s = xrpl::b58_ref::encodeBase58Token( - tokType, b256Data.data(), b256Data.size()); + std::string const s = xrpl::b58_ref::encodeBase58Token(tokType, b256Data.data(), b256Data.size()); BEAST_EXPECT(s.size()); b58Result[i] = outBuf.subspan(0, s.size()); std::copy(s.begin(), s.end(), b58Result[i].begin()); @@ -365,11 +339,7 @@ class base58_test : public beast::unit_test::suite } if (BEAST_EXPECT(b58Result[0].size() == b58Result[1].size())) { - if (!BEAST_EXPECT( - memcmp( - b58Result[0].data(), - b58Result[1].data(), - b58Result[0].size()) == 0)) + if (!BEAST_EXPECT(memcmp(b58Result[0].data(), b58Result[1].data(), b58Result[0].size()) == 0)) { printAsChar(b58Result[0], b58Result[1]); } @@ -377,24 +347,18 @@ class base58_test : public beast::unit_test::suite for (int i = 0; i < 2; ++i) { - std::span const outBuf{ - b256ResultBuf[i].data(), b256ResultBuf[i].size()}; + std::span const outBuf{b256ResultBuf[i].data(), b256ResultBuf[i].size()}; if (i == 0) { - std::string const in( - b58Result[i].data(), - b58Result[i].data() + b58Result[i].size()); - auto const r = - xrpl::b58_fast::decodeBase58Token(tokType, in, outBuf); + std::string const in(b58Result[i].data(), b58Result[i].data() + b58Result[i].size()); + auto const r = xrpl::b58_fast::decodeBase58Token(tokType, in, outBuf); BEAST_EXPECT(r); b256Result[i] = r.value(); } else { - std::string const st( - b58Result[i].begin(), b58Result[i].end()); - std::string const s = - xrpl::b58_ref::decodeBase58Token(st, tokType); + std::string const st(b58Result[i].begin(), b58Result[i].end()); + std::string const s = xrpl::b58_ref::decodeBase58Token(st, tokType); BEAST_EXPECT(s.size()); b256Result[i] = outBuf.subspan(0, s.size()); std::copy(s.begin(), s.end(), b256Result[i].begin()); @@ -403,19 +367,14 @@ class base58_test : public beast::unit_test::suite if (BEAST_EXPECT(b256Result[0].size() == b256Result[1].size())) { - if (!BEAST_EXPECT( - memcmp( - b256Result[0].data(), - b256Result[1].data(), - b256Result[0].size()) == 0)) + if (!BEAST_EXPECT(memcmp(b256Result[0].data(), b256Result[1].data(), b256Result[0].size()) == 0)) { printAsInt(b256Result[0], b256Result[1]); } } }; - auto testIt = [&](xrpl::TokenType const tokType, - std::span const& b256Data) { + auto testIt = [&](xrpl::TokenType const tokType, std::span const& b256Data) { testRawEncode(b256Data); testTokenEncode(tokType, b256Data); }; diff --git a/src/test/basics/base_uint_test.cpp b/src/test/basics/base_uint_test.cpp index 8f764fd58b..9fdc2c7f29 100644 --- a/src/test/basics/base_uint_test.cpp +++ b/src/test/basics/base_uint_test.cpp @@ -47,15 +47,13 @@ struct base_uint_test : beast::unit_test::suite testComparisons() { { - static constexpr std:: - array, 6> - test_args{ - {{"0000000000000000", "0000000000000001"}, - {"0000000000000000", "ffffffffffffffff"}, - {"1234567812345678", "2345678923456789"}, - {"8000000000000000", "8000000000000001"}, - {"aaaaaaaaaaaaaaa9", "aaaaaaaaaaaaaaaa"}, - {"fffffffffffffffe", "ffffffffffffffff"}}}; + static constexpr std::array, 6> test_args{ + {{"0000000000000000", "0000000000000001"}, + {"0000000000000000", "ffffffffffffffff"}, + {"1234567812345678", "2345678923456789"}, + {"8000000000000000", "8000000000000001"}, + {"aaaaaaaaaaaaaaa9", "aaaaaaaaaaaaaaaa"}, + {"fffffffffffffffe", "ffffffffffffffff"}}}; for (auto const& arg : test_args) { @@ -78,17 +76,14 @@ struct base_uint_test : beast::unit_test::suite } { - static constexpr std::array< - std::pair, - 6> - test_args{{ - {"000000000000000000000000", "000000000000000000000001"}, - {"000000000000000000000000", "ffffffffffffffffffffffff"}, - {"0123456789ab0123456789ab", "123456789abc123456789abc"}, - {"555555555555555555555555", "55555555555a555555555555"}, - {"aaaaaaaaaaaaaaa9aaaaaaaa", "aaaaaaaaaaaaaaaaaaaaaaaa"}, - {"fffffffffffffffffffffffe", "ffffffffffffffffffffffff"}, - }}; + static constexpr std::array, 6> test_args{{ + {"000000000000000000000000", "000000000000000000000001"}, + {"000000000000000000000000", "ffffffffffffffffffffffff"}, + {"0123456789ab0123456789ab", "123456789abc123456789abc"}, + {"555555555555555555555555", "55555555555a555555555555"}, + {"aaaaaaaaaaaaaaa9aaaaaaaa", "aaaaaaaaaaaaaaaaaaaaaaaa"}, + {"fffffffffffffffffffffffe", "ffffffffffffffffffffffff"}, + }}; for (auto const& arg : test_args) { @@ -116,10 +111,8 @@ struct base_uint_test : beast::unit_test::suite { testcase("base_uint: general purpose tests"); - static_assert( - !std::is_constructible>::value); - static_assert( - !std::is_assignable>::value); + static_assert(!std::is_constructible>::value); + static_assert(!std::is_assignable>::value); testComparisons(); @@ -296,9 +289,7 @@ struct base_uint_test : beast::unit_test::suite } catch (std::invalid_argument const& e) { - BEAST_EXPECT( - e.what() == - std::string("invalid length for hex string")); + BEAST_EXPECT(e.what() == std::string("invalid length for hex string")); caught = true; } BEAST_EXPECT(caught); @@ -316,8 +307,7 @@ struct base_uint_test : beast::unit_test::suite } catch (std::range_error const& e) { - BEAST_EXPECT( - e.what() == std::string("invalid hex character")); + BEAST_EXPECT(e.what() == std::string("invalid hex character")); caught = true; } BEAST_EXPECT(caught); diff --git a/src/test/basics/hardened_hash_test.cpp b/src/test/basics/hardened_hash_test.cpp index f7eb78ce31..1a6609ac29 100644 --- a/src/test/basics/hardened_hash_test.cpp +++ b/src/test/basics/hardened_hash_test.cpp @@ -66,12 +66,10 @@ template using test_hardened_unordered_map = std::unordered_map>; template -using test_hardened_unordered_multiset = - std::unordered_multiset>; +using test_hardened_unordered_multiset = std::unordered_multiset>; template -using test_hardened_unordered_multimap = - std::unordered_multimap>; +using test_hardened_unordered_multimap = std::unordered_multimap>; } // namespace detail @@ -83,13 +81,9 @@ private: std::is_integral::value && std::is_unsigned::value, "UInt must be an unsigned integral type"); - static_assert( - Bits % (8 * sizeof(UInt)) == 0, - "Bits must be a multiple of 8*sizeof(UInt)"); + static_assert(Bits % (8 * sizeof(UInt)) == 0, "Bits must be a multiple of 8*sizeof(UInt)"); - static_assert( - Bits >= (8 * sizeof(UInt)), - "Bits must be at least 8*sizeof(UInt)"); + static_assert(Bits >= (8 * sizeof(UInt)), "Bits must be at least 8*sizeof(UInt)"); static std::size_t const size = Bits / (8 * sizeof(UInt)); @@ -136,8 +130,7 @@ public: operator<<(std::ostream& s, unsigned_integer const& v) { for (std::size_t i(0); i < size; ++i) - s << std::hex << std::setfill('0') << std::setw(2 * sizeof(UInt)) - << v.m_vec[i]; + s << std::hex << std::setfill('0') << std::setw(2 * sizeof(UInt)) << v.m_vec[i]; return s; } }; diff --git a/src/test/basics/join_test.cpp b/src/test/basics/join_test.cpp index 5354f2ab60..9739624c63 100644 --- a/src/test/basics/join_test.cpp +++ b/src/test/basics/join_test.cpp @@ -23,13 +23,9 @@ struct join_test : beast::unit_test::suite }; // C++ array - test( - CollectionAndDelimiter(std::array{2, -1, 5, 10}, "/"), - "2/-1/5/10"); + test(CollectionAndDelimiter(std::array{2, -1, 5, 10}, "/"), "2/-1/5/10"); // One item C++ array edge case - test( - CollectionAndDelimiter(std::array{"test"}, " & "), - "test"); + test(CollectionAndDelimiter(std::array{"test"}, " & "), "test"); // Empty C++ array edge case test(CollectionAndDelimiter(std::array{}, ","), ""); { @@ -48,20 +44,13 @@ struct join_test : beast::unit_test::suite test(CollectionAndDelimiter(words, "\n"), "thing"); } // Initializer list - test( - CollectionAndDelimiter(std::initializer_list{19, 25}, "+"), - "19+25"); + test(CollectionAndDelimiter(std::initializer_list{19, 25}, "+"), "19+25"); // vector - test( - CollectionAndDelimiter(std::vector{0, 42}, std::to_string(99)), - "09942"); + test(CollectionAndDelimiter(std::vector{0, 42}, std::to_string(99)), "09942"); { // vector with one item edge case using namespace jtx; - test( - CollectionAndDelimiter( - std::vector{Account::master}, "xxx"), - Account::master.human()); + test(CollectionAndDelimiter(std::vector{Account::master}, "xxx"), Account::master.human()); } // empty vector edge case test(CollectionAndDelimiter(std::vector{}, ","), ""); diff --git a/src/test/beast/IPEndpointCommon.h b/src/test/beast/IPEndpointCommon.h index 73cbe7d95b..3ca023188e 100644 --- a/src/test/beast/IPEndpointCommon.h +++ b/src/test/beast/IPEndpointCommon.h @@ -34,9 +34,7 @@ randomEP(bool v4 = true) static_cast(rand_int(1, UINT8_MAX)), static_cast(rand_int(1, UINT8_MAX))}}; }; - return Endpoint{ - v4 ? Address{AddressV4{dv4()}} : Address{AddressV6{dv6()}}, - rand_int(1, UINT16_MAX)}; + return Endpoint{v4 ? Address{AddressV4{dv4()}} : Address{AddressV6{dv6()}}, rand_int(1, UINT16_MAX)}; } } // namespace IP diff --git a/src/test/beast/IPEndpoint_test.cpp b/src/test/beast/IPEndpoint_test.cpp index 1d451e94a2..67e3f8ed7d 100644 --- a/src/test/beast/IPEndpoint_test.cpp +++ b/src/test/beast/IPEndpoint_test.cpp @@ -20,10 +20,7 @@ class IPEndpoint_test : public unit_test::suite { public: void - shouldParseAddrV4( - std::string const& s, - std::uint32_t value, - std::string const& normal = "") + shouldParseAddrV4(std::string const& s, std::uint32_t value, std::string const& normal = "") { boost::system::error_code ec; Address const result{boost::asio::ip::make_address(s, ec)}; @@ -31,12 +28,9 @@ public: return; if (!BEAST_EXPECTS(result.is_v4(), s + " not v4")) return; - if (!BEAST_EXPECTS( - result.to_v4().to_uint() == value, s + " value mismatch")) + if (!BEAST_EXPECTS(result.to_v4().to_uint() == value, s + " value mismatch")) return; - BEAST_EXPECTS( - result.to_string() == (normal.empty() ? s : normal), - s + " as string"); + BEAST_EXPECTS(result.to_string() == (normal.empty() ? s : normal), s + " as string"); } void @@ -215,14 +209,8 @@ public: shouldParseEPV4("1.2.3.4:5 ", {{1, 2, 3, 4}}, 5, "1.2.3.4:5"); shouldParseEPV4("1.2.3.4 ", {{1, 2, 3, 4}}, 0, "1.2.3.4"); shouldParseEPV4(" 1.2.3.4", {{1, 2, 3, 4}}, 0, "1.2.3.4"); - shouldParseEPV6( - "2001:db8:a0b:12f0::1", - {{32, 01, 13, 184, 10, 11, 18, 240, 0, 0, 0, 0, 0, 0, 0, 1}}, - 0); - shouldParseEPV6( - "[2001:db8:a0b:12f0::1]:8", - {{32, 01, 13, 184, 10, 11, 18, 240, 0, 0, 0, 0, 0, 0, 0, 1}}, - 8); + shouldParseEPV6("2001:db8:a0b:12f0::1", {{32, 01, 13, 184, 10, 11, 18, 240, 0, 0, 0, 0, 0, 0, 0, 1}}, 0); + shouldParseEPV6("[2001:db8:a0b:12f0::1]:8", {{32, 01, 13, 184, 10, 11, 18, 240, 0, 0, 0, 0, 0, 0, 0, 1}}, 8); shouldParseEPV6( "[2001:2002:2003:2004:2005:2006:2007:2008]:65535", {{32, 1, 32, 2, 32, 3, 32, 4, 32, 5, 32, 6, 32, 7, 32, 8}}, @@ -244,10 +232,7 @@ public: BEAST_EXPECT(is_loopback(ep)); BEAST_EXPECT(to_string(ep) == "127.0.0.1:80"); // same address as v4 mapped in ipv6 - ep = Endpoint( - boost::asio::ip::make_address_v6( - boost::asio::ip::v4_mapped, AddressV4{d}), - 80); + ep = Endpoint(boost::asio::ip::make_address_v6(boost::asio::ip::v4_mapped, AddressV4{d}), 80); BEAST_EXPECT(!is_unspecified(ep)); BEAST_EXPECT(!is_public(ep)); BEAST_EXPECT(is_private(ep)); @@ -265,11 +250,8 @@ public: BEAST_EXPECT(!is_loopback(ep)); BEAST_EXPECT(to_string(ep) == "10.0.0.1"); // same address as v4 mapped in ipv6 - ep = Endpoint(boost::asio::ip::make_address_v6( - boost::asio::ip::v4_mapped, AddressV4{d})); - BEAST_EXPECT( - get_class(boost::asio::ip::make_address_v4( - boost::asio::ip::v4_mapped, ep.to_v6())) == 'A'); + ep = Endpoint(boost::asio::ip::make_address_v6(boost::asio::ip::v4_mapped, AddressV4{d})); + BEAST_EXPECT(get_class(boost::asio::ip::make_address_v4(boost::asio::ip::v4_mapped, ep.to_v6())) == 'A'); BEAST_EXPECT(!is_unspecified(ep)); BEAST_EXPECT(!is_public(ep)); BEAST_EXPECT(is_private(ep)); @@ -286,8 +268,7 @@ public: BEAST_EXPECT(!is_loopback(ep)); BEAST_EXPECT(to_string(ep) == "166.78.151.147"); // same address as v4 mapped in ipv6 - ep = Endpoint(boost::asio::ip::make_address_v6( - boost::asio::ip::v4_mapped, AddressV4{d})); + ep = Endpoint(boost::asio::ip::make_address_v6(boost::asio::ip::v4_mapped, AddressV4{d})); BEAST_EXPECT(!is_unspecified(ep)); BEAST_EXPECT(is_public(ep)); BEAST_EXPECT(!is_private(ep)); @@ -296,8 +277,7 @@ public: BEAST_EXPECTS(to_string(ep) == "::ffff:166.78.151.147", to_string(ep)); // a private IPv6 - AddressV6::bytes_type d2 = { - {253, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}}; + AddressV6::bytes_type d2 = {{253, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}}; ep = Endpoint(AddressV6{d2}); BEAST_EXPECT(!is_unspecified(ep)); BEAST_EXPECT(!is_public(ep)); @@ -405,9 +385,7 @@ public: using namespace std::literals; T t; BEAST_EXPECT(parse(text, t)); - BEAST_EXPECTS( - to_string(t) == (normal.empty() ? text : normal), - "string mismatch for "s + text); + BEAST_EXPECTS(to_string(t) == (normal.empty() ? text : normal), "string mismatch for "s + text); } template diff --git a/src/test/beast/SemanticVersion_test.cpp b/src/test/beast/SemanticVersion_test.cpp index 4620c63670..b3394235d1 100644 --- a/src/test/beast/SemanticVersion_test.cpp +++ b/src/test/beast/SemanticVersion_test.cpp @@ -196,15 +196,9 @@ public: checkValues("1.2.3-rc1.debug.asm", 1, 2, 3, ids("rc1", "debug", "asm")); checkValues("1.2.3+full", 1, 2, 3, ids(), ids("full")); checkValues("1.2.3+full.prod", 1, 2, 3, ids(), ids("full", "prod")); + checkValues("1.2.3+full.prod.x86", 1, 2, 3, ids(), ids("full", "prod", "x86")); checkValues( - "1.2.3+full.prod.x86", 1, 2, 3, ids(), ids("full", "prod", "x86")); - checkValues( - "1.2.3-rc1.debug.asm+full.prod.x86", - 1, - 2, - 3, - ids("rc1", "debug", "asm"), - ids("full", "prod", "x86")); + "1.2.3-rc1.debug.asm+full.prod.x86", 1, 2, 3, ids("rc1", "debug", "asm"), ids("full", "prod", "x86")); } // makes sure the left version is less than the right diff --git a/src/test/beast/aged_associative_container_test.cpp b/src/test/beast/aged_associative_container_test.cpp index e40a24f08c..3af559c1cb 100644 --- a/src/test/beast/aged_associative_container_test.cpp +++ b/src/test/beast/aged_associative_container_test.cpp @@ -292,9 +292,7 @@ public: template struct ContType { - template < - class Compare = std::less, - class Allocator = std::allocator> + template , class Allocator = std::allocator> using Cont = detail::aged_ordered_container< Base::is_multi::value, Base::is_map::value, @@ -334,15 +332,10 @@ public: }; template - struct TestTraitsHelper - : MaybeUnordered< - MaybeMulti, IsMulti>, - IsUnordered> + struct TestTraitsHelper : MaybeUnordered, IsMulti>, IsUnordered> { private: - using Base = MaybeUnordered< - MaybeMulti, IsMulti>, - IsUnordered>; + using Base = MaybeUnordered, IsMulti>, IsUnordered>; public: using typename Base::Key; @@ -357,8 +350,7 @@ public: static std::string name() { - return std::string("aged_") + Base::name_ordered_part() + - Base::name_multi_part() + Base::name_map_part(); + return std::string("aged_") + Base::name_ordered_part() + Base::name_multi_part() + Base::name_map_part(); } }; @@ -372,17 +364,14 @@ public: static std::string name(Cont const&) { - return TestTraits:: - name(); + return TestTraits::name(); } template struct equal_value { bool - operator()( - typename Traits::Value const& lhs, - typename Traits::Value const& rhs) + operator()(typename Traits::Value const& lhs, typename Traits::Value const& rhs) { return Traits::extract(lhs) == Traits::extract(rhs); } @@ -398,26 +387,22 @@ public: //-------------------------------------------------------------------------- template - typename std::enable_if< - Container::is_map::value && !Container::is_multi::value>::type + typename std::enable_if::type checkMapContents(Container& c, Values const& v); template - typename std::enable_if< - !(Container::is_map::value && !Container::is_multi::value)>::type + typename std::enable_if::type checkMapContents(Container, Values const&) { } // unordered template - typename std::enable_if< - std::remove_reference::type::is_unordered::value>::type + typename std::enable_if::type::is_unordered::value>::type checkUnorderedContentsRefRef(C&& c, Values const& v); template - typename std::enable_if< - !std::remove_reference::type::is_unordered::value>::type + typename std::enable_if::type::is_unordered::value>::type checkUnorderedContentsRefRef(C&&, Values const&) { } @@ -614,11 +599,8 @@ public: // Check contents via at() and operator[] // map, unordered_map template -typename std::enable_if< - Container::is_map::value && !Container::is_multi::value>::type -aged_associative_container_test_base::checkMapContents( - Container& c, - Values const& v) +typename std::enable_if::type +aged_associative_container_test_base::checkMapContents(Container& c, Values const& v) { if (v.empty()) { @@ -643,17 +625,11 @@ aged_associative_container_test_base::checkMapContents( // unordered template -typename std::enable_if< - std::remove_reference::type::is_unordered::value>::type -aged_associative_container_test_base::checkUnorderedContentsRefRef( - C&& c, - Values const& v) +typename std::enable_if::type::is_unordered::value>::type +aged_associative_container_test_base::checkUnorderedContentsRefRef(C&& c, Values const& v) { using Cont = typename std::remove_reference::type; - using Traits = TestTraits< - Cont::is_unordered::value, - Cont::is_multi::value, - Cont::is_map::value>; + using Traits = TestTraits; using size_type = typename Cont::size_type; auto const hash(c.hash_function()); auto const key_eq(c.key_eq()); @@ -662,26 +638,19 @@ aged_associative_container_test_base::checkUnorderedContentsRefRef( auto const last(c.end(i)); for (auto iter(c.begin(i)); iter != last; ++iter) { - auto const match(std::find_if( - v.begin(), - v.end(), - [iter](typename Values::value_type const& e) { - return Traits::extract(*iter) == Traits::extract(e); - })); + auto const match(std::find_if(v.begin(), v.end(), [iter](typename Values::value_type const& e) { + return Traits::extract(*iter) == Traits::extract(e); + })); BEAST_EXPECT(match != v.end()); - BEAST_EXPECT( - key_eq(Traits::extract(*iter), Traits::extract(*match))); - BEAST_EXPECT( - hash(Traits::extract(*iter)) == hash(Traits::extract(*match))); + BEAST_EXPECT(key_eq(Traits::extract(*iter), Traits::extract(*match))); + BEAST_EXPECT(hash(Traits::extract(*iter)) == hash(Traits::extract(*match))); } } } template void -aged_associative_container_test_base::checkContentsRefRef( - C&& c, - Values const& v) +aged_associative_container_test_base::checkContentsRefRef(C&& c, Values const& v) { using Cont = typename std::remove_reference::type; using size_type = typename Cont::size_type; @@ -689,18 +658,10 @@ aged_associative_container_test_base::checkContentsRefRef( BEAST_EXPECT(c.size() == v.size()); BEAST_EXPECT(size_type(std::distance(c.begin(), c.end())) == v.size()); BEAST_EXPECT(size_type(std::distance(c.cbegin(), c.cend())) == v.size()); - BEAST_EXPECT( - size_type(std::distance( - c.chronological.begin(), c.chronological.end())) == v.size()); - BEAST_EXPECT( - size_type(std::distance( - c.chronological.cbegin(), c.chronological.cend())) == v.size()); - BEAST_EXPECT( - size_type(std::distance( - c.chronological.rbegin(), c.chronological.rend())) == v.size()); - BEAST_EXPECT( - size_type(std::distance( - c.chronological.crbegin(), c.chronological.crend())) == v.size()); + BEAST_EXPECT(size_type(std::distance(c.chronological.begin(), c.chronological.end())) == v.size()); + BEAST_EXPECT(size_type(std::distance(c.chronological.cbegin(), c.chronological.cend())) == v.size()); + BEAST_EXPECT(size_type(std::distance(c.chronological.rbegin(), c.chronological.rend())) == v.size()); + BEAST_EXPECT(size_type(std::distance(c.chronological.crbegin(), c.chronological.crend())) == v.size()); checkUnorderedContentsRefRef(c, v); } @@ -718,10 +679,7 @@ template void aged_associative_container_test_base::checkContents(Cont& c) { - using Traits = TestTraits< - Cont::is_unordered::value, - Cont::is_multi::value, - Cont::is_map::value>; + using Traits = TestTraits; using Values = typename Traits::Values; checkContents(c, Values()); } @@ -763,8 +721,7 @@ aged_associative_container_test_base::testConstructEmpty() } { - typename Traits::template Cont c( - clock, MyComp(1), MyAlloc(1)); + typename Traits::template Cont c(clock, MyComp(1), MyAlloc(1)); checkContents(c); } } @@ -791,44 +748,37 @@ aged_associative_container_test_base::testConstructEmpty() } { - typename Traits::template Cont c( - clock, MyHash(1)); + typename Traits::template Cont c(clock, MyHash(1)); checkContents(c); } { - typename Traits::template Cont c( - clock, MyEqual(1)); + typename Traits::template Cont c(clock, MyEqual(1)); checkContents(c); } { - typename Traits::template Cont c( - clock, MyAlloc(1)); + typename Traits::template Cont c(clock, MyAlloc(1)); checkContents(c); } { - typename Traits::template Cont c( - clock, MyHash(1), MyEqual(1)); + typename Traits::template Cont c(clock, MyHash(1), MyEqual(1)); checkContents(c); } { - typename Traits::template Cont c( - clock, MyHash(1), MyAlloc(1)); + typename Traits::template Cont c(clock, MyHash(1), MyAlloc(1)); checkContents(c); } { - typename Traits::template Cont c( - clock, MyEqual(1), MyAlloc(1)); + typename Traits::template Cont c(clock, MyEqual(1), MyAlloc(1)); checkContents(c); } { - typename Traits::template Cont c( - clock, MyHash(1), MyEqual(1), MyAlloc(1)); + typename Traits::template Cont c(clock, MyHash(1), MyEqual(1), MyAlloc(1)); checkContents(c); } } @@ -850,34 +800,29 @@ aged_associative_container_test_base::testConstructRange() testcase("range"); { - typename Traits::template Cont c( - v.begin(), v.end(), clock); + typename Traits::template Cont c(v.begin(), v.end(), clock); checkContents(c, v); } { - typename Traits::template Cont c( - v.begin(), v.end(), clock, MyComp(1)); + typename Traits::template Cont c(v.begin(), v.end(), clock, MyComp(1)); checkContents(c, v); } { - typename Traits::template Cont c( - v.begin(), v.end(), clock, MyAlloc(1)); + typename Traits::template Cont c(v.begin(), v.end(), clock, MyAlloc(1)); checkContents(c, v); } { - typename Traits::template Cont c( - v.begin(), v.end(), clock, MyComp(1), MyAlloc(1)); + typename Traits::template Cont c(v.begin(), v.end(), clock, MyComp(1), MyAlloc(1)); checkContents(c, v); } // swap { - typename Traits::template Cont c1( - v.begin(), v.end(), clock); + typename Traits::template Cont c1(v.begin(), v.end(), clock); typename Traits::template Cont c2(clock); std::swap(c1, c2); checkContents(c2, v); @@ -903,44 +848,37 @@ aged_associative_container_test_base::testConstructRange() testcase("range"); { - typename Traits::template Cont c( - v.begin(), v.end(), clock); + typename Traits::template Cont c(v.begin(), v.end(), clock); checkContents(c, v); } { - typename Traits::template Cont c( - v.begin(), v.end(), clock, MyHash(1)); + typename Traits::template Cont c(v.begin(), v.end(), clock, MyHash(1)); checkContents(c, v); } { - typename Traits::template Cont c( - v.begin(), v.end(), clock, MyEqual(1)); + typename Traits::template Cont c(v.begin(), v.end(), clock, MyEqual(1)); checkContents(c, v); } { - typename Traits::template Cont c( - v.begin(), v.end(), clock, MyAlloc(1)); + typename Traits::template Cont c(v.begin(), v.end(), clock, MyAlloc(1)); checkContents(c, v); } { - typename Traits::template Cont c( - v.begin(), v.end(), clock, MyHash(1), MyEqual(1)); + typename Traits::template Cont c(v.begin(), v.end(), clock, MyHash(1), MyEqual(1)); checkContents(c, v); } { - typename Traits::template Cont c( - v.begin(), v.end(), clock, MyHash(1), MyAlloc(1)); + typename Traits::template Cont c(v.begin(), v.end(), clock, MyHash(1), MyAlloc(1)); checkContents(c, v); } { - typename Traits::template Cont c( - v.begin(), v.end(), clock, MyEqual(1), MyAlloc(1)); + typename Traits::template Cont c(v.begin(), v.end(), clock, MyEqual(1), MyAlloc(1)); checkContents(c, v); } @@ -1201,9 +1139,7 @@ aged_associative_container_test_base::testReverseIterator() template void -aged_associative_container_test_base::checkInsertCopy( - Container& c, - Values const& v) +aged_associative_container_test_base::checkInsertCopy(Container& c, Values const& v) { for (auto const& e : v) c.insert(e); @@ -1212,9 +1148,7 @@ aged_associative_container_test_base::checkInsertCopy( template void -aged_associative_container_test_base::checkInsertMove( - Container& c, - Values const& v) +aged_associative_container_test_base::checkInsertMove(Container& c, Values const& v) { Values v2(v); for (auto& e : v2) @@ -1224,9 +1158,7 @@ aged_associative_container_test_base::checkInsertMove( template void -aged_associative_container_test_base::checkInsertHintCopy( - Container& c, - Values const& v) +aged_associative_container_test_base::checkInsertHintCopy(Container& c, Values const& v) { for (auto const& e : v) c.insert(c.cend(), e); @@ -1235,9 +1167,7 @@ aged_associative_container_test_base::checkInsertHintCopy( template void -aged_associative_container_test_base::checkInsertHintMove( - Container& c, - Values const& v) +aged_associative_container_test_base::checkInsertHintMove(Container& c, Values const& v) { Values v2(v); for (auto& e : v2) @@ -1247,9 +1177,7 @@ aged_associative_container_test_base::checkInsertHintMove( template void -aged_associative_container_test_base::checkEmplace( - Container& c, - Values const& v) +aged_associative_container_test_base::checkEmplace(Container& c, Values const& v) { for (auto const& e : v) c.emplace(e); @@ -1258,9 +1186,7 @@ aged_associative_container_test_base::checkEmplace( template void -aged_associative_container_test_base::checkEmplaceHint( - Container& c, - Values const& v) +aged_associative_container_test_base::checkEmplaceHint(Container& c, Values const& v) { for (auto const& e : v) c.emplace_hint(c.cend(), e); @@ -1339,12 +1265,8 @@ aged_associative_container_test_base::testChronological() typename Traits::template Cont<> c(v.begin(), v.end(), clock); - BEAST_EXPECT(std::equal( - c.chronological.cbegin(), - c.chronological.cend(), - v.begin(), - v.end(), - equal_value())); + BEAST_EXPECT( + std::equal(c.chronological.cbegin(), c.chronological.cend(), v.begin(), v.end(), equal_value())); // Test touch() with a non-const iterator. for (auto iter(v.crbegin()); iter != v.crend(); ++iter) @@ -1358,12 +1280,8 @@ aged_associative_container_test_base::testChronological() c.touch(found); } - BEAST_EXPECT(std::equal( - c.chronological.cbegin(), - c.chronological.cend(), - v.crbegin(), - v.crend(), - equal_value())); + BEAST_EXPECT( + std::equal(c.chronological.cbegin(), c.chronological.cend(), v.crbegin(), v.crend(), equal_value())); // Test touch() with a const_iterator for (auto iter(v.cbegin()); iter != v.cend(); ++iter) @@ -1377,12 +1295,8 @@ aged_associative_container_test_base::testChronological() c.touch(found); } - BEAST_EXPECT(std::equal( - c.chronological.cbegin(), - c.chronological.cend(), - v.cbegin(), - v.cend(), - equal_value())); + BEAST_EXPECT( + std::equal(c.chronological.cbegin(), c.chronological.cend(), v.cbegin(), v.cend(), equal_value())); { // Because touch (reverse_iterator pos) is not allowed, the following @@ -1435,9 +1349,7 @@ aged_associative_container_test_base::testArrayCreate() template void -aged_associative_container_test_base::reverseFillAgedContainer( - Container& c, - Values const& values) +aged_associative_container_test_base::reverseFillAgedContainer(Container& c, Values const& values) { // Just in case the passed in container was not empty. c.clear(); @@ -1463,9 +1375,7 @@ aged_associative_container_test_base::reverseFillAgedContainer( // cannot use operator-- with unordered container iterators. template Iter -aged_associative_container_test_base::nextToEndIter( - Iter beginIter, - Iter const endIter) +aged_associative_container_test_base::nextToEndIter(Iter beginIter, Iter const endIter) { if (beginIter == endIter) { @@ -1497,10 +1407,7 @@ aged_associative_container_test_base::nextToEndIter( // the whole test. template bool -aged_associative_container_test_base::doElementErase( - Container& c, - Iter const beginItr, - Iter const endItr) +aged_associative_container_test_base::doElementErase(Container& c, Iter const beginItr, Iter const endItr) { auto it(beginItr); size_t count = c.size(); @@ -1558,8 +1465,7 @@ aged_associative_container_test_base::testElementErase() { // Test standard iterators auto tempContainer(c); - if (!doElementErase( - tempContainer, tempContainer.cbegin(), tempContainer.cend())) + if (!doElementErase(tempContainer, tempContainer.cbegin(), tempContainer.cend())) return; // Test failed BEAST_EXPECT(tempContainer.empty()); @@ -1580,9 +1486,7 @@ aged_associative_container_test_base::testElementErase() auto tempContainer(c); BEAST_EXPECT(tempContainer.size() > 2); if (!doElementErase( - tempContainer, - ++tempContainer.begin(), - nextToEndIter(tempContainer.begin(), tempContainer.end()))) + tempContainer, ++tempContainer.begin(), nextToEndIter(tempContainer.begin(), tempContainer.end()))) return; // Test failed BEAST_EXPECT(tempContainer.size() == 2); @@ -1593,10 +1497,7 @@ aged_associative_container_test_base::testElementErase() auto tempContainer(c); BEAST_EXPECT(tempContainer.size() > 2); auto& chron(tempContainer.chronological); - if (!doElementErase( - tempContainer, - ++chron.begin(), - nextToEndIter(chron.begin(), chron.end()))) + if (!doElementErase(tempContainer, ++chron.begin(), nextToEndIter(chron.begin(), chron.end()))) return; // Test failed BEAST_EXPECT(tempContainer.size() == 2); @@ -1631,9 +1532,7 @@ aged_associative_container_test_base::testElementErase() // template void -aged_associative_container_test_base::doRangeErase( - Container& c, - BeginEndSrc const& beginEndSrc) +aged_associative_container_test_base::doRangeErase(Container& c, BeginEndSrc const& beginEndSrc) { BEAST_EXPECT(c.size() > 2); auto itBeginPlusOne(beginEndSrc.begin()); @@ -1793,51 +1692,35 @@ public: using T = int; static_assert( - std::is_same< - aged_set, - detail::aged_ordered_container>::value, + std::is_same, detail::aged_ordered_container>::value, "bad alias: aged_set"); static_assert( - std::is_same< - aged_multiset, - detail::aged_ordered_container>::value, + std::is_same, detail::aged_ordered_container>::value, "bad alias: aged_multiset"); static_assert( - std::is_same< - aged_map, - detail::aged_ordered_container>::value, + std::is_same, detail::aged_ordered_container>::value, "bad alias: aged_map"); static_assert( - std::is_same< - aged_multimap, - detail::aged_ordered_container>::value, + std::is_same, detail::aged_ordered_container>::value, "bad alias: aged_multimap"); static_assert( - std::is_same< - aged_unordered_set, - detail::aged_unordered_container>::value, + std::is_same, detail::aged_unordered_container>::value, "bad alias: aged_unordered_set"); static_assert( - std::is_same< - aged_unordered_multiset, - detail::aged_unordered_container>::value, + std::is_same, detail::aged_unordered_container>::value, "bad alias: aged_unordered_multiset"); static_assert( - std::is_same< - aged_unordered_map, - detail::aged_unordered_container>::value, + std::is_same, detail::aged_unordered_container>::value, "bad alias: aged_unordered_map"); static_assert( - std::is_same< - aged_unordered_multimap, - detail::aged_unordered_container>::value, + std::is_same, detail::aged_unordered_container>::value, "bad alias: aged_unordered_multimap"); void diff --git a/src/test/beast/beast_CurrentThreadName_test.cpp b/src/test/beast/beast_CurrentThreadName_test.cpp index dc12883a63..2a365c6e9c 100644 --- a/src/test/beast/beast_CurrentThreadName_test.cpp +++ b/src/test/beast/beast_CurrentThreadName_test.cpp @@ -12,10 +12,7 @@ class CurrentThreadName_test : public beast::unit_test::suite { private: static void - exerciseName( - std::string myName, - std::atomic* stop, - std::atomic* state) + exerciseName(std::string myName, std::atomic* stop, std::atomic* state) { // Verify that upon creation a thread has no name. auto const initialThreadName = beast::getCurrentThreadName(); @@ -88,20 +85,14 @@ public: BEAST_EXPECT(stateB == 2); } #if BOOST_OS_LINUX - // On Linux, verify that thread names longer than 15 characters - // are truncated to 15 characters (the 16th character is reserved for - // the null terminator). + // On Linux, verify that thread names within the 15 character limit + // are set correctly (the 16th character is reserved for the null + // terminator). { - testName( - "123456789012345", - "123456789012345"); // 15 chars, no truncation - testName( - "1234567890123456", "123456789012345"); // 16 chars, truncated - testName( - "ThisIsAVeryLongThreadNameExceedingLimit", - "ThisIsAVeryLong"); // 39 chars, truncated - testName("", ""); // empty name - testName("short", "short"); // short name, no truncation + testName("123456789012345", + "123456789012345"); // 15 chars, maximum allowed + testName("", ""); // empty name + testName("short", "short"); // short name } #endif } diff --git a/src/test/beast/beast_PropertyStream_test.cpp b/src/test/beast/beast_PropertyStream_test.cpp index e6c19c8e5a..c2e6ddc22b 100644 --- a/src/test/beast/beast_PropertyStream_test.cpp +++ b/src/test/beast/beast_PropertyStream_test.cpp @@ -9,10 +9,7 @@ public: using Source = PropertyStream::Source; void - test_peel_name( - std::string s, - std::string const& expected, - std::string const& expected_remainder) + test_peel_name(std::string s, std::string const& expected, std::string const& expected_remainder) { try { @@ -28,10 +25,7 @@ public: } void - test_peel_leading_slash( - std::string s, - std::string const& expected, - bool should_be_found) + test_peel_leading_slash(std::string s, std::string const& expected, bool should_be_found) { try { @@ -47,10 +41,7 @@ public: } void - test_peel_trailing_slashstar( - std::string s, - std::string const& expected_remainder, - bool should_be_found) + test_peel_trailing_slashstar(std::string s, std::string const& expected_remainder, bool should_be_found) { try { @@ -111,11 +102,7 @@ public: } void - test_find( - Source& root, - std::string path, - Source* expected, - bool expected_star) + test_find(Source& root, std::string path, Source* expected, bool expected_star) { try { diff --git a/src/test/beast/beast_abstract_clock_test.cpp b/src/test/beast/beast_abstract_clock_test.cpp index 453f3c535f..94b7909820 100644 --- a/src/test/beast/beast_abstract_clock_test.cpp +++ b/src/test/beast/beast_abstract_clock_test.cpp @@ -23,8 +23,7 @@ public: std::this_thread::sleep_for(std::chrono::milliseconds(1500)); auto const t2(c.now()); - log << "t1= " << t1.time_since_epoch().count() - << ", t2= " << t2.time_since_epoch().count() + log << "t1= " << t1.time_since_epoch().count() << ", t2= " << t2.time_since_epoch().count() << ", elapsed= " << (t2 - t1).count() << std::endl; pass(); @@ -46,8 +45,7 @@ public: c.set(clock_type::time_point(std::chrono::seconds(2))); auto c3 = c.now().time_since_epoch(); - log << "[" << c1.count() << "," << c2.count() << "," << c3.count() - << "]" << std::endl; + log << "[" << c1.count() << "," << c2.count() << "," << c3.count() << "]" << std::endl; pass(); } @@ -57,9 +55,7 @@ public: { test("steady_clock", get_abstract_clock()); test("system_clock", get_abstract_clock()); - test( - "high_resolution_clock", - get_abstract_clock()); + test("high_resolution_clock", get_abstract_clock()); test_manual(); } diff --git a/src/test/beast/beast_io_latency_probe_test.cpp b/src/test/beast/beast_io_latency_probe_test.cpp index 1a6b0a9a1e..4a78eb77fe 100644 --- a/src/test/beast/beast_io_latency_probe_test.cpp +++ b/src/test/beast/beast_io_latency_probe_test.cpp @@ -15,11 +15,9 @@ using namespace std::chrono_literals; -class io_latency_probe_test : public beast::unit_test::suite, - public beast::test::enable_yield_to +class io_latency_probe_test : public beast::unit_test::suite, public beast::test::enable_yield_to { - using MyTimer = - boost::asio::basic_waitable_timer; + using MyTimer = boost::asio::basic_waitable_timer; #ifdef XRPL_RUNNING_IN_CI /** @@ -29,9 +27,7 @@ class io_latency_probe_test : public beast::unit_test::suite, * timer inaccuracy impacts the io_probe tests below. * */ - template < - class Clock, - class MeasureClock = std::chrono::high_resolution_clock> + template struct measure_asio_timers { using duration = typename Clock::duration; @@ -43,9 +39,8 @@ class io_latency_probe_test : public beast::unit_test::suite, { using namespace std::chrono; boost::asio::io_context ios; - std::optional> - work{boost::asio::make_work_guard(ios)}; + std::optional> work{ + boost::asio::make_work_guard(ios)}; std::thread worker{[&] { ios.run(); }}; boost::asio::basic_waitable_timer timer{ios}; elapsed_times_.reserve(num_samples); @@ -84,8 +79,7 @@ class io_latency_probe_test : public beast::unit_test::suite, double sum = {0}; for (auto const& v : elapsed_times_) { - sum += static_cast( - std::chrono::duration_cast(v).count()); + sum += static_cast(std::chrono::duration_cast(v).count()); } return sum / elapsed_times_.size(); } @@ -94,9 +88,7 @@ class io_latency_probe_test : public beast::unit_test::suite, auto getMax() { - return std::chrono::duration_cast( - *std::max_element( - elapsed_times_.begin(), elapsed_times_.end())) + return std::chrono::duration_cast(*std::max_element(elapsed_times_.begin(), elapsed_times_.end())) .count(); } @@ -104,9 +96,7 @@ class io_latency_probe_test : public beast::unit_test::suite, auto getMin() { - return std::chrono::duration_cast( - *std::min_element( - elapsed_times_.begin(), elapsed_times_.end())) + return std::chrono::duration_cast(*std::min_element(elapsed_times_.begin(), elapsed_times_.end())) .count(); } }; @@ -117,10 +107,7 @@ class io_latency_probe_test : public beast::unit_test::suite, beast::io_latency_probe probe_; std::vector durations_; - test_sampler( - std::chrono::milliseconds interval, - boost::asio::io_context& ios) - : probe_(interval, ios) + test_sampler(std::chrono::milliseconds interval, boost::asio::io_context& ios) : probe_(interval, ios) { } @@ -173,13 +160,9 @@ class io_latency_probe_test : public beast::unit_test::suite, // adjust min expected based on measurements // if running in CI/VM environment measure_asio_timers tt{interval}; - log << "measured mean for timers: " << tt.getMean() - << "ms\n"; - log << "measured max for timers: " << tt.getMax() - << "ms\n"; - expected_probe_count_min = - static_cast( - duration_cast(probe_duration).count()) / + log << "measured mean for timers: " << tt.getMean() << "ms\n"; + log << "measured max for timers: " << tt.getMax() << "ms\n"; + expected_probe_count_min = static_cast(duration_cast(probe_duration).count()) / static_cast(tt.getMean()); #endif test_sampler io_probe{interval, get_io_context()}; @@ -190,8 +173,7 @@ class io_latency_probe_test : public beast::unit_test::suite, return; auto probes_seen = io_probe.durations_.size(); BEAST_EXPECTS( - probes_seen >= (expected_probe_count_min - 1) && - probes_seen <= (expected_probe_count_max + 1), + probes_seen >= (expected_probe_count_min - 1) && probes_seen <= (expected_probe_count_max + 1), std::string("probe count is ") + std::to_string(probes_seen)); io_probe.probe_.cancel_async(); // wait again in order to flush the remaining diff --git a/src/test/beast/define_print.cpp b/src/test/beast/define_print.cpp index 660f88b24a..07b1422a54 100644 --- a/src/test/beast/define_print.cpp +++ b/src/test/beast/define_print.cpp @@ -23,9 +23,7 @@ public: std::size_t manual = 0; std::size_t total = 0; - auto prefix = [](suite_info const& s) { - return s.manual() ? "|M| " : " "; - }; + auto prefix = [](suite_info const& s) { return s.manual() ? "|M| " : " "; }; for (auto const& s : global_suites()) { @@ -36,8 +34,7 @@ public: ++total; } - log << amount(total, "suite") << " total, " - << amount(manual, "manual suite") << std::endl; + log << amount(total, "suite") << " total, " << amount(manual, "manual suite") << std::endl; pass(); } diff --git a/src/test/beast/xxhasher_test.cpp b/src/test/beast/xxhasher_test.cpp index f740bf0821..868d522384 100644 --- a/src/test/beast/xxhasher_test.cpp +++ b/src/test/beast/xxhasher_test.cpp @@ -16,9 +16,7 @@ public: std::string objectToHash{"Hello, xxHash!"}; hasher(objectToHash.data(), objectToHash.size()); - BEAST_EXPECT( - static_cast(hasher) == - 16042857369214894119ULL); + BEAST_EXPECT(static_cast(hasher) == 16042857369214894119ULL); } void @@ -31,24 +29,19 @@ public: std::string objectToHash{"Hello, xxHash!"}; hasher(objectToHash.data(), objectToHash.size()); - BEAST_EXPECT( - static_cast(hasher) == - 14440132435660934800ULL); + BEAST_EXPECT(static_cast(hasher) == 14440132435660934800ULL); } void testWithTwoSeeds() { testcase("With two seeds"); - xxhasher hasher{ - static_cast(102), static_cast(103)}; + xxhasher hasher{static_cast(102), static_cast(103)}; std::string objectToHash{"Hello, xxHash!"}; hasher(objectToHash.data(), objectToHash.size()); - BEAST_EXPECT( - static_cast(hasher) == - 14440132435660934800ULL); + BEAST_EXPECT(static_cast(hasher) == 14440132435660934800ULL); } void @@ -63,9 +56,7 @@ public: hasher(objectToHash.data(), objectToHash.size()); } - BEAST_EXPECT( - static_cast(hasher) == - 15296278154063476002ULL); + BEAST_EXPECT(static_cast(hasher) == 15296278154063476002ULL); } void @@ -80,9 +71,7 @@ public: hasher(objectToHash.data(), objectToHash.size()); } - BEAST_EXPECT( - static_cast(hasher) == - 17285302196561698791ULL); + BEAST_EXPECT(static_cast(hasher) == 17285302196561698791ULL); } void @@ -101,9 +90,7 @@ public: hasher(bigObject.data(), bigObject.size()); hasher(objectToHash.data(), objectToHash.size()); - BEAST_EXPECT( - static_cast(hasher) == - 1865045178324729219ULL); + BEAST_EXPECT(static_cast(hasher) == 1865045178324729219ULL); } void @@ -122,9 +109,7 @@ public: hasher(bigObject.data(), bigObject.size()); hasher(objectToHash.data(), objectToHash.size()); - BEAST_EXPECT( - static_cast(hasher) == - 16189862915636005281ULL); + BEAST_EXPECT(static_cast(hasher) == 16189862915636005281ULL); } void @@ -140,9 +125,7 @@ public: } hasher(objectToHash.data(), objectToHash.size()); - BEAST_EXPECT( - static_cast(hasher) == - 15296278154063476002ULL); + BEAST_EXPECT(static_cast(hasher) == 15296278154063476002ULL); } void @@ -158,9 +141,7 @@ public: } hasher(objectToHash.data(), objectToHash.size()); - BEAST_EXPECT( - static_cast(hasher) == - 17285302196561698791ULL); + BEAST_EXPECT(static_cast(hasher) == 17285302196561698791ULL); } void diff --git a/src/test/conditions/PreimageSha256_test.cpp b/src/test/conditions/PreimageSha256_test.cpp index 71ba526be3..c3508758a7 100644 --- a/src/test/conditions/PreimageSha256_test.cpp +++ b/src/test/conditions/PreimageSha256_test.cpp @@ -1,12 +1,11 @@ -#include -#include -#include - #include #include #include #include #include +#include +#include +#include #include #include diff --git a/src/test/consensus/ByzantineFailureSim_test.cpp b/src/test/consensus/ByzantineFailureSim_test.cpp index 210333e303..62899730c2 100644 --- a/src/test/consensus/ByzantineFailureSim_test.cpp +++ b/src/test/consensus/ByzantineFailureSim_test.cpp @@ -22,8 +22,7 @@ class ByzantineFailureSim_test : public beast::unit_test::suite Sim sim; ConsensusParms const parms{}; - SimDuration const delay = - round(0.2 * parms.ledgerGRANULARITY); + SimDuration const delay = round(0.2 * parms.ledgerGRANULARITY); PeerGroup a = sim.createGroup(1); PeerGroup b = sim.createGroup(1); PeerGroup c = sim.createGroup(1); @@ -46,12 +45,10 @@ class ByzantineFailureSim_test : public beast::unit_test::suite sim.collectors.add(sc); - for (TrustGraph::ForkInfo const& fi : - sim.trustGraph.forkablePairs(0.8)) + for (TrustGraph::ForkInfo const& fi : sim.trustGraph.forkablePairs(0.8)) { std::cout << "Can fork " << PeerGroup{fi.unlA} << " " - << " " << PeerGroup{fi.unlB} << " overlap " << fi.overlap - << " required " << fi.required << "\n"; + << " " << PeerGroup{fi.unlB} << " overlap " << fi.overlap << " required " << fi.required << "\n"; }; // set prior state @@ -66,14 +63,12 @@ class ByzantineFailureSim_test : public beast::unit_test::suite // a non-consensus approved transaction if (byzantineNodes.contains(peer)) { - peer->txInjections.emplace( - peer->lastClosedLedger.seq(), Tx{42}); + peer->txInjections.emplace(peer->lastClosedLedger.seq(), Tx{42}); } } sim.run(4); std::cout << "Branches: " << sim.branches() << "\n"; - std::cout << "Fully synchronized: " << std::boolalpha - << sim.synchronized() << "\n"; + std::cout << "Fully synchronized: " << std::boolalpha << sim.synchronized() << "\n"; // Not tessting anything currently. pass(); } diff --git a/src/test/consensus/Consensus_test.cpp b/src/test/consensus/Consensus_test.cpp index b7bfb302bc..3227ad4d1c 100644 --- a/src/test/consensus/Consensus_test.cpp +++ b/src/test/consensus/Consensus_test.cpp @@ -28,33 +28,24 @@ public: ConsensusParms const p{}; // Bizarre times forcibly close - BEAST_EXPECT(shouldCloseLedger( - true, 10, 10, 10, -10s, 10s, 1s, 1s, p, journal_)); - BEAST_EXPECT(shouldCloseLedger( - true, 10, 10, 10, 100h, 10s, 1s, 1s, p, journal_)); - BEAST_EXPECT(shouldCloseLedger( - true, 10, 10, 10, 10s, 100h, 1s, 1s, p, journal_)); + BEAST_EXPECT(shouldCloseLedger(true, 10, 10, 10, -10s, 10s, 1s, 1s, p, journal_)); + BEAST_EXPECT(shouldCloseLedger(true, 10, 10, 10, 100h, 10s, 1s, 1s, p, journal_)); + BEAST_EXPECT(shouldCloseLedger(true, 10, 10, 10, 10s, 100h, 1s, 1s, p, journal_)); // Rest of network has closed - BEAST_EXPECT( - shouldCloseLedger(true, 10, 3, 5, 10s, 10s, 10s, 10s, p, journal_)); + BEAST_EXPECT(shouldCloseLedger(true, 10, 3, 5, 10s, 10s, 10s, 10s, p, journal_)); // No transactions means wait until end of internval - BEAST_EXPECT( - !shouldCloseLedger(false, 10, 0, 0, 1s, 1s, 1s, 10s, p, journal_)); - BEAST_EXPECT( - shouldCloseLedger(false, 10, 0, 0, 1s, 10s, 1s, 10s, p, journal_)); + BEAST_EXPECT(!shouldCloseLedger(false, 10, 0, 0, 1s, 1s, 1s, 10s, p, journal_)); + BEAST_EXPECT(shouldCloseLedger(false, 10, 0, 0, 1s, 10s, 1s, 10s, p, journal_)); // Enforce minimum ledger open time - BEAST_EXPECT( - !shouldCloseLedger(true, 10, 0, 0, 10s, 10s, 1s, 10s, p, journal_)); + BEAST_EXPECT(!shouldCloseLedger(true, 10, 0, 0, 10s, 10s, 1s, 10s, p, journal_)); // Don't go too much faster than last time - BEAST_EXPECT( - !shouldCloseLedger(true, 10, 0, 0, 10s, 10s, 3s, 10s, p, journal_)); + BEAST_EXPECT(!shouldCloseLedger(true, 10, 0, 0, 10s, 10s, 3s, 10s, p, journal_)); - BEAST_EXPECT( - shouldCloseLedger(true, 10, 0, 0, 10s, 10s, 10s, 10s, p, journal_)); + BEAST_EXPECT(shouldCloseLedger(true, 10, 0, 0, 10s, 10s, 10s, 10s, p, journal_)); } void @@ -70,93 +61,61 @@ public: // Disputes still in doubt // // Not enough time has elapsed - BEAST_EXPECT( - ConsensusState::No == - checkConsensus(10, 2, 2, 0, 3s, 2s, false, p, true, journal_)); + BEAST_EXPECT(ConsensusState::No == checkConsensus(10, 2, 2, 0, 3s, 2s, false, p, true, journal_)); // If not enough peers have proposed, ensure // more time for proposals - BEAST_EXPECT( - ConsensusState::No == - checkConsensus(10, 2, 2, 0, 3s, 4s, false, p, true, journal_)); + BEAST_EXPECT(ConsensusState::No == checkConsensus(10, 2, 2, 0, 3s, 4s, false, p, true, journal_)); // Enough time has elapsed and we all agree - BEAST_EXPECT( - ConsensusState::Yes == - checkConsensus(10, 2, 2, 0, 3s, 10s, false, p, true, journal_)); + BEAST_EXPECT(ConsensusState::Yes == checkConsensus(10, 2, 2, 0, 3s, 10s, false, p, true, journal_)); // Enough time has elapsed and we don't yet agree - BEAST_EXPECT( - ConsensusState::No == - checkConsensus(10, 2, 1, 0, 3s, 10s, false, p, true, journal_)); + BEAST_EXPECT(ConsensusState::No == checkConsensus(10, 2, 1, 0, 3s, 10s, false, p, true, journal_)); // Our peers have moved on // Enough time has elapsed and we all agree - BEAST_EXPECT( - ConsensusState::MovedOn == - checkConsensus(10, 2, 1, 8, 3s, 10s, false, p, true, journal_)); + BEAST_EXPECT(ConsensusState::MovedOn == checkConsensus(10, 2, 1, 8, 3s, 10s, false, p, true, journal_)); // If no peers, don't agree until time has passed. - BEAST_EXPECT( - ConsensusState::No == - checkConsensus(0, 0, 0, 0, 3s, 10s, false, p, true, journal_)); + BEAST_EXPECT(ConsensusState::No == checkConsensus(0, 0, 0, 0, 3s, 10s, false, p, true, journal_)); // Agree if no peers and enough time has passed. - BEAST_EXPECT( - ConsensusState::Yes == - checkConsensus(0, 0, 0, 0, 3s, 16s, false, p, true, journal_)); + BEAST_EXPECT(ConsensusState::Yes == checkConsensus(0, 0, 0, 0, 3s, 16s, false, p, true, journal_)); // Expire if too much time has passed without agreement - BEAST_EXPECT( - ConsensusState::Expired == - checkConsensus(10, 8, 1, 0, 1s, 19s, false, p, true, journal_)); + BEAST_EXPECT(ConsensusState::Expired == checkConsensus(10, 8, 1, 0, 1s, 19s, false, p, true, journal_)); /////////////// // Stalled // // Not enough time has elapsed - BEAST_EXPECT( - ConsensusState::No == - checkConsensus(10, 2, 2, 0, 3s, 2s, true, p, true, journal_)); + BEAST_EXPECT(ConsensusState::No == checkConsensus(10, 2, 2, 0, 3s, 2s, true, p, true, journal_)); // If not enough peers have proposed, ensure // more time for proposals - BEAST_EXPECT( - ConsensusState::No == - checkConsensus(10, 2, 2, 0, 3s, 4s, true, p, true, journal_)); + BEAST_EXPECT(ConsensusState::No == checkConsensus(10, 2, 2, 0, 3s, 4s, true, p, true, journal_)); // Enough time has elapsed and we all agree - BEAST_EXPECT( - ConsensusState::Yes == - checkConsensus(10, 2, 2, 0, 3s, 10s, true, p, true, journal_)); + BEAST_EXPECT(ConsensusState::Yes == checkConsensus(10, 2, 2, 0, 3s, 10s, true, p, true, journal_)); // Enough time has elapsed and we don't yet agree, but there's nothing // left to dispute - BEAST_EXPECT( - ConsensusState::Yes == - checkConsensus(10, 2, 1, 0, 3s, 10s, true, p, true, journal_)); + BEAST_EXPECT(ConsensusState::Yes == checkConsensus(10, 2, 1, 0, 3s, 10s, true, p, true, journal_)); // Our peers have moved on // Enough time has elapsed and we all agree, nothing left to dispute - BEAST_EXPECT( - ConsensusState::Yes == - checkConsensus(10, 2, 1, 8, 3s, 10s, true, p, true, journal_)); + BEAST_EXPECT(ConsensusState::Yes == checkConsensus(10, 2, 1, 8, 3s, 10s, true, p, true, journal_)); // If no peers, don't agree until time has passed. - BEAST_EXPECT( - ConsensusState::No == - checkConsensus(0, 0, 0, 0, 3s, 10s, true, p, true, journal_)); + BEAST_EXPECT(ConsensusState::No == checkConsensus(0, 0, 0, 0, 3s, 10s, true, p, true, journal_)); // Agree if no peers and enough time has passed. - BEAST_EXPECT( - ConsensusState::Yes == - checkConsensus(0, 0, 0, 0, 3s, 16s, true, p, true, journal_)); + BEAST_EXPECT(ConsensusState::Yes == checkConsensus(0, 0, 0, 0, 3s, 16s, true, p, true, journal_)); // We are done if there's nothing left to dispute, no matter how much // time has passed - BEAST_EXPECT( - ConsensusState::Yes == - checkConsensus(10, 8, 1, 0, 1s, 19s, true, p, true, journal_)); + BEAST_EXPECT(ConsensusState::Yes == checkConsensus(10, 8, 1, 0, 1s, 19s, true, p, true, journal_)); } void @@ -196,8 +155,7 @@ public: PeerGroup peers = sim.createGroup(5); // Connected trust and network graphs with single fixed delay - peers.trustAndConnect( - peers, round(0.2 * parms.ledgerGRANULARITY)); + peers.trustAndConnect(peers, round(0.2 * parms.ledgerGRANULARITY)); // everyone submits their own ID as a TX for (Peer* p : peers) @@ -245,11 +203,9 @@ public: network.trust(network); // Fast and slow network connections - fast.connect( - fast, round(0.2 * parms.ledgerGRANULARITY)); + fast.connect(fast, round(0.2 * parms.ledgerGRANULARITY)); - slow.connect( - network, round(1.1 * parms.ledgerGRANULARITY)); + slow.connect(network, round(1.1 * parms.ledgerGRANULARITY)); // All peers submit their own ID as a transaction for (Peer* peer : network) @@ -268,16 +224,14 @@ public: BEAST_EXPECT(lcl.seq() == Ledger::Seq{1}); BEAST_EXPECT(peer->prevProposers == network.size() - 1); - BEAST_EXPECT( - peer->prevRoundTime == network[0]->prevRoundTime); + BEAST_EXPECT(peer->prevRoundTime == network[0]->prevRoundTime); BEAST_EXPECT(lcl.txs().find(Tx{0}) == lcl.txs().end()); for (std::uint32_t i = 2; i < network.size(); ++i) BEAST_EXPECT(lcl.txs().find(Tx{i}) != lcl.txs().end()); // Tx 0 didn't make it - BEAST_EXPECT( - peer->openTxs.find(Tx{0}) != peer->openTxs.end()); + BEAST_EXPECT(peer->openTxs.find(Tx{0}) != peer->openTxs.end()); } } } @@ -301,12 +255,9 @@ public: network.trust(network); // Fast and slow network connections - fast.connect( - fast, round(0.2 * parms.ledgerGRANULARITY)); + fast.connect(fast, round(0.2 * parms.ledgerGRANULARITY)); - slow.connect( - network, - round(1.1 * parms.ledgerGRANULARITY)); + slow.connect(network, round(1.1 * parms.ledgerGRANULARITY)); for (Peer* peer : slow) peer->runAsValidator = isParticipant; @@ -330,22 +281,17 @@ public: BEAST_EXPECT(lcl.seq() == Ledger::Seq{1}); BEAST_EXPECT(lcl.txs().find(Tx{0}) == lcl.txs().end()); BEAST_EXPECT(lcl.txs().find(Tx{1}) == lcl.txs().end()); - for (std::uint32_t i = slow.size(); i < network.size(); - ++i) - BEAST_EXPECT( - lcl.txs().find(Tx{i}) != lcl.txs().end()); + for (std::uint32_t i = slow.size(); i < network.size(); ++i) + BEAST_EXPECT(lcl.txs().find(Tx{i}) != lcl.txs().end()); // Tx 0-1 didn't make it - BEAST_EXPECT( - peer->openTxs.find(Tx{0}) != peer->openTxs.end()); - BEAST_EXPECT( - peer->openTxs.find(Tx{1}) != peer->openTxs.end()); + BEAST_EXPECT(peer->openTxs.find(Tx{0}) != peer->openTxs.end()); + BEAST_EXPECT(peer->openTxs.find(Tx{1}) != peer->openTxs.end()); } Peer const* slowPeer = slow[0]; if (isParticipant) - BEAST_EXPECT( - slowPeer->prevProposers == network.size() - 1); + BEAST_EXPECT(slowPeer->prevProposers == network.size() - 1); else BEAST_EXPECT(slowPeer->prevProposers == fast.size()); @@ -369,18 +315,14 @@ public: if (isParticipant) { - BEAST_EXPECT( - peer->prevProposers == network.size() - 1); - BEAST_EXPECT( - peer->prevRoundTime > slowPeer->prevRoundTime); + BEAST_EXPECT(peer->prevProposers == network.size() - 1); + BEAST_EXPECT(peer->prevRoundTime > slowPeer->prevRoundTime); } else { - BEAST_EXPECT( - peer->prevProposers == fast.size() - 1); + BEAST_EXPECT(peer->prevProposers == fast.size() - 1); // so all peers should have closed together - BEAST_EXPECT( - peer->prevRoundTime == slowPeer->prevRoundTime); + BEAST_EXPECT(peer->prevRoundTime == slowPeer->prevRoundTime); } } } @@ -429,14 +371,12 @@ public: PeerGroup network = groupA + groupB + groupC; network.trust(network); - network.connect( - network, round(0.2 * parms.ledgerGRANULARITY)); + network.connect(network, round(0.2 * parms.ledgerGRANULARITY)); // Run consensus without skew until we have a short close time // resolution Peer* firstPeer = *groupA.begin(); - while (firstPeer->lastClosedLedger.closeTimeResolution() >= - parms.proposeFRESHNESS) + while (firstPeer->lastClosedLedger.closeTimeResolution() >= parms.proposeFRESHNESS) sim.run(1); // Introduce a shift on the time of 2/3 of peers @@ -501,8 +441,7 @@ public: PeerGroup majority = majorityA + majorityB; PeerGroup network = minority + majority; - SimDuration delay = - round(0.2 * parms.ledgerGRANULARITY); + SimDuration delay = round(0.2 * parms.ledgerGRANULARITY); minority.trustAndConnect(minority + majorityA, delay); majority.trustAndConnect(majority, delay); @@ -562,8 +501,7 @@ public: { if (BEAST_EXPECT(peerJumps.closeJumps.size() == 1)) { - JumpCollector::Jump const& jump = - peerJumps.closeJumps.front(); + JumpCollector::Jump const& jump = peerJumps.closeJumps.front(); // Jump is to a different chain BEAST_EXPECT(jump.from.seq() <= jump.to.seq()); BEAST_EXPECT(!jump.to.isAncestor(jump.from)); @@ -571,11 +509,9 @@ public: } // fully validated jump forward in same chain { - if (BEAST_EXPECT( - peerJumps.fullyValidatedJumps.size() == 1)) + if (BEAST_EXPECT(peerJumps.fullyValidatedJumps.size() == 1)) { - JumpCollector::Jump const& jump = - peerJumps.fullyValidatedJumps.front(); + JumpCollector::Jump const& jump = peerJumps.fullyValidatedJumps.front(); // Jump is to a different chain with same seq BEAST_EXPECT(jump.from.seq() < jump.to.seq()); BEAST_EXPECT(jump.to.isAncestor(jump.from)); @@ -606,8 +542,7 @@ public: clique.trust(clique); PeerGroup network = loner + clique; - network.connect( - network, round(0.2 * parms.ledgerGRANULARITY)); + network.connect(network, round(0.2 * parms.ledgerGRANULARITY)); // initial round to set prior state sim.run(1); @@ -655,8 +590,7 @@ public: // Fast and slow network connections fast.connect(fast, round(0.2 * parms.ledgerGRANULARITY)); - slow.connect( - network, round(1.1 * parms.ledgerGRANULARITY)); + slow.connect(network, round(1.1 * parms.ledgerGRANULARITY)); // Run to the ledger *prior* to decreasing the resolution sim.run(increaseLedgerTimeResolutionEvery - 2); @@ -678,8 +612,7 @@ public: NetClock::duration when = network[0]->now().time_since_epoch(); // Check we are before the 30s to 20s transition - NetClock::duration resolution = - network[0]->lastClosedLedger.closeTimeResolution(); + NetClock::duration resolution = network[0]->lastClosedLedger.closeTimeResolution(); BEAST_EXPECT(resolution == NetClock::duration{30s}); while (((when % NetClock::duration{30s}) != NetClock::duration{15s}) || @@ -756,8 +689,7 @@ public: PeerGroup network = a + b; - SimDuration delay = - round(0.2 * parms.ledgerGRANULARITY); + SimDuration delay = round(0.2 * parms.ledgerGRANULARITY); a.trustAndConnect(a, delay); b.trustAndConnect(b, delay); @@ -768,8 +700,7 @@ public: // Nodes have only seen transactions from their neighbors peer->openTxs.insert(Tx{static_cast(peer->id)}); for (Peer* to : sim.trustGraph.trustedPeers(peer)) - peer->openTxs.insert( - Tx{static_cast(to->id)}); + peer->openTxs.insert(Tx{static_cast(to->id)}); } sim.run(1); @@ -832,11 +763,7 @@ public: csf::SimDuration delay; bool reconnected = false; - Disruptor( - csf::PeerGroup& net, - csf::PeerGroup& c, - csf::PeerGroup& split, - csf::SimDuration d) + Disruptor(csf::PeerGroup& net, csf::PeerGroup& c, csf::PeerGroup& split, csf::SimDuration d) : network(net), groupCfast(c), groupCsplit(split), delay(d) { } @@ -854,8 +781,7 @@ public: // As soon as the fastC node fully validates C, disconnect // ALL c nodes from the network. The fast C node needs to disconnect // as well to prevent it from relaying the validations it did see - if (who == groupCfast[0]->id && - e.ledger.seq() == csf::Ledger::Seq{2}) + if (who == groupCfast[0]->id && e.ledger.seq() == csf::Ledger::Seq{2}) { network.disconnect(groupCsplit); network.disconnect(groupCfast); @@ -1079,11 +1005,8 @@ public: // Simulate clients submitting 1 tx every 5 seconds to a random // validator Rate const rate{1, 5s}; - auto peerSelector = makeSelector( - network.begin(), - network.end(), - std::vector(network.size(), 1.), - sim.rng); + auto peerSelector = + makeSelector(network.begin(), network.end(), std::vector(network.size(), 1.), sim.rng); auto txSubmitter = makeSubmitter( ConstantDistribution{rate.inv()}, sim.scheduler.now(), @@ -1129,10 +1052,8 @@ public: { Dispute proposingTrue{txTrue.id(), true, numPeers, journal_}; Dispute proposingFalse{txFalse.id(), false, numPeers, journal_}; - Dispute followingTrue{ - txFollowingTrue.id(), true, numPeers, journal_}; - Dispute followingFalse{ - txFollowingFalse.id(), false, numPeers, journal_}; + Dispute followingTrue{txFollowingTrue.id(), true, numPeers, journal_}; + Dispute followingFalse{txFollowingFalse.id(), false, numPeers, journal_}; BEAST_EXPECT(proposingTrue.ID() == 99); BEAST_EXPECT(proposingFalse.ID() == 98); BEAST_EXPECT(followingTrue.ID() == 97); @@ -1157,14 +1078,10 @@ public: BEAST_EXPECT(proposingFalse.getOurVote() == false); BEAST_EXPECT(followingTrue.getOurVote() == true); BEAST_EXPECT(followingFalse.getOurVote() == false); - BEAST_EXPECT( - !proposingTrue.stalled(p, true, peersUnchanged, j, clog)); - BEAST_EXPECT( - !proposingFalse.stalled(p, true, peersUnchanged, j, clog)); - BEAST_EXPECT( - !followingTrue.stalled(p, false, peersUnchanged, j, clog)); - BEAST_EXPECT( - !followingFalse.stalled(p, false, peersUnchanged, j, clog)); + BEAST_EXPECT(!proposingTrue.stalled(p, true, peersUnchanged, j, clog)); + BEAST_EXPECT(!proposingFalse.stalled(p, true, peersUnchanged, j, clog)); + BEAST_EXPECT(!followingTrue.stalled(p, false, peersUnchanged, j, clog)); + BEAST_EXPECT(!followingFalse.stalled(p, false, peersUnchanged, j, clog)); BEAST_EXPECT(clog->str() == ""); // I'm in the majority, my vote should not change @@ -1179,14 +1096,10 @@ public: BEAST_EXPECT(!followingFalse.updateVote(10, false, p)); peersUnchanged = 2; - BEAST_EXPECT( - !proposingTrue.stalled(p, true, peersUnchanged, j, clog)); - BEAST_EXPECT( - !proposingFalse.stalled(p, true, peersUnchanged, j, clog)); - BEAST_EXPECT( - !followingTrue.stalled(p, false, peersUnchanged, j, clog)); - BEAST_EXPECT( - !followingFalse.stalled(p, false, peersUnchanged, j, clog)); + BEAST_EXPECT(!proposingTrue.stalled(p, true, peersUnchanged, j, clog)); + BEAST_EXPECT(!proposingFalse.stalled(p, true, peersUnchanged, j, clog)); + BEAST_EXPECT(!followingTrue.stalled(p, false, peersUnchanged, j, clog)); + BEAST_EXPECT(!followingFalse.stalled(p, false, peersUnchanged, j, clog)); BEAST_EXPECT(clog->str() == ""); // Right now, the vote is 51%. The requirement is about to jump to @@ -1277,14 +1190,10 @@ public: BEAST_EXPECT(followingFalse.getOurVote() == false); peersUnchanged = 3; - BEAST_EXPECT( - !proposingTrue.stalled(p, true, peersUnchanged, j, clog)); - BEAST_EXPECT( - !proposingFalse.stalled(p, true, peersUnchanged, j, clog)); - BEAST_EXPECT( - !followingTrue.stalled(p, false, peersUnchanged, j, clog)); - BEAST_EXPECT( - !followingFalse.stalled(p, false, peersUnchanged, j, clog)); + BEAST_EXPECT(!proposingTrue.stalled(p, true, peersUnchanged, j, clog)); + BEAST_EXPECT(!proposingFalse.stalled(p, true, peersUnchanged, j, clog)); + BEAST_EXPECT(!followingTrue.stalled(p, false, peersUnchanged, j, clog)); + BEAST_EXPECT(!followingFalse.stalled(p, false, peersUnchanged, j, clog)); BEAST_EXPECT(clog->str() == ""); // Threshold jumps to 95% @@ -1322,67 +1231,33 @@ public: for (peersUnchanged = 0; peersUnchanged < 6; ++peersUnchanged) { - BEAST_EXPECT( - !proposingTrue.stalled(p, true, peersUnchanged, j, clog)); - BEAST_EXPECT( - !proposingFalse.stalled(p, true, peersUnchanged, j, clog)); - BEAST_EXPECT( - !followingTrue.stalled(p, false, peersUnchanged, j, clog)); - BEAST_EXPECT( - !followingFalse.stalled(p, false, peersUnchanged, j, clog)); + BEAST_EXPECT(!proposingTrue.stalled(p, true, peersUnchanged, j, clog)); + BEAST_EXPECT(!proposingFalse.stalled(p, true, peersUnchanged, j, clog)); + BEAST_EXPECT(!followingTrue.stalled(p, false, peersUnchanged, j, clog)); + BEAST_EXPECT(!followingFalse.stalled(p, false, peersUnchanged, j, clog)); BEAST_EXPECT(clog->str() == ""); } - auto expectStalled = [this, &clog]( - int txid, - bool ourVote, - int ourTime, - int peerTime, - int support, - std::uint32_t line) { - using namespace std::string_literals; + auto expectStalled = + [this, &clog](int txid, bool ourVote, int ourTime, int peerTime, int support, std::uint32_t line) { + using namespace std::string_literals; - auto const s = clog->str(); - expect(s.find("stalled"), s, __FILE__, line); - expect( - s.starts_with("Transaction "s + std::to_string(txid)), - s, - __FILE__, - line); - expect( - s.find("voting "s + (ourVote ? "YES" : "NO")) != s.npos, - s, - __FILE__, - line); - expect( - s.find("for "s + std::to_string(ourTime) + " rounds."s) != - s.npos, - s, - __FILE__, - line); - expect( - s.find( - "votes in "s + std::to_string(peerTime) + " rounds.") != - s.npos, - s, - __FILE__, - line); - expect( - s.ends_with( - "has "s + std::to_string(support) + "% support. "s), - s, - __FILE__, - line); - clog = std::make_unique(); - }; + auto const s = clog->str(); + expect(s.find("stalled"), s, __FILE__, line); + expect(s.starts_with("Transaction "s + std::to_string(txid)), s, __FILE__, line); + expect(s.find("voting "s + (ourVote ? "YES" : "NO")) != s.npos, s, __FILE__, line); + expect(s.find("for "s + std::to_string(ourTime) + " rounds."s) != s.npos, s, __FILE__, line); + expect(s.find("votes in "s + std::to_string(peerTime) + " rounds.") != s.npos, s, __FILE__, line); + expect(s.ends_with("has "s + std::to_string(support) + "% support. "s), s, __FILE__, line); + clog = std::make_unique(); + }; for (int i = 0; i < 1; ++i) { BEAST_EXPECT(!proposingTrue.updateVote(250 + 10 * i, true, p)); BEAST_EXPECT(!proposingFalse.updateVote(250 + 10 * i, true, p)); BEAST_EXPECT(!followingTrue.updateVote(250 + 10 * i, false, p)); - BEAST_EXPECT( - !followingFalse.updateVote(250 + 10 * i, false, p)); + BEAST_EXPECT(!followingFalse.updateVote(250 + 10 * i, false, p)); BEAST_EXPECT(proposingTrue.getOurVote() == true); BEAST_EXPECT(proposingFalse.getOurVote() == false); @@ -1403,20 +1278,16 @@ public: expectStalled(96, false, 11, 0, 3, __LINE__); // true vote has changed recently, so not stalled - BEAST_EXPECT( - !proposingTrue.stalled(p, true, peersUnchanged, j, clog)); + BEAST_EXPECT(!proposingTrue.stalled(p, true, peersUnchanged, j, clog)); BEAST_EXPECTS(clog->str() == "", clog->str()); // remaining votes have been unchanged in so long that we only // need to hit the second round at 95% to be stalled, regardless // of peers - BEAST_EXPECT( - proposingFalse.stalled(p, true, peersUnchanged, j, clog)); + BEAST_EXPECT(proposingFalse.stalled(p, true, peersUnchanged, j, clog)); expectStalled(98, false, 11, 6, 2, __LINE__); - BEAST_EXPECT( - followingTrue.stalled(p, false, peersUnchanged, j, clog)); + BEAST_EXPECT(followingTrue.stalled(p, false, peersUnchanged, j, clog)); expectStalled(97, true, 11, 6, 97, __LINE__); - BEAST_EXPECT( - followingFalse.stalled(p, false, peersUnchanged, j, clog)); + BEAST_EXPECT(followingFalse.stalled(p, false, peersUnchanged, j, clog)); expectStalled(96, false, 11, 6, 3, __LINE__); } for (int i = 1; i < 3; ++i) @@ -1424,8 +1295,7 @@ public: BEAST_EXPECT(!proposingTrue.updateVote(250 + 10 * i, true, p)); BEAST_EXPECT(!proposingFalse.updateVote(250 + 10 * i, true, p)); BEAST_EXPECT(!followingTrue.updateVote(250 + 10 * i, false, p)); - BEAST_EXPECT( - !followingFalse.updateVote(250 + 10 * i, false, p)); + BEAST_EXPECT(!followingFalse.updateVote(250 + 10 * i, false, p)); BEAST_EXPECT(proposingTrue.getOurVote() == true); BEAST_EXPECT(proposingFalse.getOurVote() == false); @@ -1446,18 +1316,14 @@ public: // true vote changed 2 rounds ago, and peers are NOT changing, // so stalled - BEAST_EXPECT( - proposingTrue.stalled(p, true, peersUnchanged, j, clog)); + BEAST_EXPECT(proposingTrue.stalled(p, true, peersUnchanged, j, clog)); expectStalled(99, true, 1 + i, 6, 97, __LINE__); // still stalled - BEAST_EXPECT( - proposingFalse.stalled(p, true, peersUnchanged, j, clog)); + BEAST_EXPECT(proposingFalse.stalled(p, true, peersUnchanged, j, clog)); expectStalled(98, false, 11 + i, 6, 2, __LINE__); - BEAST_EXPECT( - followingTrue.stalled(p, false, peersUnchanged, j, clog)); + BEAST_EXPECT(followingTrue.stalled(p, false, peersUnchanged, j, clog)); expectStalled(97, true, 11 + i, 6, 97, __LINE__); - BEAST_EXPECT( - followingFalse.stalled(p, false, peersUnchanged, j, clog)); + BEAST_EXPECT(followingFalse.stalled(p, false, peersUnchanged, j, clog)); expectStalled(96, false, 11 + i, 6, 3, __LINE__); } for (int i = 3; i < 5; ++i) @@ -1465,8 +1331,7 @@ public: BEAST_EXPECT(!proposingTrue.updateVote(250 + 10 * i, true, p)); BEAST_EXPECT(!proposingFalse.updateVote(250 + 10 * i, true, p)); BEAST_EXPECT(!followingTrue.updateVote(250 + 10 * i, false, p)); - BEAST_EXPECT( - !followingFalse.updateVote(250 + 10 * i, false, p)); + BEAST_EXPECT(!followingFalse.updateVote(250 + 10 * i, false, p)); BEAST_EXPECT(proposingTrue.getOurVote() == true); BEAST_EXPECT(proposingFalse.getOurVote() == false); @@ -1482,17 +1347,13 @@ public: BEAST_EXPECT(followingFalse.stalled(p, false, 0, j, clog)); expectStalled(96, false, 11 + i, 0, 3, __LINE__); - BEAST_EXPECT( - proposingTrue.stalled(p, true, peersUnchanged, j, clog)); + BEAST_EXPECT(proposingTrue.stalled(p, true, peersUnchanged, j, clog)); expectStalled(99, true, 1 + i, 6, 97, __LINE__); - BEAST_EXPECT( - proposingFalse.stalled(p, true, peersUnchanged, j, clog)); + BEAST_EXPECT(proposingFalse.stalled(p, true, peersUnchanged, j, clog)); expectStalled(98, false, 11 + i, 6, 2, __LINE__); - BEAST_EXPECT( - followingTrue.stalled(p, false, peersUnchanged, j, clog)); + BEAST_EXPECT(followingTrue.stalled(p, false, peersUnchanged, j, clog)); expectStalled(97, true, 11 + i, 6, 97, __LINE__); - BEAST_EXPECT( - followingFalse.stalled(p, false, peersUnchanged, j, clog)); + BEAST_EXPECT(followingFalse.stalled(p, false, peersUnchanged, j, clog)); expectStalled(96, false, 11 + i, 6, 3, __LINE__); } } diff --git a/src/test/consensus/DistributedValidatorsSim_test.cpp b/src/test/consensus/DistributedValidatorsSim_test.cpp index 1a088576ce..49d2c6e7e2 100644 --- a/src/test/consensus/DistributedValidatorsSim_test.cpp +++ b/src/test/consensus/DistributedValidatorsSim_test.cpp @@ -35,8 +35,7 @@ class DistributedValidators_test : public beast::unit_test::suite ledgerLog(prefix + "_ledger.csv", std::ofstream::app); // title - log << prefix << "(" << numPeers << "," << delay.count() << ")" - << std::endl; + log << prefix << "(" << numPeers << "," << delay.count() << ")" << std::endl; // number of peers, UNLs, connections BEAST_EXPECT(numPeers >= 1); @@ -68,11 +67,7 @@ class DistributedValidators_test : public beast::unit_test::suite HeartbeatTimer heart(sim.scheduler); // txs, start/stop/step, target - auto peerSelector = makeSelector( - peers.begin(), - peers.end(), - std::vector(numPeers, 1.), - sim.rng); + auto peerSelector = makeSelector(peers.begin(), peers.end(), std::vector(numPeers, 1.), sim.rng); auto txSubmitter = makeSubmitter( ConstantDistribution{rate.inv()}, sim.scheduler.now() + quiet, @@ -90,11 +85,9 @@ class DistributedValidators_test : public beast::unit_test::suite log << std::right; log << "| Peers: " << std::setw(2) << peers.size(); - log << " | Duration: " << std::setw(6) - << duration_cast(simDuration).count() << " ms"; + log << " | Duration: " << std::setw(6) << duration_cast(simDuration).count() << " ms"; log << " | Branches: " << std::setw(1) << sim.branches(); - log << " | Synchronized: " << std::setw(1) - << (sim.synchronized() ? "Y" : "N"); + log << " | Synchronized: " << std::setw(1) << (sim.synchronized() ? "Y" : "N"); log << " |" << std::endl; txCollector.report(simDuration, log, true); @@ -124,8 +117,7 @@ class DistributedValidators_test : public beast::unit_test::suite ledgerLog(prefix + "_ledger.csv", std::ofstream::app); // title - log << prefix << "(" << numPeers << "," << delay.count() << ")" - << std::endl; + log << prefix << "(" << numPeers << "," << delay.count() << ")" << std::endl; // number of peers, UNLs, connections int const numCNLs = std::max(int(1.00 * numPeers), 1); @@ -133,9 +125,7 @@ class DistributedValidators_test : public beast::unit_test::suite int const maxCNLSize = std::max(int(0.50 * numCNLs), 1); BEAST_EXPECT(numPeers >= 1); BEAST_EXPECT(numCNLs >= 1); - BEAST_EXPECT( - 1 <= minCNLSize && minCNLSize <= maxCNLSize && - maxCNLSize <= numPeers); + BEAST_EXPECT(1 <= minCNLSize && minCNLSize <= maxCNLSize && maxCNLSize <= numPeers); Sim sim; PeerGroup peers = sim.createGroup(numPeers); @@ -144,15 +134,9 @@ class DistributedValidators_test : public beast::unit_test::suite peers.trust(peers); // scale-free connect graph with fixed delay - std::vector const ranks = - sample(peers.size(), PowerLawDistribution{1, 3}, sim.rng); + std::vector const ranks = sample(peers.size(), PowerLawDistribution{1, 3}, sim.rng); randomRankedConnect( - peers, - ranks, - numCNLs, - std::uniform_int_distribution<>{minCNLSize, maxCNLSize}, - sim.rng, - delay); + peers, ranks, numCNLs, std::uniform_int_distribution<>{minCNLSize, maxCNLSize}, sim.rng, delay); // Initialize collectors to track statistics to report TxCollector txCollector; @@ -172,11 +156,7 @@ class DistributedValidators_test : public beast::unit_test::suite HeartbeatTimer heart(sim.scheduler); // txs, start/stop/step, target - auto peerSelector = makeSelector( - peers.begin(), - peers.end(), - std::vector(numPeers, 1.), - sim.rng); + auto peerSelector = makeSelector(peers.begin(), peers.end(), std::vector(numPeers, 1.), sim.rng); auto txSubmitter = makeSubmitter( ConstantDistribution{rate.inv()}, sim.scheduler.now() + quiet, @@ -194,11 +174,9 @@ class DistributedValidators_test : public beast::unit_test::suite log << std::right; log << "| Peers: " << std::setw(2) << peers.size(); - log << " | Duration: " << std::setw(6) - << duration_cast(simDuration).count() << " ms"; + log << " | Duration: " << std::setw(6) << duration_cast(simDuration).count() << " ms"; log << " | Branches: " << std::setw(1) << sim.branches(); - log << " | Synchronized: " << std::setw(1) - << (sim.synchronized() ? "Y" : "N"); + log << " | Synchronized: " << std::setw(1) << (sim.synchronized() ? "Y" : "N"); log << " |" << std::endl; txCollector.report(simDuration, log, true); @@ -225,8 +203,7 @@ class DistributedValidators_test : public beast::unit_test::suite std::chrono::milliseconds const delay(delayCount); - log << "DistributedValidators: 1 to " << maxNumValidators << " Peers" - << std::endl; + log << "DistributedValidators: 1 to " << maxNumValidators << " Peers" << std::endl; /** * Simulate with N = 1 to N diff --git a/src/test/consensus/LedgerTiming_test.cpp b/src/test/consensus/LedgerTiming_test.cpp index 0ec3563c79..ac00cd1f3a 100644 --- a/src/test/consensus/LedgerTiming_test.cpp +++ b/src/test/consensus/LedgerTiming_test.cpp @@ -26,8 +26,7 @@ class LedgerTiming_test : public beast::unit_test::suite std::uint32_t round = 0; do { - nextCloseResolution = getNextLedgerTimeResolution( - closeResolution, previousAgree, ++round); + nextCloseResolution = getNextLedgerTimeResolution(closeResolution, previousAgree, ++round); if (nextCloseResolution < closeResolution) ++res.decrease; else if (nextCloseResolution > closeResolution) diff --git a/src/test/consensus/NegativeUNL_test.cpp b/src/test/consensus/NegativeUNL_test.cpp index 535aec03bf..9e77f158a3 100644 --- a/src/test/consensus/NegativeUNL_test.cpp +++ b/src/test/consensus/NegativeUNL_test.cpp @@ -34,11 +34,7 @@ namespace test { * @return true if meet all three expectation */ bool -negUnlSizeTest( - std::shared_ptr const& l, - size_t size, - bool hasToDisable, - bool hasToReEnable); +negUnlSizeTest(std::shared_ptr const& l, size_t size, bool hasToDisable, bool hasToReEnable); /** * Try to apply a ttUNL_MODIFY Tx, and test the apply result @@ -62,9 +58,7 @@ applyAndTestResult(jtx::Env& env, OpenView& view, STTx const& tx, bool pass); * @return true if meet the expectation */ bool -VerifyPubKeyAndSeq( - std::shared_ptr const& l, - hash_map nUnlLedgerSeq); +VerifyPubKeyAndSeq(std::shared_ptr const& l, hash_map nUnlLedgerSeq); /** * Count the number of Tx in a TxSet @@ -211,10 +205,7 @@ class NegativeUNL_test : public beast::unit_test::suite std::vector publicKeys = createPublicKeys(3); // genesis ledger auto l = std::make_shared( - create_genesis, - env.app().config(), - std::vector{}, - env.app().getNodeFamily()); + create_genesis, env.app().config(), std::vector{}, env.app().getNodeFamily()); // Record the public keys and ledger sequences of expected negative UNL // validators when we build the ledger history @@ -222,8 +213,7 @@ class NegativeUNL_test : public beast::unit_test::suite { //(1) the ledger after genesis, not a flag ledger - l = std::make_shared( - *l, env.app().timeKeeper().closeTime()); + l = std::make_shared(*l, env.app().timeKeeper().closeTime()); auto txDisable_0 = createTx(true, l->seq(), publicKeys[0]); auto txReEnable_1 = createTx(false, l->seq(), publicKeys[1]); @@ -240,8 +230,7 @@ class NegativeUNL_test : public beast::unit_test::suite // generate more ledgers for (auto i = 0; i < 256 - 2; ++i) { - l = std::make_shared( - *l, env.app().timeKeeper().closeTime()); + l = std::make_shared(*l, env.app().timeKeeper().closeTime()); } BEAST_EXPECT(l->isFlagLedger()); l->updateNegativeUNL(); @@ -276,8 +265,7 @@ class NegativeUNL_test : public beast::unit_test::suite BEAST_EXPECT(good_size); if (good_size) BEAST_EXPECT(l->validatorToDisable() == publicKeys[0]); - l = std::make_shared( - *l, env.app().timeKeeper().closeTime()); + l = std::make_shared(*l, env.app().timeKeeper().closeTime()); } BEAST_EXPECT(l->isFlagLedger()); l->updateNegativeUNL(); @@ -329,8 +317,7 @@ class NegativeUNL_test : public beast::unit_test::suite BEAST_EXPECT(l->validatorToDisable() == publicKeys[1]); BEAST_EXPECT(l->validatorToReEnable() == publicKeys[0]); } - l = std::make_shared( - *l, env.app().timeKeeper().closeTime()); + l = std::make_shared(*l, env.app().timeKeeper().closeTime()); } BEAST_EXPECT(l->isFlagLedger()); l->updateNegativeUNL(); @@ -372,8 +359,7 @@ class NegativeUNL_test : public beast::unit_test::suite BEAST_EXPECT(l->negativeUNL().count(publicKeys[1])); BEAST_EXPECT(l->validatorToDisable() == publicKeys[0]); } - l = std::make_shared( - *l, env.app().timeKeeper().closeTime()); + l = std::make_shared(*l, env.app().timeKeeper().closeTime()); } BEAST_EXPECT(l->isFlagLedger()); l->updateNegativeUNL(); @@ -422,8 +408,7 @@ class NegativeUNL_test : public beast::unit_test::suite BEAST_EXPECT(l->negativeUNL().count(publicKeys[1])); BEAST_EXPECT(l->validatorToReEnable() == publicKeys[0]); } - l = std::make_shared( - *l, env.app().timeKeeper().closeTime()); + l = std::make_shared(*l, env.app().timeKeeper().closeTime()); } BEAST_EXPECT(l->isFlagLedger()); l->updateNegativeUNL(); @@ -465,8 +450,7 @@ class NegativeUNL_test : public beast::unit_test::suite BEAST_EXPECT(l->negativeUNL().count(publicKeys[1])); BEAST_EXPECT(l->validatorToReEnable() == publicKeys[1]); } - l = std::make_shared( - *l, env.app().timeKeeper().closeTime()); + l = std::make_shared(*l, env.app().timeKeeper().closeTime()); } BEAST_EXPECT(l->isFlagLedger()); l->updateNegativeUNL(); @@ -480,8 +464,7 @@ class NegativeUNL_test : public beast::unit_test::suite for (auto i = 0; i < 256; ++i) { BEAST_EXPECT(negUnlSizeTest(l, 0, false, false)); - l = std::make_shared( - *l, env.app().timeKeeper().closeTime()); + l = std::make_shared(*l, env.app().timeKeeper().closeTime()); } BEAST_EXPECT(l->isFlagLedger()); l->updateNegativeUNL(); @@ -523,9 +506,7 @@ struct NetworkHistory }; NetworkHistory(beast::unit_test::suite& suite, Parameter const& p) - : env(suite, jtx::testable_amendments()) - , param(p) - , validations(env.app().getValidations()) + : env(suite, jtx::testable_amendments()), param(p), validations(env.app().getValidations()) { createNodes(); if (!param.numLedgers) @@ -555,10 +536,7 @@ struct NetworkHistory { static uint256 fake_amendment; // So we have different genesis ledgers auto l = std::make_shared( - create_genesis, - env.app().config(), - std::vector{fake_amendment++}, - env.app().getNodeFamily()); + create_genesis, env.app().config(), std::vector{fake_amendment++}, env.app().getNodeFamily()); history.push_back(l); // When putting validators into the negative UNL, we start with @@ -566,8 +544,7 @@ struct NetworkHistory int nidx = 0; while (l->seq() <= param.numLedgers) { - l = std::make_shared( - *l, env.app().timeKeeper().closeTime()); + l = std::make_shared(*l, env.app().timeKeeper().closeTime()); history.push_back(l); if (l->isFlagLedger()) @@ -601,8 +578,7 @@ struct NetworkHistory } l->updateSkipList(); } - return negUnlSizeTest( - l, param.negUNLSize, param.hasToDisable, param.hasToReEnable); + return negUnlSizeTest(l, param.negUNLSize, param.hasToDisable, param.hasToReEnable); } /** @@ -616,11 +592,7 @@ struct NetworkHistory { static auto keyPair = randomKeyPair(KeyType::secp256k1); return std::make_shared( - env.app().timeKeeper().now(), - keyPair.first, - keyPair.second, - v, - [&](STValidation& v) { + env.app().timeKeeper().now(), keyPair.first, keyPair.second, v, [&](STValidation& v) { v.setFieldH256(sfLedgerHash, ledger->header().hash); v.setFieldU32(sfLedgerSequence, ledger->seq()); v.setFlag(vfFullValidation); @@ -688,18 +660,12 @@ auto defaultPreVote = [](NegativeUNLVote& vote) {}; */ template bool -voteAndCheck( - NetworkHistory& history, - NodeID const& myId, - std::size_t expect, - PreVote const& pre = defaultPreVote) +voteAndCheck(NetworkHistory& history, NodeID const& myId, std::size_t expect, PreVote const& pre = defaultPreVote) { NegativeUNLVote vote(myId, history.env.journal); pre(vote); - auto txSet = std::make_shared( - SHAMapType::TRANSACTION, history.env.app().getNodeFamily()); - vote.doVoting( - history.lastLedger(), history.UNLKeySet, history.validations, txSet); + auto txSet = std::make_shared(SHAMapType::TRANSACTION, history.env.app().getNodeFamily()); + vote.doVoting(history.lastLedger(), history.UNLKeySet, history.validations, txSet); return countTx(txSet) == expect; } @@ -718,12 +684,9 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite NegativeUNLVote vote(myId, env.journal); // one add, one remove - auto txSet = std::make_shared( - SHAMapType::TRANSACTION, env.app().getNodeFamily()); - PublicKey toDisableKey( - derivePublicKey(KeyType::ed25519, randomSecretKey())); - PublicKey toReEnableKey( - derivePublicKey(KeyType::ed25519, randomSecretKey())); + auto txSet = std::make_shared(SHAMapType::TRANSACTION, env.app().getNodeFamily()); + PublicKey toDisableKey(derivePublicKey(KeyType::ed25519, randomSecretKey())); + PublicKey toReEnableKey(derivePublicKey(KeyType::ed25519, randomSecretKey())); LedgerIndex seq(1234); BEAST_EXPECT(countTx(txSet) == 0); vote.addTx(seq, toDisableKey, NegativeUNLVote::ToDisable, txSet); @@ -777,12 +740,8 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite BEAST_EXPECT(history.goodHistory); if (history.goodHistory) { - NegativeUNLVote vote( - history.UNLNodeIDs[3], history.env.journal); - BEAST_EXPECT(!vote.buildScoreTable( - history.lastLedger(), - history.UNLNodeIDSet, - history.validations)); + NegativeUNLVote vote(history.UNLNodeIDs[3], history.env.journal); + BEAST_EXPECT(!vote.buildScoreTable(history.lastLedger(), history.UNLNodeIDSet, history.validations)); } } @@ -792,12 +751,8 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite BEAST_EXPECT(history.goodHistory); if (history.goodHistory) { - NegativeUNLVote vote( - history.UNLNodeIDs[3], history.env.journal); - BEAST_EXPECT(!vote.buildScoreTable( - history.lastLedger(), - history.UNLNodeIDSet, - history.validations)); + NegativeUNLVote vote(history.UNLNodeIDs[3], history.env.journal); + BEAST_EXPECT(!vote.buildScoreTable(history.lastLedger(), history.UNLNodeIDSet, history.validations)); } } @@ -809,18 +764,12 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite { NodeID myId = history.UNLNodeIDs[3]; history.walkHistoryAndAddValidations( - [&](std::shared_ptr const& l, - std::size_t idx) -> bool { + [&](std::shared_ptr const& l, std::size_t idx) -> bool { // skip half my validations. - return !( - history.UNLNodeIDs[idx] == myId && - l->seq() % 2 == 0); + return !(history.UNLNodeIDs[idx] == myId && l->seq() % 2 == 0); }); NegativeUNLVote vote(myId, history.env.journal); - BEAST_EXPECT(!vote.buildScoreTable( - history.lastLedger(), - history.UNLNodeIDSet, - history.validations)); + BEAST_EXPECT(!vote.buildScoreTable(history.lastLedger(), history.UNLNodeIDSet, history.validations)); } } @@ -831,8 +780,7 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite // We need two chains for these tests bool wrongChainSuccess = history.goodHistory; BEAST_EXPECT(wrongChainSuccess); - NetworkHistory::LedgerHistory wrongChain = - std::move(history.history); + NetworkHistory::LedgerHistory wrongChain = std::move(history.history); // Create a new chain and use it as the one that majority of nodes // follow history.createLedgerHistory(); @@ -843,8 +791,7 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite NodeID myId = history.UNLNodeIDs[3]; NodeID badNode = history.UNLNodeIDs[4]; history.walkHistoryAndAddValidations( - [&](std::shared_ptr const& l, - std::size_t idx) -> bool { + [&](std::shared_ptr const& l, std::size_t idx) -> bool { // everyone but me return !(history.UNLNodeIDs[idx] == myId); }); @@ -863,10 +810,7 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite // local node still on wrong chain, can build a scoreTable, // but all other nodes' scores are zero - auto scoreTable = vote.buildScoreTable( - wrongChain.back(), - history.UNLNodeIDSet, - history.validations); + auto scoreTable = vote.buildScoreTable(wrongChain.back(), history.UNLNodeIDSet, history.validations); BEAST_EXPECT(scoreTable); if (scoreTable) { @@ -881,10 +825,7 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite // if local node switched to right history, but cannot build // scoreTable because not enough local validations - BEAST_EXPECT(!vote.buildScoreTable( - history.lastLedger(), - history.UNLNodeIDSet, - history.validations)); + BEAST_EXPECT(!vote.buildScoreTable(history.lastLedger(), history.UNLNodeIDSet, history.validations)); } } @@ -895,14 +836,9 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite if (history.goodHistory) { history.walkHistoryAndAddValidations( - [&](std::shared_ptr const& l, - std::size_t idx) -> bool { return true; }); - NegativeUNLVote vote( - history.UNLNodeIDs[3], history.env.journal); - auto scoreTable = vote.buildScoreTable( - history.lastLedger(), - history.UNLNodeIDSet, - history.validations); + [&](std::shared_ptr const& l, std::size_t idx) -> bool { return true; }); + NegativeUNLVote vote(history.UNLNodeIDs[3], history.env.journal); + auto scoreTable = vote.buildScoreTable(history.lastLedger(), history.UNLNodeIDSet, history.validations); BEAST_EXPECT(scoreTable); if (scoreTable) { @@ -937,8 +873,7 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite std::size_t numDisable, std::size_t numReEnable) { - auto [disableCandidates, reEnableCandidates] = - vote.findAllCandidates(unl, negUnl, scoreTable); + auto [disableCandidates, reEnableCandidates] = vote.findAllCandidates(unl, negUnl, scoreTable); bool rightDisable = disableCandidates.size() == numDisable; bool rightReEnable = reEnableCandidates.size() == numReEnable; return rightDisable && rightReEnable; @@ -979,44 +914,36 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite { // all good scores - BEAST_EXPECT(checkCandidateSizes( - vote, history.UNLNodeIDSet, negUnl_012, goodScoreTable, 0, 3)); + BEAST_EXPECT(checkCandidateSizes(vote, history.UNLNodeIDSet, negUnl_012, goodScoreTable, 0, 3)); } { // all bad scores hash_map scoreTable; for (auto& n : history.UNLNodeIDs) scoreTable[n] = NegativeUNLVote::negativeUNLLowWaterMark - 1; - BEAST_EXPECT(checkCandidateSizes( - vote, history.UNLNodeIDSet, negUnl_012, scoreTable, 35 - 3, 0)); + BEAST_EXPECT(checkCandidateSizes(vote, history.UNLNodeIDSet, negUnl_012, scoreTable, 35 - 3, 0)); } { // all between watermarks hash_map scoreTable; for (auto& n : history.UNLNodeIDs) scoreTable[n] = NegativeUNLVote::negativeUNLLowWaterMark + 1; - BEAST_EXPECT(checkCandidateSizes( - vote, history.UNLNodeIDSet, negUnl_012, scoreTable, 0, 0)); + BEAST_EXPECT(checkCandidateSizes(vote, history.UNLNodeIDSet, negUnl_012, scoreTable, 0, 0)); } { // 2 good scorers in negUnl auto scoreTable = goodScoreTable; - scoreTable[*negUnl_012.begin()] = - NegativeUNLVote::negativeUNLLowWaterMark + 1; - BEAST_EXPECT(checkCandidateSizes( - vote, history.UNLNodeIDSet, negUnl_012, scoreTable, 0, 2)); + scoreTable[*negUnl_012.begin()] = NegativeUNLVote::negativeUNLLowWaterMark + 1; + BEAST_EXPECT(checkCandidateSizes(vote, history.UNLNodeIDSet, negUnl_012, scoreTable, 0, 2)); } { // 2 bad scorers not in negUnl auto scoreTable = goodScoreTable; - scoreTable[history.UNLNodeIDs[11]] = - NegativeUNLVote::negativeUNLLowWaterMark - 1; - scoreTable[history.UNLNodeIDs[12]] = - NegativeUNLVote::negativeUNLLowWaterMark - 1; - BEAST_EXPECT(checkCandidateSizes( - vote, history.UNLNodeIDSet, negUnl_012, scoreTable, 2, 3)); + scoreTable[history.UNLNodeIDs[11]] = NegativeUNLVote::negativeUNLLowWaterMark - 1; + scoreTable[history.UNLNodeIDs[12]] = NegativeUNLVote::negativeUNLLowWaterMark - 1; + BEAST_EXPECT(checkCandidateSizes(vote, history.UNLNodeIDSet, negUnl_012, scoreTable, 2, 3)); } { @@ -1025,8 +952,7 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite hash_set UNL_temp = history.UNLNodeIDSet; UNL_temp.erase(history.UNLNodeIDs[0]); UNL_temp.erase(history.UNLNodeIDs[1]); - BEAST_EXPECT(checkCandidateSizes( - vote, UNL_temp, negUnl_012, goodScoreTable, 0, 3)); + BEAST_EXPECT(checkCandidateSizes(vote, UNL_temp, negUnl_012, goodScoreTable, 0, 3)); } { @@ -1034,13 +960,11 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite auto scoreTable = goodScoreTable; scoreTable.erase(history.UNLNodeIDs[0]); scoreTable.erase(history.UNLNodeIDs[1]); - scoreTable[history.UNLNodeIDs[2]] = - NegativeUNLVote::negativeUNLLowWaterMark + 1; + scoreTable[history.UNLNodeIDs[2]] = NegativeUNLVote::negativeUNLLowWaterMark + 1; hash_set UNL_temp = history.UNLNodeIDSet; UNL_temp.erase(history.UNLNodeIDs[0]); UNL_temp.erase(history.UNLNodeIDs[1]); - BEAST_EXPECT(checkCandidateSizes( - vote, UNL_temp, negUnl_012, scoreTable, 0, 2)); + BEAST_EXPECT(checkCandidateSizes(vote, UNL_temp, negUnl_012, scoreTable, 0, 2)); } { @@ -1055,33 +979,27 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite { // 2 new validators have good scores, already in negUnl auto scoreTable = goodScoreTable; - scoreTable[new_1] = - NegativeUNLVote::negativeUNLHighWaterMark + 1; - scoreTable[new_2] = - NegativeUNLVote::negativeUNLHighWaterMark + 1; + scoreTable[new_1] = NegativeUNLVote::negativeUNLHighWaterMark + 1; + scoreTable[new_2] = NegativeUNLVote::negativeUNLHighWaterMark + 1; hash_set negUnl_temp = negUnl_012; negUnl_temp.insert(new_1); negUnl_temp.insert(new_2); - BEAST_EXPECT(checkCandidateSizes( - vote, UNL_temp, negUnl_temp, scoreTable, 0, 3 + 2)); + BEAST_EXPECT(checkCandidateSizes(vote, UNL_temp, negUnl_temp, scoreTable, 0, 3 + 2)); } { // 2 new validators have bad scores, not in negUnl auto scoreTable = goodScoreTable; scoreTable[new_1] = 0; scoreTable[new_2] = 0; - BEAST_EXPECT(checkCandidateSizes( - vote, UNL_temp, negUnl_012, scoreTable, 0, 3)); + BEAST_EXPECT(checkCandidateSizes(vote, UNL_temp, negUnl_012, scoreTable, 0, 3)); } { // expired the new validators have bad scores, not in negUnl - vote.purgeNewValidators( - 256 + NegativeUNLVote::newValidatorDisableSkip + 1); + vote.purgeNewValidators(256 + NegativeUNLVote::newValidatorDisableSkip + 1); auto scoreTable = goodScoreTable; scoreTable[new_1] = 0; scoreTable[new_2] = 0; - BEAST_EXPECT(checkCandidateSizes( - vote, UNL_temp, negUnl_012, scoreTable, 2, 3)); + BEAST_EXPECT(checkCandidateSizes(vote, UNL_temp, negUnl_012, scoreTable, 2, 3)); } } } @@ -1125,24 +1043,23 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite //== combination 1: { - auto fillScoreTable = - [&](std::uint32_t unl_size, - std::uint32_t nUnl_size, - std::uint32_t score, - hash_set& unl, - hash_set& negUnl, - hash_map& scoreTable) { - std::vector nodeIDs; - std::vector keys = createPublicKeys(unl_size); - for (auto const& k : keys) - { - nodeIDs.emplace_back(calcNodeID(k)); - unl.emplace(nodeIDs.back()); - scoreTable[nodeIDs.back()] = score; - } - for (std::uint32_t i = 0; i < nUnl_size; ++i) - negUnl.insert(nodeIDs[i]); - }; + auto fillScoreTable = [&](std::uint32_t unl_size, + std::uint32_t nUnl_size, + std::uint32_t score, + hash_set& unl, + hash_set& negUnl, + hash_map& scoreTable) { + std::vector nodeIDs; + std::vector keys = createPublicKeys(unl_size); + for (auto const& k : keys) + { + nodeIDs.emplace_back(calcNodeID(k)); + unl.emplace(nodeIDs.back()); + scoreTable[nodeIDs.back()] = score; + } + for (std::uint32_t i = 0; i < nUnl_size; ++i) + negUnl.insert(nodeIDs[i]); + }; for (auto us : unlSizes) { @@ -1153,8 +1070,7 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite hash_set unl; hash_set negUnl; hash_map scoreTable; - fillScoreTable( - us, us * np / 100, score, unl, negUnl, scoreTable); + fillScoreTable(us, us * np / 100, score, unl, negUnl, scoreTable); BEAST_EXPECT(unl.size() == us); BEAST_EXPECT(negUnl.size() == us * np / 100); BEAST_EXPECT(scoreTable.size() == us); @@ -1163,77 +1079,67 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite std::size_t toReEnable_expect = 0; if (np == 0) { - if (score < - NegativeUNLVote::negativeUNLLowWaterMark) + if (score < NegativeUNLVote::negativeUNLLowWaterMark) { toDisable_expect = us; } } else if (np == 50) { - if (score > - NegativeUNLVote::negativeUNLHighWaterMark) + if (score > NegativeUNLVote::negativeUNLHighWaterMark) { toReEnable_expect = us * np / 100; } } else { - if (score > - NegativeUNLVote::negativeUNLHighWaterMark) + if (score > NegativeUNLVote::negativeUNLHighWaterMark) { toReEnable_expect = us; } } - BEAST_EXPECT(checkCandidateSizes( - vote, - unl, - negUnl, - scoreTable, - toDisable_expect, - toReEnable_expect)); + BEAST_EXPECT( + checkCandidateSizes(vote, unl, negUnl, scoreTable, toDisable_expect, toReEnable_expect)); } } } //== combination 2: { - auto fillScoreTable = - [&](std::uint32_t unl_size, - std::uint32_t nUnl_percent, - hash_set& unl, - hash_set& negUnl, - hash_map& scoreTable) { - std::vector nodeIDs; - std::vector keys = - createPublicKeys(unl_size); - for (auto const& k : keys) - { - nodeIDs.emplace_back(calcNodeID(k)); - unl.emplace(nodeIDs.back()); - } + auto fillScoreTable = [&](std::uint32_t unl_size, + std::uint32_t nUnl_percent, + hash_set& unl, + hash_set& negUnl, + hash_map& scoreTable) { + std::vector nodeIDs; + std::vector keys = createPublicKeys(unl_size); + for (auto const& k : keys) + { + nodeIDs.emplace_back(calcNodeID(k)); + unl.emplace(nodeIDs.back()); + } - std::uint32_t nIdx = 0; - for (auto score : scores) - { - scoreTable[nodeIDs[nIdx++]] = score; - scoreTable[nodeIDs[nIdx++]] = score; - } - for (; nIdx < unl_size;) - { - scoreTable[nodeIDs[nIdx++]] = scores.back(); - } + std::uint32_t nIdx = 0; + for (auto score : scores) + { + scoreTable[nodeIDs[nIdx++]] = score; + scoreTable[nodeIDs[nIdx++]] = score; + } + for (; nIdx < unl_size;) + { + scoreTable[nodeIDs[nIdx++]] = scores.back(); + } - if (nUnl_percent == 100) - { - negUnl = unl; - } - else if (nUnl_percent == 50) - { - for (std::uint32_t i = 1; i < unl_size; i += 2) - negUnl.insert(nodeIDs[i]); - } - }; + if (nUnl_percent == 100) + { + negUnl = unl; + } + else if (nUnl_percent == 50) + { + for (std::uint32_t i = 1; i < unl_size; i += 2) + negUnl.insert(nodeIDs[i]); + } + }; for (auto us : unlSizes) { @@ -1262,13 +1168,8 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite { toReEnable_expect = negUnl.size() - 12; } - BEAST_EXPECT(checkCandidateSizes( - vote, - unl, - negUnl, - scoreTable, - toDisable_expect, - toReEnable_expect)); + BEAST_EXPECT( + checkCandidateSizes(vote, unl, negUnl, scoreTable, toDisable_expect, toReEnable_expect)); } } } @@ -1310,16 +1211,13 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite BEAST_EXPECT(vote.newValidators_[n2] == 3); } - vote.newValidators( - NegativeUNLVote::newValidatorDisableSkip, {n1, n2, n3}); + vote.newValidators(NegativeUNLVote::newValidatorDisableSkip, {n1, n2, n3}); BEAST_EXPECT(vote.newValidators_.size() == 3); if (vote.newValidators_.size() == 3) { BEAST_EXPECT(vote.newValidators_[n1] == 2); BEAST_EXPECT(vote.newValidators_[n2] == 3); - BEAST_EXPECT( - vote.newValidators_[n3] == - NegativeUNLVote::newValidatorDisableSkip); + BEAST_EXPECT(vote.newValidators_[n3] == NegativeUNLVote::newValidatorDisableSkip); } vote.purgeNewValidators(NegativeUNLVote::newValidatorDisableSkip + 2); @@ -1329,9 +1227,7 @@ class NegativeUNLVoteInternal_test : public beast::unit_test::suite vote.purgeNewValidators(NegativeUNLVote::newValidatorDisableSkip + 4); BEAST_EXPECT(vote.newValidators_.size() == 1); BEAST_EXPECT(vote.newValidators_.begin()->first == n3); - BEAST_EXPECT( - vote.newValidators_.begin()->second == - NegativeUNLVote::newValidatorDisableSkip); + BEAST_EXPECT(vote.newValidators_.begin()->second == NegativeUNLVote::newValidatorDisableSkip); } void @@ -1371,15 +1267,13 @@ class NegativeUNLVoteScoreTable_test : public beast::unit_test::suite { for (std::uint32_t sp = 0; sp < 4; ++sp) { - NetworkHistory history = { - *this, {unlSize, 0, false, false, 256 + 2}}; + NetworkHistory history = {*this, {unlSize, 0, false, false, 256 + 2}}; BEAST_EXPECT(history.goodHistory); if (history.goodHistory) { NodeID myId = history.UNLNodeIDs[3]; history.walkHistoryAndAddValidations( - [&](std::shared_ptr const& l, - std::size_t idx) -> bool { + [&](std::shared_ptr const& l, std::size_t idx) -> bool { std::size_t k; if (idx < 2) k = 0; @@ -1388,24 +1282,20 @@ class NegativeUNLVoteScoreTable_test : public beast::unit_test::suite else k = 2; - bool add_50 = - scorePattern[sp][k] == 50 && l->seq() % 2 == 0; + bool add_50 = scorePattern[sp][k] == 50 && l->seq() % 2 == 0; bool add_100 = scorePattern[sp][k] == 100; bool add_me = history.UNLNodeIDs[idx] == myId; return add_50 || add_100 || add_me; }); NegativeUNLVote vote(myId, history.env.journal); - auto scoreTable = vote.buildScoreTable( - history.lastLedger(), - history.UNLNodeIDSet, - history.validations); + auto scoreTable = + vote.buildScoreTable(history.lastLedger(), history.UNLNodeIDSet, history.validations); BEAST_EXPECT(scoreTable); if (scoreTable) { std::uint32_t i = 0; // looping unl - auto checkScores = [&](std::uint32_t score, - std::uint32_t k) -> bool { + auto checkScores = [&](std::uint32_t score, std::uint32_t k) -> bool { if (history.UNLNodeIDs[i] == myId) return score == 256; if (scorePattern[sp][k] == 0) @@ -1419,18 +1309,15 @@ class NegativeUNLVoteScoreTable_test : public beast::unit_test::suite }; for (; i < 2; ++i) { - BEAST_EXPECT(checkScores( - (*scoreTable)[history.UNLNodeIDs[i]], 0)); + BEAST_EXPECT(checkScores((*scoreTable)[history.UNLNodeIDs[i]], 0)); } for (; i < 4; ++i) { - BEAST_EXPECT(checkScores( - (*scoreTable)[history.UNLNodeIDs[i]], 1)); + BEAST_EXPECT(checkScores((*scoreTable)[history.UNLNodeIDs[i]], 1)); } for (; i < unlSize; ++i) { - BEAST_EXPECT(checkScores( - (*scoreTable)[history.UNLNodeIDs[i]], 2)); + BEAST_EXPECT(checkScores((*scoreTable)[history.UNLNodeIDs[i]], 2)); } } } @@ -1492,8 +1379,7 @@ class NegativeUNLVoteGoodScore_test : public beast::unit_test::suite if (history.goodHistory) { history.walkHistoryAndAddValidations( - [&](std::shared_ptr const& l, - std::size_t idx) -> bool { return true; }); + [&](std::shared_ptr const& l, std::size_t idx) -> bool { return true; }); BEAST_EXPECT(voteAndCheck(history, history.UNLNodeIDs[0], 0)); } } @@ -1506,8 +1392,7 @@ class NegativeUNLVoteGoodScore_test : public beast::unit_test::suite if (history.goodHistory) { history.walkHistoryAndAddValidations( - [&](std::shared_ptr const& l, - std::size_t idx) -> bool { return true; }); + [&](std::shared_ptr const& l, std::size_t idx) -> bool { return true; }); BEAST_EXPECT(voteAndCheck(history, history.UNLNodeIDs[0], 1)); } } @@ -1535,13 +1420,11 @@ class NegativeUNLVoteOffline_test : public beast::unit_test::suite if (history.goodHistory) { history.walkHistoryAndAddValidations( - [&](std::shared_ptr const& l, - std::size_t idx) -> bool { + [&](std::shared_ptr const& l, std::size_t idx) -> bool { // skip node 0 and node 1 return idx > 1; }); - BEAST_EXPECT( - voteAndCheck(history, history.UNLNodeIDs.back(), 1)); + BEAST_EXPECT(voteAndCheck(history, history.UNLNodeIDs.back(), 1)); } } @@ -1552,19 +1435,14 @@ class NegativeUNLVoteOffline_test : public beast::unit_test::suite BEAST_EXPECT(history.goodHistory); if (history.goodHistory) { - NodeID n1 = - calcNodeID(*history.lastLedger()->negativeUNL().begin()); - NodeID n2 = - calcNodeID(*history.lastLedger()->validatorToDisable()); + NodeID n1 = calcNodeID(*history.lastLedger()->negativeUNL().begin()); + NodeID n2 = calcNodeID(*history.lastLedger()->validatorToDisable()); history.walkHistoryAndAddValidations( - [&](std::shared_ptr const& l, - std::size_t idx) -> bool { + [&](std::shared_ptr const& l, std::size_t idx) -> bool { // skip node 0 and node 1 - return history.UNLNodeIDs[idx] != n1 && - history.UNLNodeIDs[idx] != n2; + return history.UNLNodeIDs[idx] != n1 && history.UNLNodeIDs[idx] != n2; }); - BEAST_EXPECT( - voteAndCheck(history, history.UNLNodeIDs.back(), 0)); + BEAST_EXPECT(voteAndCheck(history, history.UNLNodeIDs.back(), 0)); } } } @@ -1591,13 +1469,11 @@ class NegativeUNLVoteMaxListed_test : public beast::unit_test::suite if (history.goodHistory) { history.walkHistoryAndAddValidations( - [&](std::shared_ptr const& l, - std::size_t idx) -> bool { + [&](std::shared_ptr const& l, std::size_t idx) -> bool { // skip node 0 ~ 10 return idx > 10; }); - BEAST_EXPECT( - voteAndCheck(history, history.UNLNodeIDs.back(), 0)); + BEAST_EXPECT(voteAndCheck(history, history.UNLNodeIDs.back(), 0)); } } } @@ -1624,8 +1500,7 @@ class NegativeUNLVoteRetiredValidator_test : public beast::unit_test::suite if (history.goodHistory) { history.walkHistoryAndAddValidations( - [&](std::shared_ptr const& l, - std::size_t idx) -> bool { return idx > 1; }); + [&](std::shared_ptr const& l, std::size_t idx) -> bool { return idx > 1; }); BEAST_EXPECT(voteAndCheck(history, history.UNLNodeIDs[0], 0)); } } @@ -1638,8 +1513,7 @@ class NegativeUNLVoteRetiredValidator_test : public beast::unit_test::suite if (history.goodHistory) { history.walkHistoryAndAddValidations( - [&](std::shared_ptr const& l, - std::size_t idx) -> bool { return idx > 1; }); + [&](std::shared_ptr const& l, std::size_t idx) -> bool { return idx > 1; }); BEAST_EXPECT(voteAndCheck(history, NodeID(0xdeadbeef), 0)); } } @@ -1652,16 +1526,11 @@ class NegativeUNLVoteRetiredValidator_test : public beast::unit_test::suite if (history.goodHistory) { history.walkHistoryAndAddValidations( - [&](std::shared_ptr const& l, - std::size_t idx) -> bool { return idx > 1; }); - BEAST_EXPECT(voteAndCheck( - history, - history.UNLNodeIDs.back(), - 1, - [&](NegativeUNLVote& vote) { - history.UNLKeySet.erase(history.UNLKeys[0]); - history.UNLKeySet.erase(history.UNLKeys[1]); - })); + [&](std::shared_ptr const& l, std::size_t idx) -> bool { return idx > 1; }); + BEAST_EXPECT(voteAndCheck(history, history.UNLNodeIDs.back(), 1, [&](NegativeUNLVote& vote) { + history.UNLKeySet.erase(history.UNLKeys[0]); + history.UNLKeySet.erase(history.UNLKeys[1]); + })); } } } @@ -1688,60 +1557,39 @@ class NegativeUNLVoteNewValidator_test : public beast::unit_test::suite if (history.goodHistory) { history.walkHistoryAndAddValidations( - [&](std::shared_ptr const& l, - std::size_t idx) -> bool { return true; }); - BEAST_EXPECT(voteAndCheck( - history, - history.UNLNodeIDs[0], - 0, - [&](NegativeUNLVote& vote) { - auto extra_key_1 = - randomKeyPair(KeyType::ed25519).first; - auto extra_key_2 = - randomKeyPair(KeyType::ed25519).first; - history.UNLKeySet.insert(extra_key_1); - history.UNLKeySet.insert(extra_key_2); - hash_set nowTrusted; - nowTrusted.insert(calcNodeID(extra_key_1)); - nowTrusted.insert(calcNodeID(extra_key_2)); - vote.newValidators( - history.lastLedger()->seq(), nowTrusted); - })); + [&](std::shared_ptr const& l, std::size_t idx) -> bool { return true; }); + BEAST_EXPECT(voteAndCheck(history, history.UNLNodeIDs[0], 0, [&](NegativeUNLVote& vote) { + auto extra_key_1 = randomKeyPair(KeyType::ed25519).first; + auto extra_key_2 = randomKeyPair(KeyType::ed25519).first; + history.UNLKeySet.insert(extra_key_1); + history.UNLKeySet.insert(extra_key_2); + hash_set nowTrusted; + nowTrusted.insert(calcNodeID(extra_key_1)); + nowTrusted.insert(calcNodeID(extra_key_2)); + vote.newValidators(history.lastLedger()->seq(), nowTrusted); + })); } } { //== 2 expired new validators have bad scores //-- txSet.size = 1 - NetworkHistory history = { - *this, - {21, - 0, - false, - false, - NegativeUNLVote::newValidatorDisableSkip * 2}}; + NetworkHistory history = {*this, {21, 0, false, false, NegativeUNLVote::newValidatorDisableSkip * 2}}; BEAST_EXPECT(history.goodHistory); if (history.goodHistory) { history.walkHistoryAndAddValidations( - [&](std::shared_ptr const& l, - std::size_t idx) -> bool { return true; }); - BEAST_EXPECT(voteAndCheck( - history, - history.UNLNodeIDs[0], - 1, - [&](NegativeUNLVote& vote) { - auto extra_key_1 = - randomKeyPair(KeyType::ed25519).first; - auto extra_key_2 = - randomKeyPair(KeyType::ed25519).first; - history.UNLKeySet.insert(extra_key_1); - history.UNLKeySet.insert(extra_key_2); - hash_set nowTrusted; - nowTrusted.insert(calcNodeID(extra_key_1)); - nowTrusted.insert(calcNodeID(extra_key_2)); - vote.newValidators(256, nowTrusted); - })); + [&](std::shared_ptr const& l, std::size_t idx) -> bool { return true; }); + BEAST_EXPECT(voteAndCheck(history, history.UNLNodeIDs[0], 1, [&](NegativeUNLVote& vote) { + auto extra_key_1 = randomKeyPair(KeyType::ed25519).first; + auto extra_key_2 = randomKeyPair(KeyType::ed25519).first; + history.UNLKeySet.insert(extra_key_1); + history.UNLKeySet.insert(extra_key_2); + hash_set nowTrusted; + nowTrusted.insert(calcNodeID(extra_key_1)); + nowTrusted.insert(calcNodeID(extra_key_2)); + vote.newValidators(256, nowTrusted); + })); } } } @@ -1761,18 +1609,11 @@ class NegativeUNLVoteFilterValidations_test : public beast::unit_test::suite testcase("Filter Validations"); jtx::Env env(*this); auto l = std::make_shared( - create_genesis, - env.app().config(), - std::vector{}, - env.app().getNodeFamily()); + create_genesis, env.app().config(), std::vector{}, env.app().getNodeFamily()); auto createSTVal = [&](std::pair const& keys) { return std::make_shared( - env.app().timeKeeper().now(), - keys.first, - keys.second, - calcNodeID(keys.first), - [&](STValidation& v) { + env.app().timeKeeper().now(), keys.first, keys.second, calcNodeID(keys.first), [&](STValidation& v) { v.setFieldH256(sfLedgerHash, l->header().hash); v.setFieldU32(sfLedgerSequence, l->seq()); v.setFlag(vfFullValidation); @@ -1833,11 +1674,7 @@ BEAST_DEFINE_TESTSUITE_MANUAL(NegativeUNLVoteScoreTable, consensus, xrpl); BEAST_DEFINE_TESTSUITE_PRIO(NegativeUNLVoteGoodScore, consensus, xrpl, 1); BEAST_DEFINE_TESTSUITE(NegativeUNLVoteOffline, consensus, xrpl); BEAST_DEFINE_TESTSUITE(NegativeUNLVoteMaxListed, consensus, xrpl); -BEAST_DEFINE_TESTSUITE_PRIO( - NegativeUNLVoteRetiredValidator, - consensus, - ripple, - 1); +BEAST_DEFINE_TESTSUITE_PRIO(NegativeUNLVoteRetiredValidator, consensus, xrpl, 1); BEAST_DEFINE_TESTSUITE(NegativeUNLVoteNewValidator, consensus, xrpl); BEAST_DEFINE_TESTSUITE(NegativeUNLVoteFilterValidations, consensus, xrpl); @@ -1845,17 +1682,11 @@ BEAST_DEFINE_TESTSUITE(NegativeUNLVoteFilterValidations, consensus, xrpl); /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// bool -negUnlSizeTest( - std::shared_ptr const& l, - size_t size, - bool hasToDisable, - bool hasToReEnable) +negUnlSizeTest(std::shared_ptr const& l, size_t size, bool hasToDisable, bool hasToReEnable) { bool sameSize = l->negativeUNL().size() == size; - bool sameToDisable = - (l->validatorToDisable() != std::nullopt) == hasToDisable; - bool sameToReEnable = - (l->validatorToReEnable() != std::nullopt) == hasToReEnable; + bool sameToDisable = (l->validatorToDisable() != std::nullopt) == hasToDisable; + bool sameToReEnable = (l->validatorToReEnable() != std::nullopt) == hasToReEnable; return sameSize && sameToDisable && sameToReEnable; } @@ -1863,8 +1694,7 @@ negUnlSizeTest( bool applyAndTestResult(jtx::Env& env, OpenView& view, STTx const& tx, bool pass) { - auto const res = - apply(env.app(), view, tx, ApplyFlags::tapNONE, env.journal); + auto const res = apply(env.app(), view, tx, ApplyFlags::tapNONE, env.journal); if (pass) return res.ter == tesSUCCESS; else @@ -1872,9 +1702,7 @@ applyAndTestResult(jtx::Env& env, OpenView& view, STTx const& tx, bool pass) } bool -VerifyPubKeyAndSeq( - std::shared_ptr const& l, - hash_map nUnlLedgerSeq) +VerifyPubKeyAndSeq(std::shared_ptr const& l, hash_map nUnlLedgerSeq) { auto sle = l->read(keylet::negativeUNL()); if (!sle) @@ -1888,8 +1716,7 @@ VerifyPubKeyAndSeq( for (auto const& n : nUnlData) { - if (!n.isFieldPresent(sfFirstLedgerSequence) || - !n.isFieldPresent(sfPublicKey)) + if (!n.isFieldPresent(sfFirstLedgerSequence) || !n.isFieldPresent(sfPublicKey)) return false; auto seq = n.getFieldU32(sfFirstLedgerSequence); diff --git a/src/test/consensus/ScaleFreeSim_test.cpp b/src/test/consensus/ScaleFreeSim_test.cpp index dee4c77268..ae70ee9174 100644 --- a/src/test/consensus/ScaleFreeSim_test.cpp +++ b/src/test/consensus/ScaleFreeSim_test.cpp @@ -29,20 +29,13 @@ class ScaleFreeSim_test : public beast::unit_test::suite PeerGroup network = sim.createGroup(N); // generate trust ranks - std::vector const ranks = - sample(network.size(), PowerLawDistribution{1, 3}, sim.rng); + std::vector const ranks = sample(network.size(), PowerLawDistribution{1, 3}, sim.rng); // generate scale-free trust graph - randomRankedTrust( - network, - ranks, - numUNLs, - std::uniform_int_distribution<>{minUNLSize, maxUNLSize}, - sim.rng); + randomRankedTrust(network, ranks, numUNLs, std::uniform_int_distribution<>{minUNLSize, maxUNLSize}, sim.rng); // nodes with a trust line in either direction are network-connected - network.connectFromTrust( - round(0.2 * parms.ledgerGRANULARITY)); + network.connectFromTrust(round(0.2 * parms.ledgerGRANULARITY)); // Initialize collectors to track statistics to report TxCollector txCollector; @@ -62,8 +55,7 @@ class ScaleFreeSim_test : public beast::unit_test::suite Rate const rate{100, 1000ms}; // txs, start/stop/step, target - auto peerSelector = - makeSelector(network.begin(), network.end(), ranks, sim.rng); + auto peerSelector = makeSelector(network.begin(), network.end(), ranks, sim.rng); auto txSubmitter = makeSubmitter( ConstantDistribution{rate.inv()}, sim.scheduler.now() + quiet, @@ -82,12 +74,9 @@ class ScaleFreeSim_test : public beast::unit_test::suite // TODO: Clean up this formatting mess!! log << "Peers: " << network.size() << std::endl; - log << "Simulated Duration: " - << duration_cast(simDuration).count() << " ms" - << std::endl; + log << "Simulated Duration: " << duration_cast(simDuration).count() << " ms" << std::endl; log << "Branches: " << sim.branches() << std::endl; - log << "Synchronized: " << (sim.synchronized() ? "Y" : "N") - << std::endl; + log << "Synchronized: " << (sim.synchronized() ? "Y" : "N") << std::endl; log << std::endl; txCollector.report(simDuration, log); diff --git a/src/test/consensus/Validations_test.cpp b/src/test/consensus/Validations_test.cpp index 906817add0..34e0c23bad 100644 --- a/src/test/consensus/Validations_test.cpp +++ b/src/test/consensus/Validations_test.cpp @@ -25,8 +25,7 @@ class Validations_test : public beast::unit_test::suite // generated NetClock time to be well past its epoch to ensure // any subtractions are positive using namespace std::chrono; - return NetClock::time_point(duration_cast( - c.now().time_since_epoch() + 86400s)); + return NetClock::time_point(duration_cast(c.now().time_since_epoch() + 86400s)); } // Represents a node that can issue validations @@ -100,50 +99,28 @@ class Validations_test : public beast::unit_test::suite NetClock::duration seenOffset, bool full) const { - Validation v{ - id, - seq, - now() + signOffset, - now() + seenOffset, - currKey(), - nodeID_, - full, - loadFee_}; + Validation v{id, seq, now() + signOffset, now() + seenOffset, currKey(), nodeID_, full, loadFee_}; if (trusted_) v.setTrusted(); return v; } Validation - validate( - Ledger ledger, - NetClock::duration signOffset, - NetClock::duration seenOffset) const + validate(Ledger ledger, NetClock::duration signOffset, NetClock::duration seenOffset) const { - return validate( - ledger.id(), ledger.seq(), signOffset, seenOffset, true); + return validate(ledger.id(), ledger.seq(), signOffset, seenOffset, true); } Validation validate(Ledger ledger) const { - return validate( - ledger.id(), - ledger.seq(), - NetClock::duration{0}, - NetClock::duration{0}, - true); + return validate(ledger.id(), ledger.seq(), NetClock::duration{0}, NetClock::duration{0}, true); } Validation partial(Ledger ledger) const { - return validate( - ledger.id(), - ledger.seq(), - NetClock::duration{0}, - NetClock::duration{0}, - false); + return validate(ledger.id(), ledger.seq(), NetClock::duration{0}, NetClock::duration{0}, false); } }; @@ -267,16 +244,13 @@ class Validations_test : public beast::unit_test::suite harness.clock().advance(1s); - BEAST_EXPECT( - ValStatus::current == harness.add(n.validate(ledgerAB))); + BEAST_EXPECT(ValStatus::current == harness.add(n.validate(ledgerAB))); // Test the node changing signing key // Confirm old ledger on hand, but not new ledger - BEAST_EXPECT( - harness.vals().numTrustedForLedger(ledgerAB.id()) == 1); - BEAST_EXPECT( - harness.vals().numTrustedForLedger(ledgerABC.id()) == 0); + BEAST_EXPECT(harness.vals().numTrustedForLedger(ledgerAB.id()) == 1); + BEAST_EXPECT(harness.vals().numTrustedForLedger(ledgerABC.id()) == 0); // Rotate signing keys n.advanceKey(); @@ -284,20 +258,15 @@ class Validations_test : public beast::unit_test::suite harness.clock().advance(1s); // Cannot re-do the same full validation sequence - BEAST_EXPECT( - ValStatus::conflicting == harness.add(n.validate(ledgerAB))); + BEAST_EXPECT(ValStatus::conflicting == harness.add(n.validate(ledgerAB))); // Cannot send the same partial validation sequence - BEAST_EXPECT( - ValStatus::conflicting == harness.add(n.partial(ledgerAB))); + BEAST_EXPECT(ValStatus::conflicting == harness.add(n.partial(ledgerAB))); // Now trusts the newest ledger too harness.clock().advance(1s); - BEAST_EXPECT( - ValStatus::current == harness.add(n.validate(ledgerABC))); - BEAST_EXPECT( - harness.vals().numTrustedForLedger(ledgerAB.id()) == 1); - BEAST_EXPECT( - harness.vals().numTrustedForLedger(ledgerABC.id()) == 1); + BEAST_EXPECT(ValStatus::current == harness.add(n.validate(ledgerABC))); + BEAST_EXPECT(harness.vals().numTrustedForLedger(ledgerAB.id()) == 1); + BEAST_EXPECT(harness.vals().numTrustedForLedger(ledgerABC.id()) == 1); // Processing validations out of order should ignore the older // validation @@ -319,19 +288,14 @@ class Validations_test : public beast::unit_test::suite Node n = harness.makeNode(); // Establish a new current validation - BEAST_EXPECT( - ValStatus::current == harness.add(n.validate(ledgerA))); + BEAST_EXPECT(ValStatus::current == harness.add(n.validate(ledgerA))); // Process a validation that has "later" seq but early sign time - BEAST_EXPECT( - ValStatus::stale == - harness.add(n.validate(ledgerAB, -1s, -1s))); + BEAST_EXPECT(ValStatus::stale == harness.add(n.validate(ledgerAB, -1s, -1s))); // Process a validation that has a later seq and later sign // time - BEAST_EXPECT( - ValStatus::current == - harness.add(n.validate(ledgerABC, 1s, 1s))); + BEAST_EXPECT(ValStatus::current == harness.add(n.validate(ledgerABC, 1s, 1s))); } { @@ -340,19 +304,13 @@ class Validations_test : public beast::unit_test::suite Node n = harness.makeNode(); BEAST_EXPECT( - ValStatus::stale == - harness.add(n.validate( - ledgerA, -harness.parms().validationCURRENT_EARLY, 0s))); + ValStatus::stale == harness.add(n.validate(ledgerA, -harness.parms().validationCURRENT_EARLY, 0s))); BEAST_EXPECT( - ValStatus::stale == - harness.add(n.validate( - ledgerA, harness.parms().validationCURRENT_WALL, 0s))); + ValStatus::stale == harness.add(n.validate(ledgerA, harness.parms().validationCURRENT_WALL, 0s))); BEAST_EXPECT( - ValStatus::stale == - harness.add(n.validate( - ledgerA, 0s, harness.parms().validationCURRENT_LOCAL))); + ValStatus::stale == harness.add(n.validate(ledgerA, 0s, harness.parms().validationCURRENT_LOCAL))); } { @@ -377,8 +335,7 @@ class Validations_test : public beast::unit_test::suite // If we advance far enough for AB to expire, we can fully // validate or partially validate that sequence number again BEAST_EXPECT(ValStatus::conflicting == process(ledgerAZ)); - harness.clock().advance( - harness.parms().validationSET_EXPIRES + 1ms); + harness.clock().advance(harness.parms().validationSET_EXPIRES + 1ms); BEAST_EXPECT(ValStatus::current == process(ledgerAZ)); } } @@ -401,31 +358,23 @@ class Validations_test : public beast::unit_test::suite [&](TestValidations& vals) { vals.currentTrusted(); }, [&](TestValidations& vals) { vals.getCurrentNodeIDs(); }, [&](TestValidations& vals) { vals.getPreferred(genesisLedger); }, - [&](TestValidations& vals) { - vals.getNodesAfter(ledgerA, ledgerA.id()); - }}; + [&](TestValidations& vals) { vals.getNodesAfter(ledgerA, ledgerA.id()); }}; for (Trigger trigger : triggers) { TestHarness harness(h.oracle); Node n = harness.makeNode(); - BEAST_EXPECT( - ValStatus::current == harness.add(n.validate(ledgerAB))); + BEAST_EXPECT(ValStatus::current == harness.add(n.validate(ledgerAB))); trigger(harness.vals()); - BEAST_EXPECT( - harness.vals().getNodesAfter(ledgerA, ledgerA.id()) == 1); - BEAST_EXPECT( - harness.vals().getPreferred(genesisLedger) == - std::make_pair(ledgerAB.seq(), ledgerAB.id())); + BEAST_EXPECT(harness.vals().getNodesAfter(ledgerA, ledgerA.id()) == 1); + BEAST_EXPECT(harness.vals().getPreferred(genesisLedger) == std::make_pair(ledgerAB.seq(), ledgerAB.id())); harness.clock().advance(harness.parms().validationCURRENT_LOCAL); // trigger check for stale trigger(harness.vals()); - BEAST_EXPECT( - harness.vals().getNodesAfter(ledgerA, ledgerA.id()) == 0); - BEAST_EXPECT( - harness.vals().getPreferred(genesisLedger) == std::nullopt); + BEAST_EXPECT(harness.vals().getNodesAfter(ledgerA, ledgerA.id()) == 0); + BEAST_EXPECT(harness.vals().getPreferred(genesisLedger) == std::nullopt); } } @@ -446,8 +395,7 @@ class Validations_test : public beast::unit_test::suite Ledger ledgerAD = h["ad"]; TestHarness harness(h.oracle); - Node a = harness.makeNode(), b = harness.makeNode(), - c = harness.makeNode(), d = harness.makeNode(); + Node a = harness.makeNode(), b = harness.makeNode(), c = harness.makeNode(), d = harness.makeNode(); c.untrust(); // first round a,b,c agree, d has is partial @@ -457,8 +405,7 @@ class Validations_test : public beast::unit_test::suite BEAST_EXPECT(ValStatus::current == harness.add(d.partial(ledgerA))); for (Ledger const& ledger : {ledgerA, ledgerAB, ledgerABC, ledgerAD}) - BEAST_EXPECT( - harness.vals().getNodesAfter(ledger, ledger.id()) == 0); + BEAST_EXPECT(harness.vals().getNodesAfter(ledger, ledger.id()) == 0); harness.clock().advance(5s); @@ -468,18 +415,14 @@ class Validations_test : public beast::unit_test::suite BEAST_EXPECT(ValStatus::current == harness.add(d.partial(ledgerABC))); BEAST_EXPECT(harness.vals().getNodesAfter(ledgerA, ledgerA.id()) == 3); - BEAST_EXPECT( - harness.vals().getNodesAfter(ledgerAB, ledgerAB.id()) == 2); - BEAST_EXPECT( - harness.vals().getNodesAfter(ledgerABC, ledgerABC.id()) == 0); - BEAST_EXPECT( - harness.vals().getNodesAfter(ledgerAD, ledgerAD.id()) == 0); + BEAST_EXPECT(harness.vals().getNodesAfter(ledgerAB, ledgerAB.id()) == 2); + BEAST_EXPECT(harness.vals().getNodesAfter(ledgerABC, ledgerABC.id()) == 0); + BEAST_EXPECT(harness.vals().getNodesAfter(ledgerAD, ledgerAD.id()) == 0); // If given a ledger inconsistent with the id, is still able to check // using slower method BEAST_EXPECT(harness.vals().getNodesAfter(ledgerAD, ledgerA.id()) == 1); - BEAST_EXPECT( - harness.vals().getNodesAfter(ledgerAD, ledgerAB.id()) == 2); + BEAST_EXPECT(harness.vals().getNodesAfter(ledgerAD, ledgerAB.id()) == 2); } void @@ -502,22 +445,18 @@ class Validations_test : public beast::unit_test::suite // Only a is trusted BEAST_EXPECT(harness.vals().currentTrusted().size() == 1); - BEAST_EXPECT( - harness.vals().currentTrusted()[0].ledgerID() == ledgerA.id()); + BEAST_EXPECT(harness.vals().currentTrusted()[0].ledgerID() == ledgerA.id()); BEAST_EXPECT(harness.vals().currentTrusted()[0].seq() == ledgerA.seq()); harness.clock().advance(3s); for (auto const& node : {a, b}) - BEAST_EXPECT( - ValStatus::current == harness.add(node.validate(ledgerAC))); + BEAST_EXPECT(ValStatus::current == harness.add(node.validate(ledgerAC))); // New validation for a BEAST_EXPECT(harness.vals().currentTrusted().size() == 1); - BEAST_EXPECT( - harness.vals().currentTrusted()[0].ledgerID() == ledgerAC.id()); - BEAST_EXPECT( - harness.vals().currentTrusted()[0].seq() == ledgerAC.seq()); + BEAST_EXPECT(harness.vals().currentTrusted()[0].ledgerID() == ledgerAC.id()); + BEAST_EXPECT(harness.vals().currentTrusted()[0].seq() == ledgerAC.seq()); // Pass enough time for it to go stale harness.clock().advance(harness.parms().validationCURRENT_LOCAL); @@ -539,8 +478,7 @@ class Validations_test : public beast::unit_test::suite b.untrust(); for (auto const& node : {a, b}) - BEAST_EXPECT( - ValStatus::current == harness.add(node.validate(ledgerA))); + BEAST_EXPECT(ValStatus::current == harness.add(node.validate(ledgerA))); { hash_set const expectedKeys = {a.nodeID(), b.nodeID()}; @@ -554,8 +492,7 @@ class Validations_test : public beast::unit_test::suite b.advanceKey(); for (auto const& node : {a, b}) - BEAST_EXPECT( - ValStatus::current == harness.add(node.partial(ledgerAC))); + BEAST_EXPECT(ValStatus::current == harness.add(node.partial(ledgerAC))); { hash_set const expectedKeys = {a.nodeID(), b.nodeID()}; @@ -583,8 +520,7 @@ class Validations_test : public beast::unit_test::suite LedgerHistoryHelper h; TestHarness harness(h.oracle); - Node a = harness.makeNode(), b = harness.makeNode(), - c = harness.makeNode(), d = harness.makeNode(), + Node a = harness.makeNode(), b = harness.makeNode(), c = harness.makeNode(), d = harness.makeNode(), e = harness.makeNode(); c.untrust(); @@ -594,8 +530,7 @@ class Validations_test : public beast::unit_test::suite c.setLoadFee(12); e.setLoadFee(12); - hash_map, std::vector> - trustedValidations; + hash_map, std::vector> trustedValidations; //---------------------------------------------------------------------- // checkers @@ -610,12 +545,8 @@ class Validations_test : public beast::unit_test::suite auto const& seq = it.first.second; auto const& expectedValidations = it.second; - BEAST_EXPECT( - harness.vals().numTrustedForLedger(id) == - expectedValidations.size()); - BEAST_EXPECT( - sorted(harness.vals().getTrustedForLedger(id, seq)) == - sorted(expectedValidations)); + BEAST_EXPECT(harness.vals().numTrustedForLedger(id) == expectedValidations.size()); + BEAST_EXPECT(sorted(harness.vals().getTrustedForLedger(id, seq)) == sorted(expectedValidations)); std::uint32_t baseFee = 0; std::vector expectedFees; @@ -624,9 +555,7 @@ class Validations_test : public beast::unit_test::suite expectedFees.push_back(val.loadFee().value_or(baseFee)); } - BEAST_EXPECT( - sorted(harness.vals().fees(id, baseFee)) == - sorted(expectedFees)); + BEAST_EXPECT(sorted(harness.vals().fees(id, baseFee)) == sorted(expectedFees)); } }; @@ -644,8 +573,7 @@ class Validations_test : public beast::unit_test::suite auto const val = node.validate(ledgerA); BEAST_EXPECT(ValStatus::current == harness.add(val)); if (val.trusted()) - trustedValidations[{val.ledgerID(), val.seq()}].emplace_back( - val); + trustedValidations[{val.ledgerID(), val.seq()}].emplace_back(val); } // d disagrees { @@ -665,19 +593,16 @@ class Validations_test : public beast::unit_test::suite auto const val = node.validate(ledgerAC); BEAST_EXPECT(ValStatus::current == harness.add(val)); if (val.trusted()) - trustedValidations[{val.ledgerID(), val.seq()}].emplace_back( - val); + trustedValidations[{val.ledgerID(), val.seq()}].emplace_back(val); } // d now thinks ledger 1, but cannot re-issue a previously used seq // and attempting it should generate a conflict. { - BEAST_EXPECT( - ValStatus::conflicting == harness.add(d.partial(ledgerA))); + BEAST_EXPECT(ValStatus::conflicting == harness.add(d.partial(ledgerA))); } // e only issues partials { - BEAST_EXPECT( - ValStatus::current == harness.add(e.partial(ledgerAC))); + BEAST_EXPECT(ValStatus::current == harness.add(e.partial(ledgerAC))); } compare(); @@ -716,9 +641,7 @@ class Validations_test : public beast::unit_test::suite // change toKeep harness.vals().setSeqToKeep(ledgerB.seq() + one, ledgerB.seq() + two); // advance clock slowly - int const loops = harness.parms().validationSET_EXPIRES / - harness.parms().validationFRESHNESS + - 1; + int const loops = harness.parms().validationSET_EXPIRES / harness.parms().validationFRESHNESS + 1; for (int i = 0; i < loops; ++i) { harness.clock().advance(harness.parms().validationFRESHNESS); @@ -745,8 +668,7 @@ class Validations_test : public beast::unit_test::suite LedgerHistoryHelper h; TestHarness harness(h.oracle); - Node a = harness.makeNode(), b = harness.makeNode(), - c = harness.makeNode(); + Node a = harness.makeNode(), b = harness.makeNode(), c = harness.makeNode(); c.untrust(); Ledger ledgerA = h["a"]; @@ -776,8 +698,7 @@ class Validations_test : public beast::unit_test::suite LedgerHistoryHelper h; TestHarness harness(h.oracle); - Node a = harness.makeNode(), b = harness.makeNode(), - c = harness.makeNode(), d = harness.makeNode(); + Node a = harness.makeNode(), b = harness.makeNode(), c = harness.makeNode(), d = harness.makeNode(); c.untrust(); Ledger ledgerA = h["a"]; @@ -787,9 +708,7 @@ class Validations_test : public beast::unit_test::suite using Seq = Ledger::Seq; - auto pref = [](Ledger ledger) { - return std::make_pair(ledger.seq(), ledger.id()); - }; + auto pref = [](Ledger ledger) { return std::make_pair(ledger.seq(), ledger.id()); }; // Empty (no ledgers) BEAST_EXPECT(harness.vals().getPreferred(ledgerA) == std::nullopt); @@ -800,8 +719,7 @@ class Validations_test : public beast::unit_test::suite BEAST_EXPECT(harness.vals().getPreferred(ledgerB) == pref(ledgerB)); // Minimum valid sequence - BEAST_EXPECT( - harness.vals().getPreferred(ledgerA, Seq{10}) == ledgerA.id()); + BEAST_EXPECT(harness.vals().getPreferred(ledgerA, Seq{10}) == ledgerA.id()); // Untrusted doesn't impact preferred ledger // (ledgerB has tie-break over ledgerA) @@ -820,8 +738,7 @@ class Validations_test : public beast::unit_test::suite // Parent of preferred-> stick with ledger for (auto const& node : {a, b, c, d}) - BEAST_EXPECT( - ValStatus::current == harness.add(node.validate(ledgerAC))); + BEAST_EXPECT(ValStatus::current == harness.add(node.validate(ledgerAC))); // Parent of preferred stays put BEAST_EXPECT(harness.vals().getPreferred(ledgerA) == pref(ledgerA)); // Earlier different chain, switch @@ -832,11 +749,9 @@ class Validations_test : public beast::unit_test::suite // Any later grandchild or different chain is preferred harness.clock().advance(5s); for (auto const& node : {a, b, c, d}) - BEAST_EXPECT( - ValStatus::current == harness.add(node.validate(ledgerACD))); + BEAST_EXPECT(ValStatus::current == harness.add(node.validate(ledgerACD))); for (auto const& ledger : {ledgerA, ledgerB, ledgerACD}) - BEAST_EXPECT( - harness.vals().getPreferred(ledger) == pref(ledgerACD)); + BEAST_EXPECT(harness.vals().getPreferred(ledger) == pref(ledgerACD)); } void @@ -859,44 +774,30 @@ class Validations_test : public beast::unit_test::suite hash_map peerCounts; // No trusted validations or counts sticks with current ledger - BEAST_EXPECT( - harness.vals().getPreferredLCL(ledgerA, Seq{0}, peerCounts) == - ledgerA.id()); + BEAST_EXPECT(harness.vals().getPreferredLCL(ledgerA, Seq{0}, peerCounts) == ledgerA.id()); ++peerCounts[ledgerB.id()]; // No trusted validations, rely on peer counts - BEAST_EXPECT( - harness.vals().getPreferredLCL(ledgerA, Seq{0}, peerCounts) == - ledgerB.id()); + BEAST_EXPECT(harness.vals().getPreferredLCL(ledgerA, Seq{0}, peerCounts) == ledgerB.id()); ++peerCounts[ledgerC.id()]; // No trusted validations, tied peers goes with larger ID BEAST_EXPECT(ledgerC.id() > ledgerB.id()); - BEAST_EXPECT( - harness.vals().getPreferredLCL(ledgerA, Seq{0}, peerCounts) == - ledgerC.id()); + BEAST_EXPECT(harness.vals().getPreferredLCL(ledgerA, Seq{0}, peerCounts) == ledgerC.id()); peerCounts[ledgerC.id()] += 1000; // Single trusted always wins over peer counts BEAST_EXPECT(ValStatus::current == harness.add(a.validate(ledgerA))); - BEAST_EXPECT( - harness.vals().getPreferredLCL(ledgerA, Seq{0}, peerCounts) == - ledgerA.id()); - BEAST_EXPECT( - harness.vals().getPreferredLCL(ledgerB, Seq{0}, peerCounts) == - ledgerA.id()); - BEAST_EXPECT( - harness.vals().getPreferredLCL(ledgerC, Seq{0}, peerCounts) == - ledgerA.id()); + BEAST_EXPECT(harness.vals().getPreferredLCL(ledgerA, Seq{0}, peerCounts) == ledgerA.id()); + BEAST_EXPECT(harness.vals().getPreferredLCL(ledgerB, Seq{0}, peerCounts) == ledgerA.id()); + BEAST_EXPECT(harness.vals().getPreferredLCL(ledgerC, Seq{0}, peerCounts) == ledgerA.id()); // Stick with current ledger if trusted validation ledger has too old // of a sequence - BEAST_EXPECT( - harness.vals().getPreferredLCL(ledgerB, Seq{2}, peerCounts) == - ledgerB.id()); + BEAST_EXPECT(harness.vals().getPreferredLCL(ledgerB, Seq{2}, peerCounts) == ledgerB.id()); } void @@ -923,18 +824,12 @@ class Validations_test : public beast::unit_test::suite BEAST_EXPECT(harness.vals().getNodesAfter(genesisLedger, ID{0}) == 0); // Initial preferred branch falls back to the ledger we are trying to // acquire - BEAST_EXPECT( - harness.vals().getPreferred(genesisLedger) == - std::make_pair(Seq{2}, ID{2})); + BEAST_EXPECT(harness.vals().getPreferred(genesisLedger) == std::make_pair(Seq{2}, ID{2})); // After adding another unavailable validation, the preferred ledger // breaks ties via higher ID - BEAST_EXPECT( - ValStatus::current == - harness.add(b.validate(ID{3}, Seq{2}, 0s, 0s, true))); - BEAST_EXPECT( - harness.vals().getPreferred(genesisLedger) == - std::make_pair(Seq{2}, ID{3})); + BEAST_EXPECT(ValStatus::current == harness.add(b.validate(ID{3}, Seq{2}, 0s, 0s, true))); + BEAST_EXPECT(harness.vals().getPreferred(genesisLedger) == std::make_pair(Seq{2}, ID{3})); // Create the ledger Ledger ledgerAB = h["ab"]; @@ -946,26 +841,20 @@ class Validations_test : public beast::unit_test::suite Validation val2 = a.validate(ID{4}, Seq{4}, 0s, 0s, true); BEAST_EXPECT(ValStatus::current == harness.add(val2)); BEAST_EXPECT(harness.vals().numTrustedForLedger(ID{4}) == 1); - BEAST_EXPECT( - harness.vals().getPreferred(genesisLedger) == - std::make_pair(ledgerAB.seq(), ledgerAB.id())); + BEAST_EXPECT(harness.vals().getPreferred(genesisLedger) == std::make_pair(ledgerAB.seq(), ledgerAB.id())); // Another node requesting that ledger still doesn't change things Validation val3 = b.validate(ID{4}, Seq{4}, 0s, 0s, true); BEAST_EXPECT(ValStatus::current == harness.add(val3)); BEAST_EXPECT(harness.vals().numTrustedForLedger(ID{4}) == 2); - BEAST_EXPECT( - harness.vals().getPreferred(genesisLedger) == - std::make_pair(ledgerAB.seq(), ledgerAB.id())); + BEAST_EXPECT(harness.vals().getPreferred(genesisLedger) == std::make_pair(ledgerAB.seq(), ledgerAB.id())); // Switch to validation that is available harness.clock().advance(5s); Ledger ledgerABCDE = h["abcde"]; BEAST_EXPECT(ValStatus::current == harness.add(a.partial(ledgerABCDE))); BEAST_EXPECT(ValStatus::current == harness.add(b.partial(ledgerABCDE))); - BEAST_EXPECT( - harness.vals().getPreferred(genesisLedger) == - std::make_pair(ledgerABCDE.seq(), ledgerABCDE.id())); + BEAST_EXPECT(harness.vals().getPreferred(genesisLedger) == std::make_pair(ledgerABCDE.seq(), ledgerABCDE.id())); } void @@ -1013,31 +902,20 @@ class Validations_test : public beast::unit_test::suite testcase("TrustChanged"); using namespace std::chrono; - auto checker = [this]( - TestValidations& vals, - hash_set const& listed, - std::vector const& trustedVals) { - Ledger::ID testID = trustedVals.empty() ? this->genesisLedger.id() - : trustedVals[0].ledgerID(); - Ledger::Seq testSeq = trustedVals.empty() - ? this->genesisLedger.seq() - : trustedVals[0].seq(); - BEAST_EXPECT(vals.currentTrusted() == trustedVals); - BEAST_EXPECT(vals.getCurrentNodeIDs() == listed); - BEAST_EXPECT( - vals.getNodesAfter(this->genesisLedger, genesisLedger.id()) == - trustedVals.size()); - if (trustedVals.empty()) - BEAST_EXPECT( - vals.getPreferred(this->genesisLedger) == std::nullopt); - else - BEAST_EXPECT( - vals.getPreferred(this->genesisLedger)->second == testID); - BEAST_EXPECT( - vals.getTrustedForLedger(testID, testSeq) == trustedVals); - BEAST_EXPECT( - vals.numTrustedForLedger(testID) == trustedVals.size()); - }; + auto checker = + [this](TestValidations& vals, hash_set const& listed, std::vector const& trustedVals) { + Ledger::ID testID = trustedVals.empty() ? this->genesisLedger.id() : trustedVals[0].ledgerID(); + Ledger::Seq testSeq = trustedVals.empty() ? this->genesisLedger.seq() : trustedVals[0].seq(); + BEAST_EXPECT(vals.currentTrusted() == trustedVals); + BEAST_EXPECT(vals.getCurrentNodeIDs() == listed); + BEAST_EXPECT(vals.getNodesAfter(this->genesisLedger, genesisLedger.id()) == trustedVals.size()); + if (trustedVals.empty()) + BEAST_EXPECT(vals.getPreferred(this->genesisLedger) == std::nullopt); + else + BEAST_EXPECT(vals.getPreferred(this->genesisLedger)->second == testID); + BEAST_EXPECT(vals.getTrustedForLedger(testID, testSeq) == trustedVals); + BEAST_EXPECT(vals.numTrustedForLedger(testID) == trustedVals.size()); + }; { // Trusted to untrusted @@ -1081,18 +959,15 @@ class Validations_test : public beast::unit_test::suite LedgerHistoryHelper h; TestHarness harness(h.oracle); Node a = harness.makeNode(); - Validation v = - a.validate(Ledger::ID{2}, Ledger::Seq{2}, 0s, 0s, true); + Validation v = a.validate(Ledger::ID{2}, Ledger::Seq{2}, 0s, 0s, true); BEAST_EXPECT(ValStatus::current == harness.add(v)); hash_set listed({a.nodeID()}); std::vector trustedVals({v}); auto& vals = harness.vals(); BEAST_EXPECT(vals.currentTrusted() == trustedVals); - BEAST_EXPECT( - vals.getPreferred(genesisLedger)->second == v.ledgerID()); - BEAST_EXPECT( - vals.getNodesAfter(genesisLedger, genesisLedger.id()) == 0); + BEAST_EXPECT(vals.getPreferred(genesisLedger)->second == v.ledgerID()); + BEAST_EXPECT(vals.getNodesAfter(genesisLedger, genesisLedger.id()) == 0); trustedVals.clear(); harness.vals().trustChanged({}, {a.nodeID()}); @@ -1100,8 +975,7 @@ class Validations_test : public beast::unit_test::suite h["ab"]; BEAST_EXPECT(vals.currentTrusted() == trustedVals); BEAST_EXPECT(vals.getPreferred(genesisLedger) == std::nullopt); - BEAST_EXPECT( - vals.getNodesAfter(genesisLedger, genesisLedger.id()) == 0); + BEAST_EXPECT(vals.getNodesAfter(genesisLedger, genesisLedger.id()) == 0); } } diff --git a/src/test/core/ClosureCounter_test.cpp b/src/test/core/ClosureCounter_test.cpp index 47f9d9a5d1..f5e9dc7880 100644 --- a/src/test/core/ClosureCounter_test.cpp +++ b/src/test/core/ClosureCounter_test.cpp @@ -16,11 +16,7 @@ class ClosureCounter_test : public beast::unit_test::suite { // We're only using Env for its Journal. That Journal gives better // coverage in unit tests. - test::jtx::Env env_{ - *this, - jtx::envconfig(), - nullptr, - beast::severities::kDisabled}; + test::jtx::Env env_{*this, jtx::envconfig(), nullptr, beast::severities::kDisabled}; beast::Journal j{env_.app().journal("ClosureCounter_test")}; void @@ -110,14 +106,12 @@ class ClosureCounter_test : public beast::unit_test::suite } // Copy constructor - TrackedString(TrackedString const& rhs) - : copies(rhs.copies + 1), moves(rhs.moves), str(rhs.str) + TrackedString(TrackedString const& rhs) : copies(rhs.copies + 1), moves(rhs.moves), str(rhs.str) { } // Move constructor - TrackedString(TrackedString&& rhs) noexcept - : copies(rhs.copies), moves(rhs.moves + 1), str(std::move(rhs.str)) + TrackedString(TrackedString&& rhs) noexcept : copies(rhs.copies), moves(rhs.moves + 1), str(std::move(rhs.str)) { } @@ -152,8 +146,7 @@ class ClosureCounter_test : public beast::unit_test::suite ClosureCounter strCounter; BEAST_EXPECT(strCounter.count() == 0); - auto wrapped = - strCounter.wrap([](TrackedString in) { return in += "!"; }); + auto wrapped = strCounter.wrap([](TrackedString in) { return in += "!"; }); BEAST_EXPECT(strCounter.count() == 1); BEAST_EXPECT(wrapped); @@ -170,8 +163,7 @@ class ClosureCounter_test : public beast::unit_test::suite ClosureCounter strCounter; BEAST_EXPECT(strCounter.count() == 0); - auto wrapped = strCounter.wrap( - [](TrackedString const& in) { return in + "!"; }); + auto wrapped = strCounter.wrap([](TrackedString const& in) { return in + "!"; }); BEAST_EXPECT(strCounter.count() == 1); BEAST_EXPECT(wrapped); @@ -188,8 +180,7 @@ class ClosureCounter_test : public beast::unit_test::suite ClosureCounter strCounter; BEAST_EXPECT(strCounter.count() == 0); - auto wrapped = - strCounter.wrap([](TrackedString& in) { return in += "!"; }); + auto wrapped = strCounter.wrap([](TrackedString& in) { return in += "!"; }); BEAST_EXPECT(strCounter.count() == 1); BEAST_EXPECT(wrapped); diff --git a/src/test/core/Config_test.cpp b/src/test/core/Config_test.cpp index d6ec875982..d5f3bb556c 100644 --- a/src/test/core/Config_test.cpp +++ b/src/test/core/Config_test.cpp @@ -100,10 +100,8 @@ r.ripple.com 51235 backend=sqlite )xrpldConfig"); - std::string dbPathSection = - dbPath.empty() ? "" : "[database_path]\n" + dbPath; - std::string valFileSection = - validatorsFile.empty() ? "" : "[validators_file]\n" + validatorsFile; + std::string dbPathSection = dbPath.empty() ? "" : "[database_path]\n" + dbPath; + std::string valFileSection = validatorsFile.empty() ? "" : "[validators_file]\n" + validatorsFile; return boost::str(configContentsTemplate % dbPathSection % valFileSection); } @@ -132,9 +130,7 @@ public: test, std::move(subDir), configFile, - confContents.empty() - ? configContents(dbPath.string(), validatorsFile.string()) - : confContents, + confContents.empty() ? configContents(dbPath.string(), validatorsFile.string()) : confContents, useCounter) , dataDir_(dbPath) { @@ -233,9 +229,7 @@ public: : FileDirGuard( test, std::move(subDir), - path( - validatorsFileName.empty() ? Config::validatorsFileName - : validatorsFileName), + path(validatorsFileName.empty() ? Config::validatorsFileName : validatorsFileName), valFileContents(), useCounter) { @@ -301,8 +295,7 @@ port_wss_admin auto const cwd = current_path(); // Test both config file names. - char const* configFiles[] = { - Config::configFileName, Config::configLegacyName}; + char const* configFiles[] = {Config::configFileName, Config::configLegacyName}; // Config file in current directory. for (auto const& configFile : configFiles) @@ -319,9 +312,7 @@ port_wss_admin Config c; c.setup("", true, false, true); BEAST_EXPECT(c.section(SECTION_DEBUG_LOGFILE).values().size() == 1); - BEAST_EXPECT( - c.section(SECTION_DEBUG_LOGFILE).values()[0] == - "/Users/dummy/xrpld/config/log/debug.log"); + BEAST_EXPECT(c.section(SECTION_DEBUG_LOGFILE).values()[0] == "/Users/dummy/xrpld/config/log/debug.log"); } // Config file in HOME or XDG_CONFIG_HOME directory. @@ -357,16 +348,12 @@ port_wss_admin // Load the config file from the config directory and verify it. Config c; c.setup("", true, false, true); - BEAST_EXPECT( - c.section(SECTION_DEBUG_LOGFILE).values().size() == 1); - BEAST_EXPECT( - c.section(SECTION_DEBUG_LOGFILE).values()[0] == - "/Users/dummy/xrpld/config/log/debug.log"); + BEAST_EXPECT(c.section(SECTION_DEBUG_LOGFILE).values().size() == 1); + BEAST_EXPECT(c.section(SECTION_DEBUG_LOGFILE).values()[0] == "/Users/dummy/xrpld/config/log/debug.log"); // Restore the environment variables. h ? setenv("HOME", h, 1) : unsetenv("HOME"); - x ? setenv("XDG_CONFIG_HOME", x, 1) - : unsetenv("XDG_CONFIG_HOME"); + x ? setenv("XDG_CONFIG_HOME", x, 1) : unsetenv("XDG_CONFIG_HOME"); } // The XDG config directory is not set: the config file must be in a @@ -395,11 +382,8 @@ port_wss_admin // Load the config file from the config directory and verify it. Config c; c.setup("", true, false, true); - BEAST_EXPECT( - c.section(SECTION_DEBUG_LOGFILE).values().size() == 1); - BEAST_EXPECT( - c.section(SECTION_DEBUG_LOGFILE).values()[0] == - "/Users/dummy/xrpld/config/log/debug.log"); + BEAST_EXPECT(c.section(SECTION_DEBUG_LOGFILE).values().size() == 1); + BEAST_EXPECT(c.section(SECTION_DEBUG_LOGFILE).values()[0] == "/Users/dummy/xrpld/config/log/debug.log"); // Restore the environment variables. h ? setenv("HOME", h, 1) : unsetenv("HOME"); @@ -451,13 +435,7 @@ port_wss_admin detail::DirGuard const g0(*this, "test_db"); path const dataDirRel("test_data_dir"); path const dataDirAbs(cwd / g0.subdir() / dataDirRel); - detail::FileCfgGuard const g( - *this, - g0.subdir(), - dataDirAbs, - Config::configFileName, - "", - false); + detail::FileCfgGuard const g(*this, g0.subdir(), dataDirAbs, Config::configFileName, "", false); auto const& c(g.config()); BEAST_EXPECT(g.dataDirExists()); BEAST_EXPECT(g.configFileExists()); @@ -466,8 +444,7 @@ port_wss_admin { // read from file relative path std::string const dbPath("my_db"); - detail::FileCfgGuard const g( - *this, "test_db", dbPath, Config::configFileName, ""); + detail::FileCfgGuard const g(*this, "test_db", dbPath, Config::configFileName, ""); auto const& c(g.config()); std::string const nativeDbPath = absolute(path(dbPath)).string(); BEAST_EXPECT(g.dataDirExists()); @@ -476,11 +453,9 @@ port_wss_admin } { // read from file no path - detail::FileCfgGuard const g( - *this, "test_db", "", Config::configFileName, ""); + detail::FileCfgGuard const g(*this, "test_db", "", Config::configFileName, ""); auto const& c(g.config()); - std::string const nativeDbPath = - absolute(g.subdir() / path(Config::databaseDirName)).string(); + std::string const nativeDbPath = absolute(g.subdir() / path(Config::databaseDirName)).string(); BEAST_EXPECT(g.dataDirExists()); BEAST_EXPECT(g.configFileExists()); BEAST_EXPECT(c.legacy("database_path") == nativeDbPath); @@ -520,8 +495,7 @@ port_wss_admin "and [validator_token] config sections"; try { - c.loadFromString( - boost::str(configTemplate % validationSeed % token)); + c.loadFromString(boost::str(configTemplate % validationSeed % token)); } catch (std::runtime_error& e) { @@ -607,9 +581,7 @@ main boost::format cc("[validators_file]\n%1%\n"); std::string error; std::string const missingPath = "/no/way/this/path/exists"; - auto const expectedError = - "The file specified in [validators_file] does not exist: " + - missingPath; + auto const expectedError = "The file specified in [validators_file] does not exist: " + missingPath; try { Config c; @@ -623,14 +595,11 @@ main } { // load should throw for invalid [validators_file] - detail::ValidatorsTxtGuard const vtg( - *this, "test_cfg", "validators.cfg"); + detail::ValidatorsTxtGuard const vtg(*this, "test_cfg", "validators.cfg"); path const invalidFile = current_path() / vtg.subdir(); boost::format cc("[validators_file]\n%1%\n"); std::string error; - auto const expectedError = - "Invalid file specified in [validators_file]: " + - invalidFile.string(); + auto const expectedError = "Invalid file specified in [validators_file]: " + invalidFile.string(); try { Config c; @@ -665,8 +634,8 @@ nHBu9PTL9dn2GuZtdW4U2WzBwffyX9qsQCd9CNU4Z5YG3PQfViM8 Config c; std::string toLoad(R"xrpldConfig( [validator_list_sites] -xrplvalidators.com -trustthesevalidators.gov +xrpl-validators.com +trust-these-validators.gov [validator_list_keys] 021A99A537FDEBC34E4FCA03B39BEADD04299BB19E85097EC92B15A3518801E566 @@ -675,25 +644,16 @@ trustthesevalidators.gov 1 )xrpldConfig"); c.loadFromString(toLoad); - BEAST_EXPECT( - c.section(SECTION_VALIDATOR_LIST_SITES).values().size() == 2); - BEAST_EXPECT( - c.section(SECTION_VALIDATOR_LIST_SITES).values()[0] == - "xrplvalidators.com"); - BEAST_EXPECT( - c.section(SECTION_VALIDATOR_LIST_SITES).values()[1] == - "trustthesevalidators.gov"); - BEAST_EXPECT( - c.section(SECTION_VALIDATOR_LIST_KEYS).values().size() == 1); + BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_SITES).values().size() == 2); + BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_SITES).values()[0] == "xrpl-validators.com"); + BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_SITES).values()[1] == "trust-these-validators.gov"); + BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_KEYS).values().size() == 1); BEAST_EXPECT( c.section(SECTION_VALIDATOR_LIST_KEYS).values()[0] == "021A99A537FDEBC34E4FCA03B39BEADD04299BB19E85097EC92B15A3518801" "E566"); - BEAST_EXPECT( - c.section(SECTION_VALIDATOR_LIST_THRESHOLD).values().size() == - 1); - BEAST_EXPECT( - c.section(SECTION_VALIDATOR_LIST_THRESHOLD).values()[0] == "1"); + BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_THRESHOLD).values().size() == 1); + BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_THRESHOLD).values()[0] == "1"); BEAST_EXPECT(c.VALIDATOR_LIST_THRESHOLD == std::size_t(1)); } { @@ -701,8 +661,8 @@ trustthesevalidators.gov Config c; std::string toLoad(R"xrpldConfig( [validator_list_sites] -xrplvalidators.com -trustthesevalidators.gov +xrpl-validators.com +trust-these-validators.gov [validator_list_keys] 021A99A537FDEBC34E4FCA03B39BEADD04299BB19E85097EC92B15A3518801E566 @@ -711,25 +671,16 @@ trustthesevalidators.gov 0 )xrpldConfig"); c.loadFromString(toLoad); - BEAST_EXPECT( - c.section(SECTION_VALIDATOR_LIST_SITES).values().size() == 2); - BEAST_EXPECT( - c.section(SECTION_VALIDATOR_LIST_SITES).values()[0] == - "xrplvalidators.com"); - BEAST_EXPECT( - c.section(SECTION_VALIDATOR_LIST_SITES).values()[1] == - "trustthesevalidators.gov"); - BEAST_EXPECT( - c.section(SECTION_VALIDATOR_LIST_KEYS).values().size() == 1); + BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_SITES).values().size() == 2); + BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_SITES).values()[0] == "xrpl-validators.com"); + BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_SITES).values()[1] == "trust-these-validators.gov"); + BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_KEYS).values().size() == 1); BEAST_EXPECT( c.section(SECTION_VALIDATOR_LIST_KEYS).values()[0] == "021A99A537FDEBC34E4FCA03B39BEADD04299BB19E85097EC92B15A3518801" "E566"); - BEAST_EXPECT( - c.section(SECTION_VALIDATOR_LIST_THRESHOLD).values().size() == - 1); - BEAST_EXPECT( - c.section(SECTION_VALIDATOR_LIST_THRESHOLD).values()[0] == "0"); + BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_THRESHOLD).values().size() == 1); + BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_THRESHOLD).values()[0] == "0"); BEAST_EXPECT(c.VALIDATOR_LIST_THRESHOLD == std::nullopt); } { @@ -738,8 +689,8 @@ trustthesevalidators.gov Config c; std::string toLoad(R"xrpldConfig( [validator_list_sites] -xrplvalidators.com -trustthesevalidators.gov +xrpl-validators.com +trust-these-validators.gov [validator_list_keys] 021A99A537FDEBC34E4FCA03B39BEADD04299BB19E85097EC92B15A3518801E566 @@ -767,8 +718,8 @@ trustthesevalidators.gov Config c; std::string toLoad(R"xrpldConfig( [validator_list_sites] -xrplvalidators.com -trustthesevalidators.gov +xrpl-validators.com +trust-these-validators.gov [validator_list_keys] 021A99A537FDEBC34E4FCA03B39BEADD04299BB19E85097EC92B15A3518801E566 @@ -796,8 +747,8 @@ value = 2 Config c; std::string toLoad(R"xrpldConfig( [validator_list_sites] -xrplvalidators.com -trustthesevalidators.gov +xrpl-validators.com +trust-these-validators.gov [validator_list_keys] 021A99A537FDEBC34E4FCA03B39BEADD04299BB19E85097EC92B15A3518801E566 @@ -823,12 +774,11 @@ trustthesevalidators.gov Config c; std::string toLoad(R"xrpldConfig( [validator_list_sites] -xrplvalidators.com -trustthesevalidators.gov +xrpl-validators.com +trust-these-validators.gov )xrpldConfig"); std::string error; - auto const expectedError = - "[validator_list_keys] config section is missing"; + auto const expectedError = "[validator_list_keys] config section is missing"; try { c.loadFromString(toLoad); @@ -842,124 +792,80 @@ trustthesevalidators.gov } { // load from specified [validators_file] absolute path - detail::ValidatorsTxtGuard const vtg( - *this, "test_cfg", "validators.cfg"); + detail::ValidatorsTxtGuard const vtg(*this, "test_cfg", "validators.cfg"); BEAST_EXPECT(vtg.validatorsFileExists()); Config c; boost::format cc("[validators_file]\n%1%\n"); c.loadFromString(boost::str(cc % vtg.validatorsFile())); BEAST_EXPECT(c.legacy("validators_file") == vtg.validatorsFile()); BEAST_EXPECT(c.section(SECTION_VALIDATORS).values().size() == 8); - BEAST_EXPECT( - c.section(SECTION_VALIDATOR_LIST_SITES).values().size() == 2); - BEAST_EXPECT( - c.section(SECTION_VALIDATOR_LIST_KEYS).values().size() == 2); - BEAST_EXPECT( - c.section(SECTION_VALIDATOR_LIST_THRESHOLD).values().size() == - 1); + BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_SITES).values().size() == 2); + BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_KEYS).values().size() == 2); + BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_THRESHOLD).values().size() == 1); BEAST_EXPECT(c.VALIDATOR_LIST_THRESHOLD == 2); } { // load from specified [validators_file] file name // in config directory std::string const valFileName = "validators.txt"; - detail::ValidatorsTxtGuard const vtg( - *this, "test_cfg", valFileName); - detail::FileCfgGuard const rcg( - *this, - vtg.subdir(), - "", - Config::configFileName, - valFileName, - false); + detail::ValidatorsTxtGuard const vtg(*this, "test_cfg", valFileName); + detail::FileCfgGuard const rcg(*this, vtg.subdir(), "", Config::configFileName, valFileName, false); BEAST_EXPECT(vtg.validatorsFileExists()); BEAST_EXPECT(rcg.configFileExists()); auto const& c(rcg.config()); BEAST_EXPECT(c.legacy("validators_file") == valFileName); BEAST_EXPECT(c.section(SECTION_VALIDATORS).values().size() == 8); - BEAST_EXPECT( - c.section(SECTION_VALIDATOR_LIST_SITES).values().size() == 2); - BEAST_EXPECT( - c.section(SECTION_VALIDATOR_LIST_KEYS).values().size() == 2); - BEAST_EXPECT( - c.section(SECTION_VALIDATOR_LIST_THRESHOLD).values().size() == - 1); + BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_SITES).values().size() == 2); + BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_KEYS).values().size() == 2); + BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_THRESHOLD).values().size() == 1); BEAST_EXPECT(c.VALIDATOR_LIST_THRESHOLD == 2); } { // load from specified [validators_file] relative path // to config directory - detail::ValidatorsTxtGuard const vtg( - *this, "test_cfg", "validators.txt"); + detail::ValidatorsTxtGuard const vtg(*this, "test_cfg", "validators.txt"); auto const valFilePath = ".." / vtg.subdir() / "validators.txt"; - detail::FileCfgGuard const rcg( - *this, - vtg.subdir(), - "", - Config::configFileName, - valFilePath, - false); + detail::FileCfgGuard const rcg(*this, vtg.subdir(), "", Config::configFileName, valFilePath, false); BEAST_EXPECT(vtg.validatorsFileExists()); BEAST_EXPECT(rcg.configFileExists()); auto const& c(rcg.config()); BEAST_EXPECT(c.legacy("validators_file") == valFilePath); BEAST_EXPECT(c.section(SECTION_VALIDATORS).values().size() == 8); - BEAST_EXPECT( - c.section(SECTION_VALIDATOR_LIST_SITES).values().size() == 2); - BEAST_EXPECT( - c.section(SECTION_VALIDATOR_LIST_KEYS).values().size() == 2); - BEAST_EXPECT( - c.section(SECTION_VALIDATOR_LIST_THRESHOLD).values().size() == - 1); + BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_SITES).values().size() == 2); + BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_KEYS).values().size() == 2); + BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_THRESHOLD).values().size() == 1); BEAST_EXPECT(c.VALIDATOR_LIST_THRESHOLD == 2); } { // load from validators file in default location - detail::ValidatorsTxtGuard const vtg( - *this, "test_cfg", "validators.txt"); - detail::FileCfgGuard const rcg( - *this, vtg.subdir(), "", Config::configFileName, "", false); + detail::ValidatorsTxtGuard const vtg(*this, "test_cfg", "validators.txt"); + detail::FileCfgGuard const rcg(*this, vtg.subdir(), "", Config::configFileName, "", false); BEAST_EXPECT(vtg.validatorsFileExists()); BEAST_EXPECT(rcg.configFileExists()); auto const& c(rcg.config()); BEAST_EXPECT(c.legacy("validators_file").empty()); BEAST_EXPECT(c.section(SECTION_VALIDATORS).values().size() == 8); - BEAST_EXPECT( - c.section(SECTION_VALIDATOR_LIST_SITES).values().size() == 2); - BEAST_EXPECT( - c.section(SECTION_VALIDATOR_LIST_KEYS).values().size() == 2); - BEAST_EXPECT( - c.section(SECTION_VALIDATOR_LIST_THRESHOLD).values().size() == - 1); + BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_SITES).values().size() == 2); + BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_KEYS).values().size() == 2); + BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_THRESHOLD).values().size() == 1); BEAST_EXPECT(c.VALIDATOR_LIST_THRESHOLD == 2); } { // load from specified [validators_file] instead // of default location - detail::ValidatorsTxtGuard const vtg( - *this, "test_cfg", "validators.cfg"); + detail::ValidatorsTxtGuard const vtg(*this, "test_cfg", "validators.cfg"); BEAST_EXPECT(vtg.validatorsFileExists()); - detail::ValidatorsTxtGuard const vtgDefault( - *this, vtg.subdir(), "validators.txt", false); + detail::ValidatorsTxtGuard const vtgDefault(*this, vtg.subdir(), "validators.txt", false); BEAST_EXPECT(vtgDefault.validatorsFileExists()); detail::FileCfgGuard const rcg( - *this, - vtg.subdir(), - "", - Config::configFileName, - vtg.validatorsFile(), - false); + *this, vtg.subdir(), "", Config::configFileName, vtg.validatorsFile(), false); BEAST_EXPECT(rcg.configFileExists()); auto const& c(rcg.config()); BEAST_EXPECT(c.legacy("validators_file") == vtg.validatorsFile()); BEAST_EXPECT(c.section(SECTION_VALIDATORS).values().size() == 8); - BEAST_EXPECT( - c.section(SECTION_VALIDATOR_LIST_SITES).values().size() == 2); - BEAST_EXPECT( - c.section(SECTION_VALIDATOR_LIST_KEYS).values().size() == 2); - BEAST_EXPECT( - c.section(SECTION_VALIDATOR_LIST_THRESHOLD).values().size() == - 1); + BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_SITES).values().size() == 2); + BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_KEYS).values().size() == 2); + BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_THRESHOLD).values().size() == 1); BEAST_EXPECT(c.VALIDATOR_LIST_THRESHOLD == 2); } @@ -981,26 +887,21 @@ nHB1X37qrniVugfQcuBTAjswphC1drx7QjFFojJPZwKHHnt8kU7v nHUkAWDR4cB8AgPg7VXMX6et8xRTQb2KJfgv1aBEXozwrawRKgMB [validator_list_sites] -xrplvalidators.com -trustthesevalidators.gov +xrpl-validators.com +trust-these-validators.gov [validator_list_keys] 021A99A537FDEBC34E4FCA03B39BEADD04299BB19E85097EC92B15A3518801E566 )xrpldConfig"); - detail::ValidatorsTxtGuard const vtg( - *this, "test_cfg", "validators.cfg"); + detail::ValidatorsTxtGuard const vtg(*this, "test_cfg", "validators.cfg"); BEAST_EXPECT(vtg.validatorsFileExists()); Config c; c.loadFromString(boost::str(cc % vtg.validatorsFile())); BEAST_EXPECT(c.legacy("validators_file") == vtg.validatorsFile()); BEAST_EXPECT(c.section(SECTION_VALIDATORS).values().size() == 15); - BEAST_EXPECT( - c.section(SECTION_VALIDATOR_LIST_SITES).values().size() == 4); - BEAST_EXPECT( - c.section(SECTION_VALIDATOR_LIST_KEYS).values().size() == 3); - BEAST_EXPECT( - c.section(SECTION_VALIDATOR_LIST_THRESHOLD).values().size() == - 1); + BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_SITES).values().size() == 4); + BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_KEYS).values().size() == 3); + BEAST_EXPECT(c.section(SECTION_VALIDATOR_LIST_THRESHOLD).values().size() == 1); BEAST_EXPECT(c.VALIDATOR_LIST_THRESHOLD == 2); } { @@ -1014,8 +915,7 @@ trustthesevalidators.gov 1 )xrpldConfig"); std::string error; - detail::ValidatorsTxtGuard const vtg( - *this, "test_cfg", "validators.cfg"); + detail::ValidatorsTxtGuard const vtg(*this, "test_cfg", "validators.cfg"); BEAST_EXPECT(vtg.validatorsFileExists()); auto const expectedError = "Config section [validator_list_threshold] should contain " @@ -1039,8 +939,7 @@ trustthesevalidators.gov Config c; boost::format cc("[validators_file]\n%1%\n"); std::string error; - detail::ValidatorsTxtGuard const vtg( - *this, "test_cfg", "validators.cfg"); + detail::ValidatorsTxtGuard const vtg(*this, "test_cfg", "validators.cfg"); BEAST_EXPECT(vtg.validatorsFileExists()); auto const expectedError = "The file specified in [validators_file] does not contain a " @@ -1064,12 +963,7 @@ trustthesevalidators.gov void testSetup(bool explicitPath) { - detail::FileCfgGuard const cfg( - *this, - "testSetup", - explicitPath ? "test_db" : "", - Config::configFileName, - ""); + detail::FileCfgGuard const cfg(*this, "testSetup", explicitPath ? "test_db" : "", Config::configFileName, ""); /* FileCfgGuard has a Config object that gets loaded on construction, but Config::setup is not reentrant, so we need a fresh config for every test case, so ignore it. @@ -1137,8 +1031,7 @@ trustthesevalidators.gov BEAST_EXPECT(!config.silent()); BEAST_EXPECT(config.standalone()); BEAST_EXPECT(config.LEDGER_HISTORY == 0); - BEAST_EXPECT( - config.legacy("database_path").empty() == !explicitPath); + BEAST_EXPECT(config.legacy("database_path").empty() == !explicitPath); } { Config config; @@ -1151,8 +1044,7 @@ trustthesevalidators.gov BEAST_EXPECT(!config.silent()); BEAST_EXPECT(config.standalone()); BEAST_EXPECT(config.LEDGER_HISTORY == 0); - BEAST_EXPECT( - config.legacy("database_path").empty() == !explicitPath); + BEAST_EXPECT(config.legacy("database_path").empty() == !explicitPath); } { Config config; @@ -1165,8 +1057,7 @@ trustthesevalidators.gov BEAST_EXPECT(config.silent()); BEAST_EXPECT(config.standalone()); BEAST_EXPECT(config.LEDGER_HISTORY == 0); - BEAST_EXPECT( - config.legacy("database_path").empty() == !explicitPath); + BEAST_EXPECT(config.legacy("database_path").empty() == !explicitPath); } { Config config; @@ -1179,16 +1070,14 @@ trustthesevalidators.gov BEAST_EXPECT(config.silent()); BEAST_EXPECT(config.standalone()); BEAST_EXPECT(config.LEDGER_HISTORY == 0); - BEAST_EXPECT( - config.legacy("database_path").empty() == !explicitPath); + BEAST_EXPECT(config.legacy("database_path").empty() == !explicitPath); } } void testPort() { - detail::FileCfgGuard const cfg( - *this, "testPort", "", Config::configFileName, ""); + detail::FileCfgGuard const cfg(*this, "testPort", "", Config::configFileName, ""); auto const& conf = cfg.config(); if (!BEAST_EXPECT(conf.exists("port_rpc"))) return; @@ -1207,27 +1096,17 @@ trustthesevalidators.gov void testZeroPort() { - auto const contents = std::regex_replace( - detail::configContents("", ""), - std::regex("port\\s*=\\s*\\d+"), - "port = 0"); + auto const contents = + std::regex_replace(detail::configContents("", ""), std::regex("port\\s*=\\s*\\d+"), "port = 0"); try { - detail::FileCfgGuard const cfg( - *this, - "testPort", - "", - Config::configFileName, - "", - true, - contents); + detail::FileCfgGuard const cfg(*this, "testPort", "", Config::configFileName, "", true, contents); BEAST_EXPECT(false); } catch (std::exception const& ex) { - BEAST_EXPECT(std::string_view(ex.what()).starts_with( - "Invalid value '0' for key 'port'")); + BEAST_EXPECT(std::string_view(ex.what()).starts_with("Invalid value '0' for key 'port'")); } } @@ -1264,12 +1143,10 @@ r.ripple.com 51235 cfg.exists("port_rpc") && cfg.section("port_rpc").lines().empty() && cfg.section("port_rpc").values().empty()); BEAST_EXPECT( - cfg.exists(SECTION_IPS) && - cfg.section(SECTION_IPS).lines().size() == 1 && + cfg.exists(SECTION_IPS) && cfg.section(SECTION_IPS).lines().size() == 1 && cfg.section(SECTION_IPS).values().size() == 1); BEAST_EXPECT( - cfg.exists(SECTION_IPS_FIXED) && - cfg.section(SECTION_IPS_FIXED).lines().size() == 2 && + cfg.exists(SECTION_IPS_FIXED) && cfg.section(SECTION_IPS_FIXED).lines().size() == 2 && cfg.section(SECTION_IPS_FIXED).values().size() == 2); } @@ -1320,12 +1197,10 @@ r.ripple.com:51235 cfg.exists("port_rpc") && cfg.section("port_rpc").lines().empty() && cfg.section("port_rpc").values().empty()); BEAST_EXPECT( - cfg.exists(SECTION_IPS) && - cfg.section(SECTION_IPS).lines().size() == 1 && + cfg.exists(SECTION_IPS) && cfg.section(SECTION_IPS).lines().size() == 1 && cfg.section(SECTION_IPS).values().size() == 1); BEAST_EXPECT( - cfg.exists(SECTION_IPS_FIXED) && - cfg.section(SECTION_IPS_FIXED).lines().size() == 15 && + cfg.exists(SECTION_IPS_FIXED) && cfg.section(SECTION_IPS_FIXED).lines().size() == 15 && cfg.section(SECTION_IPS_FIXED).values().size() == 15); BEAST_EXPECT(cfg.IPS[0] == "r.ripple.com 51235"); @@ -1344,11 +1219,8 @@ r.ripple.com:51235 BEAST_EXPECT(cfg.IPS_FIXED[10] == "::1"); BEAST_EXPECT(cfg.IPS_FIXED[11] == "::1:12345"); BEAST_EXPECT(cfg.IPS_FIXED[12] == "[::1]:12345"); - BEAST_EXPECT( - cfg.IPS_FIXED[13] == - "2001:db8:3333:4444:5555:6666:7777:8888:12345"); - BEAST_EXPECT( - cfg.IPS_FIXED[14] == "[2001:db8:3333:4444:5555:6666:7777:8888]:1"); + BEAST_EXPECT(cfg.IPS_FIXED[13] == "2001:db8:3333:4444:5555:6666:7777:8888:12345"); + BEAST_EXPECT(cfg.IPS_FIXED[14] == "[2001:db8:3333:4444:5555:6666:7777:8888]:1"); } void @@ -1542,8 +1414,7 @@ r.ripple.com:51235 { c.loadFromString(toLoad); if (shouldPass) - BEAST_EXPECT( - c.AMENDMENT_MAJORITY_TIME.count() == val * sec); + BEAST_EXPECT(c.AMENDMENT_MAJORITY_TIME.count() == val * sec); else fail(); } @@ -1562,8 +1433,7 @@ r.ripple.com:51235 { testcase("overlay: unknown time"); - auto testUnknown = - [](std::string value) -> std::optional { + auto testUnknown = [](std::string value) -> std::optional { try { Config c; @@ -1597,8 +1467,7 @@ r.ripple.com:51235 testcase("overlay: diverged time"); // In bounds: - auto testDiverged = - [](std::string value) -> std::optional { + auto testDiverged = [](std::string value) -> std::optional { try { Config c; diff --git a/src/test/core/Coroutine_test.cpp b/src/test/core/Coroutine_test.cpp index 72a4c02434..73dc3c2f8f 100644 --- a/src/test/core/Coroutine_test.cpp +++ b/src/test/core/Coroutine_test.cpp @@ -55,13 +55,12 @@ public: gate g1, g2; std::shared_ptr c; - env.app().getJobQueue().postCoro( - jtCLIENT, "Coroutine-Test", [&](auto const& cr) { - c = cr; - g1.signal(); - c->yield(); - g2.signal(); - }); + env.app().getJobQueue().postCoro(jtCLIENT, "CoroTest", [&](auto const& cr) { + c = cr; + g1.signal(); + c->yield(); + g2.signal(); + }); BEAST_EXPECT(g1.wait_for(5s)); c->join(); c->post(); @@ -82,12 +81,11 @@ public: })); gate g; - env.app().getJobQueue().postCoro( - jtCLIENT, "Coroutine-Test", [&](auto const& c) { - c->post(); - c->yield(); - g.signal(); - }); + env.app().getJobQueue().postCoro(jtCLIENT, "CoroTest", [&](auto const& c) { + c->post(); + c->yield(); + g.signal(); + }); BEAST_EXPECT(g.wait_for(5s)); } @@ -109,7 +107,7 @@ public: BEAST_EXPECT(*lv == -1); gate g; - jq.addJob(jtCLIENT, "LocalValue-Test", [&]() { + jq.addJob(jtCLIENT, "LocalValTest", [&]() { this->BEAST_EXPECT(*lv == -1); *lv = -2; this->BEAST_EXPECT(*lv == -2); @@ -120,7 +118,7 @@ public: for (int i = 0; i < N; ++i) { - jq.postCoro(jtCLIENT, "Coroutine-Test", [&, id = i](auto const& c) { + jq.postCoro(jtCLIENT, "CoroTest", [&, id = i](auto const& c) { a[id] = c; g.signal(); c->yield(); @@ -148,7 +146,7 @@ public: c->join(); } - jq.addJob(jtCLIENT, "LocalValue-Test", [&]() { + jq.addJob(jtCLIENT, "LocalValTest", [&]() { this->BEAST_EXPECT(*lv == -2); g.signal(); }); diff --git a/src/test/core/JobQueue_test.cpp b/src/test/core/JobQueue_test.cpp index 641a5fa317..0eee9ce6f2 100644 --- a/src/test/core/JobQueue_test.cpp +++ b/src/test/core/JobQueue_test.cpp @@ -19,9 +19,7 @@ class JobQueue_test : public beast::unit_test::suite { // addJob() should run the Job (and return true). std::atomic jobRan{false}; - BEAST_EXPECT(jQueue.addJob(jtCLIENT, "JobAddTest1", [&jobRan]() { - jobRan = true; - }) == true); + BEAST_EXPECT(jQueue.addJob(jtCLIENT, "JobAddTest1", [&jobRan]() { jobRan = true; }) == true); // Wait for the Job to run. while (jobRan == false) @@ -38,10 +36,7 @@ class JobQueue_test : public beast::unit_test::suite // unprotected variable on the stack should be completely safe. // Not recommended for the faint of heart... bool unprotected; - BEAST_EXPECT( - jQueue.addJob(jtCLIENT, "JobAddTest2", [&unprotected]() { - unprotected = false; - }) == false); + BEAST_EXPECT(jQueue.addJob(jtCLIENT, "JobAddTest2", [&unprotected]() { unprotected = false; }) == false); } } @@ -55,9 +50,7 @@ class JobQueue_test : public beast::unit_test::suite // Test repeated post()s until the Coro completes. std::atomic yieldCount{0}; auto const coro = jQueue.postCoro( - jtCLIENT, - "PostCoroTest1", - [&yieldCount](std::shared_ptr const& coroCopy) { + jtCLIENT, "PostCoroTest1", [&yieldCount](std::shared_ptr const& coroCopy) { while (++yieldCount < 4) coroCopy->yield(); }); @@ -84,9 +77,7 @@ class JobQueue_test : public beast::unit_test::suite // Test repeated resume()s until the Coro completes. int yieldCount{0}; auto const coro = jQueue.postCoro( - jtCLIENT, - "PostCoroTest2", - [&yieldCount](std::shared_ptr const& coroCopy) { + jtCLIENT, "PostCoroTest2", [&yieldCount](std::shared_ptr const& coroCopy) { while (++yieldCount < 4) coroCopy->yield(); }); @@ -121,10 +112,8 @@ class JobQueue_test : public beast::unit_test::suite // unprotected variable on the stack should be completely safe. // Not recommended for the faint of heart... bool unprotected; - auto const coro = jQueue.postCoro( - jtCLIENT, - "PostCoroTest3", - [&unprotected](std::shared_ptr const&) { + auto const coro = + jQueue.postCoro(jtCLIENT, "PostCoroTest3", [&unprotected](std::shared_ptr const&) { unprotected = false; }); BEAST_EXPECT(coro == nullptr); diff --git a/src/test/core/SociDB_test.cpp b/src/test/core/SociDB_test.cpp index fc3c86a994..fe73d42b0a 100644 --- a/src/test/core/SociDB_test.cpp +++ b/src/test/core/SociDB_test.cpp @@ -1,9 +1,8 @@ #include -#include - #include #include +#include #include #include @@ -13,9 +12,7 @@ class SociDB_test final : public TestSuite { private: static void - setupSQLiteConfig( - BasicConfig& config, - boost::filesystem::path const& dbPath) + setupSQLiteConfig(BasicConfig& config, boost::filesystem::path const& dbPath) { config.overwrite("sqdb", "backend", "sqlite"); auto value = dbPath.string(); @@ -45,8 +42,7 @@ private: if (!is_directory(dbPath)) { // someone created a file where we want to put out directory - Throw( - "Cannot create directory: " + dbPath.string()); + Throw("Cannot create directory: " + dbPath.string()); } } static boost::filesystem::path @@ -84,16 +80,12 @@ public: BasicConfig c; setupSQLiteConfig(c, getDatabasePath()); std::vector> const d( - {{"peerfinder", ".sqlite"}, - {"state", ".db"}, - {"random", ".db"}, - {"validators", ".sqlite"}}); + {{"peerfinder", ".sqlite"}, {"state", ".db"}, {"random", ".db"}, {"validators", ".sqlite"}}); for (auto const& i : d) { DBConfig sc(c, i.first); - BEAST_EXPECT( - boost::ends_with(sc.connectionString(), i.first + i.second)); + BEAST_EXPECT(boost::ends_with(sc.connectionString(), i.first + i.second)); } } void @@ -103,27 +95,19 @@ public: BasicConfig c; setupSQLiteConfig(c, getDatabasePath()); DBConfig sc(c, "SociTestDB"); - std::vector const stringData( - {"String1", "String2", "String3"}); + std::vector const stringData({"String1", "String2", "String3"}); std::vector const intData({1, 2, 3}); auto checkValues = [this, &stringData, &intData](soci::session& s) { // Check values in db std::vector stringResult(20 * stringData.size()); std::vector intResult(20 * intData.size()); - s << "SELECT StringData, IntData FROM SociTestTable;", - soci::into(stringResult), soci::into(intResult); - BEAST_EXPECT( - stringResult.size() == stringData.size() && - intResult.size() == intData.size()); + s << "SELECT StringData, IntData FROM SociTestTable;", soci::into(stringResult), soci::into(intResult); + BEAST_EXPECT(stringResult.size() == stringData.size() && intResult.size() == intData.size()); for (int i = 0; i < stringResult.size(); ++i) { - auto si = std::distance( - stringData.begin(), - std::find( - stringData.begin(), stringData.end(), stringResult[i])); - auto ii = std::distance( - intData.begin(), - std::find(intData.begin(), intData.end(), intResult[i])); + auto si = + std::distance(stringData.begin(), std::find(stringData.begin(), stringData.end(), stringResult[i])); + auto ii = std::distance(intData.begin(), std::find(intData.begin(), intData.end(), intResult[i])); BEAST_EXPECT(si == ii && si < stringResult.size()); } }; @@ -164,11 +148,9 @@ public: BasicConfig c; setupSQLiteConfig(c, getDatabasePath()); DBConfig sc(c, "SociTestDB"); - std::vector const ubid( - {(std::uint64_t)std::numeric_limits::max(), 20, 30}); + std::vector const ubid({(std::uint64_t)std::numeric_limits::max(), 20, 30}); std::vector const bid({-10, -20, -30}); - std::vector const uid( - {std::numeric_limits::max(), 2, 3}); + std::vector const uid({std::numeric_limits::max(), 2, 3}); std::vector const id({-1, -2, -3}); { @@ -194,11 +176,9 @@ public: std::uint32_t uig = 0; std::int64_t big = 0; std::uint64_t ubig = 0; - s << "SELECT I, UI, BI, UBI from STT;", soci::into(ig), - soci::into(uig), soci::into(big), soci::into(ubig); - BEAST_EXPECT( - ig == id[0] && uig == uid[0] && big == bid[0] && - ubig == ubid[0]); + s << "SELECT I, UI, BI, UBI from STT;", soci::into(ig), soci::into(uig), soci::into(big), + soci::into(ubig); + BEAST_EXPECT(ig == id[0] && uig == uid[0] && big == bid[0] && ubig == ubid[0]); } catch (std::exception&) { @@ -214,11 +194,9 @@ public: uint32_t uig = 0; boost::optional big; boost::optional ubig; - s << "SELECT I, UI, BI, UBI from STT;", soci::into(ig), - soci::into(uig), soci::into(big), soci::into(ubig); - BEAST_EXPECT( - *ig == id[0] && uig == uid[0] && *big == bid[0] && - *ubig == ubid[0]); + s << "SELECT I, UI, BI, UBI from STT;", soci::into(ig), soci::into(uig), soci::into(big), + soci::into(ubig); + BEAST_EXPECT(*ig == id[0] && uig == uid[0] && *big == bid[0] && *ubig == ubid[0]); } catch (std::exception&) { diff --git a/src/test/core/Workers_test.cpp b/src/test/core/Workers_test.cpp index 0a552e9d61..1f1c16b12b 100644 --- a/src/test/core/Workers_test.cpp +++ b/src/test/core/Workers_test.cpp @@ -49,8 +49,7 @@ class PerfLogTest : public PerfLog } void - jobFinish(JobType const type, std::chrono::microseconds dur, int instance) - override + jobFinish(JobType const type, std::chrono::microseconds dur, int instance) override { } @@ -102,13 +101,10 @@ public: void testThreads(int const tc1, int const tc2, int const tc3) { - testcase( - "threadCounts: " + std::to_string(tc1) + " -> " + - std::to_string(tc2) + " -> " + std::to_string(tc3)); + testcase("threadCounts: " + std::to_string(tc1) + " -> " + std::to_string(tc2) + " -> " + std::to_string(tc3)); TestCallback cb; - std::unique_ptr perfLog = - std::make_unique(); + std::unique_ptr perfLog = std::make_unique(); Workers w(cb, perfLog.get(), "Test", tc1); BEAST_EXPECT(w.getNumberOfThreads() == tc1); @@ -128,8 +124,7 @@ public: // using namespace std::chrono_literals; std::unique_lock lk{cb.mut}; - bool const signaled = - cb.cv.wait_for(lk, 10s, [&cb] { return cb.count == 0; }); + bool const signaled = cb.cv.wait_for(lk, 10s, [&cb] { return cb.count == 0; }); BEAST_EXPECT(signaled); BEAST_EXPECT(cb.count == 0); }; diff --git a/src/test/csf/BasicNetwork.h b/src/test/csf/BasicNetwork.h index cb4e691317..697b20c2c7 100644 --- a/src/test/csf/BasicNetwork.h +++ b/src/test/csf/BasicNetwork.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_CSF_BASICNETWORK_H_INCLUDED -#define XRPL_TEST_CSF_BASICNETWORK_H_INCLUDED +#pragma once #include #include @@ -116,10 +115,7 @@ public: @return `true` if a new connection was established */ bool - connect( - Peer const& from, - Peer const& to, - duration const& delay = std::chrono::seconds{0}); + connect(Peer const& from, Peer const& to, duration const& delay = std::chrono::seconds{0}); /** Break a link. @@ -184,10 +180,7 @@ BasicNetwork::BasicNetwork(Scheduler& s) : scheduler(s) template inline bool -BasicNetwork::connect( - Peer const& from, - Peer const& to, - duration const& delay) +BasicNetwork::connect(Peer const& from, Peer const& to, duration const& delay) { if (to == from) return false; @@ -221,19 +214,16 @@ BasicNetwork::send(Peer const& from, Peer const& to, Function&& f) if (!link) return; time_point const sent = scheduler.now(); - scheduler.in( - link->delay, [from, to, sent, f = std::forward(f), this] { - // only process if still connected and connection was - // not broken since the message was sent - if (auto l = links_.edge(from, to); l && l->established <= sent) - { - f(); - } - }); + scheduler.in(link->delay, [from, to, sent, f = std::forward(f), this] { + // only process if still connected and connection was + // not broken since the message was sent + if (auto l = links_.edge(from, to); l && l->established <= sent) + { + f(); + } + }); } } // namespace csf } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/csf/BasicNetwork_test.cpp b/src/test/csf/BasicNetwork_test.cpp index 0b29f90ad3..d66f5c9891 100644 --- a/src/test/csf/BasicNetwork_test.cpp +++ b/src/test/csf/BasicNetwork_test.cpp @@ -33,9 +33,7 @@ public: if (id == 0) { for (auto const link : net.links(this)) - net.send(this, link.target, [&, to = link.target] { - to->receive(net, this, 1); - }); + net.send(this, link.target, [&, to = link.target] { to->receive(net, this, 1); }); } else { @@ -52,9 +50,7 @@ public: if (m < 5) { for (auto const link : net.links(this)) - net.send(this, link.target, [&, mm = m, to = link.target] { - to->receive(net, this, mm); - }); + net.send(this, link.target, [&, mm = m, to = link.target] { to->receive(net, this, mm); }); } } }; diff --git a/src/test/csf/CollectorRef.h b/src/test/csf/CollectorRef.h index 022db01008..735a42ab16 100644 --- a/src/test/csf/CollectorRef.h +++ b/src/test/csf/CollectorRef.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_CSF_COLLECTOREF_H_INCLUDED -#define XRPL_TEST_CSF_COLLECTOREF_H_INCLUDED +#pragma once #include #include @@ -328,5 +327,3 @@ public: } // namespace csf } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/csf/Digraph.h b/src/test/csf/Digraph.h index a283f2f7cc..672445ca95 100644 --- a/src/test/csf/Digraph.h +++ b/src/test/csf/Digraph.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_CSF_DIGRAPH_H_INCLUDED -#define XRPL_TEST_CSF_DIGRAPH_H_INCLUDED +#pragma once #include #include @@ -129,9 +128,7 @@ public: auto outVertices() const { - return boost::adaptors::transform( - graph_, - [](typename Graph::value_type const& v) { return v.first; }); + return boost::adaptors::transform(graph_, [](typename Graph::value_type const& v) { return v.first; }); } /** Range over target vertices @@ -142,9 +139,7 @@ public: auto outVertices(Vertex source) const { - auto transform = [](typename Links::value_type const& link) { - return link.first; - }; + auto transform = [](typename Links::value_type const& link) { return link.first; }; auto it = graph_.find(source); if (it != graph_.end()) return boost::adaptors::transform(it->second, transform); @@ -232,4 +227,3 @@ public: } // namespace csf } // namespace test } // namespace xrpl -#endif diff --git a/src/test/csf/Histogram.h b/src/test/csf/Histogram.h index 61ec680939..9e7b471a2b 100644 --- a/src/test/csf/Histogram.h +++ b/src/test/csf/Histogram.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_CSF_HISTOGRAM_H_INCLUDED -#define XRPL_TEST_CSF_HISTOGRAM_H_INCLUDED +#pragma once #include #include @@ -112,5 +111,3 @@ public: } // namespace csf } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/csf/Peer.h b/src/test/csf/Peer.h index b86991ba5f..7b19c977d6 100644 --- a/src/test/csf/Peer.h +++ b/src/test/csf/Peer.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_CSF_PEER_H_INCLUDED -#define XRPL_TEST_CSF_PEER_H_INCLUDED +#pragma once #include #include @@ -405,20 +404,18 @@ struct Peer minDuration = std::min(minDuration, link.data.delay); // Send a message to neighbors to find the ledger - net.send( - this, link.target, [to = link.target, from = this, ledgerID]() { - if (auto it = to->ledgers.find(ledgerID); - it != to->ledgers.end()) - { - // if the ledger is found, send it back to the original - // requesting peer where it is added to the available - // ledgers - to->net.send(to, from, [from, ledger = it->second]() { - from->acquiringLedgers.erase(ledger.id()); - from->ledgers.emplace(ledger.id(), ledger); - }); - } - }); + net.send(this, link.target, [to = link.target, from = this, ledgerID]() { + if (auto it = to->ledgers.find(ledgerID); it != to->ledgers.end()) + { + // if the ledger is found, send it back to the original + // requesting peer where it is added to the available + // ledgers + to->net.send(to, from, [from, ledger = it->second]() { + from->acquiringLedgers.erase(ledger.id()); + from->ledgers.emplace(ledger.id(), ledger); + }); + } + }); } acquiringLedgers[ledgerID] = scheduler.now() + 2 * minDuration; return nullptr; @@ -451,20 +448,18 @@ struct Peer { minDuration = std::min(minDuration, link.data.delay); // Send a message to neighbors to find the tx set - net.send( - this, link.target, [to = link.target, from = this, setId]() { - if (auto it = to->txSets.find(setId); - it != to->txSets.end()) - { - // If the txSet is found, send it back to the original - // requesting peer, where it is handled like a TxSet - // that was broadcast over the network - to->net.send(to, from, [from, txSet = it->second]() { - from->acquiringTxSets.erase(txSet.id()); - from->handle(txSet); - }); - } - }); + net.send(this, link.target, [to = link.target, from = this, setId]() { + if (auto it = to->txSets.find(setId); it != to->txSets.end()) + { + // If the txSet is found, send it back to the original + // requesting peer, where it is handled like a TxSet + // that was broadcast over the network + to->net.send(to, from, [from, txSet = it->second]() { + from->acquiringTxSets.erase(txSet.id()); + from->handle(txSet); + }); + } + }); } acquiringTxSets[setId] = scheduler.now() + 2 * minDuration; return nullptr; @@ -489,22 +484,12 @@ struct Peer } Result - onClose( - Ledger const& prevLedger, - NetClock::time_point closeTime, - ConsensusMode mode) + onClose(Ledger const& prevLedger, NetClock::time_point closeTime, ConsensusMode mode) { issue(CloseLedger{prevLedger, openTxs}); return Result( - TxSet{openTxs}, - Proposal( - prevLedger.id(), - Proposal::seqJoin, - TxSet::calcID(openTxs), - closeTime, - now(), - id)); + TxSet{openTxs}, Proposal(prevLedger.id(), Proposal::seqJoin, TxSet::calcID(openTxs), closeTime, now(), id)); } void @@ -516,14 +501,7 @@ struct Peer ConsensusMode const& mode, Json::Value&& consensusJson) { - onAccept( - result, - prevLedger, - closeResolution, - rawCloseTimes, - mode, - std::move(consensusJson), - validating()); + onAccept(result, prevLedger, closeResolution, rawCloseTimes, mode, std::move(consensusJson), validating()); } void @@ -541,11 +519,8 @@ struct Peer bool const consensusFail = result.state == ConsensusState::MovedOn; TxSet const acceptedTxs = injectTxs(prevLedger, result.txns); - Ledger const newLedger = oracle.accept( - prevLedger, - acceptedTxs.txs(), - closeResolution, - result.position.closeTime()); + Ledger const newLedger = + oracle.accept(prevLedger, acceptedTxs.txs(), closeResolution, result.position.closeTime()); ledgers[newLedger.id()] = newLedger; issue(AcceptLedger{newLedger, lastClosedLedger}); @@ -554,30 +529,19 @@ struct Peer lastClosedLedger = newLedger; auto const it = std::remove_if( - openTxs.begin(), openTxs.end(), [&](Tx const& tx) { - return acceptedTxs.exists(tx.id()); - }); + openTxs.begin(), openTxs.end(), [&](Tx const& tx) { return acceptedTxs.exists(tx.id()); }); openTxs.erase(it, openTxs.end()); // Only send validation if the new ledger is compatible with our // fully validated ledger - bool const isCompatible = - newLedger.isAncestor(fullyValidatedLedger); + bool const isCompatible = newLedger.isAncestor(fullyValidatedLedger); // Can only send one validated ledger per seq - if (runAsValidator && isCompatible && !consensusFail && - validations.canValidateSeq(newLedger.seq())) + if (runAsValidator && isCompatible && !consensusFail && validations.canValidateSeq(newLedger.seq())) { bool isFull = proposing; - Validation v{ - newLedger.id(), - newLedger.seq(), - now(), - now(), - key, - id, - isFull}; + Validation v{newLedger.id(), newLedger.seq(), now(), now(), key, id, isFull}; // share the new validation; it is trusted by the receiver share(v); // we trust ourselves @@ -608,17 +572,13 @@ struct Peer } Ledger::ID - getPrevLedger( - Ledger::ID const& ledgerID, - Ledger const& ledger, - ConsensusMode mode) + getPrevLedger(Ledger::ID const& ledgerID, Ledger const& ledger, ConsensusMode mode) { // only do if we are past the genesis ledger if (ledger.seq() == Ledger::Seq{0}) return ledgerID; - Ledger::ID const netLgr = - validations.getPreferred(ledger, earliestAllowedSeq()); + Ledger::ID const netLgr = validations.getPreferred(ledger, earliestAllowedSeq()); if (netLgr != ledgerID) { @@ -749,12 +709,7 @@ struct Peer if (link.target->router.lastObservedSeq[bm.origin] < bm.seq) { issue(Relay{link.target->id, bm.msg}); - net.send( - this, - link.target, - [to = link.target, bm, id = this->id] { - to->receive(bm, id); - }); + net.send(this, link.target, [to = link.target, bm, id = this->id] { to->receive(bm, id); }); } } } @@ -800,8 +755,7 @@ struct Peer bool handle(TxSet const& txs) { - bool const inserted = - txSets.insert(std::make_pair(txs.id(), txs)).second; + bool const inserted = txSets.insert(std::make_pair(txs.id(), txs)).second; if (inserted) consensus.gotTxSet(now(), txs); // relay only if new @@ -906,8 +860,7 @@ struct Peer // Between rounds, we take the majority ledger // In the future, consider taking peer dominant ledger if no validations // yet - Ledger::ID bestLCL = - validations.getPreferred(lastClosedLedger, earliestAllowedSeq()); + Ledger::ID bestLCL = validations.getPreferred(lastClosedLedger, earliestAllowedSeq()); if (bestLCL == Ledger::ID{0}) bestLCL = lastClosedLedger.id(); @@ -915,8 +868,7 @@ struct Peer // Not yet modeling dynamic UNL. hash_set nowUntrusted; - consensus.startRound( - now(), bestLCL, lastClosedLedger, nowUntrusted, runAsValidator, {}); + consensus.startRound(now(), bestLCL, lastClosedLedger, nowUntrusted, runAsValidator, {}); } // Start the consensus process assuming it is not yet running @@ -939,8 +891,8 @@ struct Peer // code are positive. (e.g. proposeFRESHNESS) using namespace std::chrono; using namespace std::chrono_literals; - return NetClock::time_point(duration_cast( - scheduler.now().time_since_epoch() + 86400s + clockSkew)); + return NetClock::time_point( + duration_cast(scheduler.now().time_since_epoch() + 86400s + clockSkew)); } Ledger::ID @@ -984,4 +936,3 @@ struct Peer } // namespace csf } // namespace test } // namespace xrpl -#endif diff --git a/src/test/csf/PeerGroup.h b/src/test/csf/PeerGroup.h index 8a215eaf8d..ce7325f659 100644 --- a/src/test/csf/PeerGroup.h +++ b/src/test/csf/PeerGroup.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_CSF_PEERGROUP_H_INCLUDED -#define XRPL_TEST_CSF_PEERGROUP_H_INCLUDED +#pragma once #include #include @@ -86,9 +85,7 @@ public: bool contains(PeerID id) { - return std::find_if(peers_.begin(), peers_.end(), [id](Peer const* p) { - return p->id == id; - }) != peers_.end(); + return std::find_if(peers_.begin(), peers_.end(), [id](Peer const* p) { return p->id == id; }) != peers_.end(); } std::size_t @@ -217,11 +214,7 @@ public: { PeerGroup res; std::set_union( - a.peers_.begin(), - a.peers_.end(), - b.peers_.begin(), - b.peers_.end(), - std::back_inserter(res.peers_)); + a.peers_.begin(), a.peers_.end(), b.peers_.begin(), b.peers_.end(), std::back_inserter(res.peers_)); return res; } @@ -232,11 +225,7 @@ public: PeerGroup res; std::set_difference( - a.peers_.begin(), - a.peers_.end(), - b.peers_.begin(), - b.peers_.end(), - std::back_inserter(res.peers_)); + a.peers_.begin(), a.peers_.end(), b.peers_.begin(), b.peers_.end(), std::back_inserter(res.peers_)); return res; } @@ -313,8 +302,7 @@ randomRankedTrust( RandomNumberDistribution sizeDist, Generator& g) { - std::vector const groups = - randomRankedGroups(peers, ranks, numGroups, sizeDist, g); + std::vector const groups = randomRankedGroups(peers, ranks, numGroups, sizeDist, g); std::uniform_int_distribution u(0, groups.size() - 1); for (auto& peer : peers) @@ -338,8 +326,7 @@ randomRankedConnect( Generator& g, SimDuration delay) { - std::vector const groups = - randomRankedGroups(peers, ranks, numGroups, sizeDist, g); + std::vector const groups = randomRankedGroups(peers, ranks, numGroups, sizeDist, g); std::uniform_int_distribution u(0, groups.size() - 1); for (auto& peer : peers) @@ -352,4 +339,3 @@ randomRankedConnect( } // namespace csf } // namespace test } // namespace xrpl -#endif diff --git a/src/test/csf/Proposal.h b/src/test/csf/Proposal.h index 0bcf838080..641fd2010a 100644 --- a/src/test/csf/Proposal.h +++ b/src/test/csf/Proposal.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_CSF_PROPOSAL_H_INCLUDED -#define XRPL_TEST_CSF_PROPOSAL_H_INCLUDED +#pragma once #include #include @@ -18,5 +17,3 @@ using Proposal = ConsensusProposal; } // namespace csf } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/csf/Scheduler.h b/src/test/csf/Scheduler.h index 2c250e6def..2f7535ef16 100644 --- a/src/test/csf/Scheduler.h +++ b/src/test/csf/Scheduler.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_CSF_SCHEDULER_H_INCLUDED -#define XRPL_TEST_CSF_SCHEDULER_H_INCLUDED +#pragma once #include #include @@ -35,8 +34,7 @@ public: using time_point = typename clock_type::time_point; private: - using by_when_hook = boost::intrusive::set_base_hook< - boost::intrusive::link_mode>; + using by_when_hook = boost::intrusive::set_base_hook>; struct event : by_when_hook { @@ -75,8 +73,7 @@ private: operator=(event_impl const&) = delete; template - event_impl(time_point when_, DeducedHandler&& h) - : event(when_), h_(std::forward(h)) + event_impl(time_point when_, DeducedHandler&& h) : event(when_), h_(std::forward(h)) { } @@ -90,9 +87,8 @@ private: class queue_type { private: - using by_when_set = typename boost::intrusive::make_multiset< - event, - boost::intrusive::constant_time_size>::type; + using by_when_set = + typename boost::intrusive::make_multiset>::type; // alloc_ is owned by the scheduler boost::container::pmr::monotonic_buffer_resource* alloc_; by_when_set by_when_; @@ -104,8 +100,7 @@ private: queue_type& operator=(queue_type const&) = delete; - explicit queue_type( - boost::container::pmr::monotonic_buffer_resource* alloc); + explicit queue_type(boost::container::pmr::monotonic_buffer_resource* alloc); ~queue_type(); @@ -256,9 +251,7 @@ public: //------------------------------------------------------------------------------ -inline Scheduler::queue_type::queue_type( - boost::container::pmr::monotonic_buffer_resource* alloc) - : alloc_(alloc) +inline Scheduler::queue_type::queue_type(boost::container::pmr::monotonic_buffer_resource* alloc) : alloc_(alloc) { } @@ -293,8 +286,7 @@ Scheduler::queue_type::end() -> iterator template inline auto -Scheduler::queue_type::emplace(time_point when, Handler&& h) -> - typename by_when_set::iterator +Scheduler::queue_type::emplace(time_point when, Handler&& h) -> typename by_when_set::iterator { using event_type = event_impl>; auto const p = alloc_->allocate(sizeof(event_type)); @@ -435,5 +427,3 @@ Scheduler::step_for(std::chrono::duration const& amount) } // namespace csf } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/csf/Sim.h b/src/test/csf/Sim.h index ad0927e87e..709226b216 100644 --- a/src/test/csf/Sim.h +++ b/src/test/csf/Sim.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_CSF_SIM_H_INCLUDED -#define XRPL_TEST_CSF_SIM_H_INCLUDED +#pragma once #include #include @@ -24,8 +23,7 @@ class BasicSink : public beast::Journal::Sink Scheduler::clock_type const& clock_; public: - BasicSink(Scheduler::clock_type const& clock) - : Sink(beast::severities::kDisabled, false), clock_{clock} + BasicSink(Scheduler::clock_type const& clock) : Sink(beast::severities::kDisabled, false), clock_{clock} { } @@ -35,16 +33,13 @@ public: if (level < threshold()) return; - std::cout << clock_.now().time_since_epoch().count() << " " << text - << std::endl; + std::cout << clock_.now().time_since_epoch().count() << " " << text << std::endl; } void - writeAlways(beast::severities::Severity level, std::string const& text) - override + writeAlways(beast::severities::Severity level, std::string const& text) override { - std::cout << clock_.now().time_since_epoch().count() << " " << text - << std::endl; + std::cout << clock_.now().time_since_epoch().count() << " " << text << std::endl; } }; @@ -94,13 +89,7 @@ public: for (std::size_t i = 0; i < numPeers; ++i) { peers.emplace_back( - PeerID{static_cast(peers.size())}, - scheduler, - oracle, - net, - trustGraph, - collectors, - j); + PeerID{static_cast(peers.size())}, scheduler, oracle, net, trustGraph, collectors, j); newPeers.emplace_back(&peers.back()); } PeerGroup res{newPeers}; @@ -158,5 +147,3 @@ public: } // namespace csf } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/csf/SimTime.h b/src/test/csf/SimTime.h index 5d8c67b8f8..2131de9b41 100644 --- a/src/test/csf/SimTime.h +++ b/src/test/csf/SimTime.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_CSF_SIMTIME_H_INCLUDED -#define XRPL_TEST_CSF_SIMTIME_H_INCLUDED +#pragma once #include @@ -20,5 +19,3 @@ using SimTime = typename SimClock::time_point; } // namespace csf } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/csf/TrustGraph.h b/src/test/csf/TrustGraph.h index f5b8a9e755..d25925ad38 100644 --- a/src/test/csf/TrustGraph.h +++ b/src/test/csf/TrustGraph.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_CSF_UNL_H_INCLUDED -#define XRPL_TEST_CSF_UNL_H_INCLUDED +#pragma once #include @@ -110,8 +109,7 @@ public: std::set unique; for (Peer const peer : graph_.outVertices()) { - unique.emplace( - std::begin(trustedPeers(peer)), std::end(trustedPeers(peer))); + unique.emplace(std::begin(trustedPeers(peer)), std::end(trustedPeers(peer))); } std::vector uniqueUNLs(unique.begin(), unique.end()); @@ -124,18 +122,14 @@ public: { auto const& unlA = uniqueUNLs[i]; auto const& unlB = uniqueUNLs[j]; - double rhs = - 2.0 * (1. - quorum) * std::max(unlA.size(), unlB.size()); + double rhs = 2.0 * (1. - quorum) * std::max(unlA.size(), unlB.size()); int intersectionSize = - std::count_if(unlA.begin(), unlA.end(), [&](Peer p) { - return unlB.find(p) != unlB.end(); - }); + std::count_if(unlA.begin(), unlA.end(), [&](Peer p) { return unlB.find(p) != unlB.end(); }); if (intersectionSize < rhs) { - res.emplace_back( - ForkInfo{unlA, unlB, intersectionSize, rhs}); + res.emplace_back(ForkInfo{unlA, unlB, intersectionSize, rhs}); } } } @@ -155,5 +149,3 @@ public: } // namespace csf } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/csf/Tx.h b/src/test/csf/Tx.h index cf3ee85940..20c90cbac5 100644 --- a/src/test/csf/Tx.h +++ b/src/test/csf/Tx.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_CSF_TX_H_INCLUDED -#define XRPL_TEST_CSF_TX_H_INCLUDED +#pragma once #include #include @@ -145,11 +144,7 @@ public: auto populate_diffs = [&res](auto const& a, auto const& b, bool s) { auto populator = [&](auto const& tx) { res[tx.id()] = s; }; std::set_difference( - a.begin(), - a.end(), - b.begin(), - b.end(), - boost::make_function_output_iterator(std::ref(populator))); + a.begin(), a.end(), b.begin(), b.end(), boost::make_function_output_iterator(std::ref(populator))); }; populate_diffs(txs_, other.txs_, true); @@ -211,5 +206,3 @@ hash_append(Hasher& h, Tx const& tx) } // namespace csf } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/csf/Validation.h b/src/test/csf/Validation.h index 907eca79d0..5ebbcf3ae5 100644 --- a/src/test/csf/Validation.h +++ b/src/test/csf/Validation.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_CSF_VALIDATION_H_INCLUDED -#define XRPL_TEST_CSF_VALIDATION_H_INCLUDED +#pragma once #include @@ -140,15 +139,7 @@ public: asTie() const { // trusted is a status set by the receiver, so it is not part of the tie - return std::tie( - ledgerID_, - seq_, - signTime_, - seenTime_, - key_, - nodeID_, - loadFee_, - full_); + return std::tie(ledgerID_, seq_, signTime_, seenTime_, key_, nodeID_, loadFee_, full_); } bool operator==(Validation const& o) const @@ -184,5 +175,3 @@ public: } // namespace csf } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/csf/collectors.h b/src/test/csf/collectors.h index 3b6bc0e0f3..20fc31a01f 100644 --- a/src/test/csf/collectors.h +++ b/src/test/csf/collectors.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_CSF_COLLECTORS_H_INCLUDED -#define XRPL_TEST_CSF_COLLECTORS_H_INCLUDED +#pragma once #include #include @@ -46,12 +45,7 @@ class Collectors template static void - apply( - std::tuple& cs, - PeerID who, - SimTime when, - E e, - std::index_sequence) + apply(std::tuple& cs, PeerID who, SimTime when, E e, std::index_sequence) { (..., apply(std::get(cs), who, when, e)); } @@ -235,18 +229,14 @@ struct TxCollector std::size_t orphaned() const { - return std::count_if(txs.begin(), txs.end(), [](auto const& it) { - return !it.second.accepted; - }); + return std::count_if(txs.begin(), txs.end(), [](auto const& it) { return !it.second.accepted; }); } // Returns the number of txs which were never validated std::size_t unvalidated() const { - return std::count_if(txs.begin(), txs.end(), [](auto const& it) { - return !it.second.validated; - }); + return std::count_if(txs.begin(), txs.end(), [](auto const& it) { return !it.second.validated; }); } template @@ -258,86 +248,64 @@ struct TxCollector return double(count) / duration_cast(simDuration).count(); }; - auto fmtS = [](SimDuration dur) { - return duration_cast>(dur).count(); - }; + auto fmtS = [](SimDuration dur) { return duration_cast>(dur).count(); }; if (printBreakline) { - log << std::setw(11) << std::setfill('-') << "-" << "-" - << std::setw(7) << std::setfill('-') << "-" << "-" - << std::setw(7) << std::setfill('-') << "-" << "-" - << std::setw(36) << std::setfill('-') << "-" << std::endl; + log << std::setw(11) << std::setfill('-') << "-" << "-" << std::setw(7) << std::setfill('-') << "-" << "-" + << std::setw(7) << std::setfill('-') << "-" << "-" << std::setw(36) << std::setfill('-') << "-" + << std::endl; log << std::setfill(' '); } - log << std::left << std::setw(11) << "TxStats" << "|" << std::setw(7) - << "Count" << "|" << std::setw(7) << "Per Sec" << "|" - << std::setw(15) << "Latency (sec)" << std::right << std::setw(7) - << "10-ile" << std::setw(7) << "50-ile" << std::setw(7) << "90-ile" - << std::left << std::endl; + log << std::left << std::setw(11) << "TxStats" << "|" << std::setw(7) << "Count" << "|" << std::setw(7) + << "Per Sec" << "|" << std::setw(15) << "Latency (sec)" << std::right << std::setw(7) << "10-ile" + << std::setw(7) << "50-ile" << std::setw(7) << "90-ile" << std::left << std::endl; - log << std::setw(11) << std::setfill('-') << "-" << "|" << std::setw(7) - << std::setfill('-') << "-" << "|" << std::setw(7) - << std::setfill('-') << "-" << "|" << std::setw(36) - << std::setfill('-') << "-" << std::endl; + log << std::setw(11) << std::setfill('-') << "-" << "|" << std::setw(7) << std::setfill('-') << "-" << "|" + << std::setw(7) << std::setfill('-') << "-" << "|" << std::setw(36) << std::setfill('-') << "-" + << std::endl; log << std::setfill(' '); - log << std::left << std::setw(11) << "Submit " << "|" << std::right - << std::setw(7) << submitted << "|" << std::setw(7) - << std::setprecision(2) << perSec(submitted) << "|" << std::setw(36) - << "" << std::endl; + log << std::left << std::setw(11) << "Submit " << "|" << std::right << std::setw(7) << submitted << "|" + << std::setw(7) << std::setprecision(2) << perSec(submitted) << "|" << std::setw(36) << "" << std::endl; - log << std::left << std::setw(11) << "Accept " << "|" << std::right - << std::setw(7) << accepted << "|" << std::setw(7) - << std::setprecision(2) << perSec(accepted) << "|" << std::setw(15) - << std::left << "From Submit" << std::right << std::setw(7) - << std::setprecision(2) << fmtS(submitToAccept.percentile(0.1f)) - << std::setw(7) << std::setprecision(2) - << fmtS(submitToAccept.percentile(0.5f)) << std::setw(7) - << std::setprecision(2) << fmtS(submitToAccept.percentile(0.9f)) + log << std::left << std::setw(11) << "Accept " << "|" << std::right << std::setw(7) << accepted << "|" + << std::setw(7) << std::setprecision(2) << perSec(accepted) << "|" << std::setw(15) << std::left + << "From Submit" << std::right << std::setw(7) << std::setprecision(2) + << fmtS(submitToAccept.percentile(0.1f)) << std::setw(7) << std::setprecision(2) + << fmtS(submitToAccept.percentile(0.5f)) << std::setw(7) << std::setprecision(2) + << fmtS(submitToAccept.percentile(0.9f)) << std::endl; + + log << std::left << std::setw(11) << "Validate " << "|" << std::right << std::setw(7) << validated << "|" + << std::setw(7) << std::setprecision(2) << perSec(validated) << "|" << std::setw(15) << std::left + << "From Submit" << std::right << std::setw(7) << std::setprecision(2) + << fmtS(submitToValidate.percentile(0.1f)) << std::setw(7) << std::setprecision(2) + << fmtS(submitToValidate.percentile(0.5f)) << std::setw(7) << std::setprecision(2) + << fmtS(submitToValidate.percentile(0.9f)) << std::endl; + + log << std::left << std::setw(11) << "Orphan" << "|" << std::right << std::setw(7) << orphaned() << "|" + << std::setw(7) << "" << "|" << std::setw(36) << std::endl; + + log << std::left << std::setw(11) << "Unvalidated" << "|" << std::right << std::setw(7) << unvalidated() << "|" + << std::setw(7) << "" << "|" << std::setw(43) << std::endl; + + log << std::setw(11) << std::setfill('-') << "-" << "-" << std::setw(7) << std::setfill('-') << "-" << "-" + << std::setw(7) << std::setfill('-') << "-" << "-" << std::setw(36) << std::setfill('-') << "-" << std::endl; - - log << std::left << std::setw(11) << "Validate " << "|" << std::right - << std::setw(7) << validated << "|" << std::setw(7) - << std::setprecision(2) << perSec(validated) << "|" << std::setw(15) - << std::left << "From Submit" << std::right << std::setw(7) - << std::setprecision(2) << fmtS(submitToValidate.percentile(0.1f)) - << std::setw(7) << std::setprecision(2) - << fmtS(submitToValidate.percentile(0.5f)) << std::setw(7) - << std::setprecision(2) << fmtS(submitToValidate.percentile(0.9f)) - << std::endl; - - log << std::left << std::setw(11) << "Orphan" << "|" << std::right - << std::setw(7) << orphaned() << "|" << std::setw(7) << "" << "|" - << std::setw(36) << std::endl; - - log << std::left << std::setw(11) << "Unvalidated" << "|" << std::right - << std::setw(7) << unvalidated() << "|" << std::setw(7) << "" << "|" - << std::setw(43) << std::endl; - - log << std::setw(11) << std::setfill('-') << "-" << "-" << std::setw(7) - << std::setfill('-') << "-" << "-" << std::setw(7) - << std::setfill('-') << "-" << "-" << std::setw(36) - << std::setfill('-') << "-" << std::endl; log << std::setfill(' '); } template void - csv(SimDuration simDuration, - T& log, - Tag const& tag, - bool printHeaders = false) + csv(SimDuration simDuration, T& log, Tag const& tag, bool printHeaders = false) { using namespace std::chrono; auto perSec = [&simDuration](std::size_t count) { return double(count) / duration_cast(simDuration).count(); }; - auto fmtS = [](SimDuration dur) { - return duration_cast>(dur).count(); - }; + auto fmtS = [](SimDuration dur) { return duration_cast>(dur).count(); }; if (printHeaders) { @@ -395,8 +363,7 @@ struct TxCollector << std::setprecision(2) << fmtS(submitToValidate.percentile(0.5f)) << "," // txLatencySubmitToValidate90Pctl - << std::setprecision(2) << fmtS(submitToValidate.percentile(0.9f)) - << "," << std::endl; + << std::setprecision(2) << fmtS(submitToValidate.percentile(0.9f)) << "," << std::endl; } }; @@ -476,8 +443,7 @@ struct LedgerCollector auto& parentTracker = parentIt->second; if (parentTracker.fullyValidated) { - fullyValidToFullyValid.insert( - when - *parentTracker.fullyValidated); + fullyValidToFullyValid.insert(when - *parentTracker.fullyValidated); } } } @@ -488,9 +454,7 @@ struct LedgerCollector unvalidated() const { return std::count_if( - ledgers_.begin(), ledgers_.end(), [](auto const& it) { - return !it.second.fullyValidated; - }); + ledgers_.begin(), ledgers_.end(), [](auto const& it) { return !it.second.fullyValidated; }); } template @@ -502,74 +466,56 @@ struct LedgerCollector return double(count) / duration_cast(simDuration).count(); }; - auto fmtS = [](SimDuration dur) { - return duration_cast>(dur).count(); - }; + auto fmtS = [](SimDuration dur) { return duration_cast>(dur).count(); }; if (printBreakline) { - log << std::setw(11) << std::setfill('-') << "-" << "-" - << std::setw(7) << std::setfill('-') << "-" << "-" - << std::setw(7) << std::setfill('-') << "-" << "-" - << std::setw(36) << std::setfill('-') << "-" << std::endl; + log << std::setw(11) << std::setfill('-') << "-" << "-" << std::setw(7) << std::setfill('-') << "-" << "-" + << std::setw(7) << std::setfill('-') << "-" << "-" << std::setw(36) << std::setfill('-') << "-" + << std::endl; log << std::setfill(' '); } - log << std::left << std::setw(11) << "LedgerStats" << "|" - << std::setw(7) << "Count" << "|" << std::setw(7) << "Per Sec" - << "|" << std::setw(15) << "Latency (sec)" << std::right - << std::setw(7) << "10-ile" << std::setw(7) << "50-ile" - << std::setw(7) << "90-ile" << std::left << std::endl; + log << std::left << std::setw(11) << "LedgerStats" << "|" << std::setw(7) << "Count" << "|" << std::setw(7) + << "Per Sec" + << "|" << std::setw(15) << "Latency (sec)" << std::right << std::setw(7) << "10-ile" << std::setw(7) + << "50-ile" << std::setw(7) << "90-ile" << std::left << std::endl; - log << std::setw(11) << std::setfill('-') << "-" << "|" << std::setw(7) - << std::setfill('-') << "-" << "|" << std::setw(7) - << std::setfill('-') << "-" << "|" << std::setw(36) - << std::setfill('-') << "-" << std::endl; + log << std::setw(11) << std::setfill('-') << "-" << "|" << std::setw(7) << std::setfill('-') << "-" << "|" + << std::setw(7) << std::setfill('-') << "-" << "|" << std::setw(36) << std::setfill('-') << "-" + << std::endl; log << std::setfill(' '); - log << std::left << std::setw(11) << "Accept " << "|" << std::right - << std::setw(7) << accepted << "|" << std::setw(7) - << std::setprecision(2) << perSec(accepted) << "|" << std::setw(15) - << std::left << "From Accept" << std::right << std::setw(7) - << std::setprecision(2) << fmtS(acceptToAccept.percentile(0.1f)) - << std::setw(7) << std::setprecision(2) - << fmtS(acceptToAccept.percentile(0.5f)) << std::setw(7) - << std::setprecision(2) << fmtS(acceptToAccept.percentile(0.9f)) - << std::endl; + log << std::left << std::setw(11) << "Accept " << "|" << std::right << std::setw(7) << accepted << "|" + << std::setw(7) << std::setprecision(2) << perSec(accepted) << "|" << std::setw(15) << std::left + << "From Accept" << std::right << std::setw(7) << std::setprecision(2) + << fmtS(acceptToAccept.percentile(0.1f)) << std::setw(7) << std::setprecision(2) + << fmtS(acceptToAccept.percentile(0.5f)) << std::setw(7) << std::setprecision(2) + << fmtS(acceptToAccept.percentile(0.9f)) << std::endl; - log << std::left << std::setw(11) << "Validate " << "|" << std::right - << std::setw(7) << fullyValidated << "|" << std::setw(7) - << std::setprecision(2) << perSec(fullyValidated) << "|" - << std::setw(15) << std::left << "From Validate " << std::right - << std::setw(7) << std::setprecision(2) - << fmtS(fullyValidToFullyValid.percentile(0.1f)) << std::setw(7) - << std::setprecision(2) - << fmtS(fullyValidToFullyValid.percentile(0.5f)) << std::setw(7) - << std::setprecision(2) + log << std::left << std::setw(11) << "Validate " << "|" << std::right << std::setw(7) << fullyValidated << "|" + << std::setw(7) << std::setprecision(2) << perSec(fullyValidated) << "|" << std::setw(15) << std::left + << "From Validate " << std::right << std::setw(7) << std::setprecision(2) + << fmtS(fullyValidToFullyValid.percentile(0.1f)) << std::setw(7) << std::setprecision(2) + << fmtS(fullyValidToFullyValid.percentile(0.5f)) << std::setw(7) << std::setprecision(2) << fmtS(fullyValidToFullyValid.percentile(0.9f)) << std::endl; - log << std::setw(11) << std::setfill('-') << "-" << "-" << std::setw(7) - << std::setfill('-') << "-" << "-" << std::setw(7) - << std::setfill('-') << "-" << "-" << std::setw(36) - << std::setfill('-') << "-" << std::endl; + log << std::setw(11) << std::setfill('-') << "-" << "-" << std::setw(7) << std::setfill('-') << "-" << "-" + << std::setw(7) << std::setfill('-') << "-" << "-" << std::setw(36) << std::setfill('-') << "-" + << std::endl; log << std::setfill(' '); } template void - csv(SimDuration simDuration, - T& log, - Tag const& tag, - bool printHeaders = false) + csv(SimDuration simDuration, T& log, Tag const& tag, bool printHeaders = false) { using namespace std::chrono; auto perSec = [&simDuration](std::size_t count) { return double(count) / duration_cast(simDuration).count(); }; - auto fmtS = [](SimDuration dur) { - return duration_cast>(dur).count(); - }; + auto fmtS = [](SimDuration dur) { return duration_cast>(dur).count(); }; if (printHeaders) { @@ -608,16 +554,13 @@ struct LedgerCollector << std::setprecision(2) << fmtS(acceptToAccept.percentile(0.9f)) << "," // ledgerLatencyFullyValidToFullyValid10Pctl - << std::setprecision(2) - << fmtS(fullyValidToFullyValid.percentile(0.1f)) + << std::setprecision(2) << fmtS(fullyValidToFullyValid.percentile(0.1f)) << "," // ledgerLatencyFullyValidToFullyValid50Pctl - << std::setprecision(2) - << fmtS(fullyValidToFullyValid.percentile(0.5f)) + << std::setprecision(2) << fmtS(fullyValidToFullyValid.percentile(0.5f)) << "," // ledgerLatencyFullyValidToFullyValid90Pctl - << std::setprecision(2) - << fmtS(fullyValidToFullyValid.percentile(0.9f)) << std::endl; + << std::setprecision(2) << fmtS(fullyValidToFullyValid.percentile(0.9f)) << std::endl; } }; @@ -640,16 +583,14 @@ struct StreamCollector void on(PeerID who, SimTime when, AcceptLedger const& e) { - out << when.time_since_epoch().count() << ": Node " << who - << " accepted " << "L" << e.ledger.id() << " " << e.ledger.txs() - << "\n"; + out << when.time_since_epoch().count() << ": Node " << who << " accepted " << "L" << e.ledger.id() << " " + << e.ledger.txs() << "\n"; } void on(PeerID who, SimTime when, FullyValidateLedger const& e) { - out << when.time_since_epoch().count() << ": Node " << who - << " fully-validated " << "L" << e.ledger.id() << " " + out << when.time_since_epoch().count() << ": Node " << who << " fully-validated " << "L" << e.ledger.id() << " " << e.ledger.txs() << "\n"; } }; @@ -692,13 +633,10 @@ struct JumpCollector { // Not a direct child -> parent switch if (e.ledger.parentID() != e.prior.id()) - fullyValidatedJumps.emplace_back( - Jump{who, when, e.prior, e.ledger}); + fullyValidatedJumps.emplace_back(Jump{who, when, e.prior, e.ledger}); } }; } // namespace csf } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/csf/events.h b/src/test/csf/events.h index 29f434f4ad..2aae22d125 100644 --- a/src/test/csf/events.h +++ b/src/test/csf/events.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_CSF_EVENTS_H_INCLUDED -#define XRPL_TEST_CSF_EVENTS_H_INCLUDED +#pragma once #include #include @@ -130,5 +129,3 @@ struct FullyValidateLedger } // namespace csf } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/csf/impl/ledgers.cpp b/src/test/csf/impl/ledgers.cpp index 09a098f2d6..12d461a214 100644 --- a/src/test/csf/impl/ledgers.cpp +++ b/src/test/csf/impl/ledgers.cpp @@ -88,8 +88,7 @@ LedgerOracle::accept( next.closeTimeResolution = closeTimeResolution; next.closeTimeAgree = consensusCloseTime != NetClock::time_point{}; if (next.closeTimeAgree) - next.closeTime = effCloseTime( - consensusCloseTime, closeTimeResolution, parent.closeTime()); + next.closeTime = effCloseTime(consensusCloseTime, closeTimeResolution, parent.closeTime()); else next.closeTime = parent.closeTime() + 1s; diff --git a/src/test/csf/ledgers.h b/src/test/csf/ledgers.h index 7614482635..d78c7c29fa 100644 --- a/src/test/csf/ledgers.h +++ b/src/test/csf/ledgers.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_CSF_LEDGERS_H_INCLUDED -#define XRPL_TEST_CSF_LEDGERS_H_INCLUDED +#pragma once #include @@ -94,14 +93,7 @@ private: auto asTie() const { - return std::tie( - seq, - txs, - closeTimeResolution, - closeTime, - closeTimeAgree, - parentID, - parentCloseTime); + return std::tie(seq, txs, closeTimeResolution, closeTime, closeTimeAgree, parentID, parentCloseTime); } friend bool @@ -267,11 +259,7 @@ public: accept(Ledger const& curr, Tx tx) { using namespace std::chrono_literals; - return accept( - curr, - TxSetType{tx}, - curr.closeTimeResolution(), - curr.closeTime() + 1s); + return accept(curr, TxSetType{tx}, curr.closeTimeResolution(), curr.closeTime() + 1s); } /** Determine the number of distinct branches for the set of ledgers. @@ -334,13 +322,10 @@ struct LedgerHistoryHelper assert(seen.emplace(s.back()).second); Ledger const& parent = (*this)[s.substr(0, s.size() - 1)]; - return ledgers.emplace(s, oracle.accept(parent, Tx{++nextTx})) - .first->second; + return ledgers.emplace(s, oracle.accept(parent, Tx{++nextTx})).first->second; } }; } // namespace csf } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/csf/random.h b/src/test/csf/random.h index 8b3ac7e971..fc5098af32 100644 --- a/src/test/csf/random.h +++ b/src/test/csf/random.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_CSF_RANDOM_H_INCLUDED -#define XRPL_TEST_CSF_RANDOM_H_INCLUDED +#pragma once #include #include @@ -72,11 +71,7 @@ public: @param w Vector of weights of size list-first @param g the pseudo-random number generator */ - Selector( - RAIter first, - RAIter last, - std::vector const& w, - Generator& g) + Selector(RAIter first, RAIter last, std::vector const& w, Generator& g) : first_{first}, last_{last}, dd_{w.begin(), w.end()}, g_{g} { using tag = typename std::iterator_traits::iterator_category; @@ -157,5 +152,3 @@ public: } // namespace csf } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/csf/submitters.h b/src/test/csf/submitters.h index 0c5d46e075..2300b91388 100644 --- a/src/test/csf/submitters.h +++ b/src/test/csf/submitters.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_CSF_SUBMITTERS_H_INCLUDED -#define XRPL_TEST_CSF_SUBMITTERS_H_INCLUDED +#pragma once #include #include @@ -80,13 +79,7 @@ class Submitter } public: - Submitter( - Distribution dist, - SimTime start, - SimTime end, - Selector& selector, - Scheduler& s, - Generator& g) + Submitter(Distribution dist, SimTime start, SimTime end, Selector& selector, Scheduler& s, Generator& g) : dist_{dist}, stop_{end}, selector_{selector}, scheduler_{s}, g_{g} { scheduler_.at(start, [&]() { submit(); }); @@ -95,20 +88,11 @@ public: template Submitter -makeSubmitter( - Distribution dist, - SimTime start, - SimTime end, - Selector& sel, - Scheduler& s, - Generator& g) +makeSubmitter(Distribution dist, SimTime start, SimTime end, Selector& sel, Scheduler& s, Generator& g) { - return Submitter( - dist, start, end, sel, s, g); + return Submitter(dist, start, end, sel, s, g); } } // namespace csf } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/csf/timers.h b/src/test/csf/timers.h index b5902393c7..a071844a41 100644 --- a/src/test/csf/timers.h +++ b/src/test/csf/timers.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_CSF_TIMERS_H_INCLUDED -#define XRPL_TEST_CSF_TIMERS_H_INCLUDED +#pragma once #include #include @@ -26,10 +25,7 @@ class HeartbeatTimer SimTime startSimTime_; public: - HeartbeatTimer( - Scheduler& sched, - SimDuration interval = std::chrono::seconds{60}, - std::ostream& out = std::cerr) + HeartbeatTimer(Scheduler& sched, SimDuration interval = std::chrono::seconds{60}, std::ostream& out = std::cerr) : scheduler_{sched} , interval_{interval} , out_{out} @@ -53,10 +49,8 @@ public: RealDuration realDuration = realTime - startRealTime_; SimDuration simDuration = simTime - startSimTime_; - out_ << "Heartbeat. Time Elapsed: {sim: " - << duration_cast(simDuration).count() - << "s | real: " << duration_cast(realDuration).count() - << "s}\n" + out_ << "Heartbeat. Time Elapsed: {sim: " << duration_cast(simDuration).count() + << "s | real: " << duration_cast(realDuration).count() << "s}\n" << std::flush; scheduler_.in(interval_, [this]() { beat(scheduler_.now()); }); @@ -66,5 +60,3 @@ public: } // namespace csf } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/json/TestOutputSuite.h b/src/test/json/TestOutputSuite.h index 934fe1de81..88b7e22580 100644 --- a/src/test/json/TestOutputSuite.h +++ b/src/test/json/TestOutputSuite.h @@ -1,5 +1,4 @@ -#ifndef XRPL_RPC_TESTOUTPUTSUITE_H_INCLUDED -#define XRPL_RPC_TESTOUTPUTSUITE_H_INCLUDED +#pragma once #include @@ -35,5 +34,3 @@ protected: } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx.h b/src/test/jtx.h index 1d7f38ff54..903b029f29 100644 --- a/src/test/jtx.h +++ b/src/test/jtx.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_H_INCLUDED -#define XRPL_TEST_JTX_H_INCLUDED +#pragma once // Convenience header that includes everything @@ -60,5 +59,3 @@ #include #include - -#endif diff --git a/src/test/jtx/AMM.h b/src/test/jtx/AMM.h index 65c16ec627..4d8059d172 100644 --- a/src/test/jtx/AMM.h +++ b/src/test/jtx/AMM.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_AMM_H_INCLUDED -#define XRPL_TEST_JTX_AMM_H_INCLUDED +#pragma once #include #include @@ -142,11 +141,7 @@ public: ter const& ter, bool log = false, bool close = true); - AMM(Env& env, - Account const& account, - STAmount const& asset1, - STAmount const& asset2, - CreateArg const& arg); + AMM(Env& env, Account const& account, STAmount const& asset1, STAmount const& asset2, CreateArg const& arg); /** Send amm_info RPC command */ @@ -172,10 +167,7 @@ public: /** Get AMM balances for the token pair. */ std::tuple - balances( - Issue const& issue1, - Issue const& issue2, - std::optional const& account = std::nullopt) const; + balances(Issue const& issue1, Issue const& issue2, std::optional const& account = std::nullopt) const; std::tuple balances(std::optional const& account = std::nullopt) const @@ -192,10 +184,7 @@ public: * @param expectedPrice expected slot price */ [[nodiscard]] bool - expectAuctionSlot( - std::uint32_t fee, - std::optional timeSlot, - IOUAmount expectedPrice) const; + expectAuctionSlot(std::uint32_t fee, std::optional timeSlot, IOUAmount expectedPrice) const; [[nodiscard]] bool expectAuctionSlot(std::vector const& authAccount) const; @@ -263,11 +252,7 @@ public: std::optional const& ter = std::nullopt) { return withdraw( - account, - std::nullopt, - asset1OutDetails, - asset1OutDetails ? tfOneAssetWithdrawAll : tfWithdrawAll, - ter); + account, std::nullopt, asset1OutDetails, asset1OutDetails ? tfOneAssetWithdrawAll : tfWithdrawAll, ter); } IOUAmount @@ -327,8 +312,7 @@ public: } IOUAmount - getLPTokensBalance( - std::optional const& account = std::nullopt) const; + getLPTokensBalance(std::optional const& account = std::nullopt) const; friend std::ostream& operator<<(std::ostream& s, AMM const& amm) @@ -351,9 +335,7 @@ public: } void - ammDelete( - AccountID const& deleter, - std::optional const& ter = std::nullopt); + ammDelete(AccountID const& deleter, std::optional const& ter = std::nullopt); void setClose(bool close) @@ -368,9 +350,7 @@ public: } void - setTokens( - Json::Value& jv, - std::optional> const& assets = std::nullopt); + setTokens(Json::Value& jv, std::optional> const& assets = std::nullopt); private: AccountID @@ -403,17 +383,11 @@ private: } [[nodiscard]] bool - expectAmmInfo( - STAmount const& asset1, - STAmount const& asset2, - IOUAmount const& balance, - Json::Value const& jv) const; + expectAmmInfo(STAmount const& asset1, STAmount const& asset2, IOUAmount const& balance, Json::Value const& jv) + const; void - submit( - Json::Value const& jv, - std::optional const& seq, - std::optional const& ter); + submit(Json::Value const& jv, std::optional const& seq, std::optional const& ter); [[nodiscard]] bool expectAuctionSlot(auto&& cb) const; @@ -424,10 +398,7 @@ private: namespace amm { Json::Value -trust( - AccountID const& account, - STAmount const& amount, - std::uint32_t flags = 0); +trust(AccountID const& account, STAmount const& amount, std::uint32_t flags = 0); Json::Value pay(Account const& account, AccountID const& to, STAmount const& amount); @@ -443,5 +414,3 @@ ammClawback( } // namespace jtx } // namespace test } // namespace xrpl - -#endif // XRPL_TEST_JTX_AMM_H_INCLUDED diff --git a/src/test/jtx/AMMTest.h b/src/test/jtx/AMMTest.h index 208e3c4e5f..be6e228c0a 100644 --- a/src/test/jtx/AMMTest.h +++ b/src/test/jtx/AMMTest.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_AMMTEST_H_INCLUDED -#define XRPL_TEST_JTX_AMMTEST_H_INCLUDED +#pragma once #include #include @@ -24,8 +23,7 @@ struct TestAMMArg std::vector features = { // For now, just disable SAV entirely, which locks in the small Number // mantissas - jtx::testable_amendments() - featureSingleAssetVault - - featureLendingProtocol}; + jtx::testable_amendments() - featureSingleAssetVault - featureLendingProtocol}; bool noLog = false; }; @@ -76,8 +74,7 @@ public: { // For now, just disable SAV entirely, which locks in the small Number // mantissas - return jtx::testable_amendments() - featureSingleAssetVault - - featureLendingProtocol; + return jtx::testable_amendments() - featureSingleAssetVault - featureLendingProtocol; } protected: @@ -93,9 +90,7 @@ protected: std::vector const& features = {testable_amendments()}); void - testAMM( - std::function&& cb, - TestAMMArg const& arg); + testAMM(std::function&& cb, TestAMMArg const& arg); }; class AMMTest : public jtx::AMMTestBase @@ -163,5 +158,3 @@ protected: } // namespace jtx } // namespace test } // namespace xrpl - -#endif // XRPL_TEST_JTX_AMMTEST_H_INCLUDED diff --git a/src/test/jtx/AbstractClient.h b/src/test/jtx/AbstractClient.h index 0bdfbd67de..9b1ef178ca 100644 --- a/src/test/jtx/AbstractClient.h +++ b/src/test/jtx/AbstractClient.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_ABSTRACTCLIENT_H_INCLUDED -#define XRPL_TEST_ABSTRACTCLIENT_H_INCLUDED +#pragma once #include @@ -41,5 +40,3 @@ public: } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/Account.h b/src/test/jtx/Account.h index af8870f22a..6f796e08b3 100644 --- a/src/test/jtx/Account.h +++ b/src/test/jtx/Account.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_ACCOUNT_H_INCLUDED -#define XRPL_TEST_JTX_ACCOUNT_H_INCLUDED +#pragma once #include #include @@ -40,18 +39,14 @@ public: /** @{ */ Account(std::string name, KeyType type = KeyType::secp256k1); - Account(char const* name, KeyType type = KeyType::secp256k1) - : Account(std::string(name), type) + Account(char const* name, KeyType type = KeyType::secp256k1) : Account(std::string(name), type) { } // This constructor needs to be public so `std::pair` can use it when // emplacing into the cache. However, it is logically `private`. This is // enforced with the `privateTag` parameter. - Account( - std::string name, - std::pair const& keys, - Account::privateCtorTag); + Account(std::string name, std::pair const& keys, Account::privateCtorTag); /** @} */ @@ -116,9 +111,7 @@ public: operator[](std::string const& s) const; private: - static std:: - unordered_map, Account, beast::uhash<>> - cache_; + static std::unordered_map, Account, beast::uhash<>> cache_; // Return the account from the cache & add it to the cache if needed static Account @@ -153,5 +146,3 @@ operator<=>(Account const& lhs, Account const& rhs) noexcept } // namespace jtx } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/CaptureLogs.h b/src/test/jtx/CaptureLogs.h index 0ac855e402..f8d0449977 100644 --- a/src/test/jtx/CaptureLogs.h +++ b/src/test/jtx/CaptureLogs.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_CAPTURELOGS_H_INCLUDED -#define XRPL_TEST_JTX_CAPTURELOGS_H_INCLUDED +#pragma once #include @@ -27,27 +26,20 @@ class CaptureLogs : public Logs std::stringstream& strm_; public: - CaptureSink( - beast::severities::Severity threshold, - std::mutex& mutex, - std::stringstream& strm) - : beast::Journal::Sink(threshold, false) - , strmMutex_(mutex) - , strm_(strm) + CaptureSink(beast::severities::Severity threshold, std::mutex& mutex, std::stringstream& strm) + : beast::Journal::Sink(threshold, false), strmMutex_(mutex), strm_(strm) { } void - write(beast::severities::Severity level, std::string const& text) - override + write(beast::severities::Severity level, std::string const& text) override { std::lock_guard lock(strmMutex_); strm_ << text; } void - writeAlways(beast::severities::Severity level, std::string const& text) - override + writeAlways(beast::severities::Severity level, std::string const& text) override { std::lock_guard lock(strmMutex_); strm_ << text; @@ -55,8 +47,7 @@ class CaptureLogs : public Logs }; public: - explicit CaptureLogs(std::string* pResult) - : Logs(beast::severities::kInfo), pResult_(pResult) + explicit CaptureLogs(std::string* pResult) : Logs(beast::severities::kInfo), pResult_(pResult) { } @@ -66,9 +57,7 @@ public: } std::unique_ptr - makeSink( - std::string const& partition, - beast::severities::Severity threshold) override + makeSink(std::string const& partition, beast::severities::Severity threshold) override { return std::make_unique(threshold, strmMutex_, strm_); } @@ -76,5 +65,3 @@ public: } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/CheckMessageLogs.h b/src/test/jtx/CheckMessageLogs.h index b0e5f4c82e..286cfa1844 100644 --- a/src/test/jtx/CheckMessageLogs.h +++ b/src/test/jtx/CheckMessageLogs.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_CHECKMESSAGELOGS_H_INCLUDED -#define XRPL_TEST_JTX_CHECKMESSAGELOGS_H_INCLUDED +#pragma once #include @@ -18,24 +17,20 @@ class CheckMessageLogs : public Logs CheckMessageLogs& owner_; public: - CheckMessageSink( - beast::severities::Severity threshold, - CheckMessageLogs& owner) + CheckMessageSink(beast::severities::Severity threshold, CheckMessageLogs& owner) : beast::Journal::Sink(threshold, false), owner_(owner) { } void - write(beast::severities::Severity level, std::string const& text) - override + write(beast::severities::Severity level, std::string const& text) override { if (text.find(owner_.msg_) != std::string::npos) *owner_.pFound_ = true; } void - writeAlways(beast::severities::Severity level, std::string const& text) - override + writeAlways(beast::severities::Severity level, std::string const& text) override { write(level, text); } @@ -54,9 +49,7 @@ public: } std::unique_ptr - makeSink( - std::string const& partition, - beast::severities::Severity threshold) override + makeSink(std::string const& partition, beast::severities::Severity threshold) override { return std::make_unique(threshold, *this); } @@ -64,5 +57,3 @@ public: } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/Env.h b/src/test/jtx/Env.h index 26a664efbd..7d7dcd2cb8 100644 --- a/src/test/jtx/Env.h +++ b/src/test/jtx/Env.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_ENV_H_INCLUDED -#define XRPL_TEST_JTX_ENV_H_INCLUDED +#pragma once #include #include @@ -32,6 +31,7 @@ #include #include +#include #include #include #include @@ -43,6 +43,27 @@ namespace xrpl { namespace test { namespace jtx { +/** Wrapper that captures std::source_location when implicitly constructed. + This solves the problem of combining std::source_location with variadic + templates. The std::source_location default argument is evaluated at the + call site when the wrapper is constructed via implicit conversion. + + This is a template struct that holds the value directly, allowing implicit + conversion without template argument deduction issues via CTAD. +*/ +template +struct WithSourceLocation +{ + T value; + std::source_location loc; + + // Non-explicit constructor allows implicit conversion. + // The default argument for loc is evaluated at the call site. + WithSourceLocation(T v, std::source_location l = std::source_location::current()) : value(std::move(v)), loc(l) + { + } +}; + /** Designate accounts as no-ripple in Env::fund */ template std::array @@ -64,8 +85,7 @@ testable_amendments() if (auto const f = getRegisteredFeature(s)) feats.push_back(*f); else - Throw( - "Unknown feature: " + s + " in allAmendments."); + Throw("Unknown feature: " + s + " in allAmendments."); } return FeatureBitset(feats); }(); @@ -79,17 +99,14 @@ class SuiteLogs : public Logs beast::unit_test::suite& suite_; public: - explicit SuiteLogs(beast::unit_test::suite& suite) - : Logs(beast::severities::kError), suite_(suite) + explicit SuiteLogs(beast::unit_test::suite& suite) : Logs(beast::severities::kError), suite_(suite) { } ~SuiteLogs() override = default; std::unique_ptr - makeSink( - std::string const& partition, - beast::severities::Severity threshold) override + makeSink(std::string const& partition, beast::severities::Severity threshold) override { return std::make_unique(partition, threshold, suite_); } @@ -173,10 +190,7 @@ public: { memoize(Account::master); Pathfinder::initPathTable(); - foreachFeature( - features, [&appFeats = app().config().features](uint256 const& f) { - appFeats.insert(f); - }); + foreachFeature(features, [&appFeats = app().config().features](uint256 const& f) { appFeats.insert(f); }); } /** @@ -192,9 +206,7 @@ public: * @param args collection of features * */ - Env(beast::unit_test::suite& suite_, - FeatureBitset features, - std::unique_ptr logs = nullptr) + Env(beast::unit_test::suite& suite_, FeatureBitset features, std::unique_ptr logs = nullptr) : Env(suite_, envconfig(), features, std::move(logs)) { } @@ -215,11 +227,7 @@ public: std::unique_ptr config, std::unique_ptr logs = nullptr, beast::severities::Severity thresh = beast::severities::kError) - : Env(suite_, - std::move(config), - testable_amendments(), - std::move(logs), - thresh) + : Env(suite_, std::move(config), testable_amendments(), std::move(logs), thresh) { } @@ -232,8 +240,7 @@ public: * * @param suite_ the current unit_test::suite */ - Env(beast::unit_test::suite& suite_, - beast::severities::Severity thresh = beast::severities::kError) + Env(beast::unit_test::suite& suite_, beast::severities::Severity thresh = beast::severities::kError) : Env(suite_, envconfig(), nullptr, thresh) { } @@ -294,9 +301,7 @@ public: template Json::Value - rpc(std::unordered_map const& headers, - std::string const& cmd, - Args&&... args); + rpc(std::unordered_map const& headers, std::string const& cmd, Args&&... args); template Json::Value @@ -346,9 +351,7 @@ public: @return true if no error, false if error */ bool - close( - NetClock::time_point closeTime, - std::optional consensusDelay = std::nullopt); + close(NetClock::time_point closeTime, std::optional consensusDelay = std::nullopt); /** Close and advance the ledger. @@ -541,13 +544,16 @@ public: This calls postconditions. */ virtual void - submit(JTx const& jt); + submit(JTx const& jt, std::source_location const& loc = std::source_location::current()); /** Use the submit RPC command with a provided JTx object. This calls postconditions. */ void - sign_and_submit(JTx const& jt, Json::Value params = Json::nullValue); + sign_and_submit( + JTx const& jt, + Json::Value params = Json::nullValue, + std::source_location const& loc = std::source_location::current()); /** Check expected postconditions of JTx submission. @@ -556,23 +562,39 @@ public: postconditions( JTx const& jt, ParsedResult const& parsed, - Json::Value const& jr = Json::Value()); + Json::Value const& jr = Json::Value(), + std::source_location const& loc = std::source_location::current()); /** Apply funclets and submit. */ /** @{ */ - template + template Env& - apply(JsonValue&& jv, FN const&... fN) + apply(WithSourceLocation jv, FN const&... fN) { - submit(jt(std::forward(jv), fN...)); + submit(jt(std::move(jv.value), fN...), jv.loc); return *this; } - template + template Env& - operator()(JsonValue&& jv, FN const&... fN) + apply(WithSourceLocation jv, FN const&... fN) { - return apply(std::forward(jv), fN...); + submit(jt(std::move(jv.value), fN...), jv.loc); + return *this; + } + + template + Env& + operator()(WithSourceLocation jv, FN const&... fN) + { + return apply(std::move(jv), fN...); + } + + template + Env& + operator()(WithSourceLocation jv, FN const&... fN) + { + return apply(std::move(jv), fN...); } /** @} */ @@ -700,11 +722,7 @@ public: template void - trust( - STAmount const& amount, - Account const& to0, - Account const& to1, - Accounts const&... toN) + trust(STAmount const& amount, Account const& to0, Account const& to1, Accounts const&... toN) { trust(amount, to0); trust(amount, to1, toN...); @@ -777,48 +795,30 @@ Env::rpc( std::string const& cmd, Args&&... args) { - return do_rpc( - apiVersion, - std::vector{cmd, std::forward(args)...}, - headers); + return do_rpc(apiVersion, std::vector{cmd, std::forward(args)...}, headers); } template Json::Value Env::rpc(unsigned apiVersion, std::string const& cmd, Args&&... args) { - return rpc( - apiVersion, - std::unordered_map(), - cmd, - std::forward(args)...); + return rpc(apiVersion, std::unordered_map(), cmd, std::forward(args)...); } template Json::Value -Env::rpc( - std::unordered_map const& headers, - std::string const& cmd, - Args&&... args) +Env::rpc(std::unordered_map const& headers, std::string const& cmd, Args&&... args) { - return do_rpc( - RPC::apiCommandLineVersion, - std::vector{cmd, std::forward(args)...}, - headers); + return do_rpc(RPC::apiCommandLineVersion, std::vector{cmd, std::forward(args)...}, headers); } template Json::Value Env::rpc(std::string const& cmd, Args&&... args) { - return rpc( - std::unordered_map(), - cmd, - std::forward(args)...); + return rpc(std::unordered_map(), cmd, std::forward(args)...); } } // namespace jtx } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/Env_ss.h b/src/test/jtx/Env_ss.h index 734eca5819..9c178a1c13 100644 --- a/src/test/jtx/Env_ss.h +++ b/src/test/jtx/Env_ss.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_ENV_SS_H_INCLUDED -#define XRPL_TEST_JTX_ENV_SS_H_INCLUDED +#pragma once #include @@ -24,19 +23,20 @@ private: SignSubmitRunner& operator=(SignSubmitRunner&&) = delete; - SignSubmitRunner(Env& env, JTx&& jt) : env_(env), jt_(jt) + SignSubmitRunner(Env& env, JTx&& jt, std::source_location loc) : env_(env), jt_(jt), loc_(loc) { } void operator()(Json::Value const& params = Json::nullValue) { - env_.sign_and_submit(jt_, params); + env_.sign_and_submit(jt_, params, loc_); } private: Env& env_; JTx const jt_; + std::source_location const loc_; }; public: @@ -48,17 +48,23 @@ public: { } - template + template SignSubmitRunner - operator()(JsonValue&& jv, FN const&... fN) + operator()(WithSourceLocation jv, FN const&... fN) { - auto jtx = env_.jt(std::forward(jv), fN...); - return SignSubmitRunner(env_, std::move(jtx)); + auto jtx = env_.jt(std::move(jv.value), fN...); + return SignSubmitRunner(env_, std::move(jtx), jv.loc); + } + + template + SignSubmitRunner + operator()(WithSourceLocation jv, FN const&... fN) + { + auto jtx = env_.jt(std::move(jv.value), fN...); + return SignSubmitRunner(env_, std::move(jtx), jv.loc); } }; } // namespace jtx } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/Env_test.cpp b/src/test/jtx/Env_test.cpp index fbe51c2a8d..f0a46ba55c 100644 --- a/src/test/jtx/Env_test.cpp +++ b/src/test/jtx/Env_test.cpp @@ -1,6 +1,5 @@ #include -#include #include #include @@ -8,6 +7,7 @@ #include #include #include +#include #include @@ -61,18 +61,10 @@ public: PrettyAmount(0u); PrettyAmount(1u); PrettyAmount(-1); - static_assert( - !std::is_trivially_constructible::value, ""); - static_assert( - !std::is_trivially_constructible:: - value, - ""); - static_assert( - !std::is_trivially_constructible::value, ""); - static_assert( - !std::is_trivially_constructible:: - value, - ""); + static_assert(!std::is_trivially_constructible::value, ""); + static_assert(!std::is_trivially_constructible::value, ""); + static_assert(!std::is_trivially_constructible::value, ""); + static_assert(!std::is_trivially_constructible::value, ""); try { @@ -139,11 +131,7 @@ public: // unfunded { Env env(*this); - env(pay("alice", "bob", XRP(1000)), - seq(1), - fee(10), - sig("alice"), - ter(terNO_ACCOUNT)); + env(pay("alice", "bob", XRP(1000)), seq(1), fee(10), sig("alice"), ter(terNO_ACCOUNT)); } // fund @@ -187,8 +175,7 @@ public: env.trust(USD(1000), alice); env(pay(gw, alice, USD(10))); BEAST_EXPECT(to_string(env.balance("alice", USD)) == "10/USD(gw)"); - BEAST_EXPECT( - to_string(env.balance(gw, alice["USD"])) == "-10/USD(alice)"); + BEAST_EXPECT(to_string(env.balance(gw, alice["USD"])) == "-10/USD(alice)"); } // seq @@ -234,10 +221,8 @@ public: env(pay(gw, "alice", USD(10)), require(balance("alice", USD(10)))); env.require(nflags("alice", asfRequireDest)); - env(fset("alice", asfRequireDest), - require(flags("alice", asfRequireDest))); - env(fclear("alice", asfRequireDest), - require(nflags("alice", asfRequireDest))); + env(fset("alice", asfRequireDest), require(flags("alice", asfRequireDest))); + env(fclear("alice", asfRequireDest), require(nflags("alice", asfRequireDest))); } // Signing with secp256k1 and ed25519 keys @@ -256,9 +241,7 @@ public: env(noop(alice)); env(noop(bob)); env(noop(alice), sig("alice"), ter(tefBAD_AUTH)); - env(noop(alice), - sig(Account("alice", KeyType::secp256k1)), - ter(tefBAD_AUTH)); + env(noop(alice), sig(Account("alice", KeyType::secp256k1)), ter(tefBAD_AUTH)); env(noop(bob), sig(Account("bob", KeyType::ed25519)), ter(tefBAD_AUTH)); env(noop(alice), sig(carol), ter(tefBAD_AUTH)); @@ -273,9 +256,7 @@ public: env(noop(alice)); env(noop(alice), sig(bob)); env(noop(alice), sig(alice), ter(tefMASTER_DISABLED)); - env(fclear(alice, asfDisableMaster), - sig(alice), - ter(tefMASTER_DISABLED)); + env(fclear(alice, asfDisableMaster), sig(alice), ter(tefMASTER_DISABLED)); env(fclear(alice, asfDisableMaster), sig(bob)); env(noop(alice), sig(alice)); } @@ -314,10 +295,7 @@ public: env(offer("carol", XRP(50), USD(50)), require(owners("carol", 2))); env(pay("alice", "bob", any(USD(10))), ter(tecPATH_DRY)); - env(pay("alice", "bob", any(USD(10))), - paths(XRP), - sendmax(XRP(10)), - ter(tecPATH_PARTIAL)); + env(pay("alice", "bob", any(USD(10))), paths(XRP), sendmax(XRP(10)), ter(tecPATH_PARTIAL)); env(pay("alice", "bob", any(USD(10))), paths(XRP), sendmax(XRP(20))); env.require(balance("bob", USD(10))); env.require(balance("carol", USD(39.5))); @@ -329,9 +307,7 @@ public: env(noop("alice"), sig("eric")); env(noop("alice"), sig("bob"), ter(tefBAD_AUTH)); env(fset("alice", asfDisableMaster), ter(tecNEED_MASTER_KEY)); - env(fset("alice", asfDisableMaster), - sig("eric"), - ter(tecNEED_MASTER_KEY)); + env(fset("alice", asfDisableMaster), sig("eric"), ter(tecNEED_MASTER_KEY)); env.require(nflags("alice", asfDisableMaster)); env(fset("alice", asfDisableMaster), sig("alice")); env.require(flags("alice", asfDisableMaster)); @@ -341,9 +317,7 @@ public: env(noop("alice"), sig("eric")); env(noop("alice"), sig("bob"), ter(tefBAD_AUTH)); env(fclear("alice", asfDisableMaster), sig("bob"), ter(tefBAD_AUTH)); - env(fclear("alice", asfDisableMaster), - sig("alice"), - ter(tefMASTER_DISABLED)); + env(fclear("alice", asfDisableMaster), sig("alice"), ter(tefMASTER_DISABLED)); env(fclear("alice", asfDisableMaster)); env.require(nflags("alice", asfDisableMaster)); env(regkey("alice", disabled)); @@ -366,8 +340,7 @@ public: env.fund(XRP(10000), alice); auto const localTxCnt = env.app().getOPs().getLocalTxCount(); - auto const queueTxCount = - env.app().getTxQ().getMetrics(*env.current()).txCount; + auto const queueTxCount = env.app().getTxQ().getMetrics(*env.current()).txCount; auto const openTxCount = env.current()->txCount(); BEAST_EXPECT(localTxCnt == 2 && queueTxCount == 0 && openTxCount == 2); @@ -387,46 +360,35 @@ public: auto jr = applyTxn(noop(alice), fee(1)); BEAST_EXPECT(jr[jss::result][jss::engine_result] == "telINSUF_FEE_P"); - BEAST_EXPECT( - env.app().getTxQ().getMetrics(*env.current()).txCount == - queueTxCount); + BEAST_EXPECT(env.app().getTxQ().getMetrics(*env.current()).txCount == queueTxCount); BEAST_EXPECT(env.app().getOPs().getLocalTxCount() == localTxCnt); BEAST_EXPECT(env.current()->txCount() == openTxCount); jr = applyTxn(noop(alice), sig("bob")); BEAST_EXPECT(jr[jss::result][jss::engine_result] == "tefBAD_AUTH"); - BEAST_EXPECT( - env.app().getTxQ().getMetrics(*env.current()).txCount == - queueTxCount); + BEAST_EXPECT(env.app().getTxQ().getMetrics(*env.current()).txCount == queueTxCount); BEAST_EXPECT(env.app().getOPs().getLocalTxCount() == localTxCnt); BEAST_EXPECT(env.current()->txCount() == openTxCount); jr = applyTxn(noop(alice), seq(20)); BEAST_EXPECT(jr[jss::result][jss::engine_result] == "terPRE_SEQ"); - BEAST_EXPECT( - env.app().getTxQ().getMetrics(*env.current()).txCount == - queueTxCount); + BEAST_EXPECT(env.app().getTxQ().getMetrics(*env.current()).txCount == queueTxCount); BEAST_EXPECT(env.app().getOPs().getLocalTxCount() == localTxCnt); BEAST_EXPECT(env.current()->txCount() == openTxCount); jr = applyTxn(offer(alice, XRP(1000), USD(1000))); - BEAST_EXPECT( - jr[jss::result][jss::engine_result] == "tecUNFUNDED_OFFER"); - BEAST_EXPECT( - env.app().getTxQ().getMetrics(*env.current()).txCount == - queueTxCount); + BEAST_EXPECT(jr[jss::result][jss::engine_result] == "tecUNFUNDED_OFFER"); + BEAST_EXPECT(env.app().getTxQ().getMetrics(*env.current()).txCount == queueTxCount); BEAST_EXPECT(env.app().getOPs().getLocalTxCount() == localTxCnt); BEAST_EXPECT(env.current()->txCount() == openTxCount); jr = applyTxn(noop(alice), fee(drops(-10))); BEAST_EXPECT(jr[jss::result][jss::engine_result] == "temBAD_FEE"); - BEAST_EXPECT( - env.app().getTxQ().getMetrics(*env.current()).txCount == - queueTxCount); + BEAST_EXPECT(env.app().getTxQ().getMetrics(*env.current()).txCount == queueTxCount); BEAST_EXPECT(env.app().getOPs().getLocalTxCount() == localTxCnt); BEAST_EXPECT(env.current()->txCount() == openTxCount); @@ -445,8 +407,7 @@ public: Env env(*this); env.fund(XRP(10000), "alice"); - env(signers("alice", 1, {{"alice", 1}, {"bob", 2}}), - ter(temBAD_SIGNER)); + env(signers("alice", 1, {{"alice", 1}, {"bob", 2}}), ter(temBAD_SIGNER)); env(signers("alice", 1, {{"bob", 1}, {"carol", 2}})); env(noop("alice")); @@ -454,10 +415,7 @@ public: env(noop("alice"), msig("bob"), fee(2 * baseFee)); env(noop("alice"), msig("carol"), fee(2 * baseFee)); env(noop("alice"), msig("bob", "carol"), fee(3 * baseFee)); - env(noop("alice"), - msig("bob", "carol", "dilbert"), - fee(4 * baseFee), - ter(tefBAD_SIGNATURE)); + env(noop("alice"), msig("bob", "carol", "dilbert"), fee(4 * baseFee), ter(tefBAD_SIGNATURE)); env(signers("alice", none)); } @@ -472,10 +430,8 @@ public: { Env env(*this); env.fund(XRP(10000), "alice"); - env(noop("alice"), - require(owners("alice", 0), tickets("alice", 0))); - env(ticket::create("alice", 1), - require(owners("alice", 1), tickets("alice", 1))); + env(noop("alice"), require(owners("alice", 0), tickets("alice", 0))); + env(ticket::create("alice", 1), require(owners("alice", 1), tickets("alice", 1))); } } @@ -531,10 +487,7 @@ public: auto jt2 = env.jt(noop("alice"), prop(-1)); BEAST_EXPECT(jt2.get()); BEAST_EXPECT(*jt2.get() == 65535); - auto jt3 = env.jt( - noop("alice"), - prop("Hello, world!"), - prop(false)); + auto jt3 = env.jt(noop("alice"), prop("Hello, world!"), prop(false)); BEAST_EXPECT(jt3.get()); BEAST_EXPECT(*jt3.get() == "Hello, world!"); BEAST_EXPECT(jt3.get()); @@ -600,9 +553,7 @@ public: env(noop("alice"), memo_format("format")); env(noop("alice"), memo_type("type")); env(noop("alice"), memo("data", "format", "type")); - env(noop("alice"), - memo("data1", "format1", "type1"), - memo("data2", "format2", "type2")); + env(noop("alice"), memo("data1", "format1", "type1"), memo("data2", "format2", "type2")); } void @@ -614,12 +565,9 @@ public: memo("data", "format", "type")(env, jt); auto const& memo = jt.jv["Memos"][0u]["Memo"]; - BEAST_EXPECT( - memo["MemoData"].asString() == strHex(std::string("data"))); - BEAST_EXPECT( - memo["MemoFormat"].asString() == strHex(std::string("format"))); - BEAST_EXPECT( - memo["MemoType"].asString() == strHex(std::string("type"))); + BEAST_EXPECT(memo["MemoData"].asString() == strHex(std::string("data"))); + BEAST_EXPECT(memo["MemoFormat"].asString() == strHex(std::string("format"))); + BEAST_EXPECT(memo["MemoType"].asString() == strHex(std::string("type"))); } void @@ -684,8 +632,7 @@ public: std::uint32_t const aliceSeq = env.seq("alice"); // Sign jsonNoop. - Json::Value jsonNoop = - env.json(noop("alice"), fee(baseFee), seq(aliceSeq), sig("alice")); + Json::Value jsonNoop = env.json(noop("alice"), fee(baseFee), seq(aliceSeq), sig("alice")); // Re-sign jsonNoop. JTx jt = env.jt(jsonNoop); env(jt); @@ -734,15 +681,9 @@ public: params[jss::fee_mult_max] = 1; params[jss::fee_div_max] = 2; - auto const expectedErrorString = "Fee of " + - std::to_string(baseFee.drops()) + - " exceeds the requested tx limit of " + - std::to_string(baseFee.drops() / 2); - envs( - noop(alice), - fee(none), - seq(none), - rpc(rpcHIGH_FEE, expectedErrorString))(params); + auto const expectedErrorString = "Fee of " + std::to_string(baseFee.drops()) + + " exceeds the requested tx limit of " + std::to_string(baseFee.drops() / 2); + envs(noop(alice), fee(none), seq(none), rpc(rpcHIGH_FEE, expectedErrorString))(params); auto tx = env.tx(); BEAST_EXPECT(!tx); @@ -771,51 +712,40 @@ public: if (!neverSupportedFeat) { - log << "No unsupported features found - skipping test." - << std::endl; + log << "No unsupported features found - skipping test." << std::endl; pass(); return; } auto hasFeature = [](Env& env, uint256 const& f) { - return ( - env.app().config().features.find(f) != - env.app().config().features.end()); + return (env.app().config().features.find(f) != env.app().config().features.end()); }; { // default Env has all supported features Env env{*this}; - BEAST_EXPECT( - supported.count() == env.app().config().features.size()); - foreachFeature(supported, [&](uint256 const& f) { - this->BEAST_EXPECT(hasFeature(env, f)); - }); + BEAST_EXPECT(supported.count() == env.app().config().features.size()); + foreachFeature(supported, [&](uint256 const& f) { this->BEAST_EXPECT(hasFeature(env, f)); }); } { // a Env FeatureBitset has *only* those features - Env env{ - *this, FeatureBitset{featureDynamicMPT | featureTokenEscrow}}; + Env env{*this, FeatureBitset{featureDynamicMPT | featureTokenEscrow}}; BEAST_EXPECT(env.app().config().features.size() == 2); foreachFeature(supported, [&](uint256 const& f) { - bool const has = - (f == featureDynamicMPT || f == featureTokenEscrow); + bool const has = (f == featureDynamicMPT || f == featureTokenEscrow); this->BEAST_EXPECT(has == hasFeature(env, f)); }); } - auto const missingSomeFeatures = - testable_amendments() - featureDynamicMPT - featureTokenEscrow; + auto const missingSomeFeatures = testable_amendments() - featureDynamicMPT - featureTokenEscrow; BEAST_EXPECT(missingSomeFeatures.count() == (supported.count() - 2)); { // a Env supported_features_except is missing *only* those features Env env{*this, missingSomeFeatures}; - BEAST_EXPECT( - env.app().config().features.size() == (supported.count() - 2)); + BEAST_EXPECT(env.app().config().features.size() == (supported.count() - 2)); foreachFeature(supported, [&](uint256 const& f) { - bool hasnot = - (f == featureDynamicMPT || f == featureTokenEscrow); + bool hasnot = (f == featureDynamicMPT || f == featureTokenEscrow); this->BEAST_EXPECT(hasnot != hasFeature(env, f)); }); } @@ -825,12 +755,7 @@ public: // along with a list of explicit amendments // the unsupported feature should be enabled along with // the two supported ones - Env env{ - *this, - FeatureBitset{ - featureDynamicMPT, - featureTokenEscrow, - *neverSupportedFeat}}; + Env env{*this, FeatureBitset{featureDynamicMPT, featureTokenEscrow, *neverSupportedFeat}}; // this app will have just 2 supported amendments and // one additional never supported feature flag @@ -847,19 +772,14 @@ public: // add a feature that is NOT in the supported amendments list // and omit a few standard amendments // the unsupported features should be enabled - Env env{ - *this, - missingSomeFeatures | FeatureBitset{*neverSupportedFeat}}; + Env env{*this, missingSomeFeatures | FeatureBitset{*neverSupportedFeat}}; // this app will have all supported amendments minus 2 and then the // one additional never supported feature flag - BEAST_EXPECT( - env.app().config().features.size() == - (supported.count() - 2 + 1)); + BEAST_EXPECT(env.app().config().features.size() == (supported.count() - 2 + 1)); BEAST_EXPECT(hasFeature(env, *neverSupportedFeat)); foreachFeature(supported, [&](uint256 const& f) { - bool hasnot = - (f == featureDynamicMPT || f == featureTokenEscrow); + bool hasnot = (f == featureDynamicMPT || f == featureTokenEscrow); this->BEAST_EXPECT(hasnot != hasFeature(env, f)); }); } @@ -872,12 +792,9 @@ public: // this app will have all supported amendments and then the // one additional never supported feature flag - BEAST_EXPECT( - env.app().config().features.size() == (supported.count() + 1)); + BEAST_EXPECT(env.app().config().features.size() == (supported.count() + 1)); BEAST_EXPECT(hasFeature(env, *neverSupportedFeat)); - foreachFeature(supported, [&](uint256 const& f) { - this->BEAST_EXPECT(hasFeature(env, f)); - }); + foreachFeature(supported, [&](uint256 const& f) { this->BEAST_EXPECT(hasFeature(env, f)); }); } } diff --git a/src/test/jtx/JSONRPCClient.h b/src/test/jtx/JSONRPCClient.h index 0513b43a93..41129a36ec 100644 --- a/src/test/jtx/JSONRPCClient.h +++ b/src/test/jtx/JSONRPCClient.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_HTTPCLIENT_H_INCLUDED -#define XRPL_TEST_HTTPCLIENT_H_INCLUDED +#pragma once #include @@ -16,5 +15,3 @@ makeJSONRPCClient(Config const& cfg, unsigned rpc_version = 2); } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/JTx.h b/src/test/jtx/JTx.h index aa87ce333d..90fbb8a6b6 100644 --- a/src/test/jtx/JTx.h +++ b/src/test/jtx/JTx.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_JTX_H_INCLUDED -#define XRPL_TEST_JTX_JTX_H_INCLUDED +#pragma once #include #include @@ -28,8 +27,7 @@ struct JTx requires_t require; std::optional ter = TER{tesSUCCESS}; std::optional> rpcCode = std::nullopt; - std::optional>> - rpcException = std::nullopt; + std::optional>> rpcException = std::nullopt; bool fill_fee = true; bool fill_seq = true; bool fill_sig = true; @@ -160,5 +158,3 @@ private: } // namespace jtx } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/ManualTimeKeeper.h b/src/test/jtx/ManualTimeKeeper.h index df3c7ff89a..d5fdd467e1 100644 --- a/src/test/jtx/ManualTimeKeeper.h +++ b/src/test/jtx/ManualTimeKeeper.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_MANUALTIMEKEEPER_H_INCLUDED -#define XRPL_TEST_MANUALTIMEKEEPER_H_INCLUDED +#pragma once #include @@ -31,5 +30,3 @@ public: } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/Oracle.h b/src/test/jtx/Oracle.h index 17d72384f6..da241c0ce8 100644 --- a/src/test/jtx/Oracle.h +++ b/src/test/jtx/Oracle.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_ORACLE_H_INCLUDED -#define XRPL_TEST_JTX_ORACLE_H_INCLUDED +#pragma once #include @@ -11,8 +10,7 @@ namespace jtx { namespace oracle { using AnyValue = std::variant; -using OraclesData = - std::vector, std::optional>>; +using OraclesData = std::vector, std::optional>>; // Special string value, which is converted to unquoted string in the string // passed to rpc. @@ -33,11 +31,8 @@ void toJsonHex(Json::Value& jv, AnyValue const& v); // base asset, quote asset, price, scale -using DataSeries = std::vector, - std::optional>>; +using DataSeries = + std::vector, std::optional>>; // Typical defaults for Create struct CreateArg @@ -90,8 +85,7 @@ struct RemoveArg // The value doesn't matter much, it has to be greater // than maxLastUpdateTimeDelta in order to pass LastUpdateTime // validation {close-maxLastUpdateTimeDelta,close+maxLastUpdateTimeDelta}. -constexpr static std::chrono::seconds testStartTime = - epoch_offset + std::chrono::seconds(10'000); +constexpr static std::chrono::seconds testStartTime = epoch_offset + std::chrono::seconds(10'000); /** Oracle class facilitates unit-testing of the Price Oracle feature. * It defines functions to create, update, and delete the Oracle object, @@ -186,5 +180,3 @@ public: } // namespace jtx } // namespace test } // namespace xrpl - -#endif // XRPL_TEST_JTX_ORACLE_H_INCLUDED diff --git a/src/test/jtx/PathSet.h b/src/test/jtx/PathSet.h index 0c54b6fb77..3f30d7193f 100644 --- a/src/test/jtx/PathSet.h +++ b/src/test/jtx/PathSet.h @@ -1,5 +1,4 @@ -#ifndef XRPL_LEDGER_TESTS_PATHSET_H_INCLUDED -#define XRPL_LEDGER_TESTS_PATHSET_H_INCLUDED +#pragma once #include @@ -12,49 +11,33 @@ namespace test { /** Count offer */ inline std::size_t -countOffers( - jtx::Env& env, - jtx::Account const& account, - Issue const& takerPays, - Issue const& takerGets) +countOffers(jtx::Env& env, jtx::Account const& account, Issue const& takerPays, Issue const& takerGets) { size_t count = 0; - forEachItem( - *env.current(), account, [&](std::shared_ptr const& sle) { - if (sle->getType() == ltOFFER && - sle->getFieldAmount(sfTakerPays).issue() == takerPays && - sle->getFieldAmount(sfTakerGets).issue() == takerGets) - ++count; - }); + forEachItem(*env.current(), account, [&](std::shared_ptr const& sle) { + if (sle->getType() == ltOFFER && sle->getFieldAmount(sfTakerPays).issue() == takerPays && + sle->getFieldAmount(sfTakerGets).issue() == takerGets) + ++count; + }); return count; } inline std::size_t -countOffers( - jtx::Env& env, - jtx::Account const& account, - STAmount const& takerPays, - STAmount const& takerGets) +countOffers(jtx::Env& env, jtx::Account const& account, STAmount const& takerPays, STAmount const& takerGets) { size_t count = 0; - forEachItem( - *env.current(), account, [&](std::shared_ptr const& sle) { - if (sle->getType() == ltOFFER && - sle->getFieldAmount(sfTakerPays) == takerPays && - sle->getFieldAmount(sfTakerGets) == takerGets) - ++count; - }); + forEachItem(*env.current(), account, [&](std::shared_ptr const& sle) { + if (sle->getType() == ltOFFER && sle->getFieldAmount(sfTakerPays) == takerPays && + sle->getFieldAmount(sfTakerGets) == takerGets) + ++count; + }); return count; } /** An offer exists */ inline bool -isOffer( - jtx::Env& env, - jtx::Account const& account, - STAmount const& takerPays, - STAmount const& takerGets) +isOffer(jtx::Env& env, jtx::Account const& account, STAmount const& takerPays, STAmount const& takerGets) { return countOffers(env, account, takerPays, takerGets) > 0; } @@ -62,11 +45,7 @@ isOffer( /** An offer exists */ inline bool -isOffer( - jtx::Env& env, - jtx::Account const& account, - Issue const& takerPays, - Issue const& takerGets) +isOffer(jtx::Env& env, jtx::Account const& account, Issue const& takerPays, Issue const& takerGets) { return countOffers(env, account, takerPays, takerGets) > 0; } @@ -114,11 +93,7 @@ Path::push_back(STPathElement const& pe) inline Path& Path::push_back(Issue const& iss) { - path.emplace_back( - STPathElement::typeCurrency | STPathElement::typeIssuer, - beast::zero, - iss.currency, - iss.account); + path.emplace_back(STPathElement::typeCurrency | STPathElement::typeIssuer, beast::zero, iss.currency, iss.account); return *this; } @@ -183,5 +158,3 @@ private: } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/SignerUtils.h b/src/test/jtx/SignerUtils.h index 272909c887..37b1d85ec7 100644 --- a/src/test/jtx/SignerUtils.h +++ b/src/test/jtx/SignerUtils.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_SIGNERUTILS_H_INCLUDED -#define XRPL_TEST_JTX_SIGNERUTILS_H_INCLUDED +#pragma once #include @@ -18,8 +17,7 @@ struct Reg { } - Reg(Account const& acct_, Account const& regularSig) - : acct(acct_), sig(regularSig) + Reg(Account const& acct_, Account const& regularSig) : acct(acct_), sig(regularSig) { } @@ -27,8 +25,7 @@ struct Reg { } - Reg(char const* acct_, char const* regularSig) - : acct(acct_), sig(regularSig) + Reg(char const* acct_, char const* regularSig) : acct(acct_), sig(regularSig) { } @@ -43,14 +40,9 @@ struct Reg inline void sortSigners(std::vector& signers) { - std::sort( - signers.begin(), signers.end(), [](Reg const& lhs, Reg const& rhs) { - return lhs.acct < rhs.acct; - }); + std::sort(signers.begin(), signers.end(), [](Reg const& lhs, Reg const& rhs) { return lhs.acct < rhs.acct; }); } } // namespace jtx } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/TestHelpers.h b/src/test/jtx/TestHelpers.h index 3096a902b1..c0e54900f6 100644 --- a/src/test/jtx/TestHelpers.h +++ b/src/test/jtx/TestHelpers.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_TESTHELPERS_H_INCLUDED -#define XRPL_TEST_JTX_TESTHELPERS_H_INCLUDED +#pragma once #include @@ -15,15 +14,8 @@ #include #include -#include - -#if (defined(__clang_major__) && __clang_major__ < 15) -#include -using source_location = std::experimental::source_location; -#else #include -using std::source_location; -#endif +#include namespace xrpl { namespace test { @@ -34,10 +26,7 @@ namespace jtx { Not every helper will be able to use this because of conversions and other issues, but for classes where it's straightforward, this can simplify things. */ -template < - class SField, - class StoredValue = typename SField::type::value_type, - class OutputValue = StoredValue> +template struct JTxField { using SF = SField; @@ -49,8 +38,7 @@ protected: SV value_; public: - explicit JTxField(SF const& sfield, SV const& value) - : sfield_(sfield), value_(value) + explicit JTxField(SF const& sfield, SV const& value) : sfield_(sfield), value_(value) { } @@ -78,8 +66,7 @@ protected: SV value_; public: - explicit JTxField(SF const& sfield, SV const& value) - : sfield_(sfield), value_(value) + explicit JTxField(SF const& sfield, SV const& value) : sfield_(sfield), value_(value) { } @@ -90,8 +77,7 @@ public: } }; -struct timePointField - : public JTxField +struct timePointField : public JTxField { using SF = SF_UINT32; using SV = NetClock::time_point; @@ -102,8 +88,7 @@ protected: using base::value_; public: - explicit timePointField(SF const& sfield, SV const& value) - : JTxField(sfield, value) + explicit timePointField(SF const& sfield, SV const& value) : JTxField(sfield, value) { } @@ -125,8 +110,7 @@ protected: using base::value_; public: - explicit uint256Field(SF const& sfield, SV const& value) - : JTxField(sfield, value) + explicit uint256Field(SF const& sfield, SV const& value) : JTxField(sfield, value) { } @@ -148,8 +132,7 @@ protected: using base::value_; public: - explicit accountIDField(SF const& sfield, SV const& value) - : JTxField(sfield, value) + explicit accountIDField(SF const& sfield, SV const& value) : JTxField(sfield, value) { } @@ -171,8 +154,7 @@ protected: using base::value_; public: - explicit stAmountField(SF const& sfield, SV const& value) - : JTxField(sfield, value) + explicit stAmountField(SF const& sfield, SV const& value) : JTxField(sfield, value) { } @@ -191,21 +173,18 @@ struct blobField : public JTxField using JTxField::JTxField; - explicit blobField(SF const& sfield, Slice const& cond) - : JTxField(sfield, strHex(cond)) + explicit blobField(SF const& sfield, Slice const& cond) : JTxField(sfield, strHex(cond)) { } template - explicit blobField(SF const& sfield, std::array const& c) - : blobField(sfield, makeSlice(c)) + explicit blobField(SF const& sfield, std::array const& c) : blobField(sfield, makeSlice(c)) { } }; template -struct valueUnitField - : public JTxField, ValueType> +struct valueUnitField : public JTxField, ValueType> { using SF = SField; using SV = unit::ValueUnit; @@ -284,12 +263,8 @@ public: } }; -template < - class SField, - class UnitTag, - class ValueType = typename SField::type::value_type> -using valueUnitWrapper = - JTxFieldWrapper>; +template +using valueUnitWrapper = JTxFieldWrapper>; template using simpleField = JTxFieldWrapper>; @@ -378,10 +353,7 @@ checkVL(Slice const& result, std::string const& expected) [[nodiscard]] inline bool -checkVL( - std::shared_ptr const& sle, - SField const& field, - std::string const& expected) +checkVL(std::shared_ptr const& sle, SField const& field, std::string const& expected) { return strHex(expected) == strHex(sle->getFieldVL(field)); } @@ -461,52 +433,32 @@ PrettyAmount xrpMinusFee(Env const& env, std::int64_t xrpAmount); bool -expectHolding( - Env& env, - AccountID const& account, - STAmount const& value, - bool defaultLimits = false); +expectHolding(Env& env, AccountID const& account, STAmount const& value, bool defaultLimits = false); template bool -expectHolding( - Env& env, - AccountID const& account, - STAmount const& value, - Amts const&... amts) +expectHolding(Env& env, AccountID const& account, STAmount const& value, Amts const&... amts) { - return expectHolding(env, account, value, false) && - expectHolding(env, account, amts...); + return expectHolding(env, account, value, false) && expectHolding(env, account, amts...); } bool expectHolding(Env& env, AccountID const& account, None const& value); bool -expectOffers( - Env& env, - AccountID const& account, - std::uint16_t size, - std::vector const& toMatch = {}); +expectOffers(Env& env, AccountID const& account, std::uint16_t size, std::vector const& toMatch = {}); Json::Value ledgerEntryRoot(Env& env, Account const& acct); Json::Value -ledgerEntryState( - Env& env, - Account const& acct_a, - Account const& acct_b, - std::string const& currency); +ledgerEntryState(Env& env, Account const& acct_a, Account const& acct_b, std::string const& currency); Json::Value accountBalance(Env& env, Account const& acct); [[nodiscard]] bool -expectLedgerEntryRoot( - Env& env, - Account const& acct, - STAmount const& expectedValue); +expectLedgerEntryRoot(Env& env, Account const& acct, STAmount const& expectedValue); /* Payment Channel */ /******************************************************************************/ @@ -532,8 +484,7 @@ create( std::optional const& cancelAfter = std::nullopt, std::optional const& dstTag = std::nullopt) { - return create( - account.id(), to.id(), amount, settleDelay, pk, cancelAfter, dstTag); + return create(account.id(), to.id(), amount, settleDelay, pk, cancelAfter, dstTag); } Json::Value @@ -553,10 +504,7 @@ claim( std::optional const& pk = std::nullopt); uint256 -channel( - AccountID const& account, - AccountID const& dst, - std::uint32_t seqProxyValue); +channel(AccountID const& account, AccountID const& dst, std::uint32_t seqProxyValue); inline uint256 channel(Account const& account, Account const& dst, std::uint32_t seqProxyValue) @@ -576,12 +524,7 @@ channelExists(ReadView const& view, uint256 const& chan); /******************************************************************************/ void -n_offers( - Env& env, - std::size_t n, - Account const& account, - STAmount const& in, - STAmount const& out); +n_offers(Env& env, std::size_t n, Account const& account, STAmount const& in, STAmount const& out); /* Pay Strand */ /***************************************************************/ @@ -592,7 +535,7 @@ cpe(Currency const& c); // All path element STPathElement -allpe(AccountID const& a, Issue const& iss); +allPathElements(AccountID const& a, Issue const& iss); /***************************************************************/ /* Check */ @@ -616,10 +559,7 @@ create(A const& account, A const& dest, STAmount const& sendMax) // clang-format on inline Json::Value -create( - jtx::Account const& account, - jtx::Account const& dest, - STAmount const& sendMax) +create(jtx::Account const& account, jtx::Account const& dest, STAmount const& sendMax) { return create(account.id(), dest.id(), sendMax); } @@ -640,7 +580,7 @@ checkMetrics( std::size_t expectedPerLedger, std::uint64_t expectedMinFeeLevel = baseFeeLevel.fee(), std::uint64_t expectedMedFeeLevel = minEscalationFeeLevel.fee(), - source_location const location = source_location::current()) + std::source_location const location = std::source_location::current()) { int line = location.line(); char const* file = location.file_name(); @@ -649,74 +589,61 @@ checkMetrics( auto const metrics = env.app().getTxQ().getMetrics(*env.current()); using namespace std::string_literals; - metrics.referenceFeeLevel == baseFeeLevel - ? test.pass() - : test.fail( - "reference: "s + - std::to_string(metrics.referenceFeeLevel.value()) + "/" + - std::to_string(baseFeeLevel.value()), - file, - line); + metrics.referenceFeeLevel == baseFeeLevel ? test.pass() + : test.fail( + "reference: "s + std::to_string(metrics.referenceFeeLevel.value()) + + "/" + std::to_string(baseFeeLevel.value()), + file, + line); metrics.txCount == expectedCount ? test.pass() - : test.fail( - "txCount: "s + std::to_string(metrics.txCount) + "/" + - std::to_string(expectedCount), - file, - line); + : test.fail("txCount: "s + std::to_string(metrics.txCount) + "/" + std::to_string(expectedCount), file, line); - metrics.txQMaxSize == expectedMaxCount - ? test.pass() - : test.fail( - "txQMaxSize: "s + std::to_string(metrics.txQMaxSize.value_or(0)) + - "/" + std::to_string(expectedMaxCount.value_or(0)), - file, - line); + metrics.txQMaxSize == expectedMaxCount ? test.pass() + : test.fail( + "txQMaxSize: "s + std::to_string(metrics.txQMaxSize.value_or(0)) + + "/" + std::to_string(expectedMaxCount.value_or(0)), + file, + line); metrics.txInLedger == expectedInLedger ? test.pass() : test.fail( - "txInLedger: "s + std::to_string(metrics.txInLedger) + "/" + - std::to_string(expectedInLedger), + "txInLedger: "s + std::to_string(metrics.txInLedger) + "/" + std::to_string(expectedInLedger), file, line); metrics.txPerLedger == expectedPerLedger ? test.pass() : test.fail( - "txPerLedger: "s + std::to_string(metrics.txPerLedger) + "/" + - std::to_string(expectedPerLedger), + "txPerLedger: "s + std::to_string(metrics.txPerLedger) + "/" + std::to_string(expectedPerLedger), file, line); metrics.minProcessingFeeLevel == expectedMin ? test.pass() : test.fail( - "minProcessingFeeLevel: "s + - std::to_string(metrics.minProcessingFeeLevel.value()) + "/" + + "minProcessingFeeLevel: "s + std::to_string(metrics.minProcessingFeeLevel.value()) + "/" + std::to_string(expectedMin.value()), file, line); - metrics.medFeeLevel == expectedMed - ? test.pass() - : test.fail( - "medFeeLevel: "s + std::to_string(metrics.medFeeLevel.value()) + - "/" + std::to_string(expectedMed.value()), - file, - line); + metrics.medFeeLevel == expectedMed ? test.pass() + : test.fail( + "medFeeLevel: "s + std::to_string(metrics.medFeeLevel.value()) + "/" + + std::to_string(expectedMed.value()), + file, + line); auto const expectedCurFeeLevel = expectedInLedger > expectedPerLedger - ? expectedMed * expectedInLedger * expectedInLedger / - (expectedPerLedger * expectedPerLedger) + ? expectedMed * expectedInLedger * expectedInLedger / (expectedPerLedger * expectedPerLedger) : metrics.referenceFeeLevel; metrics.openLedgerFeeLevel == expectedCurFeeLevel ? test.pass() : test.fail( - "openLedgerFeeLevel: "s + - std::to_string(metrics.openLedgerFeeLevel.value()) + "/" + + "openLedgerFeeLevel: "s + std::to_string(metrics.openLedgerFeeLevel.value()) + "/" + std::to_string(expectedCurFeeLevel.value()), file, line); @@ -735,18 +662,10 @@ Json::Value del(AccountID const& account, uint256 const& brokerID, std::uint32_t flags = 0); Json::Value -coverDeposit( - AccountID const& account, - uint256 const& brokerID, - STAmount const& amount, - std::uint32_t flags = 0); +coverDeposit(AccountID const& account, uint256 const& brokerID, STAmount const& amount, std::uint32_t flags = 0); Json::Value -coverWithdraw( - AccountID const& account, - uint256 const& brokerID, - STAmount const& amount, - std::uint32_t flags = 0); +coverWithdraw(AccountID const& account, uint256 const& brokerID, STAmount const& amount, std::uint32_t flags = 0); // Must specify at least one of loanBrokerID or amount. Json::Value @@ -754,16 +673,13 @@ coverClawback(AccountID const& account, std::uint32_t flags = 0); auto const loanBrokerID = JTxFieldWrapper(sfLoanBrokerID); -auto const managementFeeRate = - valueUnitWrapper(sfManagementFeeRate); +auto const managementFeeRate = valueUnitWrapper(sfManagementFeeRate); auto const debtMaximum = simpleField(sfDebtMaximum); -auto const coverRateMinimum = - valueUnitWrapper(sfCoverRateMinimum); +auto const coverRateMinimum = valueUnitWrapper(sfCoverRateMinimum); -auto const coverRateLiquidation = - valueUnitWrapper(sfCoverRateLiquidation); +auto const coverRateLiquidation = valueUnitWrapper(sfCoverRateLiquidation); auto const destination = JTxFieldWrapper(sfDestination); @@ -774,10 +690,7 @@ auto const destination = JTxFieldWrapper(sfDestination); namespace loan { Json::Value -set(AccountID const& account, - uint256 const& loanBrokerID, - Number principalRequested, - std::uint32_t flags = 0); +set(AccountID const& account, uint256 const& loanBrokerID, Number principalRequested, std::uint32_t flags = 0); auto const counterparty = JTxFieldWrapper(sfCounterparty); @@ -791,20 +704,15 @@ auto const latePaymentFee = simpleField(sfLatePaymentFee); auto const closePaymentFee = simpleField(sfClosePaymentFee); -auto const overpaymentFee = - valueUnitWrapper(sfOverpaymentFee); +auto const overpaymentFee = valueUnitWrapper(sfOverpaymentFee); -auto const interestRate = - valueUnitWrapper(sfInterestRate); +auto const interestRate = valueUnitWrapper(sfInterestRate); -auto const lateInterestRate = - valueUnitWrapper(sfLateInterestRate); +auto const lateInterestRate = valueUnitWrapper(sfLateInterestRate); -auto const closeInterestRate = - valueUnitWrapper(sfCloseInterestRate); +auto const closeInterestRate = valueUnitWrapper(sfCloseInterestRate); -auto const overpaymentInterestRate = - valueUnitWrapper(sfOverpaymentInterestRate); +auto const overpaymentInterestRate = valueUnitWrapper(sfOverpaymentInterestRate); auto const paymentTotal = simpleField(sfPaymentTotal); @@ -819,15 +727,10 @@ Json::Value del(AccountID const& account, uint256 const& loanID, std::uint32_t flags = 0); Json::Value -pay(AccountID const& account, - uint256 const& loanID, - STAmount const& amount, - std::uint32_t flags = 0); +pay(AccountID const& account, uint256 const& loanID, STAmount const& amount, std::uint32_t flags = 0); } // namespace loan } // namespace jtx } // namespace test } // namespace xrpl - -#endif // XRPL_TEST_JTX_TESTHELPERS_H_INCLUDED diff --git a/src/test/jtx/TestSuite.h b/src/test/jtx/TestSuite.h index 69cbd2a210..1558f68d39 100644 --- a/src/test/jtx/TestSuite.h +++ b/src/test/jtx/TestSuite.h @@ -1,5 +1,4 @@ -#ifndef XRPL_BASICS_TESTSUITE_H_INCLUDED -#define XRPL_BASICS_TESTSUITE_H_INCLUDED +#pragma once #include @@ -48,14 +47,10 @@ public: template bool - expectCollectionEquals( - Collection const& actual, - Collection const& expected, - std::string const& message = "") + expectCollectionEquals(Collection const& actual, Collection const& expected, std::string const& message = "") { auto msg = addPrefix(message); - bool success = expectEquals( - actual.size(), expected.size(), msg + "Sizes are different"); + bool success = expectEquals(actual.size(), expected.size(), msg + "Sizes are different"); using std::begin; using std::end; @@ -65,11 +60,7 @@ public: for (; i != end(actual) && j != end(expected); ++i, ++j, ++k) { - if (!expectEquals( - *i, - *j, - msg + "Elements at " + std::to_string(k) + - " are different.")) + if (!expectEquals(*i, *j, msg + "Elements at " + std::to_string(k) + " are different.")) return false; } @@ -120,5 +111,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/src/test/jtx/TrustedPublisherServer.h b/src/test/jtx/TrustedPublisherServer.h index e7ddef7ac9..a46e98ad50 100644 --- a/src/test/jtx/TrustedPublisherServer.h +++ b/src/test/jtx/TrustedPublisherServer.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_TRUSTED_PUBLISHER_SERVER_H_INCLUDED -#define XRPL_TEST_TRUSTED_PUBLISHER_SERVER_H_INCLUDED +#pragma once #include @@ -26,17 +25,14 @@ namespace xrpl { namespace test { -class TrustedPublisherServer - : public std::enable_shared_from_this +class TrustedPublisherServer : public std::enable_shared_from_this { using endpoint_type = boost::asio::ip::tcp::endpoint; using address_type = boost::asio::ip::address; using socket_type = boost::asio::ip::tcp::socket; - using req_type = - boost::beast::http::request; - using resp_type = - boost::beast::http::response; + using req_type = boost::beast::http::request; + using resp_type = boost::beast::http::response; using error_code = boost::system::error_code; socket_type sock_; @@ -62,21 +58,16 @@ class TrustedPublisherServer load_server_certificate() { sslCtx_.set_password_callback( - [](std::size_t, boost::asio::ssl::context_base::password_purpose) { - return "test"; - }); + [](std::size_t, boost::asio::ssl::context_base::password_purpose) { return "test"; }); sslCtx_.set_options( - boost::asio::ssl::context::default_workarounds | - boost::asio::ssl::context::no_sslv2 | + boost::asio::ssl::context::default_workarounds | boost::asio::ssl::context::no_sslv2 | boost::asio::ssl::context::single_dh_use); - sslCtx_.use_certificate_chain( - boost::asio::buffer(cert().data(), cert().size())); + sslCtx_.use_certificate_chain(boost::asio::buffer(cert().data(), cert().size())); sslCtx_.use_private_key( - boost::asio::buffer(key().data(), key().size()), - boost::asio::ssl::context::file_format::pem); + boost::asio::buffer(key().data(), key().size()), boost::asio::ssl::context::file_format::pem); sslCtx_.use_tmp_dh(boost::asio::buffer(dh().data(), dh().size())); } @@ -102,12 +93,7 @@ public: }; static std::string - makeManifestString( - PublicKey const& pk, - SecretKey const& sk, - PublicKey const& spk, - SecretKey const& ssk, - int seq) + makeManifestString(PublicKey const& pk, SecretKey const& sk, PublicKey const& spk, SecretKey const& ssk, int seq) { STObject st(sfGeneric); st[sfSequence] = seq; @@ -115,18 +101,12 @@ public: st[sfSigningPubKey] = spk; sign(st, HashPrefix::manifest, *publicKeyType(spk), ssk); - sign( - st, - HashPrefix::manifest, - *publicKeyType(pk), - sk, - sfMasterSignature); + sign(st, HashPrefix::manifest, *publicKeyType(pk), sk, sfMasterSignature); Serializer s; st.add(s); - return base64_encode( - std::string(static_cast(s.data()), s.size())); + return base64_encode(std::string(static_cast(s.data()), s.size())); } static Validator @@ -138,12 +118,7 @@ public: return { masterPublic, signingKeys.first, - makeManifestString( - masterPublic, - secret, - signingKeys.first, - signingKeys.second, - 1)}; + makeManifestString(masterPublic, secret, signingKeys.first, signingKeys.second, 1)}; } // TrustedPublisherServer must be accessed through a shared_ptr. @@ -156,9 +131,7 @@ public: boost::asio::io_context& ioc, std::vector const& validators, NetClock::time_point validUntil, - std::vector< - std::pair> const& - futures, + std::vector> const& futures, bool useSSL = false, int version = 1, bool immediateStart = true, @@ -173,22 +146,18 @@ public: , publisherPublic_{derivePublicKey(KeyType::ed25519, publisherSecret_)} { auto const keys = randomKeyPair(KeyType::secp256k1); - auto const manifest = makeManifestString( - publisherPublic_, publisherSecret_, keys.first, keys.second, 1); + auto const manifest = makeManifestString(publisherPublic_, publisherSecret_, keys.first, keys.second, 1); std::vector blobInfo; blobInfo.reserve(futures.size() + 1); auto const [data, blob] = [&]() -> std::pair { // Builds the validator list, then encodes it into a blob. std::string data = "{\"sequence\":" + std::to_string(sequence) + - ",\"expiration\":" + - std::to_string(validUntil.time_since_epoch().count()) + - ",\"validators\":["; + ",\"expiration\":" + std::to_string(validUntil.time_since_epoch().count()) + ",\"validators\":["; for (auto const& val : validators) { - data += "{\"validation_public_key\":\"" + - strHex(val.masterPublic) + "\",\"manifest\":\"" + + data += "{\"validation_public_key\":\"" + strHex(val.masterPublic) + "\",\"manifest\":\"" + val.manifest + "\"},"; } data.pop_back(); @@ -201,33 +170,27 @@ public: getList_ = [blob = blob, sig, manifest, version](int interval) { // Build the contents of a version 1 format UNL file std::stringstream l; - l << "{\"blob\":\"" << blob << "\"" << ",\"signature\":\"" << sig - << "\"" << ",\"manifest\":\"" << manifest << "\"" - << ",\"refresh_interval\": " << interval - << ",\"version\":" << version << '}'; + l << "{\"blob\":\"" << blob << "\"" << ",\"signature\":\"" << sig << "\"" << ",\"manifest\":\"" << manifest + << "\"" + << ",\"refresh_interval\": " << interval << ",\"version\":" << version << '}'; return l.str(); }; for (auto const& future : futures) { std::string data = "{\"sequence\":" + std::to_string(++sequence) + - ",\"effective\":" + - std::to_string(future.first.time_since_epoch().count()) + - ",\"expiration\":" + - std::to_string(future.second.time_since_epoch().count()) + - ",\"validators\":["; + ",\"effective\":" + std::to_string(future.first.time_since_epoch().count()) + + ",\"expiration\":" + std::to_string(future.second.time_since_epoch().count()) + ",\"validators\":["; // Use the same set of validators for simplicity for (auto const& val : validators) { - data += "{\"validation_public_key\":\"" + - strHex(val.masterPublic) + "\",\"manifest\":\"" + + data += "{\"validation_public_key\":\"" + strHex(val.masterPublic) + "\",\"manifest\":\"" + val.manifest + "\"},"; } data.pop_back(); data += "]}"; std::string blob = base64_encode(data); - auto const sig = - strHex(sign(keys.first, keys.second, makeSlice(data))); + auto const sig = strHex(sign(keys.first, keys.second, makeSlice(data))); blobInfo.emplace_back(blob, sig); } getList2_ = [blobInfo, manifest, version](int interval) { @@ -237,15 +200,13 @@ public: std::stringstream l; for (auto const& info : blobInfo) { - l << "{\"blob\":\"" << info.blob << "\"" << ",\"signature\":\"" - << info.signature << "\"},"; + l << "{\"blob\":\"" << info.blob << "\"" << ",\"signature\":\"" << info.signature << "\"},"; } std::string blobs = l.str(); blobs.pop_back(); l.str(std::string()); - l << "{\"blobs_v2\": [ " << blobs << "],\"manifest\":\"" << manifest - << "\"" << ",\"refresh_interval\": " << interval - << ",\"version\":" << (version + 1) << '}'; + l << "{\"blobs_v2\": [ " << blobs << "],\"manifest\":\"" << manifest << "\"" + << ",\"refresh_interval\": " << interval << ",\"version\":" << (version + 1) << '}'; return l.str(); }; @@ -261,19 +222,15 @@ public: { error_code ec; acceptor_.open(ep_.protocol()); - acceptor_.set_option( - boost::asio::ip::tcp::acceptor::reuse_address(true), ec); + acceptor_.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true), ec); acceptor_.bind(ep_); acceptor_.listen(boost::asio::socket_base::max_listen_connections); - acceptor_.async_accept( - sock_, - [wp = std::weak_ptr{shared_from_this()}]( - error_code ec) { - if (auto p = wp.lock()) - { - p->on_accept(ec); - } - }); + acceptor_.async_accept(sock_, [wp = std::weak_ptr{shared_from_this()}](error_code ec) { + if (auto p = wp.lock()) + { + p->on_accept(ec); + } + }); } void @@ -483,16 +440,8 @@ private: boost::asio::executor_work_guard work; bool ssl; - lambda( - int id_, - TrustedPublisherServer& self_, - socket_type&& sock_, - bool ssl_) - : id(id_) - , self(self_) - , sock(std::move(sock_)) - , work(sock_.get_executor()) - , ssl(ssl_) + lambda(int id_, TrustedPublisherServer& self_, socket_type&& sock_, bool ssl_) + : id(id_), self(self_), sock(std::move(sock_)), work(sock_.get_executor()), ssl(ssl_) { } @@ -511,15 +460,12 @@ private: static int id_ = 0; std::thread{lambda{++id_, *this, std::move(sock_), useSSL_}}.detach(); - acceptor_.async_accept( - sock_, - [wp = std::weak_ptr{shared_from_this()}]( - error_code ec) { - if (auto p = wp.lock()) - { - p->on_accept(ec); - } - }); + acceptor_.async_accept(sock_, [wp = std::weak_ptr{shared_from_this()}](error_code ec) { + if (auto p = wp.lock()) + { + p->on_accept(ec); + } + }); } void @@ -573,11 +519,9 @@ private: else { int refresh = 5; - constexpr char const* refreshPrefix = - "/validators2/refresh/"; + constexpr char const* refreshPrefix = "/validators2/refresh/"; if (boost::starts_with(path, refreshPrefix)) - refresh = boost::lexical_cast( - path.substr(strlen(refreshPrefix))); + refresh = boost::lexical_cast(path.substr(strlen(refreshPrefix))); res.body() = getList2_(refresh); } } @@ -592,11 +536,9 @@ private: else { int refresh = 5; - constexpr char const* refreshPrefix = - "/validators/refresh/"; + constexpr char const* refreshPrefix = "/validators/refresh/"; if (boost::starts_with(path, refreshPrefix)) - refresh = boost::lexical_cast( - path.substr(strlen(refreshPrefix))); + refresh = boost::lexical_cast(path.substr(strlen(refreshPrefix))); res.body() = getList_(refresh); } } @@ -607,24 +549,19 @@ private: res.insert("Content-Type", "text/example"); // if huge was requested, lie about content length std::uint64_t cl = - boost::starts_with(path, "/textfile/huge") - ? std::numeric_limits::max() - : 1024; + boost::starts_with(path, "/textfile/huge") ? std::numeric_limits::max() : 1024; res.content_length(cl); if (req.method() == http::verb::get) { std::stringstream body; for (auto i = 0; i < 1024; ++i) - body << static_cast(rand_int(32, 126)), - res.body() = body.str(); + body << static_cast(rand_int(32, 126)), res.body() = body.str(); } } else if (boost::starts_with(path, "/sleep/")) { - auto const sleep_sec = - boost::lexical_cast(path.substr(7)); - std::this_thread::sleep_for( - std::chrono::seconds(sleep_sec)); + auto const sleep_sec = boost::lexical_cast(path.substr(7)); + std::this_thread::sleep_for(std::chrono::seconds(sleep_sec)); } else if (boost::starts_with(path, "/redirect")) { @@ -644,12 +581,8 @@ private: } else if (!boost::starts_with(path, "/redirect_nolo")) { - location - << (ssl ? "https://" : "http://") - << local_endpoint() - << (boost::starts_with(path, "/redirect_forever/") - ? path - : "/validators"); + location << (ssl ? "https://" : "http://") << local_endpoint() + << (boost::starts_with(path, "/redirect_forever/") ? path : "/validators"); } if (!location.str().empty()) res.insert("Location", location.str()); @@ -674,8 +607,7 @@ private: res.version(req.version()); res.insert("Server", "TrustedPublisherServer"); res.insert("Content-Type", "text/html"); - res.body() = - std::string{"An internal error occurred"} + e.what(); + res.body() = std::string{"An internal error occurred"} + e.what(); res.prepare_payload(); } @@ -699,15 +631,14 @@ make_TrustedPublisherServer( boost::asio::io_context& ioc, std::vector const& validators, NetClock::time_point validUntil, - std::vector> const& - futures, + std::vector> const& futures, bool useSSL = false, int version = 1, bool immediateStart = true, int sequence = 1) { - auto const r = std::make_shared( - ioc, validators, validUntil, futures, useSSL, version, sequence); + auto const r = + std::make_shared(ioc, validators, validUntil, futures, useSSL, version, sequence); if (immediateStart) r->start(); return r; @@ -715,4 +646,3 @@ make_TrustedPublisherServer( } // namespace test } // namespace xrpl -#endif diff --git a/src/test/jtx/WSClient.h b/src/test/jtx/WSClient.h index 2365e8ce40..86b81ac0ac 100644 --- a/src/test/jtx/WSClient.h +++ b/src/test/jtx/WSClient.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_WSCLIENT_H_INCLUDED -#define XRPL_TEST_WSCLIENT_H_INCLUDED +#pragma once #include @@ -17,15 +16,11 @@ class WSClient : public AbstractClient public: /** Retrieve a message. */ virtual std::optional - getMsg( - std::chrono::milliseconds const& timeout = std::chrono::milliseconds{ - 0}) = 0; + getMsg(std::chrono::milliseconds const& timeout = std::chrono::milliseconds{0}) = 0; /** Retrieve a message that meets the predicate criteria. */ virtual std::optional - findMsg( - std::chrono::milliseconds const& timeout, - std::function pred) = 0; + findMsg(std::chrono::milliseconds const& timeout, std::function pred) = 0; }; /** Returns a client operating through WebSockets/S. */ @@ -38,5 +33,3 @@ makeWSClient( } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/account_txn_id.h b/src/test/jtx/account_txn_id.h index fb48941925..71ac606418 100644 --- a/src/test/jtx/account_txn_id.h +++ b/src/test/jtx/account_txn_id.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_ACCOUNT_TXN_ID_H_INCLUDED -#define XRPL_TEST_JTX_ACCOUNT_TXN_ID_H_INCLUDED +#pragma once #include @@ -23,4 +22,3 @@ public: } // namespace jtx } // namespace test } // namespace xrpl -#endif diff --git a/src/test/jtx/acctdelete.h b/src/test/jtx/acctdelete.h index 71b8597db9..c081eb92a5 100644 --- a/src/test/jtx/acctdelete.h +++ b/src/test/jtx/acctdelete.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_ACCTDELETE_H_INCLUDED -#define XRPL_TEST_JTX_ACCTDELETE_H_INCLUDED +#pragma once #include #include @@ -18,14 +17,9 @@ acctdelete(Account const& account, Account const& dest); // the account. If margin is specified, close the ledger so `margin` // more closes are needed void -incLgrSeqForAccDel( - jtx::Env& env, - jtx::Account const& acc, - std::uint32_t margin = 0); +incLgrSeqForAccDel(jtx::Env& env, jtx::Account const& acc, std::uint32_t margin = 0); } // namespace jtx } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/amount.h b/src/test/jtx/amount.h index 147307f7b7..c7b66504d3 100644 --- a/src/test/jtx/amount.h +++ b/src/test/jtx/amount.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_AMOUNT_H_INCLUDED -#define XRPL_TEST_JTX_AMOUNT_H_INCLUDED +#pragma once #include #include @@ -74,8 +73,7 @@ public: PrettyAmount& operator=(PrettyAmount const&) = default; - PrettyAmount(STAmount const& amount, std::string const& name) - : amount_(amount), name_(name) + PrettyAmount(STAmount const& amount, std::string const& name) : amount_(amount), name_(name) { } @@ -83,20 +81,14 @@ public: template PrettyAmount( T v, - std::enable_if_t< - sizeof(T) >= sizeof(int) && std::is_integral_v && - std::is_signed_v>* = nullptr) + std::enable_if_t= sizeof(int) && std::is_integral_v && std::is_signed_v>* = nullptr) : amount_((v > 0) ? v : -v, v < 0) { } /** drops */ template - PrettyAmount( - T v, - std::enable_if_t= sizeof(int) && std::is_unsigned_v>* = - nullptr) - : amount_(v) + PrettyAmount(T v, std::enable_if_t= sizeof(int) && std::is_unsigned_v>* = nullptr) : amount_(v) { } @@ -166,13 +158,11 @@ private: public: template requires std::convertible_to - PrettyAsset(A const& asset, std::uint32_t scale = 1) - : PrettyAsset{Asset{asset}, scale} + PrettyAsset(A const& asset, std::uint32_t scale = 1) : PrettyAsset{Asset{asset}, scale} { } - PrettyAsset(Asset const& asset, std::uint32_t scale = 1) - : asset_(asset), scale_(scale) + PrettyAsset(Asset const& asset, std::uint32_t scale = 1) : asset_(asset), scale_(scale) { } @@ -200,8 +190,7 @@ public: } PrettyAmount - operator()(Number v, Number::rounding_mode rounding = Number::getround()) - const + operator()(Number v, Number::rounding_mode rounding = Number::getround()) const { NumberRoundModeGuard mg(rounding); STAmount amount{asset_, v * scale_}; @@ -241,8 +230,7 @@ struct BookSpec AccountID account; xrpl::Currency currency; - BookSpec(AccountID const& account_, xrpl::Currency const& currency_) - : account(account_), currency(currency_) + BookSpec(AccountID const& account_, xrpl::Currency const& currency_) : account(account_), currency(currency_) { } }; @@ -277,8 +265,7 @@ struct XRP_t PrettyAmount operator()(T v) const { - using TOut = std:: - conditional_t, std::int64_t, std::uint64_t>; + using TOut = std::conditional_t, std::int64_t, std::uint64_t>; return {TOut{v} * dropsPerXRP}; } @@ -391,8 +378,7 @@ public: Account account; xrpl::Currency currency; - IOU(Account const& account_, xrpl::Currency const& currency_) - : account(account_), currency(currency_) + IOU(Account const& account_, xrpl::Currency const& currency_) : account(account_), currency(currency_) { } @@ -426,10 +412,7 @@ public: return asset(); } - template < - class T, - class = std::enable_if_t< - sizeof(T) >= sizeof(int) && std::is_arithmetic::value>> + template = sizeof(int) && std::is_arithmetic::value>> PrettyAmount operator()(T v) const { @@ -478,8 +461,7 @@ public: std::string name; xrpl::MPTID issuanceID; - MPT(std::string const& n, xrpl::MPTID const& issuanceID_) - : name(n), issuanceID(issuanceID_) + MPT(std::string const& n, xrpl::MPTID const& issuanceID_) : name(n), issuanceID(issuanceID_) { } @@ -577,8 +559,7 @@ struct AnyAmount { } - AnyAmount(STAmount const& amount, any_t const*) - : is_any(true), value(amount) + AnyAmount(STAmount const& amount, any_t const*) : is_any(true), value(amount) { } @@ -606,5 +587,3 @@ extern any_t const any; } // namespace jtx } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/attester.h b/src/test/jtx/attester.h index 345002f90a..6904135f21 100644 --- a/src/test/jtx/attester.h +++ b/src/test/jtx/attester.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_ATTESTER_H_INCLUDED -#define XRPL_TEST_JTX_ATTESTER_H_INCLUDED +#pragma once #include #include @@ -44,5 +43,3 @@ sign_create_account_attestation( } // namespace jtx } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/balance.h b/src/test/jtx/balance.h index 999f6b7b0c..83e2e3ea03 100644 --- a/src/test/jtx/balance.h +++ b/src/test/jtx/balance.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_BALANCE_H_INCLUDED -#define XRPL_TEST_JTX_BALANCE_H_INCLUDED +#pragma once #include #include @@ -24,18 +23,15 @@ private: STAmount const value_; public: - balance(Account const& account, none_t) - : none_(true), account_(account), value_(XRP) + balance(Account const& account, none_t) : none_(true), account_(account), value_(XRP) { } - balance(Account const& account, None const& value) - : none_(true), account_(account), value_(value.asset) + balance(Account const& account, None const& value) : none_(true), account_(account), value_(value.asset) { } - balance(Account const& account, STAmount const& value) - : none_(false), account_(account), value_(value) + balance(Account const& account, STAmount const& value) : none_(false), account_(account), value_(value) { } @@ -46,5 +42,3 @@ public: } // namespace jtx } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/basic_prop.h b/src/test/jtx/basic_prop.h index 32655e9f52..080eecd34b 100644 --- a/src/test/jtx/basic_prop.h +++ b/src/test/jtx/basic_prop.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_BASIC_PROP_H_INCLUDED -#define XRPL_TEST_JTX_BASIC_PROP_H_INCLUDED +#pragma once #include @@ -42,5 +41,3 @@ struct prop_type : basic_prop } // namespace jtx } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/batch.h b/src/test/jtx/batch.h index dc9d30a420..c11a9fe17e 100644 --- a/src/test/jtx/batch.h +++ b/src/test/jtx/batch.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_BATCH_H_INCLUDED -#define XRPL_TEST_JTX_BATCH_H_INCLUDED +#pragma once #include #include @@ -24,18 +23,11 @@ namespace batch { /** Calculate Batch Fee. */ XRPAmount -calcBatchFee( - jtx::Env const& env, - uint32_t const& numSigners, - uint32_t const& txns = 0); +calcBatchFee(jtx::Env const& env, uint32_t const& numSigners, uint32_t const& txns = 0); /** Batch. */ Json::Value -outer( - jtx::Account const& account, - uint32_t seq, - STAmount const& fee, - std::uint32_t flags); +outer(jtx::Account const& account, uint32_t seq, STAmount const& fee, std::uint32_t flags); /** Adds a new Batch Txn on a JTx and autofills. */ class inner @@ -117,20 +109,15 @@ public: Account master; std::vector signers; - msig(Account const& masterAccount, std::vector signers_) - : master(masterAccount), signers(std::move(signers_)) + msig(Account const& masterAccount, std::vector signers_) : master(masterAccount), signers(std::move(signers_)) { sortSigners(signers); } template requires std::convertible_to - explicit msig( - Account const& masterAccount, - AccountType&& a0, - Accounts&&... aN) - : master(masterAccount) - , signers{std::forward(a0), std::forward(aN)...} + explicit msig(Account const& masterAccount, AccountType&& a0, Accounts&&... aN) + : master(masterAccount), signers{std::forward(a0), std::forward(aN)...} { sortSigners(signers); } @@ -145,5 +132,3 @@ public: } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/check.h b/src/test/jtx/check.h index 6152195f1f..9a1c6b2d2c 100644 --- a/src/test/jtx/check.h +++ b/src/test/jtx/check.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_CHECK_H_INCLUDED -#define XRPL_TEST_JTX_CHECK_H_INCLUDED +#pragma once #include #include @@ -27,10 +26,7 @@ struct DeliverMin /** Cash a check requiring that at least a minimum amount be delivered. */ Json::Value -cash( - jtx::Account const& dest, - uint256 const& checkId, - DeliverMin const& atLeast); +cash(jtx::Account const& dest, uint256 const& checkId, DeliverMin const& atLeast); /** Cancel a check. */ Json::Value @@ -45,5 +41,3 @@ using checks = owner_count; } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/credentials.h b/src/test/jtx/credentials.h index 2b41b5e7ef..29ecacb11b 100644 --- a/src/test/jtx/credentials.h +++ b/src/test/jtx/credentials.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_CREDENTIALS_H_INCLUDED -#define XRPL_TEST_JTX_CREDENTIALS_H_INCLUDED +#pragma once #include #include @@ -12,13 +11,9 @@ namespace jtx { namespace credentials { inline Keylet -keylet( - test::jtx::Account const& subject, - test::jtx::Account const& issuer, - std::string_view credType) +keylet(test::jtx::Account const& subject, test::jtx::Account const& issuer, std::string_view credType) { - return keylet::credential( - subject.id(), issuer.id(), Slice(credType.data(), credType.size())); + return keylet::credential(subject.id(), issuer.id(), Slice(credType.data(), credType.size())); } // Sets the optional URI. @@ -60,30 +55,16 @@ public: }; Json::Value -create( - jtx::Account const& subject, - jtx::Account const& issuer, - std::string_view credType); +create(jtx::Account const& subject, jtx::Account const& issuer, std::string_view credType); Json::Value -accept( - jtx::Account const& subject, - jtx::Account const& issuer, - std::string_view credType); +accept(jtx::Account const& subject, jtx::Account const& issuer, std::string_view credType); Json::Value -deleteCred( - jtx::Account const& acc, - jtx::Account const& subject, - jtx::Account const& issuer, - std::string_view credType); +deleteCred(jtx::Account const& acc, jtx::Account const& subject, jtx::Account const& issuer, std::string_view credType); Json::Value -ledgerEntry( - jtx::Env& env, - jtx::Account const& subject, - jtx::Account const& issuer, - std::string_view credType); +ledgerEntry(jtx::Env& env, jtx::Account const& subject, jtx::Account const& issuer, std::string_view credType); Json::Value ledgerEntry(jtx::Env& env, std::string const& credIdx); @@ -92,5 +73,3 @@ ledgerEntry(jtx::Env& env, std::string const& credIdx); } // namespace jtx } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/delegate.h b/src/test/jtx/delegate.h index 19707584ad..d965ab580a 100644 --- a/src/test/jtx/delegate.h +++ b/src/test/jtx/delegate.h @@ -10,15 +10,10 @@ namespace jtx { namespace delegate { Json::Value -set(jtx::Account const& account, - jtx::Account const& authorize, - std::vector const& permissions); +set(jtx::Account const& account, jtx::Account const& authorize, std::vector const& permissions); Json::Value -entry( - jtx::Env& env, - jtx::Account const& account, - jtx::Account const& authorize); +entry(jtx::Env& env, jtx::Account const& account, jtx::Account const& authorize); struct as { diff --git a/src/test/jtx/delivermin.h b/src/test/jtx/delivermin.h index 033b3f20b8..3edb38ffef 100644 --- a/src/test/jtx/delivermin.h +++ b/src/test/jtx/delivermin.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_DELIVERMIN_H_INCLUDED -#define XRPL_TEST_JTX_DELIVERMIN_H_INCLUDED +#pragma once #include @@ -27,5 +26,3 @@ public: } // namespace jtx } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/deposit.h b/src/test/jtx/deposit.h index e378366563..d7762e9ae3 100644 --- a/src/test/jtx/deposit.h +++ b/src/test/jtx/deposit.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_DEPOSIT_H_INCLUDED -#define XRPL_TEST_JTX_DEPOSIT_H_INCLUDED +#pragma once #include #include @@ -48,14 +47,10 @@ struct AuthorizeCredentials }; Json::Value -authCredentials( - jtx::Account const& account, - std::vector const& auth); +authCredentials(jtx::Account const& account, std::vector const& auth); Json::Value -unauthCredentials( - jtx::Account const& account, - std::vector const& auth); +unauthCredentials(jtx::Account const& account, std::vector const& auth); } // namespace deposit @@ -63,5 +58,3 @@ unauthCredentials( } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/did.h b/src/test/jtx/did.h index 65407028eb..9cd98a1324 100644 --- a/src/test/jtx/did.h +++ b/src/test/jtx/did.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_DID_H_INCLUDED -#define XRPL_TEST_JTX_DID_H_INCLUDED +#pragma once #include #include @@ -81,5 +80,3 @@ del(jtx::Account const& account); } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/directory.h b/src/test/jtx/directory.h index 6129b79d1c..e9fff35434 100644 --- a/src/test/jtx/directory.h +++ b/src/test/jtx/directory.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_DIRECTORY_H_INCLUDED -#define XRPL_TEST_JTX_DIRECTORY_H_INCLUDED +#pragma once #include @@ -37,8 +36,7 @@ bumpLastPage( Env& env, std::uint64_t newLastPage, Keylet directory, - std::function adjust) - -> Expected; + std::function adjust) -> Expected; /// Implementation of adjust for the most common ledger entry, i.e. one where /// page index is stored in sfOwnerNode (and only there). Pass this function @@ -58,5 +56,3 @@ maximumPageIndex(Env const& env) -> std::uint64_t } // namespace directory } // namespace xrpl::test::jtx - -#endif diff --git a/src/test/jtx/envconfig.h b/src/test/jtx/envconfig.h index d6276f2fba..dc0c48e064 100644 --- a/src/test/jtx/envconfig.h +++ b/src/test/jtx/envconfig.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_ENVCONFIG_H_INCLUDED -#define XRPL_TEST_JTX_ENVCONFIG_H_INCLUDED +#pragma once #include @@ -104,17 +103,11 @@ std::unique_ptr addGrpcConfig(std::unique_ptr); /// /// @param cfg config instance to be modified std::unique_ptr -addGrpcConfigWithSecureGateway( - std::unique_ptr, - std::string const& secureGateway); +addGrpcConfigWithSecureGateway(std::unique_ptr, std::string const& secureGateway); std::unique_ptr -makeConfig( - std::map extraTxQ = {}, - std::map extraVoting = {}); +makeConfig(std::map extraTxQ = {}, std::map extraVoting = {}); } // namespace jtx } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/escrow.h b/src/test/jtx/escrow.h index b8490d9534..c3f535e29f 100644 --- a/src/test/jtx/escrow.h +++ b/src/test/jtx/escrow.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_ESCROW_H_INCLUDED -#define XRPL_TEST_JTX_ESCROW_H_INCLUDED +#pragma once #include #include @@ -49,31 +48,26 @@ rate(Env& env, Account const& account, std::uint32_t const& seq); // A PreimageSha256 fulfillments and its associated condition. std::array const fb1 = {{0xA0, 0x02, 0x80, 0x00}}; -std::array const cb1 = { - {0xA0, 0x25, 0x80, 0x20, 0xE3, 0xB0, 0xC4, 0x42, 0x98, 0xFC, - 0x1C, 0x14, 0x9A, 0xFB, 0xF4, 0xC8, 0x99, 0x6F, 0xB9, 0x24, - 0x27, 0xAE, 0x41, 0xE4, 0x64, 0x9B, 0x93, 0x4C, 0xA4, 0x95, - 0x99, 0x1B, 0x78, 0x52, 0xB8, 0x55, 0x81, 0x01, 0x00}}; +std::array const cb1 = {{0xA0, 0x25, 0x80, 0x20, 0xE3, 0xB0, 0xC4, 0x42, 0x98, 0xFC, + 0x1C, 0x14, 0x9A, 0xFB, 0xF4, 0xC8, 0x99, 0x6F, 0xB9, 0x24, + 0x27, 0xAE, 0x41, 0xE4, 0x64, 0x9B, 0x93, 0x4C, 0xA4, 0x95, + 0x99, 0x1B, 0x78, 0x52, 0xB8, 0x55, 0x81, 0x01, 0x00}}; // Another PreimageSha256 fulfillments and its associated condition. -std::array const fb2 = { - {0xA0, 0x05, 0x80, 0x03, 0x61, 0x61, 0x61}}; +std::array const fb2 = {{0xA0, 0x05, 0x80, 0x03, 0x61, 0x61, 0x61}}; -std::array const cb2 = { - {0xA0, 0x25, 0x80, 0x20, 0x98, 0x34, 0x87, 0x6D, 0xCF, 0xB0, - 0x5C, 0xB1, 0x67, 0xA5, 0xC2, 0x49, 0x53, 0xEB, 0xA5, 0x8C, - 0x4A, 0xC8, 0x9B, 0x1A, 0xDF, 0x57, 0xF2, 0x8F, 0x2F, 0x9D, - 0x09, 0xAF, 0x10, 0x7E, 0xE8, 0xF0, 0x81, 0x01, 0x03}}; +std::array const cb2 = {{0xA0, 0x25, 0x80, 0x20, 0x98, 0x34, 0x87, 0x6D, 0xCF, 0xB0, + 0x5C, 0xB1, 0x67, 0xA5, 0xC2, 0x49, 0x53, 0xEB, 0xA5, 0x8C, + 0x4A, 0xC8, 0x9B, 0x1A, 0xDF, 0x57, 0xF2, 0x8F, 0x2F, 0x9D, + 0x09, 0xAF, 0x10, 0x7E, 0xE8, 0xF0, 0x81, 0x01, 0x03}}; // Another PreimageSha256 fulfillment and its associated condition. -std::array const fb3 = { - {0xA0, 0x06, 0x80, 0x04, 0x6E, 0x69, 0x6B, 0x62}}; +std::array const fb3 = {{0xA0, 0x06, 0x80, 0x04, 0x6E, 0x69, 0x6B, 0x62}}; -std::array const cb3 = { - {0xA0, 0x25, 0x80, 0x20, 0x6E, 0x4C, 0x71, 0x45, 0x30, 0xC0, - 0xA4, 0x26, 0x8B, 0x3F, 0xA6, 0x3B, 0x1B, 0x60, 0x6F, 0x2D, - 0x26, 0x4A, 0x2D, 0x85, 0x7B, 0xE8, 0xA0, 0x9C, 0x1D, 0xFD, - 0x57, 0x0D, 0x15, 0x85, 0x8B, 0xD4, 0x81, 0x01, 0x04}}; +std::array const cb3 = {{0xA0, 0x25, 0x80, 0x20, 0x6E, 0x4C, 0x71, 0x45, 0x30, 0xC0, + 0xA4, 0x26, 0x8B, 0x3F, 0xA6, 0x3B, 0x1B, 0x60, 0x6F, 0x2D, + 0x26, 0x4A, 0x2D, 0x85, 0x7B, 0xE8, 0xA0, 0x9C, 0x1D, 0xFD, + 0x57, 0x0D, 0x15, 0x85, 0x8B, 0xD4, 0x81, 0x01, 0x04}}; /** Set the "FinishAfter" time tag on a JTx */ auto const finish_time = JTxFieldWrapper(sfFinishAfter); @@ -91,5 +85,3 @@ auto const fulfillment = JTxFieldWrapper(sfFulfillment); } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/fee.h b/src/test/jtx/fee.h index 1b3a6ac49c..281066f0aa 100644 --- a/src/test/jtx/fee.h +++ b/src/test/jtx/fee.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_FEE_H_INCLUDED -#define XRPL_TEST_JTX_FEE_H_INCLUDED +#pragma once #include #include @@ -40,8 +39,7 @@ public: Throw("fee: not XRP"); } - explicit fee(std::uint64_t amount, bool negative = false) - : fee{STAmount{amount, negative}} + explicit fee(std::uint64_t amount, bool negative = false) : fee{STAmount{amount, negative}} { } @@ -52,5 +50,3 @@ public: } // namespace jtx } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/flags.h b/src/test/jtx/flags.h index 6b8c230a79..3dde1fa414 100644 --- a/src/test/jtx/flags.h +++ b/src/test/jtx/flags.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_FLAGS_H_INCLUDED -#define XRPL_TEST_JTX_FLAGS_H_INCLUDED +#pragma once #include @@ -112,8 +111,7 @@ private: public: template - flags(Account const& account, Args... args) - : flags_helper(args...), account_(account) + flags(Account const& account, Args... args) : flags_helper(args...), account_(account) { } @@ -129,8 +127,7 @@ private: public: template - nflags(Account const& account, Args... args) - : flags_helper(args...), account_(account) + nflags(Account const& account, Args... args) : flags_helper(args...), account_(account) { } @@ -141,5 +138,3 @@ public: } // namespace jtx } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/impl/AMM.cpp b/src/test/jtx/impl/AMM.cpp index b620126b0f..f920858ea5 100644 --- a/src/test/jtx/impl/AMM.cpp +++ b/src/test/jtx/impl/AMM.cpp @@ -27,8 +27,7 @@ AMM::initialTokens() if (!env_.enabled(fixAMMv1_3)) { auto const product = number(asset1_) * number(asset2_); - return (IOUAmount)(product.mantissa() >= 0 ? root2(product) - : root2(-product)); + return (IOUAmount)(product.mantissa() >= 0 ? root2(product) : root2(-product)); } return getLPTokensBalance(); } @@ -59,10 +58,7 @@ AMM::AMM( , msig_(ms) , fee_(fee) , ammAccount_(create(tfee, flags, seq, ter)) - , lptIssue_(xrpl::ammLPTIssue( - asset1_.issue().currency, - asset2_.issue().currency, - ammAccount_)) + , lptIssue_(xrpl::ammLPTIssue(asset1_.issue().currency, asset2_.issue().currency, ammAccount_)) , initialLPTokens_(initialTokens()) { } @@ -75,39 +71,12 @@ AMM::AMM( ter const& ter, bool log, bool close) - : AMM(env, - account, - asset1, - asset2, - log, - 0, - 0, - std::nullopt, - std::nullopt, - std::nullopt, - ter, - close) + : AMM(env, account, asset1, asset2, log, 0, 0, std::nullopt, std::nullopt, std::nullopt, ter, close) { } -AMM::AMM( - Env& env, - Account const& account, - STAmount const& asset1, - STAmount const& asset2, - CreateArg const& arg) - : AMM(env, - account, - asset1, - asset2, - arg.log, - arg.tfee, - arg.fee, - arg.flags, - arg.seq, - arg.ms, - arg.err, - arg.close) +AMM::AMM(Env& env, Account const& account, STAmount const& asset1, STAmount const& asset2, CreateArg const& arg) + : AMM(env, account, asset1, asset2, arg.log, arg.tfee, arg.fee, arg.flags, arg.seq, arg.ms, arg.err, arg.close) { } @@ -134,8 +103,7 @@ AMM::create( if (!ter || env_.ter() == tesSUCCESS) { - if (auto const amm = env_.current()->read( - keylet::amm(asset1_.issue(), asset2_.issue()))) + if (auto const amm = env_.current()->read(keylet::amm(asset1_.issue(), asset2_.issue()))) { return amm->getAccountID(sfAccount); } @@ -163,52 +131,36 @@ AMM::ammRpcInfo( if (issue1 || issue2) { if (issue1) - jv[jss::asset] = - STIssue(sfAsset, *issue1).getJson(JsonOptions::none); + jv[jss::asset] = STIssue(sfAsset, *issue1).getJson(JsonOptions::none); if (issue2) - jv[jss::asset2] = - STIssue(sfAsset2, *issue2).getJson(JsonOptions::none); + jv[jss::asset2] = STIssue(sfAsset2, *issue2).getJson(JsonOptions::none); } else if (!ammAccount) { - jv[jss::asset] = - STIssue(sfAsset, asset1_.issue()).getJson(JsonOptions::none); - jv[jss::asset2] = - STIssue(sfAsset2, asset2_.issue()).getJson(JsonOptions::none); + jv[jss::asset] = STIssue(sfAsset, asset1_.issue()).getJson(JsonOptions::none); + jv[jss::asset2] = STIssue(sfAsset2, asset2_.issue()).getJson(JsonOptions::none); } if (ammAccount) jv[jss::amm_account] = to_string(*ammAccount); } auto jr = - (apiVersion == RPC::apiInvalidVersion - ? env_.rpc("json", "amm_info", to_string(jv)) - : env_.rpc(apiVersion, "json", "amm_info", to_string(jv))); - if (jr.isObject() && jr.isMember(jss::result) && - jr[jss::result].isMember(jss::status)) + (apiVersion == RPC::apiInvalidVersion ? env_.rpc("json", "amm_info", to_string(jv)) + : env_.rpc(apiVersion, "json", "amm_info", to_string(jv))); + if (jr.isObject() && jr.isMember(jss::result) && jr[jss::result].isMember(jss::status)) return jr[jss::result]; return Json::nullValue; } std::tuple -AMM::balances( - Issue const& issue1, - Issue const& issue2, - std::optional const& account) const +AMM::balances(Issue const& issue1, Issue const& issue2, std::optional const& account) const { - if (auto const amm = - env_.current()->read(keylet::amm(asset1_.issue(), asset2_.issue()))) + if (auto const amm = env_.current()->read(keylet::amm(asset1_.issue(), asset2_.issue()))) { auto const ammAccountID = amm->getAccountID(sfAccount); - auto const [asset1Balance, asset2Balance] = ammPoolHolds( - *env_.current(), - ammAccountID, - issue1, - issue2, - FreezeHandling::fhIGNORE_FREEZE, - env_.journal); - auto const lptAMMBalance = account - ? ammLPHolds(*env_.current(), *amm, *account, env_.journal) - : amm->getFieldAmount(sfLPTokenBalance); + auto const [asset1Balance, asset2Balance] = + ammPoolHolds(*env_.current(), ammAccountID, issue1, issue2, FreezeHandling::fhIGNORE_FREEZE, env_.journal); + auto const lptAMMBalance = + account ? ammLPHolds(*env_.current(), *amm, *account, env_.journal) : amm->getFieldAmount(sfLPTokenBalance); return {asset1Balance, asset2Balance, lptAMMBalance}; } return {STAmount{}, STAmount{}, STAmount{}}; @@ -221,25 +173,16 @@ AMM::expectBalances( IOUAmount const& lpt, std::optional const& account) const { - auto const [asset1Balance, asset2Balance, lptAMMBalance] = - balances(asset1.issue(), asset2.issue(), account); - return asset1 == asset1Balance && asset2 == asset2Balance && - lptAMMBalance == STAmount{lpt, lptIssue_}; + auto const [asset1Balance, asset2Balance, lptAMMBalance] = balances(asset1.issue(), asset2.issue(), account); + return asset1 == asset1Balance && asset2 == asset2Balance && lptAMMBalance == STAmount{lpt, lptIssue_}; } IOUAmount AMM::getLPTokensBalance(std::optional const& account) const { if (account) - return accountHolds( - *env_.current(), - *account, - lptIssue_, - FreezeHandling::fhZERO_IF_FROZEN, - env_.journal) - .iou(); - if (auto const amm = - env_.current()->read(keylet::amm(asset1_.issue(), asset2_.issue()))) + return accountHolds(*env_.current(), *account, lptIssue_, FreezeHandling::fhZERO_IF_FROZEN, env_.journal).iou(); + if (auto const amm = env_.current()->read(keylet::amm(asset1_.issue(), asset2_.issue()))) return amm->getFieldAmount(sfLPTokenBalance).iou(); return IOUAmount{0}; } @@ -247,58 +190,45 @@ AMM::getLPTokensBalance(std::optional const& account) const bool AMM::expectLPTokens(AccountID const& account, IOUAmount const& expTokens) const { - if (auto const amm = - env_.current()->read(keylet::amm(asset1_.issue(), asset2_.issue()))) + if (auto const amm = env_.current()->read(keylet::amm(asset1_.issue(), asset2_.issue()))) { - auto const lptAMMBalance = - ammLPHolds(*env_.current(), *amm, account, env_.journal); + auto const lptAMMBalance = ammLPHolds(*env_.current(), *amm, account, env_.journal); return lptAMMBalance == STAmount{expTokens, lptIssue_}; } return false; } bool -AMM::expectAuctionSlot( - std::uint32_t fee, - std::optional timeSlot, - IOUAmount expectedPrice) const +AMM::expectAuctionSlot(std::uint32_t fee, std::optional timeSlot, IOUAmount expectedPrice) const { - return expectAuctionSlot([&](std::uint32_t slotFee, - std::optional slotInterval, - IOUAmount const& slotPrice, - auto const&) { - return slotFee == fee && - // Auction slot might be expired, in which case slotInterval is - // 0 - ((!timeSlot && slotInterval == 0) || slotInterval == timeSlot) && - slotPrice == expectedPrice; - }); + return expectAuctionSlot( + [&](std::uint32_t slotFee, std::optional slotInterval, IOUAmount const& slotPrice, auto const&) { + return slotFee == fee && + // Auction slot might be expired, in which case slotInterval is + // 0 + ((!timeSlot && slotInterval == 0) || slotInterval == timeSlot) && slotPrice == expectedPrice; + }); } bool AMM::expectAuctionSlot(std::vector const& authAccounts) const { - return expectAuctionSlot([&](std::uint32_t, - std::optional, - IOUAmount const&, - STArray const& accounts) { - for (auto const& account : accounts) - { - if (std::find( - authAccounts.cbegin(), - authAccounts.cend(), - account.getAccountID(sfAccount)) == authAccounts.end()) - return false; - } - return true; - }); + return expectAuctionSlot( + [&](std::uint32_t, std::optional, IOUAmount const&, STArray const& accounts) { + for (auto const& account : accounts) + { + if (std::find(authAccounts.cbegin(), authAccounts.cend(), account.getAccountID(sfAccount)) == + authAccounts.end()) + return false; + } + return true; + }); } bool AMM::expectTradingFee(std::uint16_t fee) const { - auto const amm = - env_.current()->read(keylet::amm(asset1_.issue(), asset2_.issue())); + auto const amm = env_.current()->read(keylet::amm(asset1_.issue(), asset2_.issue())); return amm && (*amm)[sfTradingFee] == fee; } @@ -306,8 +236,7 @@ bool AMM::ammExists() const { return env_.current()->read(keylet::account(ammAccount_)) != nullptr && - env_.current()->read(keylet::amm(asset1_.issue(), asset2_.issue())) != - nullptr; + env_.current()->read(keylet::amm(asset1_.issue(), asset2_.issue())) != nullptr; } bool @@ -319,23 +248,18 @@ AMM::expectAmmRpcInfo( std::optional const& ledger_index, std::optional const& ammAccount) const { - auto const jv = ammRpcInfo( - account, ledger_index, std::nullopt, std::nullopt, ammAccount); + auto const jv = ammRpcInfo(account, ledger_index, std::nullopt, std::nullopt, ammAccount); return expectAmmInfo(asset1, asset2, balance, jv); } bool -AMM::expectAmmInfo( - STAmount const& asset1, - STAmount const& asset2, - IOUAmount const& balance, - Json::Value const& jvres) const +AMM::expectAmmInfo(STAmount const& asset1, STAmount const& asset2, IOUAmount const& balance, Json::Value const& jvRes) + const { - if (!jvres.isMember(jss::amm)) + if (!jvRes.isMember(jss::amm)) return false; - auto const& jv = jvres[jss::amm]; - if (!jv.isMember(jss::amount) || !jv.isMember(jss::amount2) || - !jv.isMember(jss::lp_token)) + auto const& jv = jvRes[jss::amm]; + if (!jv.isMember(jss::amount) || !jv.isMember(jss::amount2) || !jv.isMember(jss::lp_token)) return false; STAmount asset1Info; if (!amountFromJsonNoThrow(asset1Info, jv[jss::amount])) @@ -349,28 +273,21 @@ AMM::expectAmmInfo( // ammRpcInfo returns unordered assets if (asset1Info.issue() != asset1.issue()) std::swap(asset1Info, asset2Info); - return asset1 == asset1Info && asset2 == asset2Info && - lptBalance == STAmount{balance, lptIssue_}; + return asset1 == asset1Info && asset2 == asset2Info && lptBalance == STAmount{balance, lptIssue_}; } void -AMM::setTokens( - Json::Value& jv, - std::optional> const& assets) +AMM::setTokens(Json::Value& jv, std::optional> const& assets) { if (assets) { - jv[jss::Asset] = - STIssue(sfAsset, assets->first).getJson(JsonOptions::none); - jv[jss::Asset2] = - STIssue(sfAsset, assets->second).getJson(JsonOptions::none); + jv[jss::Asset] = STIssue(sfAsset, assets->first).getJson(JsonOptions::none); + jv[jss::Asset2] = STIssue(sfAsset, assets->second).getJson(JsonOptions::none); } else { - jv[jss::Asset] = - STIssue(sfAsset, asset1_.issue()).getJson(JsonOptions::none); - jv[jss::Asset2] = - STIssue(sfAsset, asset2_.issue()).getJson(JsonOptions::none); + jv[jss::Asset] = STIssue(sfAsset, asset1_.issue()).getJson(JsonOptions::none); + jv[jss::Asset2] = STIssue(sfAsset, asset2_.issue()).getJson(JsonOptions::none); } } @@ -402,16 +319,7 @@ AMM::deposit( std::optional const& ter) { return deposit( - account, - tokens, - asset1In, - std::nullopt, - std::nullopt, - flags, - std::nullopt, - std::nullopt, - std::nullopt, - ter); + account, tokens, asset1In, std::nullopt, std::nullopt, flags, std::nullopt, std::nullopt, std::nullopt, ter); } IOUAmount @@ -425,16 +333,7 @@ AMM::deposit( { assert(!(asset2In && maxEP)); return deposit( - account, - std::nullopt, - asset1In, - asset2In, - maxEP, - flags, - std::nullopt, - std::nullopt, - std::nullopt, - ter); + account, std::nullopt, asset1In, asset2In, maxEP, flags, std::nullopt, std::nullopt, std::nullopt, ter); } IOUAmount @@ -461,26 +360,26 @@ AMM::deposit( maxEP->setJson(jv[jss::EPrice]); if (tfee) jv[jss::TradingFee] = *tfee; - std::uint32_t jvflags = 0; + std::uint32_t jvFlags = 0; if (flags) - jvflags = *flags; + jvFlags = *flags; // If including asset1In and asset2In or tokens as // deposit min amounts then must set the flags // explicitly instead of relying on this logic. - if (!(jvflags & tfDepositSubTx)) + if (!(jvFlags & tfDepositSubTx)) { if (tokens && !asset1In) - jvflags |= tfLPToken; + jvFlags |= tfLPToken; else if (tokens && asset1In) - jvflags |= tfOneAssetLPToken; + jvFlags |= tfOneAssetLPToken; else if (asset1In && asset2In) - jvflags |= tfTwoAsset; + jvFlags |= tfTwoAsset; else if (maxEP && asset1In) - jvflags |= tfLimitLPToken; + jvFlags |= tfLimitLPToken; else if (asset1In) - jvflags |= tfSingleAsset; + jvFlags |= tfSingleAsset; } - jv[jss::Flags] = jvflags; + jv[jss::Flags] = jvFlags; return deposit(account, jv, assets, seq, ter); } @@ -527,16 +426,7 @@ AMM::withdraw( std::optional const& flags, std::optional const& ter) { - return withdraw( - account, - tokens, - asset1Out, - std::nullopt, - std::nullopt, - flags, - std::nullopt, - std::nullopt, - ter); + return withdraw(account, tokens, asset1Out, std::nullopt, std::nullopt, flags, std::nullopt, std::nullopt, ter); } IOUAmount @@ -548,16 +438,7 @@ AMM::withdraw( std::optional const& ter) { assert(!(asset2Out && maxEP)); - return withdraw( - account, - std::nullopt, - asset1Out, - asset2Out, - maxEP, - std::nullopt, - std::nullopt, - std::nullopt, - ter); + return withdraw(account, std::nullopt, asset1Out, asset2Out, maxEP, std::nullopt, std::nullopt, std::nullopt, ter); } IOUAmount @@ -584,23 +465,23 @@ AMM::withdraw( STAmount const saMaxEP{*maxEP, lptIssue_}; saMaxEP.setJson(jv[jss::EPrice]); } - std::uint32_t jvflags = 0; + std::uint32_t jvFlags = 0; if (flags) - jvflags = *flags; - if (!(jvflags & tfWithdrawSubTx)) + jvFlags = *flags; + if (!(jvFlags & tfWithdrawSubTx)) { if (tokens && !asset1Out) - jvflags |= tfLPToken; + jvFlags |= tfLPToken; else if (asset1Out && asset2Out) - jvflags |= tfTwoAsset; + jvFlags |= tfTwoAsset; else if (tokens && asset1Out) - jvflags |= tfOneAssetLPToken; + jvFlags |= tfOneAssetLPToken; else if (asset1Out && maxEP) - jvflags |= tfLimitLPToken; + jvFlags |= tfLimitLPToken; else if (asset1Out) - jvflags |= tfSingleAsset; + jvFlags |= tfSingleAsset; } - jv[jss::Flags] = jvflags; + jv[jss::Flags] = jvFlags; return withdraw(account, jv, seq, assets, ter); } @@ -608,15 +489,7 @@ IOUAmount AMM::withdraw(WithdrawArg const& arg) { return withdraw( - arg.account, - arg.tokens, - arg.asset1Out, - arg.asset2Out, - arg.maxEP, - arg.flags, - arg.assets, - arg.seq, - arg.err); + arg.account, arg.tokens, arg.asset1Out, arg.asset2Out, arg.maxEP, arg.flags, arg.assets, arg.seq, arg.err); } void @@ -649,16 +522,12 @@ AMM::vote(VoteArg const& arg) Json::Value AMM::bid(BidArg const& arg) { - if (auto const amm = - env_.current()->read(keylet::amm(asset1_.issue(), asset2_.issue()))) + if (auto const amm = env_.current()->read(keylet::amm(asset1_.issue(), asset2_.issue()))) { - assert( - !env_.current()->rules().enabled(fixInnerObjTemplate) || - amm->isFieldPresent(sfAuctionSlot)); + assert(!env_.current()->rules().enabled(fixInnerObjTemplate) || amm->isFieldPresent(sfAuctionSlot)); if (amm->isFieldPresent(sfAuctionSlot)) { - auto const& auctionSlot = - static_cast(amm->peekAtField(sfAuctionSlot)); + auto const& auctionSlot = static_cast(amm->peekAtField(sfAuctionSlot)); lastPurchasePrice_ = auctionSlot[sfPrice].iou(); } } @@ -666,8 +535,7 @@ AMM::bid(BidArg const& arg) bidMax_ = std::nullopt; Json::Value jv; - jv[jss::Account] = - arg.account ? arg.account->human() : creatorAccount_.human(); + jv[jss::Account] = arg.account ? arg.account->human() : creatorAccount_.human(); setTokens(jv, arg.assets); auto getBid = [&](auto const& bid) { if (std::holds_alternative(bid)) @@ -711,10 +579,7 @@ AMM::bid(BidArg const& arg) } void -AMM::submit( - Json::Value const& jv, - std::optional const& seq, - std::optional const& ter) +AMM::submit(Json::Value const& jv, std::optional const& seq, std::optional const& ter) { if (log_) std::cout << jv.toStyledString(); @@ -744,16 +609,12 @@ AMM::submit( bool AMM::expectAuctionSlot(auto&& cb) const { - if (auto const amm = - env_.current()->read(keylet::amm(asset1_.issue(), asset2_.issue()))) + if (auto const amm = env_.current()->read(keylet::amm(asset1_.issue(), asset2_.issue()))) { - assert( - !env_.current()->rules().enabled(fixInnerObjTemplate) || - amm->isFieldPresent(sfAuctionSlot)); + assert(!env_.current()->rules().enabled(fixInnerObjTemplate) || amm->isFieldPresent(sfAuctionSlot)); if (amm->isFieldPresent(sfAuctionSlot)) { - auto const& auctionSlot = - static_cast(amm->peekAtField(sfAuctionSlot)); + auto const& auctionSlot = static_cast(amm->peekAtField(sfAuctionSlot)); if (auctionSlot.isFieldPresent(sfAccount)) { // This could fail in pre-fixInnerObjTemplate tests @@ -761,12 +622,10 @@ AMM::expectAuctionSlot(auto&& cb) const // the failure scenarios. Access as optional // to avoid the failure. auto const slotFee = auctionSlot[~sfDiscountedFee].value_or(0); - auto const slotInterval = ammAuctionTimeSlot( - env_.app().timeKeeper().now().time_since_epoch().count(), - auctionSlot); + auto const slotInterval = + ammAuctionTimeSlot(env_.app().timeKeeper().now().time_since_epoch().count(), auctionSlot); auto const slotPrice = auctionSlot[sfPrice].iou(); - auto const authAccounts = - auctionSlot.getFieldArray(sfAuthAccounts); + auto const authAccounts = auctionSlot.getFieldArray(sfAuthAccounts); return cb(slotFee, slotInterval, slotPrice, authAccounts); } } diff --git a/src/test/jtx/impl/AMMTest.cpp b/src/test/jtx/impl/AMMTest.cpp index 139b9113b9..18359ad201 100644 --- a/src/test/jtx/impl/AMMTest.cpp +++ b/src/test/jtx/impl/AMMTest.cpp @@ -88,16 +88,11 @@ AMMTestBase::testAMM( std::optional const& ter, std::vector const& vfeatures) { - testAMM( - std::move(cb), - TestAMMArg{ - .pool = pool, .tfee = tfee, .ter = ter, .features = vfeatures}); + testAMM(std::move(cb), TestAMMArg{.pool = pool, .tfee = tfee, .ter = ter, .features = vfeatures}); } void -AMMTestBase::testAMM( - std::function&& cb, - TestAMMArg const& arg) +AMMTestBase::testAMM(std::function&& cb, TestAMMArg const& arg) { using namespace jtx; @@ -115,8 +110,7 @@ AMMTestBase::testAMM( features - featureSingleAssetVault - featureLendingProtocol, arg.noLog ? std::make_unique(&logs) : nullptr}; - auto const [asset1, asset2] = - arg.pool ? *arg.pool : std::make_pair(XRP(10000), USD(10000)); + auto const [asset1, asset2] = arg.pool ? *arg.pool : std::make_pair(XRP(10000), USD(10000)); auto toFund = [&](STAmount const& a) -> STAmount { if (a.native()) { @@ -141,14 +135,8 @@ AMMTestBase::testAMM( else if (asset2.native()) fund(env, gw, {alice, carol}, toFund2, {toFund1}, Fund::All); - AMM ammAlice( - env, - alice, - asset1, - asset2, - CreateArg{.log = false, .tfee = arg.tfee, .err = arg.ter}); - if (BEAST_EXPECT( - ammAlice.expectBalances(asset1, asset2, ammAlice.tokens()))) + AMM ammAlice(env, alice, asset1, asset2, CreateArg{.log = false, .tfee = arg.tfee, .err = arg.ter}); + if (BEAST_EXPECT(ammAlice.expectBalances(asset1, asset2, ammAlice.tokens()))) cb(ammAlice, env); } } @@ -247,8 +235,7 @@ AMMTest::find_paths( std::optional const& saSendMax, std::optional const& saSrcCurrency) { - Json::Value result = find_paths_request( - env, src, dst, saDstAmount, saSendMax, saSrcCurrency); + Json::Value result = find_paths_request(env, src, dst, saDstAmount, saSendMax, saSrcCurrency); BEAST_EXPECT(!result.isMember(jss::error)); STAmount da; diff --git a/src/test/jtx/impl/Account.cpp b/src/test/jtx/impl/Account.cpp index 232c9d4e6c..31798abdc7 100644 --- a/src/test/jtx/impl/Account.cpp +++ b/src/test/jtx/impl/Account.cpp @@ -7,23 +7,15 @@ namespace xrpl { namespace test { namespace jtx { -std::unordered_map, Account, beast::uhash<>> - Account::cache_; +std::unordered_map, Account, beast::uhash<>> Account::cache_; Account const Account::master( "master", generateKeyPair(KeyType::secp256k1, generateSeed("masterpassphrase")), Account::privateCtorTag{}); -Account::Account( - std::string name, - std::pair const& keys, - Account::privateCtorTag) - : name_(std::move(name)) - , pk_(keys.first) - , sk_(keys.second) - , id_(calcAccountID(pk_)) - , human_(toBase58(id_)) +Account::Account(std::string name, std::pair const& keys, Account::privateCtorTag) + : name_(std::move(name)), pk_(keys.first), sk_(keys.second), id_(calcAccountID(pk_)), human_(toBase58(id_)) { } @@ -54,16 +46,12 @@ Account::fromCache(AcctStringType stringType, std::string name, KeyType type) return r.first->second; } -Account::Account(std::string name, KeyType type) - : Account(fromCache(Account::other, std::move(name), type)) +Account::Account(std::string name, KeyType type) : Account(fromCache(Account::other, std::move(name), type)) { } Account::Account(AcctStringType stringType, std::string base58SeedStr) - : Account(fromCache( - Account::base58Seed, - std::move(base58SeedStr), - KeyType::secp256k1)) + : Account(fromCache(Account::base58Seed, std::move(base58SeedStr), KeyType::secp256k1)) { } diff --git a/src/test/jtx/impl/Env.cpp b/src/test/jtx/impl/Env.cpp index ccef0f0398..3fdfa2bf2a 100644 --- a/src/test/jtx/impl/Env.cpp +++ b/src/test/jtx/impl/Env.cpp @@ -10,7 +10,6 @@ #include #include -#include #include #include @@ -25,8 +24,10 @@ #include #include #include +#include #include +#include namespace xrpl { namespace test { @@ -50,25 +51,18 @@ Env::AppBundle::AppBundle( { logs = std::make_unique(suite); // Use kFatal threshold to reduce noise from STObject. - setDebugLogSink( - std::make_unique("Debug", kFatal, suite)); + setDebugLogSink(std::make_unique("Debug", kFatal, suite)); } auto timeKeeper_ = std::make_unique(); timeKeeper = timeKeeper_.get(); // Hack so we don't have to call Config::setup - HTTPClient::initializeSSLContext( - config->SSL_VERIFY_DIR, - config->SSL_VERIFY_FILE, - config->SSL_VERIFY, - debugLog()); - owned = make_Application( - std::move(config), std::move(logs), std::move(timeKeeper_)); + HTTPClient::initializeSSLContext(config->SSL_VERIFY_DIR, config->SSL_VERIFY_FILE, config->SSL_VERIFY, debugLog()); + owned = make_Application(std::move(config), std::move(logs), std::move(timeKeeper_)); app = owned.get(); app->logs().threshold(thresh); if (!app->setup({})) Throw("Env::AppBundle: setup failed"); - timeKeeper->set( - app->getLedgerMaster().getClosedLedger()->header().closeTime); + timeKeeper->set(app->getLedgerMaster().getClosedLedger()->header().closeTime); app->start(false /*don't start timers*/); thread = std::thread([&]() { app->run(); }); @@ -101,9 +95,7 @@ Env::closed() } bool -Env::close( - NetClock::time_point closeTime, - std::optional consensusDelay) +Env::close(NetClock::time_point closeTime, std::optional consensusDelay) { // Round up to next distinguishable value using namespace std::chrono_literals; @@ -202,8 +194,7 @@ Env::balance(Account const& account, MPTIssue const& mptIssue) const return {STAmount(mptIssue, 0), account.name()}; // Make it negative - STAmount const amount{ - mptIssue, sle->getFieldU64(sfOutstandingAmount), 0, true}; + STAmount const amount{mptIssue, sle->getFieldU64(sfOutstandingAmount), 0, true}; return {amount, lookup(issuer).name()}; } else @@ -221,9 +212,7 @@ Env::balance(Account const& account, MPTIssue const& mptIssue) const PrettyAmount Env::balance(Account const& account, Asset const& asset) const { - return std::visit( - [&](auto const& issue) { return balance(account, issue); }, - asset.value()); + return std::visit([&](auto const& issue) { return balance(account, issue); }, asset.value()); } PrettyAmount @@ -280,20 +269,12 @@ Env::fund(bool setDefaultRipple, STAmount const& amount, Account const& account) jtx::seq(jtx::autofill), fee(jtx::autofill), sig(jtx::autofill)); - apply( - fset(account, asfDefaultRipple), - jtx::seq(jtx::autofill), - fee(jtx::autofill), - sig(jtx::autofill)); + apply(fset(account, asfDefaultRipple), jtx::seq(jtx::autofill), fee(jtx::autofill), sig(jtx::autofill)); require(flags(account, asfDefaultRipple)); } else { - apply( - pay(master, account, amount), - jtx::seq(jtx::autofill), - fee(jtx::autofill), - sig(jtx::autofill)); + apply(pay(master, account, amount), jtx::seq(jtx::autofill), fee(jtx::autofill), sig(jtx::autofill)); require(nflags(account, asfDefaultRipple)); } require(jtx::balance(account, amount)); @@ -303,11 +284,7 @@ void Env::trust(STAmount const& amount, Account const& account) { auto const start = balance(account); - apply( - jtx::trust(account, amount), - jtx::seq(jtx::autofill), - fee(jtx::autofill), - sig(jtx::autofill)); + apply(jtx::trust(account, amount), jtx::seq(jtx::autofill), fee(jtx::autofill), sig(jtx::autofill)); apply( pay(master, account, drops(current()->fees().base)), jtx::seq(jtx::autofill), @@ -327,8 +304,7 @@ Env::parseResult(Json::Value const& jr) if (!object.isObject()) return; if (object.isMember(jss::error_code)) - parsed.rpcCode = - safe_cast(object[jss::error_code].asInt()); + parsed.rpcCode = safe_cast(object[jss::error_code].asInt()); if (object.isMember(jss::error_message)) parsed.rpcMessage = object[jss::error_message].asString(); if (object.isMember(jss::error)) @@ -355,7 +331,7 @@ Env::parseResult(Json::Value const& jr) } void -Env::submit(JTx const& jt) +Env::submit(JTx const& jt, std::source_location const& loc) { ParsedResult parsedResult; auto const jr = [&]() { @@ -381,11 +357,11 @@ Env::submit(JTx const& jt) return Json::Value(); } }(); - return postconditions(jt, parsedResult, jr); + return postconditions(jt, parsedResult, jr, loc); } void -Env::sign_and_submit(JTx const& jt, Json::Value params) +Env::sign_and_submit(JTx const& jt, Json::Value params, std::source_location const& loc) { auto const account = lookup(jt.jv[jss::Account].asString()); auto const& passphrase = account.name(); @@ -402,9 +378,8 @@ Env::sign_and_submit(JTx const& jt, Json::Value params) // Use the provided parameters, and go straight // to the (RPC) client. assert(params.isObject()); - if (!params.isMember(jss::secret) && !params.isMember(jss::key_type) && - !params.isMember(jss::seed) && !params.isMember(jss::seed_hex) && - !params.isMember(jss::passphrase)) + if (!params.isMember(jss::secret) && !params.isMember(jss::key_type) && !params.isMember(jss::seed) && + !params.isMember(jss::seed_hex) && !params.isMember(jss::passphrase)) { params[jss::secret] = passphrase; } @@ -419,51 +394,41 @@ Env::sign_and_submit(JTx const& jt, Json::Value params) test.expect(parsedResult.ter, "ter uninitialized!"); ter_ = parsedResult.ter.value_or(telENV_RPC_FAILED); - return postconditions(jt, parsedResult, jr); + return postconditions(jt, parsedResult, jr, loc); } void -Env::postconditions( - JTx const& jt, - ParsedResult const& parsed, - Json::Value const& jr) +Env::postconditions(JTx const& jt, ParsedResult const& parsed, Json::Value const& jr, std::source_location const& loc) { auto const line = jt.testLine ? " (" + to_string(*jt.testLine) + ")" : ""; - bool bad = !test.expect(parsed.ter, "apply: No ter result!" + line); + auto const locStr = std::string("(") + loc.file_name() + ":" + to_string(loc.line()) + ")"; + bool bad = !test.expect(parsed.ter, "apply " + locStr + ": No ter result!" + line); bad = (jt.ter && parsed.ter && !test.expect( *parsed.ter == *jt.ter, - "apply: Got " + transToken(*parsed.ter) + " (" + - transHuman(*parsed.ter) + "); Expected " + - transToken(*jt.ter) + " (" + transHuman(*jt.ter) + ")" + - line)); + "apply " + locStr + ": Got " + transToken(*parsed.ter) + " (" + transHuman(*parsed.ter) + "); Expected " + + transToken(*jt.ter) + " (" + transHuman(*jt.ter) + ")" + line)); using namespace std::string_literals; bad = (jt.rpcCode && !test.expect( - parsed.rpcCode == jt.rpcCode->first && - parsed.rpcMessage == jt.rpcCode->second, - "apply: Got RPC result "s + - (parsed.rpcCode - ? RPC::get_error_info(*parsed.rpcCode).token.c_str() - : "NO RESULT") + - " (" + parsed.rpcMessage + "); Expected " + - RPC::get_error_info(jt.rpcCode->first).token.c_str() + " (" + + parsed.rpcCode == jt.rpcCode->first && parsed.rpcMessage == jt.rpcCode->second, + "apply " + locStr + ": Got RPC result "s + + (parsed.rpcCode ? RPC::get_error_info(*parsed.rpcCode).token.c_str() : "NO RESULT") + " (" + + parsed.rpcMessage + "); Expected " + RPC::get_error_info(jt.rpcCode->first).token.c_str() + " (" + jt.rpcCode->second + ")" + line)) || bad; // If we have an rpcCode (just checked), then the rpcException check is // optional - the 'error' field may not be defined, but if it is, it must // match rpcError. - bad = (jt.rpcException && - !test.expect( - (jt.rpcCode && parsed.rpcError.empty()) || - (parsed.rpcError == jt.rpcException->first && - (!jt.rpcException->second || - parsed.rpcException == *jt.rpcException->second)), - "apply: Got RPC result "s + parsed.rpcError + " (" + - parsed.rpcException + "); Expected " + - jt.rpcException->first + " (" + - jt.rpcException->second.value_or("n/a") + ")" + line)) || + bad = + (jt.rpcException && + !test.expect( + (jt.rpcCode && parsed.rpcError.empty()) || + (parsed.rpcError == jt.rpcException->first && + (!jt.rpcException->second || parsed.rpcException == *jt.rpcException->second)), + "apply " + locStr + ": Got RPC result "s + parsed.rpcError + " (" + parsed.rpcException + "); Expected " + + jt.rpcException->first + " (" + jt.rpcException->second.value_or("n/a") + ")" + line)) || bad; if (bad) { @@ -534,9 +499,8 @@ Env::autofill_sig(JTx& jt) // If the sig is still needed, get it here. if (!jt.fill_sig) return; - auto const account = jv.isMember(sfDelegate.jsonName) - ? lookup(jv[sfDelegate.jsonName].asString()) - : lookup(jv[jss::Account].asString()); + auto const account = jv.isMember(sfDelegate.jsonName) ? lookup(jv[sfDelegate.jsonName].asString()) + : lookup(jv[jss::Account].asString()); if (!app().checkSigs()) { jv[jss::SigningPubKey] = strHex(account.pk().slice()); @@ -638,18 +602,14 @@ Env::do_rpc( std::vector const& args, std::unordered_map const& headers) { - auto response = - rpcClient(args, app().config(), app().logs(), apiVersion, headers); + auto response = rpcClient(args, app().config(), app().logs(), apiVersion, headers); - for (unsigned ctr = 0; (ctr < retries_) and (response.first == rpcINTERNAL); - ++ctr) + for (unsigned ctr = 0; (ctr < retries_) and (response.first == rpcINTERNAL); ++ctr) { - JLOG(journal.error()) - << "Env::do_rpc error, retrying, attempt #" << ctr + 1 << " ..."; + JLOG(journal.error()) << "Env::do_rpc error, retrying, attempt #" << ctr + 1 << " ..."; std::this_thread::sleep_for(std::chrono::milliseconds(500)); - response = - rpcClient(args, app().config(), app().logs(), apiVersion, headers); + response = rpcClient(args, app().config(), app().logs(), apiVersion, headers); } return response.second; diff --git a/src/test/jtx/impl/JSONRPCClient.cpp b/src/test/jtx/impl/JSONRPCClient.cpp index df41ed39be..34d0ea2f68 100644 --- a/src/test/jtx/impl/JSONRPCClient.cpp +++ b/src/test/jtx/impl/JSONRPCClient.cpp @@ -35,8 +35,7 @@ class JSONRPCClient : public AbstractClient continue; using namespace boost::asio::ip; if (pp.ip && pp.ip->is_unspecified()) - *pp.ip = pp.ip->is_v6() ? address{address_v6::loopback()} - : address{address_v4::loopback()}; + *pp.ip = pp.ip->is_v6() ? address{address_v6::loopback()} : address{address_v4::loopback()}; if (!pp.port) Throw("Use fixConfigPorts with auto ports"); diff --git a/src/test/jtx/impl/Oracle.cpp b/src/test/jtx/impl/Oracle.cpp index 03271cc9ad..c696011da5 100644 --- a/src/test/jtx/impl/Oracle.cpp +++ b/src/test/jtx/impl/Oracle.cpp @@ -12,8 +12,7 @@ namespace test { namespace jtx { namespace oracle { -Oracle::Oracle(Env& env, CreateArg const& arg, bool submit) - : env_(env), owner_{}, documentID_{} +Oracle::Oracle(Env& env, CreateArg const& arg, bool submit) : env_(env), owner_{}, documentID_{} { // LastUpdateTime is checked to be in range // {close-maxLastUpdateTimeDelta, close+maxLastUpdateTimeDelta}. @@ -95,20 +94,14 @@ Oracle::expectPrice(DataSeries const& series) const return false; for (auto const& data : series) { - if (std::find_if( - leSeries.begin(), - leSeries.end(), - [&](STObject const& o) -> bool { - auto const& baseAsset = o.getFieldCurrency(sfBaseAsset); - auto const& quoteAsset = - o.getFieldCurrency(sfQuoteAsset); - auto const& price = o.getFieldU64(sfAssetPrice); - auto const& scale = o.getFieldU8(sfScale); - return baseAsset.getText() == std::get<0>(data) && - quoteAsset.getText() == std::get<1>(data) && - price == std::get<2>(data) && - scale == std::get<3>(data); - }) == leSeries.end()) + if (std::find_if(leSeries.begin(), leSeries.end(), [&](STObject const& o) -> bool { + auto const& baseAsset = o.getFieldCurrency(sfBaseAsset); + auto const& quoteAsset = o.getFieldCurrency(sfQuoteAsset); + auto const& price = o.getFieldU64(sfAssetPrice); + auto const& scale = o.getFieldU8(sfScale); + return baseAsset.getText() == std::get<0>(data) && quoteAsset.getText() == std::get<1>(data) && + price == std::get<2>(data) && scale == std::get<3>(data); + }) == leSeries.end()) return false; } return true; @@ -177,8 +170,7 @@ Oracle::set(UpdateArg const& arg) Json::Value jv; if (arg.owner) owner_ = *arg.owner; - if (arg.documentID && - std::holds_alternative(*arg.documentID)) + if (arg.documentID && std::holds_alternative(*arg.documentID)) { documentID_ = std::get(*arg.documentID); jv[jss::OracleDocumentID] = documentID_; @@ -207,17 +199,13 @@ Oracle::set(UpdateArg const& arg) if (arg.lastUpdateTime) { if (std::holds_alternative(*arg.lastUpdateTime)) - jv[jss::LastUpdateTime] = to_string( - testStartTime.count() + - std::get(*arg.lastUpdateTime)); + jv[jss::LastUpdateTime] = to_string(testStartTime.count() + std::get(*arg.lastUpdateTime)); else toJson(jv[jss::LastUpdateTime], *arg.lastUpdateTime); } else jv[jss::LastUpdateTime] = to_string( - duration_cast( - env_.current()->header().closeTime.time_since_epoch()) - .count() + + duration_cast(env_.current()->header().closeTime.time_since_epoch()).count() + epoch_offset.count()); Json::Value dataSeries(Json::arrayValue); auto assetToStr = [](std::string const& s) { @@ -275,11 +263,9 @@ Oracle::ledgerEntry( if (account) { if (std::holds_alternative(*account)) - jvParams[jss::oracle][jss::account] = - to_string(std::get(*account)); + jvParams[jss::oracle][jss::account] = to_string(std::get(*account)); else - jvParams[jss::oracle][jss::account] = - std::get(*account); + jvParams[jss::oracle][jss::account] = std::get(*account); } if (documentID) toJson(jvParams[jss::oracle][jss::oracle_document_id], *documentID); diff --git a/src/test/jtx/impl/TestHelpers.cpp b/src/test/jtx/impl/TestHelpers.cpp index 4a9d425f01..d89dec456b 100644 --- a/src/test/jtx/impl/TestHelpers.cpp +++ b/src/test/jtx/impl/TestHelpers.cpp @@ -62,10 +62,7 @@ STPathElement IPE(Issue const& iss) { return STPathElement( - STPathElement::typeCurrency | STPathElement::typeIssuer, - xrpAccount(), - iss.currency, - iss.account); + STPathElement::typeCurrency | STPathElement::typeIssuer, xrpAccount(), iss.currency, iss.account); } /******************************************************************************/ @@ -84,11 +81,7 @@ xrpMinusFee(Env const& env, std::int64_t xrpAmount) }; [[nodiscard]] bool -expectHolding( - Env& env, - AccountID const& account, - STAmount const& value, - bool defaultLimits) +expectHolding(Env& env, AccountID const& account, STAmount const& value, bool defaultLimits) { if (auto const sle = env.le(keylet::line(account, value.issue()))) { @@ -104,8 +97,7 @@ expectHolding( low.setIssuer(accountLow ? account : issue.account); high.setIssuer(accountLow ? issue.account : account); - expectDefaultTrustLine = sle->getFieldAmount(sfLowLimit) == low && - sle->getFieldAmount(sfHighLimit) == high; + expectDefaultTrustLine = sle->getFieldAmount(sfLowLimit) == low && sle->getFieldAmount(sfHighLimit) == high; } auto amount = sle->getFieldAmount(sfBalance); @@ -118,21 +110,13 @@ expectHolding( } [[nodiscard]] bool -expectHolding( - Env& env, - AccountID const& account, - None const&, - Issue const& issue) +expectHolding(Env& env, AccountID const& account, None const&, Issue const& issue) { return !env.le(keylet::line(account, issue)); } [[nodiscard]] bool -expectHolding( - Env& env, - AccountID const& account, - None const&, - MPTIssue const& mptIssue) +expectHolding(Env& env, AccountID const& account, None const&, MPTIssue const& mptIssue) { return !env.le(keylet::mptoken(mptIssue.getMptID(), account)); } @@ -141,37 +125,27 @@ expectHolding( expectHolding(Env& env, AccountID const& account, None const& value) { return std::visit( - [&](auto const& issue) { - return expectHolding(env, account, value, issue); - }, - value.asset.value()); + [&](auto const& issue) { return expectHolding(env, account, value, issue); }, value.asset.value()); } [[nodiscard]] bool -expectOffers( - Env& env, - AccountID const& account, - std::uint16_t size, - std::vector const& toMatch) +expectOffers(Env& env, AccountID const& account, std::uint16_t size, std::vector const& toMatch) { std::uint16_t cnt = 0; std::uint16_t matched = 0; - forEachItem( - *env.current(), account, [&](std::shared_ptr const& sle) { - if (!sle) - return false; - if (sle->getType() == ltOFFER) - { - ++cnt; - if (std::find_if( - toMatch.begin(), toMatch.end(), [&](auto const& a) { - return a.in == sle->getFieldAmount(sfTakerPays) && - a.out == sle->getFieldAmount(sfTakerGets); - }) != toMatch.end()) - ++matched; - } - return true; - }); + forEachItem(*env.current(), account, [&](std::shared_ptr const& sle) { + if (!sle) + return false; + if (sle->getType() == ltOFFER) + { + ++cnt; + if (std::find_if(toMatch.begin(), toMatch.end(), [&](auto const& a) { + return a.in == sle->getFieldAmount(sfTakerPays) && a.out == sle->getFieldAmount(sfTakerGets); + }) != toMatch.end()) + ++matched; + } + return true; + }); return size == cnt && matched == toMatch.size(); } @@ -185,11 +159,7 @@ ledgerEntryRoot(Env& env, Account const& acct) } Json::Value -ledgerEntryState( - Env& env, - Account const& acct_a, - Account const& acct_b, - std::string const& currency) +ledgerEntryState(Env& env, Account const& acct_a, Account const& acct_b, std::string const& currency) { Json::Value jvParams; jvParams[jss::ledger_index] = "current"; @@ -208,10 +178,7 @@ accountBalance(Env& env, Account const& acct) } [[nodiscard]] bool -expectLedgerEntryRoot( - Env& env, - Account const& acct, - STAmount const& expectedValue) +expectLedgerEntryRoot(Env& env, Account const& acct, STAmount const& expectedValue) { return accountBalance(env, acct) == to_string(expectedValue.xrp()); } @@ -286,10 +253,7 @@ claim( } uint256 -channel( - AccountID const& account, - AccountID const& dst, - std::uint32_t seqProxyValue) +channel(AccountID const& account, AccountID const& dst, std::uint32_t seqProxyValue) { auto const k = keylet::payChan(account, dst, seqProxyValue); return k.key; @@ -317,12 +281,7 @@ channelExists(ReadView const& view, uint256 const& chan) /******************************************************************************/ void -n_offers( - Env& env, - std::size_t n, - Account const& account, - STAmount const& in, - STAmount const& out) +n_offers(Env& env, std::size_t n, Account const& account, STAmount const& in, STAmount const& out) { auto const ownerCount = env.le(account)->getFieldU32(sfOwnerCount); for (std::size_t i = 0; i < n; i++) @@ -340,17 +299,15 @@ n_offers( STPathElement cpe(Currency const& c) { - return STPathElement( - STPathElement::typeCurrency, xrpAccount(), c, xrpAccount()); + return STPathElement(STPathElement::typeCurrency, xrpAccount(), c, xrpAccount()); }; // All path element STPathElement -allpe(AccountID const& a, Issue const& iss) +allPathElements(AccountID const& a, Issue const& iss) { return STPathElement( - STPathElement::typeAccount | STPathElement::typeCurrency | - STPathElement::typeIssuer, + STPathElement::typeAccount | STPathElement::typeCurrency | STPathElement::typeIssuer, a, iss.currency, iss.account); @@ -384,11 +341,7 @@ del(AccountID const& account, uint256 const& brokerID, uint32_t flags) } Json::Value -coverDeposit( - AccountID const& account, - uint256 const& brokerID, - STAmount const& amount, - uint32_t flags) +coverDeposit(AccountID const& account, uint256 const& brokerID, STAmount const& amount, uint32_t flags) { Json::Value jv; jv[sfTransactionType] = jss::LoanBrokerCoverDeposit; @@ -400,11 +353,7 @@ coverDeposit( } Json::Value -coverWithdraw( - AccountID const& account, - uint256 const& brokerID, - STAmount const& amount, - uint32_t flags) +coverWithdraw(AccountID const& account, uint256 const& brokerID, STAmount const& amount, uint32_t flags) { Json::Value jv; jv[sfTransactionType] = jss::LoanBrokerCoverWithdraw; @@ -432,10 +381,7 @@ coverClawback(AccountID const& account, std::uint32_t flags) namespace loan { Json::Value -set(AccountID const& account, - uint256 const& loanBrokerID, - Number principalRequested, - std::uint32_t flags) +set(AccountID const& account, uint256 const& loanBrokerID, Number principalRequested, std::uint32_t flags) { Json::Value jv; jv[sfTransactionType] = jss::LoanSet; @@ -469,10 +415,7 @@ del(AccountID const& account, uint256 const& loanID, std::uint32_t flags) } Json::Value -pay(AccountID const& account, - uint256 const& loanID, - STAmount const& amount, - std::uint32_t flags) +pay(AccountID const& account, uint256 const& loanID, STAmount const& amount, std::uint32_t flags) { Json::Value jv; jv[sfTransactionType] = jss::LoanPay; diff --git a/src/test/jtx/impl/WSClient.cpp b/src/test/jtx/impl/WSClient.cpp index 878846b41d..c1012b57a4 100644 --- a/src/test/jtx/impl/WSClient.cpp +++ b/src/test/jtx/impl/WSClient.cpp @@ -49,8 +49,7 @@ class WSClientImpl : public WSClient continue; using namespace boost::asio::ip; if (pp.ip && pp.ip->is_unspecified()) - *pp.ip = pp.ip->is_v6() ? address{address_v6::loopback()} - : address{address_v4::loopback()}; + *pp.ip = pp.ip->is_v6() ? address{address_v6::loopback()} : address{address_v4::loopback()}; if (!pp.port) Throw("Use fixConfigPorts with auto ports"); @@ -74,9 +73,7 @@ class WSClientImpl : public WSClient } boost::asio::io_context ios_; - std::optional> - work_; + std::optional> work_; boost::asio::strand strand_; std::thread thread_; boost::asio::ip::tcp::socket stream_; @@ -100,24 +97,21 @@ class WSClientImpl : public WSClient void cleanup() { - boost::asio::post( - ios_, boost::asio::bind_executor(strand_, [this] { - if (!peerClosed_) - { - ws_.async_close( - {}, - boost::asio::bind_executor(strand_, [&](error_code) { - try - { - stream_.cancel(); - } - catch (boost::system::system_error const&) - { - // ignored - } - })); - } - })); + boost::asio::post(ios_, boost::asio::bind_executor(strand_, [this] { + if (!peerClosed_) + { + ws_.async_close({}, boost::asio::bind_executor(strand_, [&](error_code) { + try + { + stream_.cancel(); + } + catch (boost::system::system_error const&) + { + // ignored + } + })); + } + })); work_ = std::nullopt; thread_.join(); } @@ -139,22 +133,16 @@ public: { auto const ep = getEndpoint(cfg, v2); stream_.connect(ep); - ws_.set_option(boost::beast::websocket::stream_base::decorator( - [&](boost::beast::websocket::request_type& req) { + ws_.set_option( + boost::beast::websocket::stream_base::decorator([&](boost::beast::websocket::request_type& req) { for (auto const& h : headers) req.set(h.first, h.second); })); - ws_.handshake( - ep.address().to_string() + ":" + std::to_string(ep.port()), - "/"); + ws_.handshake(ep.address().to_string() + ":" + std::to_string(ep.port()), "/"); ws_.async_read( rb_, boost::asio::bind_executor( - strand_, - std::bind( - &WSClientImpl::on_read_msg, - this, - std::placeholders::_1))); + strand_, std::bind(&WSClientImpl::on_read_msg, this, std::placeholders::_1))); } catch (std::exception&) { @@ -191,9 +179,7 @@ public: ws_.write_some(true, buffer(s)); } - auto jv = findMsg(5s, [&](Json::Value const& jval) { - return jval[jss::type] == jss::response; - }); + auto jv = findMsg(5s, [&](Json::Value const& jval) { return jval[jss::type] == jss::response; }); if (jv) { // Normalize JSON output @@ -229,9 +215,7 @@ public: } std::optional - findMsg( - std::chrono::milliseconds const& timeout, - std::function pred) override + findMsg(std::chrono::milliseconds const& timeout, std::function pred) override { std::shared_ptr m; { @@ -284,10 +268,7 @@ private: } ws_.async_read( rb_, - boost::asio::bind_executor( - strand_, - std::bind( - &WSClientImpl::on_read_msg, this, std::placeholders::_1))); + boost::asio::bind_executor(strand_, std::bind(&WSClientImpl::on_read_msg, this, std::placeholders::_1))); } // Called when the read op terminates diff --git a/src/test/jtx/impl/acctdelete.cpp b/src/test/jtx/impl/acctdelete.cpp index 47ee1c39a6..0b87d501dd 100644 --- a/src/test/jtx/impl/acctdelete.cpp +++ b/src/test/jtx/impl/acctdelete.cpp @@ -25,9 +25,7 @@ void incLgrSeqForAccDel(jtx::Env& env, jtx::Account const& acc, std::uint32_t margin) { using namespace jtx; - auto openLedgerSeq = [](jtx::Env& env) -> std::uint32_t { - return env.current()->seq(); - }; + auto openLedgerSeq = [](jtx::Env& env) -> std::uint32_t { return env.current()->seq(); }; int const delta = [&]() -> int { if (env.seq(acc) + 255 > openLedgerSeq(env)) diff --git a/src/test/jtx/impl/amount.cpp b/src/test/jtx/impl/amount.cpp index 2548a4423b..73dad7f48e 100644 --- a/src/test/jtx/impl/amount.cpp +++ b/src/test/jtx/impl/amount.cpp @@ -74,15 +74,13 @@ operator<<(std::ostream& os, PrettyAmount const& amount) } else if (amount.value().holds()) { - os << amount.value().getText() << "/" - << to_string(amount.value().issue().currency) << "(" << amount.name() + os << amount.value().getText() << "/" << to_string(amount.value().issue().currency) << "(" << amount.name() << ")"; } else { auto const& mptIssue = amount.value().asset().get(); - os << amount.value().getText() << "/" << to_string(mptIssue) << "(" - << amount.name() << ")"; + os << amount.value().getText() << "/" << to_string(mptIssue) << "(" << amount.name() << ")"; } return os; } @@ -100,8 +98,7 @@ IOU::operator()(epsilon_t) const PrettyAmount IOU::operator()(detail::epsilon_multiple m) const { - return { - STAmount(issue(), safe_cast(m.n), -81), account.name()}; + return {STAmount(issue(), safe_cast(m.n), -81), account.name()}; } std::ostream& diff --git a/src/test/jtx/impl/attester.cpp b/src/test/jtx/impl/attester.cpp index 1d00767f0c..04b2a037c6 100644 --- a/src/test/jtx/impl/attester.cpp +++ b/src/test/jtx/impl/attester.cpp @@ -22,13 +22,7 @@ sign_claim_attestation( std::optional const& dst) { auto const toSign = Attestations::AttestationClaim::message( - bridge, - sendingAccount, - sendingAmount, - rewardAccount, - wasLockingChainSend, - claimID, - dst); + bridge, sendingAccount, sendingAmount, rewardAccount, wasLockingChainSend, claimID, dst); return sign(pk, sk, makeSlice(toSign)); } @@ -46,14 +40,7 @@ sign_create_account_attestation( AccountID const& dst) { auto const toSign = Attestations::AttestationCreateAccount::message( - bridge, - sendingAccount, - sendingAmount, - rewardAmount, - rewardAccount, - wasLockingChainSend, - createCount, - dst); + bridge, sendingAccount, sendingAmount, rewardAmount, rewardAccount, wasLockingChainSend, createCount, dst); return sign(pk, sk, makeSlice(toSign)); } diff --git a/src/test/jtx/impl/balance.cpp b/src/test/jtx/impl/balance.cpp index 4449be223c..1ebeeed437 100644 --- a/src/test/jtx/impl/balance.cpp +++ b/src/test/jtx/impl/balance.cpp @@ -4,24 +4,25 @@ namespace xrpl { namespace test { namespace jtx { +#define TEST_EXPECT(cond) env.test.expect(cond, __FILE__, __LINE__) +#define TEST_EXPECTS(cond, reason) \ + ((cond) ? (env.test.pass(), true) : (env.test.fail((reason), __FILE__, __LINE__), false)) + void -doBalance( - Env& env, - AccountID const& account, - bool none, - STAmount const& value, - Issue const& issue) +doBalance(Env& env, AccountID const& account, bool none, STAmount const& value, Issue const& issue) { if (isXRP(issue)) { auto const sle = env.le(keylet::account(account)); if (none) { - env.test.expect(!sle); + TEST_EXPECT(!sle); } - else if (env.test.expect(sle)) + else if (TEST_EXPECT(sle)) { - env.test.expect(sle->getFieldAmount(sfBalance) == value); + TEST_EXPECTS( + sle->getFieldAmount(sfBalance) == value, + sle->getFieldAmount(sfBalance).getText() + " / " + value.getText()); } } else @@ -29,36 +30,31 @@ doBalance( auto const sle = env.le(keylet::line(account, issue)); if (none) { - env.test.expect(!sle); + TEST_EXPECT(!sle); } - else if (env.test.expect(sle)) + else if (TEST_EXPECT(sle)) { auto amount = sle->getFieldAmount(sfBalance); amount.setIssuer(issue.account); if (account > issue.account) amount.negate(); - env.test.expect(amount == value); + TEST_EXPECTS(amount == value, amount.getText()); } } } void -doBalance( - Env& env, - AccountID const& account, - bool none, - STAmount const& value, - MPTIssue const& mptIssue) +doBalance(Env& env, AccountID const& account, bool none, STAmount const& value, MPTIssue const& mptIssue) { auto const sle = env.le(keylet::mptoken(mptIssue.getMptID(), account)); if (none) { - env.test.expect(!sle); + TEST_EXPECT(!sle); } - else if (env.test.expect(sle)) + else if (TEST_EXPECT(sle)) { STAmount const amount{mptIssue, sle->getFieldU64(sfMPTAmount)}; - env.test.expect(amount == value); + TEST_EXPECT(amount == value); } } @@ -66,10 +62,7 @@ void balance::operator()(Env& env) const { return std::visit( - [&](auto const& issue) { - doBalance(env, account_.id(), none_, value_, issue); - }, - value_.asset().value()); + [&](auto const& issue) { doBalance(env, account_.id(), none_, value_, issue); }, value_.asset().value()); } } // namespace jtx diff --git a/src/test/jtx/impl/batch.cpp b/src/test/jtx/impl/batch.cpp index e0a52d0218..3f993ddea1 100644 --- a/src/test/jtx/impl/batch.cpp +++ b/src/test/jtx/impl/batch.cpp @@ -16,10 +16,7 @@ namespace jtx { namespace batch { XRPAmount -calcBatchFee( - test::jtx::Env const& env, - uint32_t const& numSigners, - uint32_t const& txns) +calcBatchFee(test::jtx::Env const& env, uint32_t const& numSigners, uint32_t const& txns) { XRPAmount const feeDrops = env.current()->fees().base; return ((numSigners + 2) * feeDrops) + feeDrops * txns; @@ -27,11 +24,7 @@ calcBatchFee( // Batch. Json::Value -outer( - jtx::Account const& account, - uint32_t seq, - STAmount const& fee, - std::uint32_t flags) +outer(jtx::Account const& account, uint32_t seq, STAmount const& fee, std::uint32_t flags) { Json::Value jv; jv[jss::TransactionType] = jss::Batch; @@ -81,10 +74,8 @@ sig::operator()(Env& env, JTx& jt) const Serializer msg; serializeBatch(msg, stx.getFlags(), stx.getBatchTransactionIDs()); - auto const sig = xrpl::sign( - *publicKeyType(e.sig.pk().slice()), e.sig.sk(), msg.slice()); - jo[sfTxnSignature.getJsonName()] = - strHex(Slice{sig.data(), sig.size()}); + auto const sig = xrpl::sign(*publicKeyType(e.sig.pk().slice()), e.sig.sk(), msg.slice()); + jo[sfTxnSignature.getJsonName()] = strHex(Slice{sig.data(), sig.size()}); } } @@ -121,10 +112,8 @@ msig::operator()(Env& env, JTx& jt) const Serializer msg; serializeBatch(msg, stx.getFlags(), stx.getBatchTransactionIDs()); finishMultiSigningData(e.acct.id(), msg); - auto const sig = xrpl::sign( - *publicKeyType(e.sig.pk().slice()), e.sig.sk(), msg.slice()); - iso[sfTxnSignature.getJsonName()] = - strHex(Slice{sig.data(), sig.size()}); + auto const sig = xrpl::sign(*publicKeyType(e.sig.pk().slice()), e.sig.sk(), msg.slice()); + iso[sfTxnSignature.getJsonName()] = strHex(Slice{sig.data(), sig.size()}); } } diff --git a/src/test/jtx/impl/check.cpp b/src/test/jtx/impl/check.cpp index 769771861d..22f348aa3f 100644 --- a/src/test/jtx/impl/check.cpp +++ b/src/test/jtx/impl/check.cpp @@ -23,10 +23,7 @@ cash(jtx::Account const& dest, uint256 const& checkId, STAmount const& amount) // Cash a check requiring that at least a minimum amount be delivered. Json::Value -cash( - jtx::Account const& dest, - uint256 const& checkId, - DeliverMin const& atLeast) +cash(jtx::Account const& dest, uint256 const& checkId, DeliverMin const& atLeast) { Json::Value jv; jv[sfAccount.jsonName] = dest.human(); diff --git a/src/test/jtx/impl/creds.cpp b/src/test/jtx/impl/creds.cpp index f93d951e48..5a9ecfec59 100644 --- a/src/test/jtx/impl/creds.cpp +++ b/src/test/jtx/impl/creds.cpp @@ -10,10 +10,7 @@ namespace jtx { namespace credentials { Json::Value -create( - jtx::Account const& subject, - jtx::Account const& issuer, - std::string_view credType) +create(jtx::Account const& subject, jtx::Account const& issuer, std::string_view credType) { Json::Value jv; jv[jss::TransactionType] = jss::CredentialCreate; @@ -26,10 +23,7 @@ create( } Json::Value -accept( - jtx::Account const& subject, - jtx::Account const& issuer, - std::string_view credType) +accept(jtx::Account const& subject, jtx::Account const& issuer, std::string_view credType) { Json::Value jv; jv[jss::TransactionType] = jss::CredentialAccept; @@ -40,11 +34,7 @@ accept( } Json::Value -deleteCred( - jtx::Account const& acc, - jtx::Account const& subject, - jtx::Account const& issuer, - std::string_view credType) +deleteCred(jtx::Account const& acc, jtx::Account const& subject, jtx::Account const& issuer, std::string_view credType) { Json::Value jv; jv[jss::TransactionType] = jss::CredentialDelete; @@ -56,11 +46,7 @@ deleteCred( } Json::Value -ledgerEntry( - jtx::Env& env, - jtx::Account const& subject, - jtx::Account const& issuer, - std::string_view credType) +ledgerEntry(jtx::Env& env, jtx::Account const& subject, jtx::Account const& issuer, std::string_view credType) { Json::Value jvParams; jvParams[jss::ledger_index] = jss::validated; diff --git a/src/test/jtx/impl/delegate.cpp b/src/test/jtx/impl/delegate.cpp index 7cca9aa738..312a3f2403 100644 --- a/src/test/jtx/impl/delegate.cpp +++ b/src/test/jtx/impl/delegate.cpp @@ -9,9 +9,7 @@ namespace jtx { namespace delegate { Json::Value -set(jtx::Account const& account, - jtx::Account const& authorize, - std::vector const& permissions) +set(jtx::Account const& account, jtx::Account const& authorize, std::vector const& permissions) { Json::Value jv; jv[jss::TransactionType] = jss::DelegateSet; diff --git a/src/test/jtx/impl/deposit.cpp b/src/test/jtx/impl/deposit.cpp index 7a49bee06a..4a2ecf0139 100644 --- a/src/test/jtx/impl/deposit.cpp +++ b/src/test/jtx/impl/deposit.cpp @@ -32,9 +32,7 @@ unauth(jtx::Account const& account, jtx::Account const& unauth) // Add DepositPreauth. Json::Value -authCredentials( - jtx::Account const& account, - std::vector const& auth) +authCredentials(jtx::Account const& account, std::vector const& auth) { Json::Value jv; jv[sfAccount.jsonName] = account.human(); @@ -52,9 +50,7 @@ authCredentials( // Remove DepositPreauth. Json::Value -unauthCredentials( - jtx::Account const& account, - std::vector const& auth) +unauthCredentials(jtx::Account const& account, std::vector const& auth) { Json::Value jv; jv[sfAccount.jsonName] = account.human(); diff --git a/src/test/jtx/impl/directory.cpp b/src/test/jtx/impl/directory.cpp index bb44b8d782..7231389d1e 100644 --- a/src/test/jtx/impl/directory.cpp +++ b/src/test/jtx/impl/directory.cpp @@ -12,97 +12,94 @@ bumpLastPage( Env& env, std::uint64_t newLastPage, Keylet directory, - std::function adjust) - -> Expected + std::function adjust) -> Expected { Expected res{}; - env.app().openLedger().modify( - [&](OpenView& view, beast::Journal j) -> bool { - Sandbox sb(&view, tapNONE); + env.app().openLedger().modify([&](OpenView& view, beast::Journal j) -> bool { + Sandbox sb(&view, tapNONE); - // Find the root page - auto sleRoot = sb.peek(directory); - if (!sleRoot) - { - res = Unexpected(DirectoryRootNotFound); - return false; - } + // Find the root page + auto sleRoot = sb.peek(directory); + if (!sleRoot) + { + res = Unexpected(DirectoryRootNotFound); + return false; + } - // Find last page - auto const lastIndex = sleRoot->getFieldU64(sfIndexPrevious); - if (lastIndex == 0) - { - res = Unexpected(DirectoryTooSmall); - return false; - } + // Find last page + auto const lastIndex = sleRoot->getFieldU64(sfIndexPrevious); + if (lastIndex == 0) + { + res = Unexpected(DirectoryTooSmall); + return false; + } - if (sb.exists(keylet::page(directory, newLastPage))) - { - res = Unexpected(DirectoryPageDuplicate); - return false; - } + if (sb.exists(keylet::page(directory, newLastPage))) + { + res = Unexpected(DirectoryPageDuplicate); + return false; + } - if (lastIndex >= newLastPage) - { - res = Unexpected(InvalidLastPage); - return false; - } + if (lastIndex >= newLastPage) + { + res = Unexpected(InvalidLastPage); + return false; + } - auto slePage = sb.peek(keylet::page(directory, lastIndex)); - if (!slePage) + auto slePage = sb.peek(keylet::page(directory, lastIndex)); + if (!slePage) + { + res = Unexpected(DirectoryPageNotFound); + return false; + } + + // Copy its data and delete the page + auto indexes = slePage->getFieldV256(sfIndexes); + auto prevIndex = slePage->at(~sfIndexPrevious); + auto owner = slePage->at(~sfOwner); + sb.erase(slePage); + + // Create new page to replace slePage + auto sleNew = std::make_shared(keylet::page(directory, newLastPage)); + sleNew->setFieldH256(sfRootIndex, directory.key); + sleNew->setFieldV256(sfIndexes, indexes); + if (owner) + sleNew->setAccountID(sfOwner, *owner); + if (prevIndex) + sleNew->setFieldU64(sfIndexPrevious, *prevIndex); + sb.insert(sleNew); + + // Adjust root previous and previous node's next + sleRoot->setFieldU64(sfIndexPrevious, newLastPage); + if (prevIndex.value_or(0) == 0) + sleRoot->setFieldU64(sfIndexNext, newLastPage); + else + { + auto slePrev = sb.peek(keylet::page(directory, *prevIndex)); + if (!slePrev) { res = Unexpected(DirectoryPageNotFound); return false; } + slePrev->setFieldU64(sfIndexNext, newLastPage); + sb.update(slePrev); + } + sb.update(sleRoot); - // Copy its data and delete the page - auto indexes = slePage->getFieldV256(sfIndexes); - auto prevIndex = slePage->at(~sfIndexPrevious); - auto owner = slePage->at(~sfOwner); - sb.erase(slePage); - - // Create new page to replace slePage - auto sleNew = - std::make_shared(keylet::page(directory, newLastPage)); - sleNew->setFieldH256(sfRootIndex, directory.key); - sleNew->setFieldV256(sfIndexes, indexes); - if (owner) - sleNew->setAccountID(sfOwner, *owner); - if (prevIndex) - sleNew->setFieldU64(sfIndexPrevious, *prevIndex); - sb.insert(sleNew); - - // Adjust root previous and previous node's next - sleRoot->setFieldU64(sfIndexPrevious, newLastPage); - if (prevIndex.value_or(0) == 0) - sleRoot->setFieldU64(sfIndexNext, newLastPage); - else + // Fixup page numbers in the objects referred by indexes + if (adjust) + for (auto const key : indexes) { - auto slePrev = sb.peek(keylet::page(directory, *prevIndex)); - if (!slePrev) + if (!adjust(sb, key, newLastPage)) { - res = Unexpected(DirectoryPageNotFound); + res = Unexpected(AdjustmentError); return false; } - slePrev->setFieldU64(sfIndexNext, newLastPage); - sb.update(slePrev); } - sb.update(sleRoot); - // Fixup page numbers in the objects referred by indexes - if (adjust) - for (auto const key : indexes) - { - if (!adjust(sb, key, newLastPage)) - { - res = Unexpected(AdjustmentError); - return false; - } - } - - sb.apply(view); - return true; - }); + sb.apply(view); + return true; + }); return res; } diff --git a/src/test/jtx/impl/envconfig.cpp b/src/test/jtx/impl/envconfig.cpp index 67bbe3b457..1def778c69 100644 --- a/src/test/jtx/impl/envconfig.cpp +++ b/src/test/jtx/impl/envconfig.cpp @@ -94,8 +94,7 @@ std::unique_ptr validator(std::unique_ptr cfg, std::string const& seed) { // If the config has valid validation keys then we run as a validator. - cfg->section(SECTION_VALIDATION_SEED) - .append(std::vector{seed.empty() ? defaultseed : seed}); + cfg->section(SECTION_VALIDATION_SEED).append(std::vector{seed.empty() ? defaultseed : seed}); return cfg; } @@ -108,9 +107,7 @@ addGrpcConfig(std::unique_ptr cfg) } std::unique_ptr -addGrpcConfigWithSecureGateway( - std::unique_ptr cfg, - std::string const& secureGateway) +addGrpcConfigWithSecureGateway(std::unique_ptr cfg, std::string const& secureGateway) { (*cfg)[SECTION_PORT_GRPC].set("ip", getEnvLocalhostAddr()); @@ -122,9 +119,7 @@ addGrpcConfigWithSecureGateway( } std::unique_ptr -makeConfig( - std::map extraTxQ, - std::map extraVoting) +makeConfig(std::map extraTxQ, std::map extraVoting) { auto p = test::jtx::envconfig(); auto& section = p->section("transaction_queue"); diff --git a/src/test/jtx/impl/mpt.cpp b/src/test/jtx/impl/mpt.cpp index ceb60eb319..f505bff740 100644 --- a/src/test/jtx/impl/mpt.cpp +++ b/src/test/jtx/impl/mpt.cpp @@ -39,10 +39,7 @@ MPTTester::makeHolders(std::vector const& holders) } MPTTester::MPTTester(Env& env, Account const& issuer, MPTInit const& arg) - : env_(env) - , issuer_(issuer) - , holders_(makeHolders(arg.holders)) - , close_(arg.close) + : env_(env), issuer_(issuer), holders_(makeHolders(arg.holders)), close_(arg.close) { if (arg.fund) { @@ -66,17 +63,8 @@ MPTTester::MPTTester(Env& env, Account const& issuer, MPTInit const& arg) create(*arg.create); } -MPTTester::MPTTester( - Env& env, - Account const& issuer, - MPTID const& id, - std::vector const& holders, - bool close) - : env_(env) - , issuer_(issuer) - , holders_(makeHolders(holders)) - , id_(id) - , close_(close) +MPTTester::MPTTester(Env& env, Account const& issuer, MPTID const& id, std::vector const& holders, bool close) + : env_(env), issuer_(issuer), holders_(makeHolders(holders)), id_(id), close_(close) { } @@ -99,13 +87,7 @@ makeMPTCreate(MPTInitDef const& arg) } MPTTester::MPTTester(MPTInitDef const& arg) - : MPTTester{ - arg.env, - arg.issuer, - MPTInit{ - .fund = arg.fund, - .close = arg.close, - .create = makeMPTCreate(arg)}} + : MPTTester{arg.env, arg.issuer, MPTInit{.fund = arg.fund, .close = arg.close, .create = makeMPTCreate(arg)}} { } @@ -117,10 +99,10 @@ MPTTester::operator MPT() const } Json::Value -MPTTester::createjv(MPTCreate const& arg) +MPTTester::createJV(MPTCreate const& arg) { if (!arg.issuer) - Throw("MPTTester::createjv: issuer is not set"); + Throw("MPTTester::createJV: issuer is not set"); Json::Value jv; jv[sfAccount] = arg.issuer->human(); if (arg.assetScale) @@ -146,7 +128,7 @@ MPTTester::create(MPTCreate const& arg) if (id_) Throw("MPT can't be reused"); id_ = makeMptID(env_.seq(issuer_), issuer_); - Json::Value jv = createjv( + Json::Value jv = createJV( {.issuer = issuer_, .maxAmt = arg.maxAmt, .assetScale = arg.assetScale, @@ -157,9 +139,7 @@ MPTTester::create(MPTCreate const& arg) if (submit(arg, jv) != tesSUCCESS) { // Verify issuance doesn't exist - env_.require(requireAny([&]() -> bool { - return env_.le(keylet::mptIssuance(*id_)) == nullptr; - })); + env_.require(requireAny([&]() -> bool { return env_.le(keylet::mptIssuance(*id_)) == nullptr; })); id_.reset(); } @@ -170,8 +150,7 @@ MPTTester::create(MPTCreate const& arg) for (auto const& it : accts) { authorize({.account = getAcct(it)}); - if ((arg.flags.value_or(0) & tfMPTRequireAuth) && - arg.authHolder) + if ((arg.flags.value_or(0) & tfMPTRequireAuth) && arg.authHolder) authorize({.account = issuer_, .holder = getAcct(it)}); if (arg.pay && arg.pay->first.empty()) pay(issuer_, getAcct(it), arg.pay->second); @@ -200,11 +179,11 @@ MPTTester::create(MPTCreate const& arg) } Json::Value -MPTTester::destroyjv(MPTDestroy const& arg) +MPTTester::destroyJV(MPTDestroy const& arg) { Json::Value jv; if (!arg.issuer || !arg.id) - Throw("MPTTester::destroyjv: issuer/id is not set"); + Throw("MPTTester::destroyJV: issuer/id is not set"); jv[sfAccount] = arg.issuer->human(); jv[sfMPTokenIssuanceID] = to_string(*arg.id); jv[sfTransactionType] = jss::MPTokenIssuanceDestroy; @@ -217,9 +196,7 @@ MPTTester::destroy(MPTDestroy const& arg) { if (!arg.id && !id_) Throw("MPT has not been created"); - Json::Value jv = destroyjv( - {.issuer = arg.issuer ? arg.issuer : issuer_, - .id = arg.id ? arg.id : id_}); + Json::Value jv = destroyJV({.issuer = arg.issuer ? arg.issuer : issuer_, .id = arg.id ? arg.id : id_}); submit(arg, jv); } @@ -233,12 +210,11 @@ MPTTester::holder(std::string const& holder_) const } Json::Value -MPTTester::authorizejv(MPTAuthorize const& arg) +MPTTester::authorizeJV(MPTAuthorize const& arg) { Json::Value jv; if (!arg.account || !arg.id) - Throw( - "MPTTester::authorizejv: issuer/id is not set"); + Throw("MPTTester::authorizeJV: account/id is not set"); jv[sfAccount] = arg.account->human(); jv[sfMPTokenIssuanceID] = to_string(*arg.id); if (arg.holder) @@ -253,7 +229,7 @@ MPTTester::authorize(MPTAuthorize const& arg) { if (!arg.id && !id_) Throw("MPT has not been created"); - Json::Value jv = authorizejv({ + Json::Value jv = authorizeJV({ .account = arg.account ? arg.account : issuer_, .holder = arg.holder, .id = arg.id ? arg.id : id_, @@ -269,8 +245,7 @@ MPTTester::authorize(MPTAuthorize const& arg) env_.require(mptflags(*this, flags, arg.holder)); // issuer authorizes the holder else - env_.require( - mptflags(*this, flags | lsfMPTAuthorized, arg.holder)); + env_.require(mptflags(*this, flags | lsfMPTAuthorized, arg.holder)); } // Holder authorizes else if (arg.flags.value_or(0) != tfMPTUnauthorize) @@ -283,31 +258,23 @@ MPTTester::authorize(MPTAuthorize const& arg) else { // Verify that the MPToken doesn't exist. - forObject( - [&](SLEP const& sle) { return env_.test.BEAST_EXPECT(!sle); }, - arg.account); + forObject([&](SLEP const& sle) { return env_.test.BEAST_EXPECT(!sle); }, arg.account); } } - else if ( - arg.account && *arg.account != issuer_ && - arg.flags.value_or(0) != tfMPTUnauthorize && id_) + else if (arg.account && *arg.account != issuer_ && arg.flags.value_or(0) != tfMPTUnauthorize && id_) { if (result == tecDUPLICATE) { // Verify that MPToken already exists - env_.require(requireAny([&]() -> bool { - return env_.le(keylet::mptoken(*id_, arg.account->id())) != - nullptr; - })); + env_.require( + requireAny([&]() -> bool { return env_.le(keylet::mptoken(*id_, arg.account->id())) != nullptr; })); } else { // Verify MPToken doesn't exist if holder failed authorizing(unless // it already exists) - env_.require(requireAny([&]() -> bool { - return env_.le(keylet::mptoken(*id_, arg.account->id())) == - nullptr; - })); + env_.require( + requireAny([&]() -> bool { return env_.le(keylet::mptoken(*id_, arg.account->id())) == nullptr; })); } } } @@ -322,11 +289,11 @@ MPTTester::authorizeHolders(Holders const& holders) } Json::Value -MPTTester::setjv(MPTSet const& arg) +MPTTester::setJV(MPTSet const& arg) { Json::Value jv; if (!arg.account || !arg.id) - Throw("MPTTester::setjv: issuer/id is not set"); + Throw("MPTTester::setJV: account and/or id is not set"); jv[sfAccount] = arg.account->human(); jv[sfMPTokenIssuanceID] = to_string(*arg.id); if (arg.holder) @@ -361,7 +328,7 @@ MPTTester::set(MPTSet const& arg) { if (!arg.id && !id_) Throw("MPT has not been created"); - Json::Value jv = setjv( + Json::Value jv = setJV( {.account = arg.account ? arg.account : issuer_, .holder = arg.holder, .id = arg.id ? arg.id : id_, @@ -370,11 +337,9 @@ MPTTester::set(MPTSet const& arg) .metadata = arg.metadata, .delegate = arg.delegate, .domainID = arg.domainID}); - if (submit(arg, jv) == tesSUCCESS && - (arg.flags.value_or(0) || arg.mutableFlags)) + if (submit(arg, jv) == tesSUCCESS && (arg.flags.value_or(0) || arg.mutableFlags)) { - auto require = [&](std::optional const& holder, - bool unchanged) { + auto require = [&](std::optional const& holder, bool unchanged) { auto flags = getFlags(holder); if (!unchanged) { @@ -423,21 +388,17 @@ MPTTester::set(MPTSet const& arg) }; if (arg.account) require(std::nullopt, arg.holder.has_value()); - if (auto const account = - (arg.holder ? std::get_if(&(*arg.holder)) : nullptr)) + if (auto const account = (arg.holder ? std::get_if(&(*arg.holder)) : nullptr)) require(*account, false); } } bool -MPTTester::forObject( - std::function const& cb, - std::optional const& holder_) const +MPTTester::forObject(std::function const& cb, std::optional const& holder_) const { if (!id_) Throw("MPT has not been created"); - auto const key = holder_ ? keylet::mptoken(*id_, holder_->id()) - : keylet::mptIssuance(*id_); + auto const key = holder_ ? keylet::mptoken(*id_, holder_->id()) : keylet::mptIssuance(*id_); if (auto const sle = env_.le(key)) return cb(sle); return false; @@ -454,27 +415,19 @@ MPTTester::checkDomainID(std::optional expected) const } [[nodiscard]] bool -MPTTester::checkMPTokenAmount( - Account const& holder_, - std::int64_t expectedAmount) const +MPTTester::checkMPTokenAmount(Account const& holder_, std::int64_t expectedAmount) const { - return forObject( - [&](SLEP const& sle) { return expectedAmount == (*sle)[sfMPTAmount]; }, - holder_); + return forObject([&](SLEP const& sle) { return expectedAmount == (*sle)[sfMPTAmount]; }, holder_); } [[nodiscard]] bool MPTTester::checkMPTokenOutstandingAmount(std::int64_t expectedAmount) const { - return forObject([&](SLEP const& sle) { - return expectedAmount == (*sle)[sfOutstandingAmount]; - }); + return forObject([&](SLEP const& sle) { return expectedAmount == (*sle)[sfOutstandingAmount]; }); } [[nodiscard]] bool -MPTTester::checkFlags( - uint32_t const expectedFlags, - std::optional const& holder) const +MPTTester::checkFlags(uint32_t const expectedFlags, std::optional const& holder) const { return expectedFlags == getFlags(holder); } @@ -484,8 +437,7 @@ MPTTester::checkMetadata(std::string const& metadata) const { return forObject([&](SLEP const& sle) -> bool { if (sle->isFieldPresent(sfMPTokenMetadata)) - return strHex(sle->getFieldVL(sfMPTokenMetadata)) == - strHex(metadata); + return strHex(sle->getFieldVL(sfMPTokenMetadata)) == strHex(metadata); return false; }); } @@ -493,9 +445,7 @@ MPTTester::checkMetadata(std::string const& metadata) const [[nodiscard]] bool MPTTester::isMetadataPresent() const { - return forObject([&](SLEP const& sle) -> bool { - return sle->isFieldPresent(sfMPTokenMetadata); - }); + return forObject([&](SLEP const& sle) -> bool { return sle->isFieldPresent(sfMPTokenMetadata); }); } [[nodiscard]] bool @@ -511,9 +461,7 @@ MPTTester::checkTransferFee(std::uint16_t transferFee) const [[nodiscard]] bool MPTTester::isTransferFeePresent() const { - return forObject([&](SLEP const& sle) -> bool { - return sle->isFieldPresent(sfTransferFee); - }); + return forObject([&](SLEP const& sle) -> bool { return sle->isFieldPresent(sfTransferFee); }); } void @@ -528,13 +476,10 @@ MPTTester::pay( Throw("MPT has not been created"); auto const srcAmt = getBalance(src); auto const destAmt = getBalance(dest); - auto const outstnAmt = getBalance(issuer_); + auto const outstandingAmt = getBalance(issuer_); if (credentials) - env_( - jtx::pay(src, dest, mpt(amount)), - ter(err.value_or(tesSUCCESS)), - credentials::ids(*credentials)); + env_(jtx::pay(src, dest, mpt(amount)), ter(err.value_or(tesSUCCESS)), credentials::ids(*credentials)); else env_(jtx::pay(src, dest, mpt(amount)), ter(err.value_or(tesSUCCESS))); @@ -555,24 +500,17 @@ MPTTester::pay( else { STAmount const saAmount = {*id_, amount}; - auto const actual = - multiply(saAmount, transferRate(*env_.current(), *id_)) - .mpt() - .value(); + auto const actual = multiply(saAmount, transferRate(*env_.current(), *id_)).mpt().value(); // Sender pays the transfer fee if any env_.require(mptbalance(*this, src, srcAmt - actual)); env_.require(mptbalance(*this, dest, destAmt + amount)); // Outstanding amount is reduced by the transfer fee if any - env_.require(mptbalance(*this, issuer_, outstnAmt - (actual - amount))); + env_.require(mptbalance(*this, issuer_, outstandingAmt - (actual - amount))); } } void -MPTTester::claw( - Account const& issuer, - Account const& holder, - std::int64_t amount, - std::optional err) +MPTTester::claw(Account const& issuer, Account const& holder, std::int64_t amount, std::optional err) { if (!id_) Throw("MPT has not been created"); @@ -584,10 +522,8 @@ MPTTester::claw( if (close_) env_.close(); - env_.require( - mptbalance(*this, issuer, issuerAmt - std::min(holderAmt, amount))); - env_.require( - mptbalance(*this, holder, holderAmt - std::min(holderAmt, amount))); + env_.require(mptbalance(*this, issuer, issuerAmt - std::min(holderAmt, amount))); + env_.require(mptbalance(*this, holder, holderAmt - std::min(holderAmt, amount))); } PrettyAmount diff --git a/src/test/jtx/impl/multisign.cpp b/src/test/jtx/impl/multisign.cpp index 61af11fb3a..54bde3ebb9 100644 --- a/src/test/jtx/impl/multisign.cpp +++ b/src/test/jtx/impl/multisign.cpp @@ -12,10 +12,7 @@ namespace test { namespace jtx { Json::Value -signers( - Account const& account, - std::uint32_t quorum, - std::vector const& v) +signers(Account const& account, std::uint32_t quorum, std::vector const& v) { Json::Value jv; jv[jss::Account] = account.human(); @@ -78,10 +75,8 @@ msig::operator()(Env& env, JTx& jt) const jo[jss::SigningPubKey] = strHex(e.sig.pk().slice()); Serializer ss{buildMultiSigningData(*st, e.acct.id())}; - auto const sig = xrpl::sign( - *publicKeyType(e.sig.pk().slice()), e.sig.sk(), ss.slice()); - jo[sfTxnSignature.getJsonName()] = - strHex(Slice{sig.data(), sig.size()}); + auto const sig = xrpl::sign(*publicKeyType(e.sig.pk().slice()), e.sig.sk(), ss.slice()); + jo[sfTxnSignature.getJsonName()] = strHex(Slice{sig.data(), sig.size()}); } }; if (!subField) diff --git a/src/test/jtx/impl/offer.cpp b/src/test/jtx/impl/offer.cpp index 251b659f3b..bbcfbf07c1 100644 --- a/src/test/jtx/impl/offer.cpp +++ b/src/test/jtx/impl/offer.cpp @@ -7,11 +7,7 @@ namespace test { namespace jtx { Json::Value -offer( - Account const& account, - STAmount const& takerPays, - STAmount const& takerGets, - std::uint32_t flags) +offer(Account const& account, STAmount const& takerPays, STAmount const& takerGets, std::uint32_t flags) { Json::Value jv; jv[jss::Account] = account.human(); diff --git a/src/test/jtx/impl/owners.cpp b/src/test/jtx/impl/owners.cpp index ad449dab93..ee6efc171c 100644 --- a/src/test/jtx/impl/owners.cpp +++ b/src/test/jtx/impl/owners.cpp @@ -7,20 +7,15 @@ std::uint32_t owned_count_of(ReadView const& view, AccountID const& id, LedgerEntryType type) { std::uint32_t count = 0; - forEachItem( - view, id, [&count, type](std::shared_ptr const& sle) { - if (sle->getType() == type) - ++count; - }); + forEachItem(view, id, [&count, type](std::shared_ptr const& sle) { + if (sle->getType() == type) + ++count; + }); return count; } void -owned_count_helper( - test::jtx::Env& env, - AccountID const& id, - LedgerEntryType type, - std::uint32_t value) +owned_count_helper(test::jtx::Env& env, AccountID const& id, LedgerEntryType type, std::uint32_t value) { env.test.expect(owned_count_of(*env.current(), id, type) == value); } diff --git a/src/test/jtx/impl/paths.cpp b/src/test/jtx/impl/paths.cpp index fd93ebd841..e26f214fe4 100644 --- a/src/test/jtx/impl/paths.cpp +++ b/src/test/jtx/impl/paths.cpp @@ -30,8 +30,7 @@ paths::operator()(Env& env, JTx& jt) const } Pathfinder pf( - std::make_shared( - env.current(), env.app().journal("RippleLineCache")), + std::make_shared(env.current(), env.app().journal("RippleLineCache")), from, to, in_.currency, diff --git a/src/test/jtx/impl/permissioned_domains.cpp b/src/test/jtx/impl/permissioned_domains.cpp index aac9dcc05f..fb802cf084 100644 --- a/src/test/jtx/impl/permissioned_domains.cpp +++ b/src/test/jtx/impl/permissioned_domains.cpp @@ -8,10 +8,7 @@ namespace pdomain { // helpers // Make json for PermissionedDomainSet transaction Json::Value -setTx( - AccountID const& account, - Credentials const& credentials, - std::optional domain) +setTx(AccountID const& account, Credentials const& credentials, std::optional domain) { Json::Value jv; jv[sfTransactionType] = jss::PermissionedDomainSet; @@ -62,8 +59,7 @@ getObjects(Account const& account, Env& env, bool withType) if (withType) { // impossible to get there Throw( - "Invalid object type: " + - object["LedgerEntryType"].asString()); // LCOV_EXCL_LINE + "Invalid object type: " + object["LedgerEntryType"].asString()); // LCOV_EXCL_LINE } continue; } @@ -83,8 +79,7 @@ objectExists(uint256 const& objID, Env& env) Json::Value params; params[jss::index] = to_string(objID); - auto const result = - env.rpc("json", "ledger_entry", to_string(params))["result"]; + auto const result = env.rpc("json", "ledger_entry", to_string(params))["result"]; if ((result["status"] == "error") && (result["error"] == "entryNotFound")) return false; @@ -100,9 +95,7 @@ objectExists(uint256 const& objID, Env& env) // Extract credentials from account_object object Credentials -credentialsFromJson( - Json::Value const& object, - std::unordered_map const& human2Acc) +credentialsFromJson(Json::Value const& object, std::unordered_map const& human2Acc) { Credentials ret; Json::Value credentials(Json::arrayValue); @@ -114,9 +107,7 @@ credentialsFromJson( auto const& issuer = obj[jss::Issuer]; auto const& credentialType = obj["CredentialType"]; auto blob = strUnHex(credentialType.asString()).value(); - ret.push_back( - {human2Acc.at(issuer.asString()), - std::string(blob.begin(), blob.end())}); + ret.push_back({human2Acc.at(issuer.asString()), std::string(blob.begin(), blob.end())}); } return ret; } @@ -142,13 +133,11 @@ getNewDomain(std::shared_ptr const& meta) for (auto const& node : a) { - if (!node.isMember("CreatedNode") || - node["CreatedNode"]["LedgerEntryType"] != "PermissionedDomain") + if (!node.isMember("CreatedNode") || node["CreatedNode"]["LedgerEntryType"] != "PermissionedDomain") { continue; } - std::ignore = - ret.parseHex(node["CreatedNode"]["LedgerIndex"].asString()); + std::ignore = ret.parseHex(node["CreatedNode"]["LedgerIndex"].asString()); break; } diff --git a/src/test/jtx/impl/quality2.cpp b/src/test/jtx/impl/quality2.cpp index c202592b9d..bbd0cff319 100644 --- a/src/test/jtx/impl/quality2.cpp +++ b/src/test/jtx/impl/quality2.cpp @@ -7,14 +7,12 @@ namespace xrpl { namespace test { namespace jtx { -qualityInPercent::qualityInPercent(double percent) - : qIn_(static_cast((percent / 100) * QUALITY_ONE)) +qualityInPercent::qualityInPercent(double percent) : qIn_(static_cast((percent / 100) * QUALITY_ONE)) { assert(percent <= 400 && percent >= 0); } -qualityOutPercent::qualityOutPercent(double percent) - : qOut_(static_cast((percent / 100) * QUALITY_ONE)) +qualityOutPercent::qualityOutPercent(double percent) : qOut_(static_cast((percent / 100) * QUALITY_ONE)) { assert(percent <= 400 && percent >= 0); } diff --git a/src/test/jtx/impl/token.cpp b/src/test/jtx/impl/token.cpp index f74b66f9ae..172bd75bc7 100644 --- a/src/test/jtx/impl/token.cpp +++ b/src/test/jtx/impl/token.cpp @@ -54,8 +54,7 @@ getNextID( std::uint16_t xferFee) { // Get the nftSeq from the account root of the issuer. - std::uint32_t const nftSeq = { - env.le(issuer)->at(~sfMintedNFTokens).value_or(0)}; + std::uint32_t const nftSeq = {env.le(issuer)->at(~sfMintedNFTokens).value_or(0)}; return token::getID(env, issuer, nfTokenTaxon, nftSeq, flags, xferFee); } @@ -70,10 +69,8 @@ getID( { // We must add issuer's FirstNFTokenSequence to offset the starting NFT // sequence number. - nftSeq += - env.le(issuer)->at(~sfFirstNFTokenSequence).value_or(env.seq(issuer)); - return xrpl::NFTokenMint::createNFTokenID( - flags, xferFee, issuer, nft::toTaxon(nfTokenTaxon), nftSeq); + nftSeq += env.le(issuer)->at(~sfFirstNFTokenSequence).value_or(env.seq(issuer)); + return xrpl::NFTokenMint::createNFTokenID(flags, xferFee, issuer, nft::toTaxon(nfTokenTaxon), nftSeq); } Json::Value @@ -87,10 +84,7 @@ burn(jtx::Account const& account, uint256 const& nftokenID) } Json::Value -createOffer( - jtx::Account const& account, - uint256 const& nftokenID, - STAmount const& amount) +createOffer(jtx::Account const& account, uint256 const& nftokenID, STAmount const& amount) { Json::Value jv; jv[sfAccount.jsonName] = account.human(); @@ -135,17 +129,13 @@ cancelOfferImpl(jtx::Account const& account, T const& nftokenOffers) } Json::Value -cancelOffer( - jtx::Account const& account, - std::initializer_list const& nftokenOffers) +cancelOffer(jtx::Account const& account, std::initializer_list const& nftokenOffers) { return cancelOfferImpl(account, nftokenOffers); } Json::Value -cancelOffer( - jtx::Account const& account, - std::vector const& nftokenOffers) +cancelOffer(jtx::Account const& account, std::vector const& nftokenOffers) { return cancelOfferImpl(account, nftokenOffers); } @@ -177,10 +167,7 @@ acceptSellOffer(jtx::Account const& account, uint256 const& offerIndex) } Json::Value -brokerOffers( - jtx::Account const& account, - uint256 const& buyOfferIndex, - uint256 const& sellOfferIndex) +brokerOffers(jtx::Account const& account, uint256 const& buyOfferIndex, uint256 const& sellOfferIndex) { Json::Value jv; jv[sfAccount.jsonName] = account.human(); diff --git a/src/test/jtx/impl/trust.cpp b/src/test/jtx/impl/trust.cpp index a553efa7f2..08cd4ef94c 100644 --- a/src/test/jtx/impl/trust.cpp +++ b/src/test/jtx/impl/trust.cpp @@ -27,11 +27,7 @@ trust(Account const& account, STAmount const& amount, std::uint32_t flags) // authorises peer (third function parameter) to hold a certain currency // (amount, the second function parameter) Json::Value -trust( - Account const& account, - STAmount const& amount, - Account const& peer, - std::uint32_t flags) +trust(Account const& account, STAmount const& amount, Account const& peer, std::uint32_t flags) { if (isXRP(amount)) Throw("trust() requires IOU"); @@ -47,10 +43,7 @@ trust( } Json::Value -claw( - Account const& account, - STAmount const& amount, - std::optional const& mptHolder) +claw(Account const& account, STAmount const& amount, std::optional const& mptHolder) { Json::Value jv; jv[jss::Account] = account.human(); diff --git a/src/test/jtx/impl/utility.cpp b/src/test/jtx/impl/utility.cpp index 920e715c16..7332358031 100644 --- a/src/test/jtx/impl/utility.cpp +++ b/src/test/jtx/impl/utility.cpp @@ -63,10 +63,7 @@ fill_seq(Json::Value& jv, ReadView const& view) } Json::Value -cmdToJSONRPC( - std::vector const& args, - beast::Journal j, - unsigned int apiVersion) +cmdToJSONRPC(std::vector const& args, beast::Journal j, unsigned int apiVersion) { Json::Value jv = Json::Value(Json::objectValue); auto const paramsObj = rpcCmdToJson(args, jv, apiVersion, j); @@ -75,9 +72,7 @@ cmdToJSONRPC( jv.clear(); // Allow parser to rewrite method. - jv[jss::method] = paramsObj.isMember(jss::method) - ? paramsObj[jss::method].asString() - : args[0]; + jv[jss::method] = paramsObj.isMember(jss::method) ? paramsObj[jss::method].asString() : args[0]; // If paramsObj is not empty, put it in a [params] array. if (paramsObj.begin() != paramsObj.end()) diff --git a/src/test/jtx/impl/xchain_bridge.cpp b/src/test/jtx/impl/xchain_bridge.cpp index cc6be6c737..0f78ed3029 100644 --- a/src/test/jtx/impl/xchain_bridge.cpp +++ b/src/test/jtx/impl/xchain_bridge.cpp @@ -61,8 +61,7 @@ bridge_create( jv[sfXChainBridge.getJsonName()] = bridge; jv[sfSignatureReward.getJsonName()] = reward.getJson(JsonOptions::none); if (minAccountCreate) - jv[sfMinAccountCreateAmount.getJsonName()] = - minAccountCreate->getJson(JsonOptions::none); + jv[sfMinAccountCreateAmount.getJsonName()] = minAccountCreate->getJson(JsonOptions::none); jv[jss::TransactionType] = jss::XChainCreateBridge; return jv; @@ -80,11 +79,9 @@ bridge_modify( jv[jss::Account] = acc.human(); jv[sfXChainBridge.getJsonName()] = bridge; if (reward) - jv[sfSignatureReward.getJsonName()] = - reward->getJson(JsonOptions::none); + jv[sfSignatureReward.getJsonName()] = reward->getJson(JsonOptions::none); if (minAccountCreate) - jv[sfMinAccountCreateAmount.getJsonName()] = - minAccountCreate->getJson(JsonOptions::none); + jv[sfMinAccountCreateAmount.getJsonName()] = minAccountCreate->getJson(JsonOptions::none); jv[jss::TransactionType] = jss::XChainModifyBridge; return jv; @@ -163,8 +160,7 @@ sidechain_xchain_account_create( jv[sfXChainBridge.getJsonName()] = bridge; jv[sfDestination.getJsonName()] = dst.human(); jv[sfAmount.getJsonName()] = amt.value.getJson(JsonOptions::none); - jv[sfSignatureReward.getJsonName()] = - reward.value.getJson(JsonOptions::none); + jv[sfSignatureReward.getJsonName()] = reward.value.getJson(JsonOptions::none); jv[jss::TransactionType] = jss::XChainAccountCreateCommit; return jv; @@ -187,15 +183,7 @@ claim_attestation( auto const& pk = signer.account.pk(); auto const& sk = signer.account.sk(); auto const sig = sign_claim_attestation( - pk, - sk, - stBridge, - sendingAccount, - sendingAmount.value, - rewardAccount, - wasLockingChainSend, - claimID, - dst); + pk, sk, stBridge, sendingAccount, sendingAmount.value, rewardAccount, wasLockingChainSend, claimID, dst); Json::Value result; @@ -206,13 +194,11 @@ claim_attestation( result[sfPublicKey.getJsonName()] = strHex(pk.slice()); result[sfSignature.getJsonName()] = strHex(sig); result[sfOtherChainSource.getJsonName()] = toBase58(sendingAccount); - result[sfAmount.getJsonName()] = - sendingAmount.value.getJson(JsonOptions::none); + result[sfAmount.getJsonName()] = sendingAmount.value.getJson(JsonOptions::none); result[sfAttestationRewardAccount.getJsonName()] = toBase58(rewardAccount); result[sfWasLockingChainSend.getJsonName()] = wasLockingChainSend ? 1 : 0; - result[sfXChainClaimID.getJsonName()] = - STUInt64{claimID}.getJson(JsonOptions::none); + result[sfXChainClaimID.getJsonName()] = STUInt64{claimID}.getJson(JsonOptions::none); if (dst) result[sfDestination.getJsonName()] = toBase58(*dst); @@ -259,16 +245,13 @@ create_account_attestation( result[sfPublicKey.getJsonName()] = strHex(pk.slice()); result[sfSignature.getJsonName()] = strHex(sig); result[sfOtherChainSource.getJsonName()] = toBase58(sendingAccount); - result[sfAmount.getJsonName()] = - sendingAmount.value.getJson(JsonOptions::none); + result[sfAmount.getJsonName()] = sendingAmount.value.getJson(JsonOptions::none); result[sfAttestationRewardAccount.getJsonName()] = toBase58(rewardAccount); result[sfWasLockingChainSend.getJsonName()] = wasLockingChainSend ? 1 : 0; - result[sfXChainAccountCreateCount.getJsonName()] = - STUInt64{createCount}.getJson(JsonOptions::none); + result[sfXChainAccountCreateCount.getJsonName()] = STUInt64{createCount}.getJson(JsonOptions::none); result[sfDestination.getJsonName()] = toBase58(dst); - result[sfSignatureReward.getJsonName()] = - rewardAmount.value.getJson(JsonOptions::none); + result[sfSignatureReward.getJsonName()] = rewardAmount.value.getJson(JsonOptions::none); result[jss::TransactionType] = jss::XChainAddAccountCreateAttestation; @@ -366,8 +349,7 @@ XChainBridgeObjects::XChainBridgeObjects() , scuGw("scuGw") , mcUSD(mcGw["USD"]) , scUSD(scGw["USD"]) - , jvXRPBridgeRPC( - bridge_rpc(mcDoor, xrpIssue(), Account::master, xrpIssue())) + , jvXRPBridgeRPC(bridge_rpc(mcDoor, xrpIssue(), Account::master, xrpIssue())) , jvb(bridge(mcDoor, xrpIssue(), Account::master, xrpIssue())) , jvub(bridge(mcuDoor, xrpIssue(), Account::master, xrpIssue())) , features(testable_amendments() | FeatureBitset{featureXChainBridge}) @@ -378,9 +360,7 @@ XChainBridgeObjects::XChainBridgeObjects() for (int i = 0; i < numSigners; ++i) { using namespace std::literals; - auto const a = Account( - "signer_"s + std::to_string(i), - (i % 2) ? KeyType::ed25519 : KeyType::secp256k1); + auto const a = Account("signer_"s + std::to_string(i), (i % 2) ? KeyType::ed25519 : KeyType::secp256k1); result.emplace_back(a); } return result; @@ -392,9 +372,7 @@ XChainBridgeObjects::XChainBridgeObjects() for (int i = 0; i < numSigners; ++i) { using namespace std::literals; - auto const a = Account( - "alt_signer_"s + std::to_string(i), - (i % 2) ? KeyType::ed25519 : KeyType::secp256k1); + auto const a = Account("alt_signer_"s + std::to_string(i), (i % 2) ? KeyType::ed25519 : KeyType::secp256k1); result.emplace_back(a); } return result; @@ -421,23 +399,12 @@ XChainBridgeObjects::XChainBridgeObjects() }()) , quorum(UT_XCHAIN_DEFAULT_QUORUM) , reward(XRP(1)) - , split_reward_quorum( - divide(reward, STAmount(UT_XCHAIN_DEFAULT_QUORUM), reward.issue())) - , split_reward_everyone(divide( - reward, - STAmount(UT_XCHAIN_DEFAULT_NUM_SIGNERS), - reward.issue())) + , split_reward_quorum(divide(reward, STAmount(UT_XCHAIN_DEFAULT_QUORUM), reward.issue())) + , split_reward_everyone(divide(reward, STAmount(UT_XCHAIN_DEFAULT_NUM_SIGNERS), reward.issue())) , tiny_reward(drops(37)) - , tiny_reward_split((divide( - tiny_reward, - STAmount(UT_XCHAIN_DEFAULT_QUORUM), - tiny_reward.issue()))) + , tiny_reward_split((divide(tiny_reward, STAmount(UT_XCHAIN_DEFAULT_QUORUM), tiny_reward.issue()))) , tiny_reward_remainder( - tiny_reward - - multiply( - tiny_reward_split, - STAmount(UT_XCHAIN_DEFAULT_QUORUM), - tiny_reward.issue())) + tiny_reward - multiply(tiny_reward_split, STAmount(UT_XCHAIN_DEFAULT_QUORUM), tiny_reward.issue())) , one_xrp(XRP(1)) , xrp_dust(divide(one_xrp, STAmount(10000), one_xrp.issue())) { @@ -464,8 +431,7 @@ void XChainBridgeObjects::createScBridgeObjects(Env& scEnv) { STAmount xrp_funds{XRP(10000)}; - scEnv.fund( - xrp_funds, scDoor, scAlice, scBob, scCarol, scGw, scAttester, scReward); + scEnv.fund(xrp_funds, scDoor, scAlice, scBob, scCarol, scGw, scAttester, scReward); // Signer's list must match the attestation signers scEnv(jtx::signers(Account::master, signers.size(), signers)); diff --git a/src/test/jtx/invoice_id.h b/src/test/jtx/invoice_id.h index bdf1aa4250..fd1b7ae45b 100644 --- a/src/test/jtx/invoice_id.h +++ b/src/test/jtx/invoice_id.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_INVOICE_ID_H_INCLUDED -#define XRPL_TEST_JTX_INVOICE_ID_H_INCLUDED +#pragma once #include @@ -23,4 +22,3 @@ public: } // namespace jtx } // namespace test } // namespace xrpl -#endif diff --git a/src/test/jtx/jtx_json.h b/src/test/jtx/jtx_json.h index 32fd3c8d30..c7f52fe283 100644 --- a/src/test/jtx/jtx_json.h +++ b/src/test/jtx/jtx_json.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_JSON_H_INCLUDED -#define XRPL_TEST_JTX_JSON_H_INCLUDED +#pragma once #include @@ -41,5 +40,3 @@ public: } // namespace jtx } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/last_ledger_sequence.h b/src/test/jtx/last_ledger_sequence.h index 6544294bd6..540d6ff384 100644 --- a/src/test/jtx/last_ledger_sequence.h +++ b/src/test/jtx/last_ledger_sequence.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_LAST_LEDGER_SEQUENCE_H_INCLUDED -#define XRPL_TEST_JTX_LAST_LEDGER_SEQUENCE_H_INCLUDED +#pragma once #include @@ -24,5 +23,3 @@ public: } // namespace jtx } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/ledgerStateFix.h b/src/test/jtx/ledgerStateFix.h index f93c1bc3d8..7adc863cb4 100644 --- a/src/test/jtx/ledgerStateFix.h +++ b/src/test/jtx/ledgerStateFix.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_LEDGER_STATE_FIX_H_INCLUDED -#define XRPL_TEST_JTX_LEDGER_STATE_FIX_H_INCLUDED +#pragma once #include #include @@ -21,5 +20,3 @@ nftPageLinks(jtx::Account const& acct, jtx::Account const& owner); } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/memo.h b/src/test/jtx/memo.h index 2506f063fc..2371490b30 100644 --- a/src/test/jtx/memo.h +++ b/src/test/jtx/memo.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_MEMO_H_INCLUDED -#define XRPL_TEST_JTX_MEMO_H_INCLUDED +#pragma once #include @@ -20,10 +19,7 @@ private: std::string type_; public: - memo( - std::string const& data, - std::string const& format, - std::string const& type) + memo(std::string const& data, std::string const& format, std::string const& type) : data_(data), format_(format), type_(type) { } @@ -77,5 +73,3 @@ public: } // namespace jtx } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/mpt.h b/src/test/jtx/mpt.h index 3eea362b58..510248240d 100644 --- a/src/test/jtx/mpt.h +++ b/src/test/jtx/mpt.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_MPT_H_INCLUDED -#define XRPL_TEST_JTX_MPT_H_INCLUDED +#pragma once #include #include @@ -25,10 +24,7 @@ private: std::optional holder_; public: - mptflags( - MPTTester& tester, - std::uint32_t flags, - std::optional const& holder = std::nullopt) + mptflags(MPTTester& tester, std::uint32_t flags, std::optional const& holder = std::nullopt) : tester_(tester), flags_(flags), holder_(holder) { } @@ -86,8 +82,7 @@ struct MPTCreate std::optional> authorize = std::nullopt; // pay if seated. if authorize is not seated then authorize. // if empty vector then pay to either authorize or all holders. - std::optional, std::uint64_t>> pay = - std::nullopt; + std::optional, std::uint64_t>> pay = std::nullopt; std::optional flags = {0}; std::optional mutableFlags = std::nullopt; bool authHolder = false; @@ -182,19 +177,19 @@ public: create(MPTCreate const& arg = MPTCreate{}); static Json::Value - createjv(MPTCreate const& arg = MPTCreate{}); + createJV(MPTCreate const& arg = MPTCreate{}); void destroy(MPTDestroy const& arg = MPTDestroy{}); static Json::Value - destroyjv(MPTDestroy const& arg = MPTDestroy{}); + destroyJV(MPTDestroy const& arg = MPTDestroy{}); void authorize(MPTAuthorize const& arg = MPTAuthorize{}); static Json::Value - authorizejv(MPTAuthorize const& arg = MPTAuthorize{}); + authorizeJV(MPTAuthorize const& arg = MPTAuthorize{}); void authorizeHolders(Holders const& holders); @@ -203,22 +198,19 @@ public: set(MPTSet const& set = {}); static Json::Value - setjv(MPTSet const& set = {}); + setJV(MPTSet const& set = {}); [[nodiscard]] bool checkDomainID(std::optional expected) const; [[nodiscard]] bool - checkMPTokenAmount(Account const& holder, std::int64_t expectedAmount) - const; + checkMPTokenAmount(Account const& holder, std::int64_t expectedAmount) const; [[nodiscard]] bool checkMPTokenOutstandingAmount(std::int64_t expectedAmount) const; [[nodiscard]] bool - checkFlags( - uint32_t const expectedFlags, - std::optional const& holder = std::nullopt) const; + checkFlags(uint32_t const expectedFlags, std::optional const& holder = std::nullopt) const; [[nodiscard]] bool checkMetadata(std::string const& metadata) const; @@ -248,11 +240,7 @@ public: std::optional> credentials = std::nullopt); void - claw( - Account const& issuer, - Account const& holder, - std::int64_t amount, - std::optional err = std::nullopt); + claw(Account const& issuer, Account const& holder, std::int64_t amount, std::optional err = std::nullopt); PrettyAmount mpt(std::int64_t amount) const; @@ -279,18 +267,14 @@ public: private: using SLEP = SLE::const_pointer; bool - forObject( - std::function const& cb, - std::optional const& holder = std::nullopt) const; + forObject(std::function const& cb, std::optional const& holder = std::nullopt) + const; template TER submit(A const& arg, Json::Value const& jv) { - env_( - jv, - txflags(arg.flags.value_or(0)), - ter(arg.err.value_or(tesSUCCESS))); + env_(jv, txflags(arg.flags.value_or(0)), ter(arg.err.value_or(tesSUCCESS))); auto const err = env_.ter(); if (close_) env_.close(); @@ -314,5 +298,3 @@ private: } // namespace jtx } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/multisign.h b/src/test/jtx/multisign.h index 8582b27a77..3bbf43bb05 100644 --- a/src/test/jtx/multisign.h +++ b/src/test/jtx/multisign.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_MULTISIGN_H_INCLUDED -#define XRPL_TEST_JTX_MULTISIGN_H_INCLUDED +#pragma once #include #include @@ -22,20 +21,14 @@ struct signer Account account; std::optional tag; - signer( - Account account_, - std::uint32_t weight_ = 1, - std::optional tag_ = std::nullopt) + signer(Account account_, std::uint32_t weight_ = 1, std::optional tag_ = std::nullopt) : weight(weight_), account(std::move(account_)), tag(std::move(tag_)) { } }; Json::Value -signers( - Account const& account, - std::uint32_t quorum, - std::vector const& v); +signers(Account const& account, std::uint32_t quorum, std::vector const& v); /** Remove a signer list. */ Json::Value @@ -57,14 +50,12 @@ public: /// a subfield. static constexpr SField* const topLevel = nullptr; - msig(SField const* subField_, std::vector signers_) - : signers(std::move(signers_)), subField(subField_) + msig(SField const* subField_, std::vector signers_) : signers(std::move(signers_)), subField(subField_) { sortSigners(signers); } - msig(SField const& subField_, std::vector signers_) - : msig{&subField_, signers_} + msig(SField const& subField_, std::vector signers_) : msig{&subField_, signers_} { } @@ -75,35 +66,21 @@ public: template requires std::convertible_to explicit msig(SField const* subField_, AccountType&& a0, Accounts&&... aN) - : msig{ - subField_, - std::vector{ - std::forward(a0), - std::forward(aN)...}} + : msig{subField_, std::vector{std::forward(a0), std::forward(aN)...}} { } template requires std::convertible_to explicit msig(SField const& subField_, AccountType&& a0, Accounts&&... aN) - : msig{ - &subField_, - std::vector{ - std::forward(a0), - std::forward(aN)...}} + : msig{&subField_, std::vector{std::forward(a0), std::forward(aN)...}} { } template - requires( - std::convertible_to && - !std::is_same_v) + requires(std::convertible_to && !std::is_same_v) explicit msig(AccountType&& a0, Accounts&&... aN) - : msig{ - topLevel, - std::vector{ - std::forward(a0), - std::forward(aN)...}} + : msig{topLevel, std::vector{std::forward(a0), std::forward(aN)...}} { } @@ -119,5 +96,3 @@ using siglists = owner_count; } // namespace jtx } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/noop.h b/src/test/jtx/noop.h index 3ef3a57c4b..47d12fb9af 100644 --- a/src/test/jtx/noop.h +++ b/src/test/jtx/noop.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_NOOP_H_INCLUDED -#define XRPL_TEST_JTX_NOOP_H_INCLUDED +#pragma once #include @@ -17,5 +16,3 @@ noop(Account const& account) } // namespace jtx } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/offer.h b/src/test/jtx/offer.h index 8b01a9381b..dab15a4c8c 100644 --- a/src/test/jtx/offer.h +++ b/src/test/jtx/offer.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_OFFER_H_INCLUDED -#define XRPL_TEST_JTX_OFFER_H_INCLUDED +#pragma once #include @@ -12,11 +11,7 @@ namespace jtx { /** Create an offer. */ Json::Value -offer( - Account const& account, - STAmount const& takerPays, - STAmount const& takerGets, - std::uint32_t flags = 0); +offer(Account const& account, STAmount const& takerPays, STAmount const& takerGets, std::uint32_t flags = 0); /** Cancel an offer. */ Json::Value @@ -25,5 +20,3 @@ offer_cancel(Account const& account, std::uint32_t offerSeq); } // namespace jtx } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/owners.h b/src/test/jtx/owners.h index fabaa148e4..87fa26417a 100644 --- a/src/test/jtx/owners.h +++ b/src/test/jtx/owners.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_OWNERS_H_INCLUDED -#define XRPL_TEST_JTX_OWNERS_H_INCLUDED +#pragma once #include @@ -17,11 +16,7 @@ std::uint32_t owned_count_of(ReadView const& view, AccountID const& id, LedgerEntryType type); void -owned_count_helper( - test::jtx::Env& env, - AccountID const& id, - LedgerEntryType type, - std::uint32_t value); +owned_count_helper(test::jtx::Env& env, AccountID const& id, LedgerEntryType type, std::uint32_t value); } // namespace detail @@ -37,8 +32,7 @@ private: std::uint32_t value_; public: - owner_count(Account const& account, std::uint32_t value) - : account_(account), value_(value) + owner_count(Account const& account, std::uint32_t value) : account_(account), value_(value) { } @@ -57,8 +51,7 @@ private: std::uint32_t value_; public: - owners(Account const& account, std::uint32_t value) - : account_(account), value_(value) + owners(Account const& account, std::uint32_t value) : account_(account), value_(value) { } @@ -75,5 +68,3 @@ using offers = owner_count; } // namespace jtx } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/paths.h b/src/test/jtx/paths.h index b603db3f7b..c4e69fe3f3 100644 --- a/src/test/jtx/paths.h +++ b/src/test/jtx/paths.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_PATHS_H_INCLUDED -#define XRPL_TEST_JTX_PATHS_H_INCLUDED +#pragma once #include @@ -20,8 +19,7 @@ private: unsigned int limit_; public: - paths(Issue const& in, int depth = 7, unsigned int limit = 4) - : in_(in), depth_(depth), limit_(limit) + paths(Issue const& in, int depth = 7, unsigned int limit = 4) : in_(in), depth_(depth), limit_(limit) { } @@ -95,5 +93,3 @@ path::append(T const& t, Args const&... args) } // namespace jtx } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/pay.h b/src/test/jtx/pay.h index 4ef13d72a3..a155d7bdc8 100644 --- a/src/test/jtx/pay.h +++ b/src/test/jtx/pay.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_PAY_H_INCLUDED -#define XRPL_TEST_JTX_PAY_H_INCLUDED +#pragma once #include #include @@ -19,5 +18,3 @@ pay(Account const& account, Account const& to, AnyAmount amount); } // namespace jtx } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/permissioned_domains.h b/src/test/jtx/permissioned_domains.h index c0adacd0c5..ff8ab129ae 100644 --- a/src/test/jtx/permissioned_domains.h +++ b/src/test/jtx/permissioned_domains.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_PERMISSIONED_DOMAINS_H_INCLUDED -#define XRPL_TEST_JTX_PERMISSIONED_DOMAINS_H_INCLUDED +#pragma once #include #include @@ -17,10 +16,7 @@ using Credentials = std::vector; // helpers // Make json for PermissionedDomainSet transaction Json::Value -setTx( - AccountID const& account, - Credentials const& credentials, - std::optional domain = std::nullopt); +setTx(AccountID const& account, Credentials const& credentials, std::optional domain = std::nullopt); // Make json for PermissionedDomainDelete transaction Json::Value @@ -36,9 +32,7 @@ objectExists(uint256 const& objID, Env& env); // Extract credentials from account_object object Credentials -credentialsFromJson( - Json::Value const& object, - std::unordered_map const& human2Acc); +credentialsFromJson(Json::Value const& object, std::unordered_map const& human2Acc); // Sort credentials the same way as PermissionedDomainSet Credentials @@ -52,5 +46,3 @@ getNewDomain(std::shared_ptr const& meta); } // namespace jtx } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/prop.h b/src/test/jtx/prop.h index 3478e23d9b..b1f8cb5ffc 100644 --- a/src/test/jtx/prop.h +++ b/src/test/jtx/prop.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_PROP_H_INCLUDED -#define XRPL_TEST_JTX_PROP_H_INCLUDED +#pragma once #include @@ -16,8 +15,7 @@ struct prop std::unique_ptr p_; template - prop(Args&&... args) - : p_(std::make_unique>(std::forward(args)...)) + prop(Args&&... args) : p_(std::make_unique>(std::forward(args)...)) { } @@ -31,5 +29,3 @@ struct prop } // namespace jtx } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/quality.h b/src/test/jtx/quality.h index c112ad9934..34c960224f 100644 --- a/src/test/jtx/quality.h +++ b/src/test/jtx/quality.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_QUALITY_H_INCLUDED -#define XRPL_TEST_JTX_QUALITY_H_INCLUDED +#pragma once #include @@ -66,5 +65,3 @@ public: } // namespace jtx } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/rate.h b/src/test/jtx/rate.h index 2ed8cec6f2..a92bd2364a 100644 --- a/src/test/jtx/rate.h +++ b/src/test/jtx/rate.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_RATE_H_INCLUDED -#define XRPL_TEST_JTX_RATE_H_INCLUDED +#pragma once #include @@ -16,5 +15,3 @@ rate(Account const& account, double multiplier); } // namespace jtx } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/regkey.h b/src/test/jtx/regkey.h index b3ab9a0ed9..2c95baacc3 100644 --- a/src/test/jtx/regkey.h +++ b/src/test/jtx/regkey.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_REGKEY_H_INCLUDED -#define XRPL_TEST_JTX_REGKEY_H_INCLUDED +#pragma once #include #include @@ -21,5 +20,3 @@ regkey(Account const& account, Account const& signer); } // namespace jtx } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/require.h b/src/test/jtx/require.h index 21ff8a29ec..7d712e8ab7 100644 --- a/src/test/jtx/require.h +++ b/src/test/jtx/require.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_REQUIRE_H_INCLUDED -#define XRPL_TEST_JTX_REQUIRE_H_INCLUDED +#pragma once #include @@ -64,5 +63,3 @@ public: } // namespace jtx } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/requires.h b/src/test/jtx/requires.h index 379c5ad67d..2411d040c6 100644 --- a/src/test/jtx/requires.h +++ b/src/test/jtx/requires.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_REQUIRES_H_INCLUDED -#define XRPL_TEST_JTX_REQUIRES_H_INCLUDED +#pragma once #include #include @@ -16,5 +15,3 @@ using requires_t = std::vector; } // namespace jtx } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/rpc.h b/src/test/jtx/rpc.h index ba3c71074d..6946cbc4e1 100644 --- a/src/test/jtx/rpc.h +++ b/src/test/jtx/rpc.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_RPC_H_INCLUDED -#define XRPL_TEST_JTX_RPC_H_INCLUDED +#pragma once #include @@ -22,15 +21,12 @@ private: public: /// If there's an error code, we expect an error message - explicit rpc(error_code_i code, std::optional m = {}) - : code_(code), errorMessage_(m) + explicit rpc(error_code_i code, std::optional m = {}) : code_(code), errorMessage_(m) { } /// If there is not a code, we expect an exception message - explicit rpc( - std::string error, - std::optional exceptionMessage = {}) + explicit rpc(std::string error, std::optional exceptionMessage = {}) : error_(error), errorException_(exceptionMessage) { } @@ -51,9 +47,7 @@ public: // Take advantage of that fact to populate jt.rpcException. The // check will be aware of whether the rpcException can be safely // ignored. - jt.rpcCode = { - *code_, - errorMessage_ ? *errorMessage_ : errorInfo.message.c_str()}; + jt.rpcCode = {*code_, errorMessage_ ? *errorMessage_ : errorInfo.message.c_str()}; jt.rpcException = {errorInfo.token.c_str(), std::nullopt}; } if (error_) @@ -64,5 +58,3 @@ public: } // namespace jtx } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/sendmax.h b/src/test/jtx/sendmax.h index 9082ef9ddd..8a471be3cd 100644 --- a/src/test/jtx/sendmax.h +++ b/src/test/jtx/sendmax.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_SENDMAX_H_INCLUDED -#define XRPL_TEST_JTX_SENDMAX_H_INCLUDED +#pragma once #include @@ -27,5 +26,3 @@ public: } // namespace jtx } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/seq.h b/src/test/jtx/seq.h index 102961db0e..b861800ac9 100644 --- a/src/test/jtx/seq.h +++ b/src/test/jtx/seq.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_SEQ_H_INCLUDED -#define XRPL_TEST_JTX_SEQ_H_INCLUDED +#pragma once #include #include @@ -37,5 +36,3 @@ public: } // namespace jtx } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/sig.h b/src/test/jtx/sig.h index 27d18b322e..ab22a46c69 100644 --- a/src/test/jtx/sig.h +++ b/src/test/jtx/sig.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_SIG_H_INCLUDED -#define XRPL_TEST_JTX_SIG_H_INCLUDED +#pragma once #include @@ -40,13 +39,11 @@ public: { } - explicit sig(SField const* subField, Account const& account) - : subField_(subField), account_(account) + explicit sig(SField const* subField, Account const& account) : subField_(subField), account_(account) { } - explicit sig(SField const& subField, Account const& account) - : sig(&subField, account) + explicit sig(SField const& subField, Account const& account) : sig(&subField, account) { } @@ -61,5 +58,3 @@ public: } // namespace jtx } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/tag.h b/src/test/jtx/tag.h index 688d2e92c1..c8d5723754 100644 --- a/src/test/jtx/tag.h +++ b/src/test/jtx/tag.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_TAG_H_INCLUDED -#define XRPL_TEST_JTX_TAG_H_INCLUDED +#pragma once #include @@ -42,5 +41,3 @@ public: } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/tags.h b/src/test/jtx/tags.h index 445bdebcb4..c8a6170048 100644 --- a/src/test/jtx/tags.h +++ b/src/test/jtx/tags.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_TAGS_H_INCLUDED -#define XRPL_TEST_JTX_TAGS_H_INCLUDED +#pragma once namespace xrpl { namespace test { @@ -44,5 +43,3 @@ static increment_t const increment; } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/ter.h b/src/test/jtx/ter.h index f13c2a90e6..074ba307cb 100644 --- a/src/test/jtx/ter.h +++ b/src/test/jtx/ter.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_TER_H_INCLUDED -#define XRPL_TEST_JTX_TER_H_INCLUDED +#pragma once #include @@ -36,5 +35,3 @@ public: } // namespace jtx } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/testline.h b/src/test/jtx/testline.h index beda870345..e2be1f0276 100644 --- a/src/test/jtx/testline.h +++ b/src/test/jtx/testline.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_TESTLINE_H_INCLUDED -#define XRPL_TEST_JTX_TESTLINE_H_INCLUDED +#pragma once #include @@ -30,5 +29,3 @@ public: } // namespace jtx } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/ticket.h b/src/test/jtx/ticket.h index 10cb772bbd..dca16ac7c6 100644 --- a/src/test/jtx/ticket.h +++ b/src/test/jtx/ticket.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_TICKET_H_INCLUDED -#define XRPL_TEST_JTX_TICKET_H_INCLUDED +#pragma once #include #include @@ -48,5 +47,3 @@ using tickets = owner_count; } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/token.h b/src/test/jtx/token.h index 5280799582..f6d562587a 100644 --- a/src/test/jtx/token.h +++ b/src/test/jtx/token.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_NFT_H_INCLUDED -#define XRPL_TEST_JTX_NFT_H_INCLUDED +#pragma once #include #include @@ -104,10 +103,7 @@ burn(jtx::Account const& account, uint256 const& nftokenID); /** Create an NFTokenOffer. */ Json::Value -createOffer( - jtx::Account const& account, - uint256 const& nftokenID, - STAmount const& amount); +createOffer(jtx::Account const& account, uint256 const& nftokenID, STAmount const& amount); /** Sets the optional Owner on an NFTokenOffer. */ class owner @@ -156,14 +152,10 @@ public: /** Cancel NFTokenOffers. */ Json::Value -cancelOffer( - jtx::Account const& account, - std::initializer_list const& nftokenOffers = {}); +cancelOffer(jtx::Account const& account, std::initializer_list const& nftokenOffers = {}); Json::Value -cancelOffer( - jtx::Account const& account, - std::vector const& nftokenOffers); +cancelOffer(jtx::Account const& account, std::vector const& nftokenOffers); /** Sets the optional RootIndex field when canceling NFTokenOffers. */ class rootIndex @@ -190,10 +182,7 @@ acceptSellOffer(jtx::Account const& account, uint256 const& offerIndex); /** Broker two NFToken offers. */ Json::Value -brokerOffers( - jtx::Account const& account, - uint256 const& buyOfferIndex, - uint256 const& sellOfferIndex); +brokerOffers(jtx::Account const& account, uint256 const& buyOfferIndex, uint256 const& sellOfferIndex); /** Sets the optional NFTokenBrokerFee field in a brokerOffer transaction. */ class brokerFee @@ -228,5 +217,3 @@ modify(jtx::Account const& account, uint256 const& nftokenID); } // namespace test } // namespace xrpl - -#endif // XRPL_TEST_JTX_NFT_H_INCLUDED diff --git a/src/test/jtx/trust.h b/src/test/jtx/trust.h index 69a3e7ba53..462538854b 100644 --- a/src/test/jtx/trust.h +++ b/src/test/jtx/trust.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_TRUST_H_INCLUDED -#define XRPL_TEST_JTX_TRUST_H_INCLUDED +#pragma once #include @@ -16,20 +15,11 @@ trust(Account const& account, STAmount const& amount, std::uint32_t flags = 0); /** Change flags on a trust line. */ Json::Value -trust( - Account const& account, - STAmount const& amount, - Account const& peer, - std::uint32_t flags); +trust(Account const& account, STAmount const& amount, Account const& peer, std::uint32_t flags); Json::Value -claw( - Account const& account, - STAmount const& amount, - std::optional const& mptHolder = std::nullopt); +claw(Account const& account, STAmount const& amount, std::optional const& mptHolder = std::nullopt); } // namespace jtx } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/txflags.h b/src/test/jtx/txflags.h index 75a0d2740b..f51c26d035 100644 --- a/src/test/jtx/txflags.h +++ b/src/test/jtx/txflags.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_TXFLAGS_H_INCLUDED -#define XRPL_TEST_JTX_TXFLAGS_H_INCLUDED +#pragma once #include @@ -25,5 +24,3 @@ public: } // namespace jtx } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/utility.h b/src/test/jtx/utility.h index a824f86c1a..895d00f12b 100644 --- a/src/test/jtx/utility.h +++ b/src/test/jtx/utility.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_UTILITY_H_INCLUDED -#define XRPL_TEST_JTX_UTILITY_H_INCLUDED +#pragma once #include @@ -53,13 +52,8 @@ fill_seq(Json::Value& jv, ReadView const& view); /** Given a rippled unit test rpc command, return the corresponding JSON. */ Json::Value -cmdToJSONRPC( - std::vector const& args, - beast::Journal j, - unsigned int apiVersion); +cmdToJSONRPC(std::vector const& args, beast::Journal j, unsigned int apiVersion); } // namespace jtx } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/vault.h b/src/test/jtx/vault.h index 485940f9f4..65a5706354 100644 --- a/src/test/jtx/vault.h +++ b/src/test/jtx/vault.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_VAULT_H_INCLUDED -#define XRPL_TEST_JTX_VAULT_H_INCLUDED +#pragma once #include #include @@ -86,5 +85,3 @@ struct Vault } // namespace jtx } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/jtx/xchain_bridge.h b/src/test/jtx/xchain_bridge.h index dfd6073ca4..cdacede234 100644 --- a/src/test/jtx/xchain_bridge.h +++ b/src/test/jtx/xchain_bridge.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TEST_JTX_XCHAINBRIDGE_H_INCLUDED -#define XRPL_TEST_JTX_XCHAINBRIDGE_H_INCLUDED +#pragma once #include #include @@ -71,11 +70,7 @@ sidechain_xchain_account_create( AnyAmount const& xChainFee); Json::Value -sidechain_xchain_account_claim( - Account const& acc, - Json::Value const& bridge, - Account const& dst, - AnyAmount const& amt); +sidechain_xchain_account_claim(Account const& acc, Json::Value const& bridge, Account const& dst, AnyAmount const& amt); Json::Value claim_attestation( @@ -206,18 +201,7 @@ struct XChainBridgeObjects std::size_t const fromIdx = 0) { return create_account_attestations( - scAttester, - jvb, - mcCarol, - amt, - reward, - payees, - true, - createCount, - dst, - signers, - numAtts, - fromIdx); + scAttester, jvb, mcCarol, amt, reward, payees, true, createCount, dst, signers, numAtts, fromIdx); } Json::Value @@ -227,16 +211,10 @@ struct XChainBridgeObjects STAmount const& _reward = XRP(1), std::optional const& minAccountCreate = std::nullopt) { - return bridge_create( - acc, - bridge == Json::nullValue ? jvb : bridge, - _reward, - minAccountCreate); + return bridge_create(acc, bridge == Json::nullValue ? jvb : bridge, _reward, minAccountCreate); } }; } // namespace jtx } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/ledger/BookDirs_test.cpp b/src/test/ledger/BookDirs_test.cpp index 4f5cf5cca2..45e585d68d 100644 --- a/src/test/ledger/BookDirs_test.cpp +++ b/src/test/ledger/BookDirs_test.cpp @@ -33,18 +33,13 @@ struct BookDirs_test : public beast::unit_test::suite { env(offer("alice", Account("alice")["USD"](50), XRP(10))); - auto d = BookDirs( - *env.current(), - Book( - Account("alice")["USD"].issue(), xrpIssue(), std::nullopt)); + auto d = BookDirs(*env.current(), Book(Account("alice")["USD"].issue(), xrpIssue(), std::nullopt)); BEAST_EXPECT(std::distance(d.begin(), d.end()) == 1); } { env(offer("alice", gw["CNY"](50), XRP(10))); - auto d = BookDirs( - *env.current(), - Book(gw["CNY"].issue(), xrpIssue(), std::nullopt)); + auto d = BookDirs(*env.current(), Book(gw["CNY"].issue(), xrpIssue(), std::nullopt)); BEAST_EXPECT(std::distance(d.begin(), d.end()) == 1); } @@ -52,9 +47,7 @@ struct BookDirs_test : public beast::unit_test::suite env.trust(Account("bob")["CNY"](10), "alice"); env(pay("bob", "alice", Account("bob")["CNY"](10))); env(offer("alice", USD(50), Account("bob")["CNY"](10))); - auto d = BookDirs( - *env.current(), - Book(USD.issue(), Account("bob")["CNY"].issue(), std::nullopt)); + auto d = BookDirs(*env.current(), Book(USD.issue(), Account("bob")["CNY"].issue(), std::nullopt)); BEAST_EXPECT(std::distance(d.begin(), d.end()) == 1); } @@ -64,8 +57,7 @@ struct BookDirs_test : public beast::unit_test::suite for (auto k = 0; k < 80; ++k) env(offer("alice", AUD(i), XRP(j))); - auto d = BookDirs( - *env.current(), Book(AUD.issue(), xrpIssue(), std::nullopt)); + auto d = BookDirs(*env.current(), Book(AUD.issue(), xrpIssue(), std::nullopt)); BEAST_EXPECT(std::distance(d.begin(), d.end()) == 240); auto i = 1, j = 3, k = 0; for (auto const& e : d) diff --git a/src/test/ledger/Directory_test.cpp b/src/test/ledger/Directory_test.cpp index 721b919238..0774390490 100644 --- a/src/test/ledger/Directory_test.cpp +++ b/src/test/ledger/Directory_test.cpp @@ -89,8 +89,7 @@ struct Directory_test : public beast::unit_test::suite do { - auto p = - view->read(keylet::page(keylet::ownerDir(alice), page)); + auto p = view->read(keylet::page(keylet::ownerDir(alice), page)); // Ensure that the entries in the page are sorted auto const& v = p->getFieldV256(sfIndexes); @@ -98,8 +97,7 @@ struct Directory_test : public beast::unit_test::suite // Ensure that the page contains the correct orders by // calculating which sequence numbers belong here. - std::uint32_t const minSeq = - firstOfferSeq + (page * dirNodeMaxEntries); + std::uint32_t const minSeq = firstOfferSeq + (page * dirNodeMaxEntries); std::uint32_t const maxSeq = minSeq + dirNodeMaxEntries; for (auto const& e : v) @@ -116,8 +114,7 @@ struct Directory_test : public beast::unit_test::suite // Now check the orderbook: it should be in the order we placed // the offers. - auto book = BookDirs( - *env.current(), Book({xrpIssue(), USD.issue(), std::nullopt})); + auto book = BookDirs(*env.current(), Book({xrpIssue(), USD.issue(), std::nullopt})); int count = 1; for (auto const& offer : book) @@ -167,7 +164,7 @@ struct Directory_test : public beast::unit_test::suite return c; }(); - // First, Alices creates a lot of trustlines, and then + // First, Alice creates a lot of trustlines, and then // deletes them in a different order: { auto cl = currencies; @@ -266,8 +263,7 @@ struct Directory_test : public beast::unit_test::suite { for (int i = 0; i < dirNodeMaxEntries; ++i) { - env(offer_cancel( - alice, firstOfferSeq + page * dirNodeMaxEntries + i)); + env(offer_cancel(alice, firstOfferSeq + page * dirNodeMaxEntries + i)); env.close(); } } @@ -276,8 +272,7 @@ struct Directory_test : public beast::unit_test::suite // should have no entries and be empty: { Sandbox sb(env.closed().get(), tapNONE); - uint256 const bookBase = - getBookBase({xrpIssue(), USD.issue(), std::nullopt}); + uint256 const bookBase = getBookBase({xrpIssue(), USD.issue(), std::nullopt}); BEAST_EXPECT(dirIsEmpty(sb, keylet::page(bookBase))); BEAST_EXPECT(!sb.succ(bookBase, getQualityNext(bookBase))); @@ -309,11 +304,9 @@ struct Directory_test : public beast::unit_test::suite env.fund(XRP(10000), alice); env.close(); - constexpr uint256 base( - "fb71c9aa3310141da4b01d6c744a98286af2d72ab5448d5adc0910ca0c910880"); + constexpr uint256 base("fb71c9aa3310141da4b01d6c744a98286af2d72ab5448d5adc0910ca0c910880"); - constexpr uint256 item( - "bad0f021aa3b2f6754a8fe82a5779730aa0bbbab82f17201ef24900efc2c7312"); + constexpr uint256 item("bad0f021aa3b2f6754a8fe82a5779730aa0bbbab82f17201ef24900efc2c7312"); { // Create a chain of three pages: @@ -333,8 +326,7 @@ struct Directory_test : public beast::unit_test::suite // Now, try to delete the item from the middle // page. This should cause all pages to be deleted: - BEAST_EXPECT(sb.dirRemove( - keylet::page(base, 0), 1, keylet::unchecked(item), false)); + BEAST_EXPECT(sb.dirRemove(keylet::page(base, 0), 1, keylet::unchecked(item), false)); BEAST_EXPECT(!sb.peek(keylet::page(base, 2))); BEAST_EXPECT(!sb.peek(keylet::page(base, 1))); BEAST_EXPECT(!sb.peek(keylet::page(base, 0))); @@ -367,8 +359,7 @@ struct Directory_test : public beast::unit_test::suite // Now, try to delete the item from page 2. // This should cause pages 2 and 3 to be // deleted: - BEAST_EXPECT(sb.dirRemove( - keylet::page(base, 0), 2, keylet::unchecked(item), false)); + BEAST_EXPECT(sb.dirRemove(keylet::page(base, 0), 2, keylet::unchecked(item), false)); BEAST_EXPECT(!sb.peek(keylet::page(base, 3))); BEAST_EXPECT(!sb.peek(keylet::page(base, 2))); @@ -398,8 +389,7 @@ struct Directory_test : public beast::unit_test::suite Json::Value params; params[jss::type] = jss::directory; params[jss::ledger_index] = "validated"; - auto const result = - env.rpc("json", "ledger_data", to_string(params))[jss::result]; + auto const result = env.rpc("json", "ledger_data", to_string(params))[jss::result]; BEAST_EXPECT(!result.isMember(jss::marker)); return result; }; @@ -418,9 +408,7 @@ struct Directory_test : public beast::unit_test::suite BEAST_EXPECTS(checkArraySize(jstate, 2), jrr.toStyledString()); for (auto const& directory : jstate) { - BEAST_EXPECT( - directory["LedgerEntryType"] == - jss::DirectoryNode); // sanity check + BEAST_EXPECT(directory["LedgerEntryType"] == jss::DirectoryNode); // sanity check // The PreviousTxnID and PreviousTxnLgrSeq fields should not be // on the DirectoryNode object when the amendment is disabled BEAST_EXPECT(!directory.isMember("PreviousTxnID")); @@ -448,9 +436,7 @@ struct Directory_test : public beast::unit_test::suite BEAST_EXPECTS(checkArraySize(jstate, 3), jrr.toStyledString()); for (auto const& directory : jstate) { - BEAST_EXPECT( - directory["LedgerEntryType"] == - jss::DirectoryNode); // sanity check + BEAST_EXPECT(directory["LedgerEntryType"] == jss::DirectoryNode); // sanity check if (directory[jss::Owner] == gw.human()) { // gw's directory did not get touched, so it @@ -463,9 +449,7 @@ struct Directory_test : public beast::unit_test::suite // All of the other directories, including the order // book, did get touched, so they should have those // fields - BEAST_EXPECT( - directory.isMember("PreviousTxnID") && - directory["PreviousTxnID"].asString() == txID); + BEAST_EXPECT(directory.isMember("PreviousTxnID") && directory["PreviousTxnID"].asString() == txID); BEAST_EXPECT( directory.isMember("PreviousTxnLgrSeq") && directory["PreviousTxnLgrSeq"].asUInt() == ledgerSeq); @@ -502,8 +486,7 @@ struct Directory_test : public beast::unit_test::suite env, lastPage, keylet::ownerDir(alice.id()), - [lastPage, this]( - ApplyView& view, uint256 key, std::uint64_t page) { + [lastPage, this](ApplyView& view, uint256 key, std::uint64_t page) { auto sle = view.peek({ltCREDENTIAL, key}); if (!BEAST_EXPECT(sle)) return false; @@ -525,8 +508,7 @@ struct Directory_test : public beast::unit_test::suite // Destroy all objects in directory for (int i = 0; i < 64; ++i) - env(credentials::deleteCred( - alice, alice, alice, std::to_string(i))); + env(credentials::deleteCred(alice, alice, alice, std::to_string(i))); if (!full) env(credentials::deleteCred(alice, alice, alice, "foo")); @@ -539,12 +521,10 @@ struct Directory_test : public beast::unit_test::suite env.close(); }; - testCase( - testable_amendments() - fixDirectoryLimit, - [this](Env&) -> std::tuple { - testcase("directory full without fixDirectoryLimit"); - return {dirNodeMaxPages - 1, true}; - }); + testCase(testable_amendments() - fixDirectoryLimit, [this](Env&) -> std::tuple { + testcase("directory full without fixDirectoryLimit"); + return {dirNodeMaxPages - 1, true}; + }); testCase( testable_amendments(), // [this](Env&) -> std::tuple { diff --git a/src/test/ledger/PaymentSandbox_test.cpp b/src/test/ledger/PaymentSandbox_test.cpp index b5acb38156..cd5b1d1c19 100644 --- a/src/test/ledger/PaymentSandbox_test.cpp +++ b/src/test/ledger/PaymentSandbox_test.cpp @@ -66,9 +66,7 @@ class PaymentSandbox_test : public beast::unit_test::suite PathSet paths(Path(gw1, USD_gw2, gw2), Path(gw2, USD_gw1, gw1)); - env(pay(snd, rcv, any(USD_gw1(4))), - json(paths.json()), - txflags(tfNoRippleDirect | tfPartialPayment)); + env(pay(snd, rcv, any(USD_gw1(4))), json(paths.json()), txflags(tfNoRippleDirect | tfPartialPayment)); env.require(balance("rcv", USD_gw1(0))); env.require(balance("rcv", USD_gw2(2))); @@ -105,23 +103,19 @@ class PaymentSandbox_test : public beast::unit_test::suite ApplyViewImpl av(&*env.current(), tapNONE); auto const iss = USD_gw1.issue(); - auto const startingAmount = accountHolds( - av, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j); + auto const startingAmount = accountHolds(av, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j); { auto r = accountSend(av, gw1, alice, toCredit, j); BEAST_EXPECT(r == tesSUCCESS); } BEAST_EXPECT( - accountHolds( - av, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == - startingAmount + toCredit); + accountHolds(av, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == startingAmount + toCredit); { auto r = accountSend(av, alice, gw1, toDebit, j); BEAST_EXPECT(r == tesSUCCESS); } BEAST_EXPECT( - accountHolds( - av, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == + accountHolds(av, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == startingAmount + toCredit - toDebit); } @@ -130,19 +124,15 @@ class PaymentSandbox_test : public beast::unit_test::suite ApplyViewImpl av(&*env.current(), tapNONE); auto const iss = USD_gw1.issue(); - auto const startingAmount = accountHolds( - av, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j); + auto const startingAmount = accountHolds(av, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j); rippleCredit(av, gw1, alice, toCredit, true, j); BEAST_EXPECT( - accountHolds( - av, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == - startingAmount + toCredit); + accountHolds(av, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == startingAmount + toCredit); rippleCredit(av, alice, gw1, toDebit, true, j); BEAST_EXPECT( - accountHolds( - av, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == + accountHolds(av, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == startingAmount + toCredit - toDebit); } @@ -152,26 +142,20 @@ class PaymentSandbox_test : public beast::unit_test::suite PaymentSandbox pv(&av); auto const iss = USD_gw1.issue(); - auto const startingAmount = accountHolds( - pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j); + auto const startingAmount = accountHolds(pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j); { auto r = accountSend(pv, gw1, alice, toCredit, j); BEAST_EXPECT(r == tesSUCCESS); } - BEAST_EXPECT( - accountHolds( - pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == - startingAmount); + BEAST_EXPECT(accountHolds(pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == startingAmount); { auto r = accountSend(pv, alice, gw1, toDebit, j); BEAST_EXPECT(r == tesSUCCESS); } BEAST_EXPECT( - accountHolds( - pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == - startingAmount - toDebit); + accountHolds(pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == startingAmount - toDebit); } { @@ -180,14 +164,10 @@ class PaymentSandbox_test : public beast::unit_test::suite PaymentSandbox pv(&av); auto const iss = USD_gw1.issue(); - auto const startingAmount = accountHolds( - pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j); + auto const startingAmount = accountHolds(pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j); rippleCredit(pv, gw1, alice, toCredit, true, j); - BEAST_EXPECT( - accountHolds( - pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == - startingAmount); + BEAST_EXPECT(accountHolds(pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == startingAmount); } { @@ -196,14 +176,11 @@ class PaymentSandbox_test : public beast::unit_test::suite PaymentSandbox pv(&av); auto const iss = USD_gw1.issue(); - auto const startingAmount = accountHolds( - pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j); + auto const startingAmount = accountHolds(pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j); BEAST_EXPECT(redeemIOU(pv, alice, toDebit, iss, j) == tesSUCCESS); BEAST_EXPECT( - accountHolds( - pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == - startingAmount - toDebit); + accountHolds(pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == startingAmount - toDebit); } { @@ -212,14 +189,10 @@ class PaymentSandbox_test : public beast::unit_test::suite PaymentSandbox pv(&av); auto const iss = USD_gw1.issue(); - auto const startingAmount = accountHolds( - pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j); + auto const startingAmount = accountHolds(pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j); BEAST_EXPECT(issueIOU(pv, alice, toCredit, iss, j) == tesSUCCESS); - BEAST_EXPECT( - accountHolds( - pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == - startingAmount); + BEAST_EXPECT(accountHolds(pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == startingAmount); } { @@ -228,40 +201,22 @@ class PaymentSandbox_test : public beast::unit_test::suite PaymentSandbox pv(&av); auto const iss = USD_gw1.issue(); - auto const startingAmount = accountHolds( - pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j); + auto const startingAmount = accountHolds(pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j); { auto r = accountSend(pv, gw1, alice, toCredit, j); BEAST_EXPECT(r == tesSUCCESS); } - BEAST_EXPECT( - accountHolds( - pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == - startingAmount); + BEAST_EXPECT(accountHolds(pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == startingAmount); { PaymentSandbox pv2(&pv); - BEAST_EXPECT( - accountHolds( - pv2, - alice, - iss.currency, - iss.account, - fhIGNORE_FREEZE, - j) == startingAmount); + BEAST_EXPECT(accountHolds(pv2, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == startingAmount); { auto r = accountSend(pv2, gw1, alice, toCredit, j); BEAST_EXPECT(r == tesSUCCESS); } - BEAST_EXPECT( - accountHolds( - pv2, - alice, - iss.currency, - iss.account, - fhIGNORE_FREEZE, - j) == startingAmount); + BEAST_EXPECT(accountHolds(pv2, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == startingAmount); } { @@ -269,9 +224,7 @@ class PaymentSandbox_test : public beast::unit_test::suite BEAST_EXPECT(r == tesSUCCESS); } BEAST_EXPECT( - accountHolds( - pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == - startingAmount - toDebit); + accountHolds(pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j) == startingAmount - toDebit); } } @@ -293,18 +246,8 @@ class PaymentSandbox_test : public beast::unit_test::suite auto const USD = gw["USD"]; auto const issue = USD.issue(); - STAmount tinyAmt( - issue, - STAmount::cMinValue, - STAmount::cMinOffset + 1, - false, - STAmount::unchecked{}); - STAmount hugeAmt( - issue, - STAmount::cMaxValue, - STAmount::cMaxOffset - 1, - false, - STAmount::unchecked{}); + STAmount tinyAmt(issue, STAmount::cMinValue, STAmount::cMinOffset + 1, false, STAmount::unchecked{}); + STAmount hugeAmt(issue, STAmount::cMaxValue, STAmount::cMaxOffset - 1, false, STAmount::unchecked{}); ApplyViewImpl av(&*env.current(), tapNONE); PaymentSandbox pv(&av); @@ -318,11 +261,8 @@ class PaymentSandbox_test : public beast::unit_test::suite testcase("Reserve"); using namespace jtx; - auto accountFundsXRP = [](ReadView const& view, - AccountID const& id, - beast::Journal j) -> XRPAmount { - return toAmount(accountHolds( - view, id, xrpCurrency(), xrpAccount(), fhZERO_IF_FROZEN, j)); + auto accountFundsXRP = [](ReadView const& view, AccountID const& id, beast::Journal j) -> XRPAmount { + return toAmount(accountHolds(view, id, xrpCurrency(), xrpAccount(), fhZERO_IF_FROZEN, j)); }; auto reserve = [](jtx::Env& env, std::uint32_t count) -> XRPAmount { @@ -343,17 +283,14 @@ class PaymentSandbox_test : public beast::unit_test::suite // zero (there was a bug that caused her funds to become negative). { - auto r = - accountSend(sb, xrpAccount(), alice, XRP(100), env.journal); + auto r = accountSend(sb, xrpAccount(), alice, XRP(100), env.journal); BEAST_EXPECT(r == tesSUCCESS); } { - auto r = - accountSend(sb, alice, xrpAccount(), XRP(100), env.journal); + auto r = accountSend(sb, alice, xrpAccount(), XRP(100), env.journal); BEAST_EXPECT(r == tesSUCCESS); } - BEAST_EXPECT( - accountFundsXRP(sb, alice, env.journal) == beast::zero); + BEAST_EXPECT(accountFundsXRP(sb, alice, env.journal) == beast::zero); } } @@ -383,8 +320,7 @@ class PaymentSandbox_test : public beast::unit_test::suite sb.creditHook(gw.id(), alice.id(), {USD, 100}, {tlIssue, 600}); // Expect that the STAmount issuer returned by balanceHook() is correct. - STAmount const balance = - sb.balanceHook(gw.id(), alice.id(), {USD, 600}); + STAmount const balance = sb.balanceHook(gw.id(), alice.id(), {USD, 600}); BEAST_EXPECT(balance.getIssuer() == USD.issue().account); } diff --git a/src/test/ledger/SkipList_test.cpp b/src/test/ledger/SkipList_test.cpp index 12fedea5c1..2f4a231c14 100644 --- a/src/test/ledger/SkipList_test.cpp +++ b/src/test/ledger/SkipList_test.cpp @@ -17,16 +17,12 @@ class SkipList_test : public beast::unit_test::suite std::vector> history; { Config config; - auto prev = std::make_shared( - create_genesis, - config, - std::vector{}, - env.app().getNodeFamily()); + auto prev = + std::make_shared(create_genesis, config, std::vector{}, env.app().getNodeFamily()); history.push_back(prev); for (auto i = 0; i < 1023; ++i) { - auto next = std::make_shared( - *prev, env.app().timeKeeper().closeTime()); + auto next = std::make_shared(*prev, env.app().timeKeeper().closeTime()); next->updateSkipList(); history.push_back(next); prev = next; @@ -35,47 +31,31 @@ class SkipList_test : public beast::unit_test::suite { auto l = *(std::next(std::begin(history))); - BEAST_EXPECT( - (*std::begin(history))->header().seq < l->header().seq); - BEAST_EXPECT( - !hashOfSeq(*l, l->header().seq + 1, env.journal).has_value()); - BEAST_EXPECT( - hashOfSeq(*l, l->header().seq, env.journal) == - l->header().hash); - BEAST_EXPECT( - hashOfSeq(*l, l->header().seq - 1, env.journal) == - l->header().parentHash); - BEAST_EXPECT( - !hashOfSeq(*history.back(), l->header().seq, env.journal) - .has_value()); + BEAST_EXPECT((*std::begin(history))->header().seq < l->header().seq); + BEAST_EXPECT(!hashOfSeq(*l, l->header().seq + 1, env.journal).has_value()); + BEAST_EXPECT(hashOfSeq(*l, l->header().seq, env.journal) == l->header().hash); + BEAST_EXPECT(hashOfSeq(*l, l->header().seq - 1, env.journal) == l->header().parentHash); + BEAST_EXPECT(!hashOfSeq(*history.back(), l->header().seq, env.journal).has_value()); } // ledger skip lists store up to the previous 256 hashes for (auto i = history.crbegin(); i != history.crend(); i += 256) { - for (auto n = i; - n != std::next(i, (*i)->header().seq - 256 > 1 ? 257 : 256); - ++n) + for (auto n = i; n != std::next(i, (*i)->header().seq - 256 > 1 ? 257 : 256); ++n) { - BEAST_EXPECT( - hashOfSeq(**i, (*n)->header().seq, env.journal) == - (*n)->header().hash); + BEAST_EXPECT(hashOfSeq(**i, (*n)->header().seq, env.journal) == (*n)->header().hash); } // edge case accessing beyond 256 - BEAST_EXPECT(!hashOfSeq(**i, (*i)->header().seq - 258, env.journal) - .has_value()); + BEAST_EXPECT(!hashOfSeq(**i, (*i)->header().seq - 258, env.journal).has_value()); } // every 256th hash beyond the first 256 is stored - for (auto i = history.crbegin(); i != std::next(history.crend(), -512); - i += 256) + for (auto i = history.crbegin(); i != std::next(history.crend(), -512); i += 256) { for (auto n = std::next(i, 512); n != history.crend(); n += 256) { - BEAST_EXPECT( - hashOfSeq(**i, (*n)->header().seq, env.journal) == - (*n)->header().hash); + BEAST_EXPECT(hashOfSeq(**i, (*n)->header().seq, env.journal) == (*n)->header().hash); } } } diff --git a/src/test/ledger/View_test.cpp b/src/test/ledger/View_test.cpp index a486792209..33813e135e 100644 --- a/src/test/ledger/View_test.cpp +++ b/src/test/ledger/View_test.cpp @@ -60,8 +60,7 @@ class View_test : public beast::unit_test::suite next = view.succ(*next); if (!next) break; - view.rawErase(std::make_shared( - *view.read(keylet::unchecked(*next)))); + view.rawErase(std::make_shared(*view.read(keylet::unchecked(*next)))); } return true; }); @@ -78,17 +77,13 @@ class View_test : public beast::unit_test::suite next = ledger.succ(*next); if (!next) break; - ledger.rawErase( - std::make_shared(*ledger.read(keylet::unchecked(*next)))); + ledger.rawErase(std::make_shared(*ledger.read(keylet::unchecked(*next)))); } } // Test succ correctness void - succ( - ReadView const& v, - std::uint32_t id, - std::optional answer) + succ(ReadView const& v, std::uint32_t id, std::optional answer) { auto const next = v.succ(k(id).key); if (answer) @@ -118,13 +113,9 @@ class View_test : public beast::unit_test::suite using namespace jtx; Env env(*this); Config config; - std::shared_ptr const genesis = std::make_shared( - create_genesis, - config, - std::vector{}, - env.app().getNodeFamily()); - auto const ledger = std::make_shared( - *genesis, env.app().timeKeeper().closeTime()); + std::shared_ptr const genesis = + std::make_shared(create_genesis, config, std::vector{}, env.app().getNodeFamily()); + auto const ledger = std::make_shared(*genesis, env.app().timeKeeper().closeTime()); wipe(*ledger); ReadView& v = *ledger; succ(v, 0, std::nullopt); @@ -385,13 +376,9 @@ class View_test : public beast::unit_test::suite using namespace jtx; Env env(*this); Config config; - std::shared_ptr const genesis = std::make_shared( - create_genesis, - config, - std::vector{}, - env.app().getNodeFamily()); - auto const ledger = std::make_shared( - *genesis, env.app().timeKeeper().closeTime()); + std::shared_ptr const genesis = + std::make_shared(create_genesis, config, std::vector{}, env.app().getNodeFamily()); + auto const ledger = std::make_shared(*genesis, env.app().timeKeeper().closeTime()); auto setup = [&ledger](std::vector const& vec) { wipe(*ledger); @@ -500,9 +487,8 @@ class View_test : public beast::unit_test::suite } { // some full trees, some empty trees, etc - setup({0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, - 13, 14, 15, 16, 20, 25, 30, 32, 33, 34, 35, 36, 37, - 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 66, 100}); + setup({0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 20, 25, 30, + 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 66, 100}); BEAST_EXPECT( sles(*ledger) == list( @@ -549,98 +535,38 @@ class View_test : public beast::unit_test::suite auto e = ledger->stateMap().end(); BEAST_EXPECT(ledger->stateMap().lower_bound(uint256(0)) == e); BEAST_EXPECT(ledger->stateMap().lower_bound(uint256(1)) == b); - BEAST_EXPECT( - ledger->stateMap().lower_bound(uint256(5))->key() == - uint256(4)); - BEAST_EXPECT( - ledger->stateMap().lower_bound(uint256(15))->key() == - uint256(14)); - BEAST_EXPECT( - ledger->stateMap().lower_bound(uint256(16))->key() == - uint256(15)); - BEAST_EXPECT( - ledger->stateMap().lower_bound(uint256(19))->key() == - uint256(16)); - BEAST_EXPECT( - ledger->stateMap().lower_bound(uint256(20))->key() == - uint256(16)); - BEAST_EXPECT( - ledger->stateMap().lower_bound(uint256(24))->key() == - uint256(20)); - BEAST_EXPECT( - ledger->stateMap().lower_bound(uint256(31))->key() == - uint256(30)); - BEAST_EXPECT( - ledger->stateMap().lower_bound(uint256(32))->key() == - uint256(30)); - BEAST_EXPECT( - ledger->stateMap().lower_bound(uint256(40))->key() == - uint256(39)); - BEAST_EXPECT( - ledger->stateMap().lower_bound(uint256(47))->key() == - uint256(46)); - BEAST_EXPECT( - ledger->stateMap().lower_bound(uint256(48))->key() == - uint256(47)); - BEAST_EXPECT( - ledger->stateMap().lower_bound(uint256(64))->key() == - uint256(48)); + BEAST_EXPECT(ledger->stateMap().lower_bound(uint256(5))->key() == uint256(4)); + BEAST_EXPECT(ledger->stateMap().lower_bound(uint256(15))->key() == uint256(14)); + BEAST_EXPECT(ledger->stateMap().lower_bound(uint256(16))->key() == uint256(15)); + BEAST_EXPECT(ledger->stateMap().lower_bound(uint256(19))->key() == uint256(16)); + BEAST_EXPECT(ledger->stateMap().lower_bound(uint256(20))->key() == uint256(16)); + BEAST_EXPECT(ledger->stateMap().lower_bound(uint256(24))->key() == uint256(20)); + BEAST_EXPECT(ledger->stateMap().lower_bound(uint256(31))->key() == uint256(30)); + BEAST_EXPECT(ledger->stateMap().lower_bound(uint256(32))->key() == uint256(30)); + BEAST_EXPECT(ledger->stateMap().lower_bound(uint256(40))->key() == uint256(39)); + BEAST_EXPECT(ledger->stateMap().lower_bound(uint256(47))->key() == uint256(46)); + BEAST_EXPECT(ledger->stateMap().lower_bound(uint256(48))->key() == uint256(47)); + BEAST_EXPECT(ledger->stateMap().lower_bound(uint256(64))->key() == uint256(48)); - BEAST_EXPECT( - ledger->stateMap().lower_bound(uint256(90))->key() == - uint256(66)); - BEAST_EXPECT( - ledger->stateMap().lower_bound(uint256(96))->key() == - uint256(66)); - BEAST_EXPECT( - ledger->stateMap().lower_bound(uint256(100))->key() == - uint256(66)); + BEAST_EXPECT(ledger->stateMap().lower_bound(uint256(90))->key() == uint256(66)); + BEAST_EXPECT(ledger->stateMap().lower_bound(uint256(96))->key() == uint256(66)); + BEAST_EXPECT(ledger->stateMap().lower_bound(uint256(100))->key() == uint256(66)); - BEAST_EXPECT( - ledger->stateMap().upper_bound(uint256(0))->key() == - uint256(1)); - BEAST_EXPECT( - ledger->stateMap().upper_bound(uint256(5))->key() == - uint256(6)); - BEAST_EXPECT( - ledger->stateMap().upper_bound(uint256(15))->key() == - uint256(16)); - BEAST_EXPECT( - ledger->stateMap().upper_bound(uint256(16))->key() == - uint256(20)); - BEAST_EXPECT( - ledger->stateMap().upper_bound(uint256(18))->key() == - uint256(20)); - BEAST_EXPECT( - ledger->stateMap().upper_bound(uint256(20))->key() == - uint256(25)); - BEAST_EXPECT( - ledger->stateMap().upper_bound(uint256(31))->key() == - uint256(32)); - BEAST_EXPECT( - ledger->stateMap().upper_bound(uint256(32))->key() == - uint256(33)); - BEAST_EXPECT( - ledger->stateMap().upper_bound(uint256(47))->key() == - uint256(48)); - BEAST_EXPECT( - ledger->stateMap().upper_bound(uint256(48))->key() == - uint256(66)); - BEAST_EXPECT( - ledger->stateMap().upper_bound(uint256(53))->key() == - uint256(66)); - BEAST_EXPECT( - ledger->stateMap().upper_bound(uint256(66))->key() == - uint256(100)); - BEAST_EXPECT( - ledger->stateMap().upper_bound(uint256(70))->key() == - uint256(100)); - BEAST_EXPECT( - ledger->stateMap().upper_bound(uint256(85))->key() == - uint256(100)); - BEAST_EXPECT( - ledger->stateMap().upper_bound(uint256(98))->key() == - uint256(100)); + BEAST_EXPECT(ledger->stateMap().upper_bound(uint256(0))->key() == uint256(1)); + BEAST_EXPECT(ledger->stateMap().upper_bound(uint256(5))->key() == uint256(6)); + BEAST_EXPECT(ledger->stateMap().upper_bound(uint256(15))->key() == uint256(16)); + BEAST_EXPECT(ledger->stateMap().upper_bound(uint256(16))->key() == uint256(20)); + BEAST_EXPECT(ledger->stateMap().upper_bound(uint256(18))->key() == uint256(20)); + BEAST_EXPECT(ledger->stateMap().upper_bound(uint256(20))->key() == uint256(25)); + BEAST_EXPECT(ledger->stateMap().upper_bound(uint256(31))->key() == uint256(32)); + BEAST_EXPECT(ledger->stateMap().upper_bound(uint256(32))->key() == uint256(33)); + BEAST_EXPECT(ledger->stateMap().upper_bound(uint256(47))->key() == uint256(48)); + BEAST_EXPECT(ledger->stateMap().upper_bound(uint256(48))->key() == uint256(66)); + BEAST_EXPECT(ledger->stateMap().upper_bound(uint256(53))->key() == uint256(66)); + BEAST_EXPECT(ledger->stateMap().upper_bound(uint256(66))->key() == uint256(100)); + BEAST_EXPECT(ledger->stateMap().upper_bound(uint256(70))->key() == uint256(100)); + BEAST_EXPECT(ledger->stateMap().upper_bound(uint256(85))->key() == uint256(100)); + BEAST_EXPECT(ledger->stateMap().upper_bound(uint256(98))->key() == uint256(100)); BEAST_EXPECT(ledger->stateMap().upper_bound(uint256(100)) == e); BEAST_EXPECT(ledger->stateMap().upper_bound(uint256(155)) == e); } @@ -654,13 +580,9 @@ class View_test : public beast::unit_test::suite using namespace jtx; Env env(*this); Config config; - std::shared_ptr const genesis = std::make_shared( - create_genesis, - config, - std::vector{}, - env.app().getNodeFamily()); - auto const ledger = std::make_shared( - *genesis, env.app().timeKeeper().closeTime()); + std::shared_ptr const genesis = + std::make_shared(create_genesis, config, std::vector{}, env.app().getNodeFamily()); + auto const ledger = std::make_shared(*genesis, env.app().timeKeeper().closeTime()); auto setup123 = [&ledger, this]() { // erase middle element wipe(*ledger); @@ -810,15 +732,7 @@ class View_test : public beast::unit_test::suite env.close(); // Alice's USD balance should be zero if frozen. - BEAST_EXPECT( - USD(0) == - accountHolds( - *env.closed(), - alice, - USD.currency, - gw, - fhZERO_IF_FROZEN, - env.journal)); + BEAST_EXPECT(USD(0) == accountHolds(*env.closed(), alice, USD.currency, gw, fhZERO_IF_FROZEN, env.journal)); // Thaw gw and try again. env(fclear(gw, asfGlobalFreeze)); @@ -835,28 +749,12 @@ class View_test : public beast::unit_test::suite env.close(); // Bob's balance should be zero if frozen. - BEAST_EXPECT( - USD(0) == - accountHolds( - *env.closed(), - bob, - USD.currency, - gw, - fhZERO_IF_FROZEN, - env.journal)); + BEAST_EXPECT(USD(0) == accountHolds(*env.closed(), bob, USD.currency, gw, fhZERO_IF_FROZEN, env.journal)); // gw thaws bob's trust line. bob gets his money back. env(trust(gw, USD(100), bob, tfClearFreeze)); env.close(); - BEAST_EXPECT( - USD(50) == - accountHolds( - *env.closed(), - bob, - USD.currency, - gw, - fhZERO_IF_FROZEN, - env.journal)); + BEAST_EXPECT(USD(50) == accountHolds(*env.closed(), bob, USD.currency, gw, fhZERO_IF_FROZEN, env.journal)); } { // accountHolds(). @@ -864,35 +762,15 @@ class View_test : public beast::unit_test::suite env.close(); // carol has no EUR. - BEAST_EXPECT( - EUR(0) == - accountHolds( - *env.closed(), - carol, - EUR.currency, - gw, - fhZERO_IF_FROZEN, - env.journal)); + BEAST_EXPECT(EUR(0) == accountHolds(*env.closed(), carol, EUR.currency, gw, fhZERO_IF_FROZEN, env.journal)); // But carol does have USD. BEAST_EXPECT( - USD(50) == - accountHolds( - *env.closed(), - carol, - USD.currency, - gw, - fhZERO_IF_FROZEN, - env.journal)); + USD(50) == accountHolds(*env.closed(), carol, USD.currency, gw, fhZERO_IF_FROZEN, env.journal)); // carol's XRP balance should be her holdings minus her reserve. - auto const carolsXRP = accountHolds( - *env.closed(), - carol, - xrpCurrency(), - xrpAccount(), - fhZERO_IF_FROZEN, - env.journal); + auto const carolsXRP = + accountHolds(*env.closed(), carol, xrpCurrency(), xrpAccount(), fhZERO_IF_FROZEN, env.journal); // carol's XRP balance: 10000 // base reserve: -200 // 1 trust line times its reserve: 1 * -50 @@ -907,37 +785,26 @@ class View_test : public beast::unit_test::suite // carol's XRP balance should now show as zero. BEAST_EXPECT( - XRP(0) == - accountHolds( - *env.closed(), - carol, - xrpCurrency(), - gw, - fhZERO_IF_FROZEN, - env.journal)); + XRP(0) == accountHolds(*env.closed(), carol, xrpCurrency(), gw, fhZERO_IF_FROZEN, env.journal)); } { // accountFunds(). // Gateways have whatever funds they claim to have. - auto const gwUSD = accountFunds( - *env.closed(), gw, USD(314159), fhZERO_IF_FROZEN, env.journal); + auto const gwUSD = accountFunds(*env.closed(), gw, USD(314159), fhZERO_IF_FROZEN, env.journal); BEAST_EXPECT(gwUSD == USD(314159)); // carol has funds from the gateway. - auto carolsUSD = accountFunds( - *env.closed(), carol, USD(0), fhZERO_IF_FROZEN, env.journal); + auto carolsUSD = accountFunds(*env.closed(), carol, USD(0), fhZERO_IF_FROZEN, env.journal); BEAST_EXPECT(carolsUSD == USD(50)); // If carol's funds are frozen she has no funds... env(fset(gw, asfGlobalFreeze)); env.close(); - carolsUSD = accountFunds( - *env.closed(), carol, USD(0), fhZERO_IF_FROZEN, env.journal); + carolsUSD = accountFunds(*env.closed(), carol, USD(0), fhZERO_IF_FROZEN, env.journal); BEAST_EXPECT(carolsUSD == USD(0)); // ... unless the query ignores the FROZEN state. - carolsUSD = accountFunds( - *env.closed(), carol, USD(0), fhIGNORE_FREEZE, env.journal); + carolsUSD = accountFunds(*env.closed(), carol, USD(0), fhIGNORE_FREEZE, env.journal); BEAST_EXPECT(carolsUSD == USD(50)); // Just to be tidy, thaw gw. @@ -1044,13 +911,8 @@ class View_test : public beast::unit_test::suite Env env(*this); Config config; std::shared_ptr const genesis = - std::make_shared( - create_genesis, - config, - std::vector{}, - env.app().getNodeFamily()); - auto const ledger = std::make_shared( - *genesis, env.app().timeKeeper().closeTime()); + std::make_shared(create_genesis, config, std::vector{}, env.app().getNodeFamily()); + auto const ledger = std::make_shared(*genesis, env.app().timeKeeper().closeTime()); wipe(*ledger); ledger->rawInsert(sle(1)); ReadView& v0 = *ledger; @@ -1120,8 +982,8 @@ class GetAmendments_test : public beast::unit_test::suite BEAST_EXPECT(majorities.size() >= 2); // None of the amendments should be enabled yet. - auto enableds = getEnabledAmendments(*env.closed()); - BEAST_EXPECT(enableds.empty()); + auto enabledAmendments = getEnabledAmendments(*env.closed()); + BEAST_EXPECT(enabledAmendments.empty()); // Now wait 2 weeks modulo 256 ledgers for the amendments to be // enabled. Speed the process by closing ledgers every 80 minutes, @@ -1130,12 +992,12 @@ class GetAmendments_test : public beast::unit_test::suite { using namespace std::chrono_literals; env.close(80min); - enableds = getEnabledAmendments(*env.closed()); - if (!enableds.empty()) + enabledAmendments = getEnabledAmendments(*env.closed()); + if (!enabledAmendments.empty()) break; } BEAST_EXPECT(i == 255); - BEAST_EXPECT(enableds.size() >= 2); + BEAST_EXPECT(enabledAmendments.size() >= 2); } void diff --git a/src/test/nodestore/Backend_test.cpp b/src/test/nodestore/Backend_test.cpp index 07b35ed9fc..19f3bc43e5 100644 --- a/src/test/nodestore/Backend_test.cpp +++ b/src/test/nodestore/Backend_test.cpp @@ -19,10 +19,7 @@ class Backend_test : public TestBase { public: void - testBackend( - std::string const& type, - std::uint64_t const seedValue, - int numObjsToTest = 2000) + testBackend(std::string const& type, std::uint64_t const seedValue, int numObjsToTest = 2000) { DummyScheduler scheduler; @@ -43,8 +40,8 @@ public: { // Open the backend - std::unique_ptr backend = Manager::instance().make_Backend( - params, megabytes(4), scheduler, journal); + std::unique_ptr backend = + Manager::instance().make_Backend(params, megabytes(4), scheduler, journal); backend->open(); // Write the batch @@ -68,8 +65,8 @@ public: { // Re-open the backend - std::unique_ptr backend = Manager::instance().make_Backend( - params, megabytes(4), scheduler, journal); + std::unique_ptr backend = + Manager::instance().make_Backend(params, megabytes(4), scheduler, journal); backend->open(); // Read it back in diff --git a/src/test/nodestore/Basics_test.cpp b/src/test/nodestore/Basics_test.cpp index 3a7c6a1fdd..e37544f58e 100644 --- a/src/test/nodestore/Basics_test.cpp +++ b/src/test/nodestore/Basics_test.cpp @@ -40,15 +40,13 @@ public: { EncodedBlob encoded(batch[i]); - DecodedBlob decoded( - encoded.getKey(), encoded.getData(), encoded.getSize()); + DecodedBlob decoded(encoded.getKey(), encoded.getData(), encoded.getSize()); BEAST_EXPECT(decoded.wasOk()); if (decoded.wasOk()) { - std::shared_ptr const object( - decoded.createObject()); + std::shared_ptr const object(decoded.createObject()); BEAST_EXPECT(isSame(batch[i], object)); } diff --git a/src/test/nodestore/Database_test.cpp b/src/test/nodestore/Database_test.cpp index e5446374ec..1229923e7d 100644 --- a/src/test/nodestore/Database_test.cpp +++ b/src/test/nodestore/Database_test.cpp @@ -4,11 +4,10 @@ #include #include -#include - #include #include #include +#include namespace xrpl { @@ -44,12 +43,9 @@ public: if (BEAST_EXPECT(s.globalPragma->size() == 3)) { - BEAST_EXPECT( - s.globalPragma->at(0) == "PRAGMA journal_mode=wal;"); - BEAST_EXPECT( - s.globalPragma->at(1) == "PRAGMA synchronous=normal;"); - BEAST_EXPECT( - s.globalPragma->at(2) == "PRAGMA temp_store=file;"); + BEAST_EXPECT(s.globalPragma->at(0) == "PRAGMA journal_mode=wal;"); + BEAST_EXPECT(s.globalPragma->at(1) == "PRAGMA synchronous=normal;"); + BEAST_EXPECT(s.globalPragma->at(2) == "PRAGMA temp_store=file;"); } } { @@ -68,8 +64,7 @@ public: return Env( *this, std::move(p), - std::make_unique( - integrityWarning, &found), + std::make_unique(integrityWarning, &found), beast::severities::kWarning); }(); @@ -77,12 +72,9 @@ public: auto const s = setup_DatabaseCon(env.app().config()); if (BEAST_EXPECT(s.globalPragma->size() == 3)) { - BEAST_EXPECT( - s.globalPragma->at(0) == "PRAGMA journal_mode=wal;"); - BEAST_EXPECT( - s.globalPragma->at(1) == "PRAGMA synchronous=normal;"); - BEAST_EXPECT( - s.globalPragma->at(2) == "PRAGMA temp_store=file;"); + BEAST_EXPECT(s.globalPragma->at(0) == "PRAGMA journal_mode=wal;"); + BEAST_EXPECT(s.globalPragma->at(1) == "PRAGMA synchronous=normal;"); + BEAST_EXPECT(s.globalPragma->at(2) == "PRAGMA temp_store=file;"); } } { @@ -101,8 +93,7 @@ public: return Env( *this, std::move(p), - std::make_unique( - integrityWarning, &found), + std::make_unique(integrityWarning, &found), beast::severities::kWarning); }(); @@ -110,12 +101,9 @@ public: auto const s = setup_DatabaseCon(env.app().config()); if (BEAST_EXPECT(s.globalPragma->size() == 3)) { - BEAST_EXPECT( - s.globalPragma->at(0) == "PRAGMA journal_mode=memory;"); - BEAST_EXPECT( - s.globalPragma->at(1) == "PRAGMA synchronous=off;"); - BEAST_EXPECT( - s.globalPragma->at(2) == "PRAGMA temp_store=memory;"); + BEAST_EXPECT(s.globalPragma->at(0) == "PRAGMA journal_mode=memory;"); + BEAST_EXPECT(s.globalPragma->at(1) == "PRAGMA synchronous=off;"); + BEAST_EXPECT(s.globalPragma->at(2) == "PRAGMA temp_store=memory;"); } } { @@ -135,8 +123,7 @@ public: return Env( *this, std::move(p), - std::make_unique( - integrityWarning, &found), + std::make_unique(integrityWarning, &found), beast::severities::kWarning); }(); @@ -146,12 +133,9 @@ public: auto const s = setup_DatabaseCon(env.app().config()); if (BEAST_EXPECT(s.globalPragma->size() == 3)) { - BEAST_EXPECT( - s.globalPragma->at(0) == "PRAGMA journal_mode=off;"); - BEAST_EXPECT( - s.globalPragma->at(1) == "PRAGMA synchronous=extra;"); - BEAST_EXPECT( - s.globalPragma->at(2) == "PRAGMA temp_store=default;"); + BEAST_EXPECT(s.globalPragma->at(0) == "PRAGMA journal_mode=off;"); + BEAST_EXPECT(s.globalPragma->at(1) == "PRAGMA synchronous=extra;"); + BEAST_EXPECT(s.globalPragma->at(2) == "PRAGMA temp_store=default;"); } } { @@ -172,8 +156,7 @@ public: return Env( *this, std::move(p), - std::make_unique( - integrityWarning, &found), + std::make_unique(integrityWarning, &found), beast::severities::kWarning); }(); @@ -183,12 +166,9 @@ public: auto const s = setup_DatabaseCon(env.app().config()); if (BEAST_EXPECT(s.globalPragma->size() == 3)) { - BEAST_EXPECT( - s.globalPragma->at(0) == "PRAGMA journal_mode=off;"); - BEAST_EXPECT( - s.globalPragma->at(1) == "PRAGMA synchronous=extra;"); - BEAST_EXPECT( - s.globalPragma->at(2) == "PRAGMA temp_store=default;"); + BEAST_EXPECT(s.globalPragma->at(0) == "PRAGMA journal_mode=off;"); + BEAST_EXPECT(s.globalPragma->at(1) == "PRAGMA synchronous=extra;"); + BEAST_EXPECT(s.globalPragma->at(2) == "PRAGMA temp_store=default;"); } } { @@ -429,12 +409,9 @@ public: if (BEAST_EXPECT(s.txPragma.size() == 4)) { BEAST_EXPECT(s.txPragma.at(0) == "PRAGMA page_size=4096;"); - BEAST_EXPECT( - s.txPragma.at(1) == "PRAGMA journal_size_limit=1582080;"); - BEAST_EXPECT( - s.txPragma.at(2) == "PRAGMA max_page_count=4294967294;"); - BEAST_EXPECT( - s.txPragma.at(3) == "PRAGMA mmap_size=17179869184;"); + BEAST_EXPECT(s.txPragma.at(1) == "PRAGMA journal_size_limit=1582080;"); + BEAST_EXPECT(s.txPragma.at(2) == "PRAGMA max_page_count=4294967294;"); + BEAST_EXPECT(s.txPragma.at(3) == "PRAGMA mmap_size=17179869184;"); } } { @@ -452,18 +429,14 @@ public: if (BEAST_EXPECT(s.txPragma.size() == 4)) { BEAST_EXPECT(s.txPragma.at(0) == "PRAGMA page_size=512;"); - BEAST_EXPECT( - s.txPragma.at(1) == "PRAGMA journal_size_limit=2582080;"); - BEAST_EXPECT( - s.txPragma.at(2) == "PRAGMA max_page_count=4294967294;"); - BEAST_EXPECT( - s.txPragma.at(3) == "PRAGMA mmap_size=17179869184;"); + BEAST_EXPECT(s.txPragma.at(1) == "PRAGMA journal_size_limit=2582080;"); + BEAST_EXPECT(s.txPragma.at(2) == "PRAGMA max_page_count=4294967294;"); + BEAST_EXPECT(s.txPragma.at(3) == "PRAGMA mmap_size=17179869184;"); } } { // Error: Invalid values - auto const expected = - "Invalid page_size. Must be between 512 and 65536."; + auto const expected = "Invalid page_size. Must be between 512 and 65536."; bool found = false; auto p = test::jtx::envconfig(); { @@ -486,8 +459,7 @@ public: } { // Error: Invalid values - auto const expected = - "Invalid page_size. Must be between 512 and 65536."; + auto const expected = "Invalid page_size. Must be between 512 and 65536."; bool found = false; auto p = test::jtx::envconfig(); { @@ -536,10 +508,7 @@ public: //-------------------------------------------------------------------------- void - testImport( - std::string const& destBackendType, - std::string const& srcBackendType, - std::int64_t seedValue) + testImport(std::string const& destBackendType, std::string const& srcBackendType, std::int64_t seedValue) { DummyScheduler scheduler; @@ -553,8 +522,8 @@ public: // Write to source db { - std::unique_ptr src = Manager::instance().make_Database( - megabytes(4), scheduler, 2, srcParams, journal_); + std::unique_ptr src = + Manager::instance().make_Database(megabytes(4), scheduler, 2, srcParams, journal_); storeBatch(*src, batch); } @@ -562,8 +531,8 @@ public: { // Re-open the db - std::unique_ptr src = Manager::instance().make_Database( - megabytes(4), scheduler, 2, srcParams, journal_); + std::unique_ptr src = + Manager::instance().make_Database(megabytes(4), scheduler, 2, srcParams, journal_); // Set up the destination database beast::temp_dir dest_db; @@ -571,12 +540,10 @@ public: destParams.set("type", destBackendType); destParams.set("path", dest_db.path()); - std::unique_ptr dest = Manager::instance().make_Database( - megabytes(4), scheduler, 2, destParams, journal_); + std::unique_ptr dest = + Manager::instance().make_Database(megabytes(4), scheduler, 2, destParams, journal_); - testcase( - "import into '" + destBackendType + "' from '" + - srcBackendType + "'"); + testcase("import into '" + destBackendType + "' from '" + srcBackendType + "'"); // Do the import dest->importDatabase(*src); @@ -618,8 +585,8 @@ public: { // Open the database - std::unique_ptr db = Manager::instance().make_Database( - megabytes(4), scheduler, 2, nodeParams, journal_); + std::unique_ptr db = + Manager::instance().make_Database(megabytes(4), scheduler, 2, nodeParams, journal_); // Write the batch storeBatch(*db, batch); @@ -643,8 +610,8 @@ public: if (testPersistence) { // Re-open the database without the ephemeral DB - std::unique_ptr db = Manager::instance().make_Database( - megabytes(4), scheduler, 2, nodeParams, journal_); + std::unique_ptr db = + Manager::instance().make_Database(megabytes(4), scheduler, 2, nodeParams, journal_); // Read it back in Batch copy; @@ -661,10 +628,8 @@ public: // Verify default earliest ledger sequence { std::unique_ptr db = - Manager::instance().make_Database( - megabytes(4), scheduler, 2, nodeParams, journal_); - BEAST_EXPECT( - db->earliestLedgerSeq() == XRP_LEDGER_EARLIEST_SEQ); + Manager::instance().make_Database(megabytes(4), scheduler, 2, nodeParams, journal_); + BEAST_EXPECT(db->earliestLedgerSeq() == XRP_LEDGER_EARLIEST_SEQ); } // Set an invalid earliest ledger sequence @@ -672,21 +637,18 @@ public: { nodeParams.set("earliest_seq", "0"); std::unique_ptr db = - Manager::instance().make_Database( - megabytes(4), scheduler, 2, nodeParams, journal_); + Manager::instance().make_Database(megabytes(4), scheduler, 2, nodeParams, journal_); } catch (std::runtime_error const& e) { - BEAST_EXPECT( - std::strcmp(e.what(), "Invalid earliest_seq") == 0); + BEAST_EXPECT(std::strcmp(e.what(), "Invalid earliest_seq") == 0); } { // Set a valid earliest ledger sequence nodeParams.set("earliest_seq", "1"); std::unique_ptr db = - Manager::instance().make_Database( - megabytes(4), scheduler, 2, nodeParams, journal_); + Manager::instance().make_Database(megabytes(4), scheduler, 2, nodeParams, journal_); // Verify database uses the earliest ledger sequence setting BEAST_EXPECT(db->earliestLedgerSeq() == 1); @@ -696,17 +658,13 @@ public: try { // Set to default earliest ledger sequence - nodeParams.set( - "earliest_seq", std::to_string(XRP_LEDGER_EARLIEST_SEQ)); + nodeParams.set("earliest_seq", std::to_string(XRP_LEDGER_EARLIEST_SEQ)); std::unique_ptr db2 = - Manager::instance().make_Database( - megabytes(4), scheduler, 2, nodeParams, journal_); + Manager::instance().make_Database(megabytes(4), scheduler, 2, nodeParams, journal_); } catch (std::runtime_error const& e) { - BEAST_EXPECT( - std::strcmp(e.what(), "earliest_seq set more than once") == - 0); + BEAST_EXPECT(std::strcmp(e.what(), "earliest_seq set more than once") == 0); } } } diff --git a/src/test/nodestore/NuDBFactory_test.cpp b/src/test/nodestore/NuDBFactory_test.cpp index b91425259c..7d8f1df45d 100644 --- a/src/test/nodestore/NuDBFactory_test.cpp +++ b/src/test/nodestore/NuDBFactory_test.cpp @@ -30,17 +30,14 @@ private: // Helper function to create a backend and test basic functionality bool - testBackendFunctionality( - Section const& params, - std::size_t expectedBlocksize) + testBackendFunctionality(Section const& params, std::size_t expectedBlocksize) { try { DummyScheduler scheduler; test::SuiteJournal journal("NuDBFactory_test", *this); - auto backend = Manager::instance().make_Backend( - params, megabytes(4), scheduler, journal); + auto backend = Manager::instance().make_Backend(params, megabytes(4), scheduler, journal); if (!BEAST_EXPECT(backend)) return false; @@ -72,17 +69,13 @@ private: // Helper function to test log messages void - testLogMessage( - Section const& params, - beast::severities::Severity level, - std::string const& expectedMessage) + testLogMessage(Section const& params, beast::severities::Severity level, std::string const& expectedMessage) { test::StreamSink sink(level); beast::Journal journal(sink); DummyScheduler scheduler; - auto backend = Manager::instance().make_Backend( - params, megabytes(4), scheduler, journal); + auto backend = Manager::instance().make_Backend(params, megabytes(4), scheduler, journal); std::string logOutput = sink.messages().str(); BEAST_EXPECT(logOutput.find(expectedMessage) != std::string::npos); @@ -99,12 +92,10 @@ private: beast::Journal journal(sink); DummyScheduler scheduler; - auto backend = Manager::instance().make_Backend( - params, megabytes(4), scheduler, journal); + auto backend = Manager::instance().make_Backend(params, megabytes(4), scheduler, journal); std::string logOutput = sink.messages().str(); - bool hasWarning = - logOutput.find("Invalid nudb_block_size") != std::string::npos; + bool hasWarning = logOutput.find("Invalid nudb_block_size") != std::string::npos; BEAST_EXPECT(hasWarning == !shouldWork); } @@ -199,10 +190,7 @@ public: beast::temp_dir tempDir; auto params = createSection(tempDir.path(), "8192"); - testLogMessage( - params, - beast::severities::kInfo, - "Using custom NuDB block size: 8192"); + testLogMessage(params, beast::severities::kInfo, "Using custom NuDB block size: 8192"); } // Test invalid block size failure @@ -216,20 +204,14 @@ public: DummyScheduler scheduler; try { - auto backend = Manager::instance().make_Backend( - params, megabytes(4), scheduler, journal); + auto backend = Manager::instance().make_Backend(params, megabytes(4), scheduler, journal); fail(); } catch (std::exception const& e) { std::string logOutput{e.what()}; - BEAST_EXPECT( - logOutput.find("Invalid nudb_block_size: 5000") != - std::string::npos); - BEAST_EXPECT( - logOutput.find( - "Must be power of 2 between 4096 and 32768") != - std::string::npos); + BEAST_EXPECT(logOutput.find("Invalid nudb_block_size: 5000") != std::string::npos); + BEAST_EXPECT(logOutput.find("Must be power of 2 between 4096 and 32768") != std::string::npos); } } @@ -244,17 +226,14 @@ public: DummyScheduler scheduler; try { - auto backend = Manager::instance().make_Backend( - params, megabytes(4), scheduler, journal); + auto backend = Manager::instance().make_Backend(params, megabytes(4), scheduler, journal); fail(); } catch (std::exception const& e) { std::string logOutput{e.what()}; - BEAST_EXPECT( - logOutput.find("Invalid nudb_block_size value: invalid") != - std::string::npos); + BEAST_EXPECT(logOutput.find("Invalid nudb_block_size value: invalid") != std::string::npos); } } } @@ -290,16 +269,13 @@ public: DummyScheduler scheduler; try { - auto backend = Manager::instance().make_Backend( - params, megabytes(4), scheduler, journal); + auto backend = Manager::instance().make_Backend(params, megabytes(4), scheduler, journal); BEAST_EXPECT(shouldWork); } catch (std::exception const& e) { std::string logOutput{e.what()}; - BEAST_EXPECT( - logOutput.find("Invalid nudb_block_size") != - std::string::npos); + BEAST_EXPECT(logOutput.find("Invalid nudb_block_size") != std::string::npos); } } } @@ -317,8 +293,7 @@ public: // Test first constructor (without nudb::context) { - auto backend1 = Manager::instance().make_Backend( - params, megabytes(4), scheduler, journal); + auto backend1 = Manager::instance().make_Backend(params, megabytes(4), scheduler, journal); BEAST_EXPECT(backend1 != nullptr); BEAST_EXPECT(testBackendFunctionality(params, 16384)); } @@ -358,14 +333,11 @@ public: beast::Journal journal(sink); DummyScheduler scheduler; - auto backend = Manager::instance().make_Backend( - params, megabytes(4), scheduler, journal); + auto backend = Manager::instance().make_Backend(params, megabytes(4), scheduler, journal); // Should log success message for valid values std::string logOutput = sink.messages().str(); - bool hasSuccessMessage = - logOutput.find("Using custom NuDB block size") != - std::string::npos; + bool hasSuccessMessage = logOutput.find("Using custom NuDB block size") != std::string::npos; BEAST_EXPECT(hasSuccessMessage); } @@ -383,8 +355,7 @@ public: DummyScheduler scheduler; try { - auto backend = Manager::instance().make_Backend( - params, megabytes(4), scheduler, journal); + auto backend = Manager::instance().make_Backend(params, megabytes(4), scheduler, journal); fail(); } catch (...) @@ -400,8 +371,7 @@ public: { testcase("Data persistence with different block sizes"); - std::vector blockSizes = { - "4096", "8192", "16384", "32768"}; + std::vector blockSizes = {"4096", "8192", "16384", "32768"}; for (auto const& size : blockSizes) { @@ -416,8 +386,7 @@ public: // Store data { - auto backend = Manager::instance().make_Backend( - params, megabytes(4), scheduler, journal); + auto backend = Manager::instance().make_Backend(params, megabytes(4), scheduler, journal); backend->open(); storeBatch(*backend, batch); backend->close(); @@ -425,8 +394,7 @@ public: // Retrieve data in new backend instance { - auto backend = Manager::instance().make_Backend( - params, megabytes(4), scheduler, journal); + auto backend = Manager::instance().make_Backend(params, megabytes(4), scheduler, journal); backend->open(); Batch copy; diff --git a/src/test/nodestore/TestBase.h b/src/test/nodestore/TestBase.h index 83db83b1df..dfa2b05642 100644 --- a/src/test/nodestore/TestBase.h +++ b/src/test/nodestore/TestBase.h @@ -1,5 +1,4 @@ -#ifndef XRPL_NODESTORE_BASE_H_INCLUDED -#define XRPL_NODESTORE_BASE_H_INCLUDED +#pragma once #include #include @@ -27,9 +26,7 @@ namespace NodeStore { struct LessThan { bool - operator()( - std::shared_ptr const& lhs, - std::shared_ptr const& rhs) const noexcept + operator()(std::shared_ptr const& lhs, std::shared_ptr const& rhs) const noexcept { return lhs->getHash() < rhs->getHash(); } @@ -37,12 +34,9 @@ struct LessThan /** Returns `true` if objects are identical. */ inline bool -isSame( - std::shared_ptr const& lhs, - std::shared_ptr const& rhs) +isSame(std::shared_ptr const& lhs, std::shared_ptr const& rhs) { - return (lhs->getType() == rhs->getType()) && - (lhs->getHash() == rhs->getHash()) && + return (lhs->getType() == rhs->getType()) && (lhs->getHash() == rhs->getHash()) && (lhs->getData() == rhs->getData()); } @@ -91,8 +85,7 @@ public: Blob blob(rand_int(rng, minPayloadBytes, maxPayloadBytes)); beast::rngfill(blob.data(), blob.size(), rng); - batch.push_back( - NodeObject::createObject(type, std::move(blob), hash)); + batch.push_back(NodeObject::createObject(type, std::move(blob), hash)); } return batch; @@ -144,8 +137,7 @@ public: { std::shared_ptr object; - Status const status = - backend.fetch(batch[i]->getHash().cbegin(), &object); + Status const status = backend.fetch(batch[i]->getHash().cbegin(), &object); BEAST_EXPECT(status == ok); @@ -165,8 +157,7 @@ public: { std::shared_ptr object; - Status const status = - backend.fetch(batch[i]->getHash().cbegin(), &object); + Status const status = backend.fetch(batch[i]->getHash().cbegin(), &object); BEAST_EXPECT(status == notFound); } @@ -182,11 +173,7 @@ public: Blob data(object->getData()); - db.store( - object->getType(), - std::move(data), - object->getHash(), - db.earliestLedgerSeq()); + db.store(object->getType(), std::move(data), object->getHash(), db.earliestLedgerSeq()); } } @@ -199,8 +186,7 @@ public: for (int i = 0; i < batch.size(); ++i) { - std::shared_ptr object = - db.fetchNodeObject(batch[i]->getHash(), 0); + std::shared_ptr object = db.fetchNodeObject(batch[i]->getHash(), 0); if (object != nullptr) pCopy->push_back(object); @@ -210,5 +196,3 @@ public: } // namespace NodeStore } // namespace xrpl - -#endif diff --git a/src/test/nodestore/Timing_test.cpp b/src/test/nodestore/Timing_test.cpp index 9c91311416..09e39028e8 100644 --- a/src/test/nodestore/Timing_test.cpp +++ b/src/test/nodestore/Timing_test.cpp @@ -31,13 +31,9 @@ namespace xrpl { namespace NodeStore { std::unique_ptr -make_Backend( - Section const& config, - Scheduler& scheduler, - beast::Journal journal) +make_Backend(Section const& config, Scheduler& scheduler, beast::Journal journal) { - return Manager::instance().make_Backend( - config, megabytes(4), scheduler, journal); + return Manager::instance().make_Backend(config, megabytes(4), scheduler, journal); } // Fill memory with random bits @@ -104,8 +100,7 @@ public: rngcpy(data + 1, key.size() - 1, gen_); Blob value(d_size_(gen_)); rngcpy(&value[0], value.size(), gen_); - return NodeObject::createObject( - safe_cast(d_type_(gen_)), std::move(value), key); + return NodeObject::createObject(safe_cast(d_type_(gen_)), std::move(value), key); } // returns a batch of NodeObjects starting at n @@ -150,8 +145,7 @@ public: { std::string s; for (auto iter = config.begin(); iter != config.end(); ++iter) - s += (iter != config.begin() ? "," : "") + iter->first + "=" + - iter->second; + s += (iter != config.begin() ? "," : "") + iter->first + "=" + iter->second; return s; } @@ -185,8 +179,7 @@ public: std::atomic& c_; public: - parallel_for_lambda(std::size_t n, std::atomic& c) - : n_(n), c_(c) + parallel_for_lambda(std::size_t n, std::atomic& c) : n_(n), c_(c) { } @@ -213,10 +206,7 @@ public: */ template void - parallel_for( - std::size_t const n, - std::size_t number_of_threads, - Args const&... args) + parallel_for(std::size_t const n, std::size_t number_of_threads, Args const&... args) { std::atomic c(0); std::vector t; @@ -229,10 +219,7 @@ public: template void - parallel_for_id( - std::size_t const n, - std::size_t number_of_threads, - Args const&... args) + parallel_for_id(std::size_t const n, std::size_t number_of_threads, Args const&... args) { std::atomic c(0); std::vector t; @@ -247,10 +234,7 @@ public: // Insert only void - do_insert( - Section const& config, - Params const& params, - beast::Journal journal) + do_insert(Section const& config, Params const& params, beast::Journal journal) { DummyScheduler scheduler; auto backend = make_Backend(config, scheduler, journal); @@ -265,8 +249,7 @@ public: Sequence seq_; public: - explicit Body(suite& s, Backend& backend) - : suite_(s), backend_(backend), seq_(1) + explicit Body(suite& s, Backend& backend) : suite_(s), backend_(backend), seq_(1) { } @@ -286,11 +269,7 @@ public: try { - parallel_for( - params.items, - params.threads, - std::ref(*this), - std::ref(*backend)); + parallel_for(params.items, params.threads, std::ref(*this), std::ref(*backend)); } catch (std::exception const&) { @@ -304,10 +283,7 @@ public: // Fetch existing keys void - do_fetch( - Section const& config, - Params const& params, - beast::Journal journal) + do_fetch(Section const& config, Params const& params, beast::Journal journal) { DummyScheduler scheduler; auto backend = make_Backend(config, scheduler, journal); @@ -324,16 +300,8 @@ public: std::uniform_int_distribution dist_; public: - Body( - std::size_t id, - suite& s, - Params const& params, - Backend& backend) - : suite_(s) - , backend_(backend) - , seq1_(1) - , gen_(id + 1) - , dist_(0, params.items - 1) + Body(std::size_t id, suite& s, Params const& params, Backend& backend) + : suite_(s), backend_(backend), seq1_(1), gen_(id + 1), dist_(0, params.items - 1) { } @@ -356,12 +324,7 @@ public: }; try { - parallel_for_id( - params.items, - params.threads, - std::ref(*this), - std::ref(params), - std::ref(*backend)); + parallel_for_id(params.items, params.threads, std::ref(*this), std::ref(params), std::ref(*backend)); } catch (std::exception const&) { @@ -375,10 +338,7 @@ public: // Perform lookups of non-existent keys void - do_missing( - Section const& config, - Params const& params, - beast::Journal journal) + do_missing(Section const& config, Params const& params, beast::Journal journal) { DummyScheduler scheduler; auto backend = make_Backend(config, scheduler, journal); @@ -396,11 +356,7 @@ public: std::uniform_int_distribution dist_; public: - Body( - std::size_t id, - suite& s, - Params const& params, - Backend& backend) + Body(std::size_t id, suite& s, Params const& params, Backend& backend) : suite_(s) //, params_ (params) , backend_(backend) @@ -429,12 +385,7 @@ public: try { - parallel_for_id( - params.items, - params.threads, - std::ref(*this), - std::ref(params), - std::ref(*backend)); + parallel_for_id(params.items, params.threads, std::ref(*this), std::ref(params), std::ref(*backend)); } catch (std::exception const&) { @@ -448,10 +399,7 @@ public: // Fetch with present and missing keys void - do_mixed( - Section const& config, - Params const& params, - beast::Journal journal) + do_mixed(Section const& config, Params const& params, beast::Journal journal) { DummyScheduler scheduler; auto backend = make_Backend(config, scheduler, journal); @@ -471,11 +419,7 @@ public: std::uniform_int_distribution dist_; public: - Body( - std::size_t id, - suite& s, - Params const& params, - Backend& backend) + Body(std::size_t id, suite& s, Params const& params, Backend& backend) : suite_(s) //, params_ (params) , backend_(backend) @@ -517,12 +461,7 @@ public: try { - parallel_for_id( - params.items, - params.threads, - std::ref(*this), - std::ref(params), - std::ref(*backend)); + parallel_for_id(params.items, params.threads, std::ref(*this), std::ref(params), std::ref(*backend)); } catch (std::exception const&) { @@ -561,11 +500,7 @@ public: std::uniform_int_distribution older_; public: - Body( - std::size_t id, - suite& s, - Params const& params, - Backend& backend) + Body(std::size_t id, suite& s, Params const& params, Backend& backend) : suite_(s) , params_(params) , backend_(backend) @@ -631,12 +566,7 @@ public: try { - parallel_for_id( - params.items, - params.threads, - std::ref(*this), - std::ref(params), - std::ref(*backend)); + parallel_for_id(params.items, params.threads, std::ref(*this), std::ref(params), std::ref(*backend)); } catch (std::exception const&) { @@ -650,36 +580,26 @@ public: //-------------------------------------------------------------------------- - using test_func = - void (Timing_test::*)(Section const&, Params const&, beast::Journal); + using test_func = void (Timing_test::*)(Section const&, Params const&, beast::Journal); using test_list = std::vector>; duration_type - do_test( - test_func f, - Section const& config, - Params const& params, - beast::Journal journal) + do_test(test_func f, Section const& config, Params const& params, beast::Journal journal) { auto const start = clock_type::now(); (this->*f)(config, params, journal); - return std::chrono::duration_cast( - clock_type::now() - start); + return std::chrono::duration_cast(clock_type::now() - start); } void - do_tests( - std::size_t threads, - test_list const& tests, - std::vector const& config_strings) + do_tests(std::size_t threads, test_list const& tests, std::vector const& config_strings) { using std::setw; int w = 8; for (auto const& test : tests) if (w < test.first.size()) w = test.first.size(); - log << threads << " Thread" << (threads > 1 ? "s" : "") << ", " - << default_items << " Objects" << std::endl; + log << threads << " Thread" << (threads > 1 ? "s" : "") << ", " << default_items << " Objects" << std::endl; { std::stringstream ss; ss << std::left << setw(10) << "Backend" << std::right; @@ -702,12 +622,9 @@ public: Section config = parse(config_string); config.set("path", tempDir.path()); std::stringstream ss; - ss << std::left << setw(10) - << get(config, "type", std::string()) << std::right; + ss << std::left << setw(10) << get(config, "type", std::string()) << std::right; for (auto const& test : tests) - ss << " " << setw(w) - << to_string( - do_test(test.second, config, params, journal)); + ss << " " << setw(w) << to_string(do_test(test.second, config, params, journal)); ss << " " << to_string(config); log << ss.str() << std::endl; } diff --git a/src/test/nodestore/import_test.cpp b/src/test/nodestore/import_test.cpp index 9a786801cb..896f9558da 100644 --- a/src/test/nodestore/import_test.cpp +++ b/src/test/nodestore/import_test.cpp @@ -62,10 +62,7 @@ public: save_stream_state& operator=(save_stream_state const&) = delete; explicit save_stream_state(std::ostream& os) - : os_(os) - , precision_(os.precision()) - , flags_(os.flags()) - , fill_(os.fill()) + : os_(os), precision_(os.precision()), flags_(os.flags()), fill_(os.fill()) { } }; @@ -212,11 +209,9 @@ public: return; } auto const rate = elapsed.count() / double(work); - clock_type::duration const remain( - static_cast((work_ - work) * rate)); - log << "Remaining: " << detail::fmtdur(remain) << " (" << work << " of " - << work_ << " in " << detail::fmtdur(elapsed) << ", " - << (work - prev_) << " in " << detail::fmtdur(now - report_) << ")"; + clock_type::duration const remain(static_cast((work_ - work) * rate)); + log << "Remaining: " << detail::fmtdur(remain) << " (" << work << " of " << work_ << " in " + << detail::fmtdur(elapsed) << ", " << (work - prev_) << " in " << detail::fmtdur(now - report_) << ")"; report_ = now; prev_ = work; } @@ -335,11 +330,9 @@ public: options.create_if_missing = false; options.max_open_files = 2000; // 5000? rocksdb::DB* pdb = nullptr; - rocksdb::Status status = - rocksdb::DB::OpenForReadOnly(options, from_path, &pdb); + rocksdb::Status status = rocksdb::DB::OpenForReadOnly(options, from_path, &pdb); if (!status.ok() || !pdb) - Throw( - "Can't open '" + from_path + "': " + status.ToString()); + Throw("Can't open '" + from_path + "': " + status.ToString()); db.reset(pdb); } // Create data file with values @@ -372,9 +365,7 @@ public: for (it->SeekToFirst(); it->Valid(); it->Next()) { if (it->key().size() != 32) - Throw( - "Unexpected key size " + - std::to_string(it->key().size())); + Throw("Unexpected key size " + std::to_string(it->key().size())); void const* const key = it->key().data(); void const* const data = it->value().data(); auto const size = it->value().size(); @@ -385,11 +376,9 @@ public: // Verify codec correctness { buffer buf2; - auto const check = - nodeobject_decompress(out.first, out.second, buf2); + auto const check = nodeobject_decompress(out.first, out.second, buf2); BEAST_EXPECT(check.second == size); - BEAST_EXPECT( - std::memcmp(check.first, clean.get(), size) == 0); + BEAST_EXPECT(std::memcmp(check.first, clean.get(), size) == 0); } // Data Record auto os = dw.prepare( @@ -409,8 +398,7 @@ public: Throw(ec); } db.reset(); - log << "Import data: " - << detail::fmtdur(std::chrono::steady_clock::now() - start); + log << "Import data: " << detail::fmtdur(std::chrono::steady_clock::now() - start); auto const df_size = df.size(ec); if (ec) Throw(ec); @@ -424,8 +412,7 @@ public: kh.pepper = pepper(kh.salt); kh.block_size = block_size(kp); kh.load_factor = std::min(65536.0 * load_factor, 65535); - kh.buckets = - std::ceil(nitems / (bucket_capacity(kh.block_size) * load_factor)); + kh.buckets = std::ceil(nitems / (bucket_capacity(kh.block_size) * load_factor)); kh.modulus = ceil_pow2(kh.buckets); native_file kf; kf.create(file_mode::append, kp, ec); @@ -443,8 +430,7 @@ public: // Build contiguous sequential sections of the // key file using multiple passes over the data. // - auto const buckets = - std::max(1, buffer_size / kh.block_size); + auto const buckets = std::max(1, buffer_size / kh.block_size); buf.reserve(buckets * kh.block_size); auto const passes = (kh.buckets + buckets - 1) / buckets; log << "items: " << nitems @@ -471,8 +457,7 @@ public: } // Insert all keys into buckets // Iterate Data File - bulk_reader r( - df, dat_file_header::size, df_size, bulk_size); + bulk_reader r(df, dat_file_header::size, df_size, bulk_size); while (!r.eof()) { auto const offset = r.offset(); @@ -497,8 +482,7 @@ public: p(log, npass * df_size + r.offset()); if (n < b0 || n >= b1) continue; - bucket b( - kh.block_size, buf.get() + (n - b0) * kh.block_size); + bucket b(kh.block_size, buf.get() + (n - b0) * kh.block_size); maybe_spill(b, dw, ec); if (ec) Throw(ec); @@ -517,8 +501,7 @@ public: Throw(ec); } } - kf.write( - (b0 + 1) * kh.block_size, buf.get(), bn * kh.block_size, ec); + kf.write((b0 + 1) * kh.block_size, buf.get(), bn * kh.block_size, ec); if (ec) Throw(ec); ++npass; diff --git a/src/test/overlay/ProtocolVersion_test.cpp b/src/test/overlay/ProtocolVersion_test.cpp index 507a42eca0..02cbaba909 100644 --- a/src/test/overlay/ProtocolVersion_test.cpp +++ b/src/test/overlay/ProtocolVersion_test.cpp @@ -62,18 +62,10 @@ public: testcase("Protocol version negotiation"); BEAST_EXPECT(negotiateProtocolVersion("RTXP/1.2") == std::nullopt); - BEAST_EXPECT( - negotiateProtocolVersion("RTXP/1.2, XRPL/2.0, XRPL/2.1") == - make_protocol(2, 1)); - BEAST_EXPECT( - negotiateProtocolVersion("XRPL/2.2") == make_protocol(2, 2)); - BEAST_EXPECT( - negotiateProtocolVersion( - "RTXP/1.2, XRPL/2.2, XRPL/2.3, XRPL/999.999") == - make_protocol(2, 2)); - BEAST_EXPECT( - negotiateProtocolVersion("XRPL/999.999, WebSocket/1.0") == - std::nullopt); + BEAST_EXPECT(negotiateProtocolVersion("RTXP/1.2, XRPL/2.0, XRPL/2.1") == make_protocol(2, 1)); + BEAST_EXPECT(negotiateProtocolVersion("XRPL/2.2") == make_protocol(2, 2)); + BEAST_EXPECT(negotiateProtocolVersion("RTXP/1.2, XRPL/2.2, XRPL/2.3, XRPL/999.999") == make_protocol(2, 2)); + BEAST_EXPECT(negotiateProtocolVersion("XRPL/999.999, WebSocket/1.0") == std::nullopt); BEAST_EXPECT(negotiateProtocolVersion("") == std::nullopt); } } diff --git a/src/test/overlay/TMGetObjectByHash_test.cpp b/src/test/overlay/TMGetObjectByHash_test.cpp new file mode 100644 index 0000000000..c4e70ba305 --- /dev/null +++ b/src/test/overlay/TMGetObjectByHash_test.cpp @@ -0,0 +1,195 @@ +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace xrpl { +namespace test { + +using namespace jtx; + +/** + * Test for TMGetObjectByHash reply size limiting. + * + * This verifies the fix that limits TMGetObjectByHash replies to + * Tuning::hardMaxReplyNodes to prevent excessive memory usage and + * potential DoS attacks from peers requesting large numbers of objects. + */ +class TMGetObjectByHash_test : public beast::unit_test::suite +{ + using middle_type = boost::beast::tcp_stream; + using stream_type = boost::beast::ssl_stream; + using socket_type = boost::asio::ip::tcp::socket; + using shared_context = std::shared_ptr; + /** + * Test peer that captures sent messages for verification. + */ + class PeerTest : public PeerImp + { + public: + PeerTest( + Application& app, + std::shared_ptr const& slot, + http_request_type&& request, + PublicKey const& publicKey, + ProtocolVersion protocol, + Resource::Consumer consumer, + std::unique_ptr&& stream_ptr, + OverlayImpl& overlay) + : PeerImp( + app, + id_++, + slot, + std::move(request), + publicKey, + protocol, + consumer, + std::move(stream_ptr), + overlay) + { + } + + ~PeerTest() = default; + + void + run() override + { + } + + void + send(std::shared_ptr const& m) override + { + lastSentMessage_ = m; + } + + std::shared_ptr + getLastSentMessage() const + { + return lastSentMessage_; + } + + static void + resetId() + { + id_ = 0; + } + + private: + inline static Peer::id_t id_ = 0; + std::shared_ptr lastSentMessage_; + }; + + shared_context context_{make_SSLContext("")}; + ProtocolVersion protocolVersion_{1, 7}; + + std::shared_ptr + createPeer(jtx::Env& env) + { + auto& overlay = dynamic_cast(env.app().overlay()); + boost::beast::http::request request; + auto stream_ptr = std::make_unique(socket_type(env.app().getIOContext()), *context_); + + beast::IP::Endpoint local(boost::asio::ip::make_address("172.1.1.1"), 51235); + beast::IP::Endpoint remote(boost::asio::ip::make_address("172.1.1.2"), 51235); + + PublicKey key(std::get<0>(randomKeyPair(KeyType::ed25519))); + auto consumer = overlay.resourceManager().newInboundEndpoint(remote); + auto [slot, _] = overlay.peerFinder().new_inbound_slot(local, remote); + + auto peer = std::make_shared( + env.app(), slot, std::move(request), key, protocolVersion_, consumer, std::move(stream_ptr), overlay); + + overlay.add_active(peer); + return peer; + } + + std::shared_ptr + createRequest(size_t const numObjects, Env& env) + { + // Store objects in the NodeStore that will be found during the query + auto& nodeStore = env.app().getNodeStore(); + + // Create and store objects + std::vector hashes; + hashes.reserve(numObjects); + for (int i = 0; i < numObjects; ++i) + { + uint256 hash(xrpl::sha512Half(i)); + hashes.push_back(hash); + + Blob data(100, static_cast(i % 256)); + nodeStore.store(hotLEDGER, std::move(data), hash, nodeStore.earliestLedgerSeq()); + } + + // Create a request with more objects than hardMaxReplyNodes + auto request = std::make_shared(); + request->set_type(protocol::TMGetObjectByHash_ObjectType_otLEDGER); + request->set_query(true); + + for (int i = 0; i < numObjects; ++i) + { + auto object = request->add_objects(); + object->set_hash(hashes[i].data(), hashes[i].size()); + object->set_ledgerseq(i); + } + return request; + } + + /** + * Test that reply is limited to hardMaxReplyNodes when more objects + * are requested than the limit allows. + */ + void + testReplyLimit(size_t const numObjects, int const expectedReplySize) + { + testcase("Reply Limit"); + + Env env(*this); + PeerTest::resetId(); + + auto peer = createPeer(env); + + auto request = createRequest(numObjects, env); + // Call the onMessage handler + peer->onMessage(request); + + // Verify that a reply was sent + auto sentMessage = peer->getLastSentMessage(); + BEAST_EXPECT(sentMessage != nullptr); + + // Parse the reply message + auto const& buffer = sentMessage->getBuffer(compression::Compressed::Off); + + BEAST_EXPECT(buffer.size() > 6); + // Skip the message header (6 bytes: 4 for size, 2 for type) + protocol::TMGetObjectByHash reply; + BEAST_EXPECT(reply.ParseFromArray(buffer.data() + 6, buffer.size() - 6) == true); + + // Verify the reply is limited to expectedReplySize + BEAST_EXPECT(reply.objects_size() == expectedReplySize); + } + + void + run() override + { + int const limit = static_cast(Tuning::hardMaxReplyNodes); + testReplyLimit(limit + 1, limit); + testReplyLimit(limit, limit); + testReplyLimit(limit - 1, limit - 1); + } +}; + +BEAST_DEFINE_TESTSUITE(TMGetObjectByHash, overlay, xrpl); + +} // namespace test +} // namespace xrpl diff --git a/src/test/overlay/cluster_test.cpp b/src/test/overlay/cluster_test.cpp index 4638434233..60fd5d62b3 100644 --- a/src/test/overlay/cluster_test.cpp +++ b/src/test/overlay/cluster_test.cpp @@ -69,8 +69,7 @@ public: { testcase("Membership: Non-empty cluster and some present"); - std::vector cluster( - network.begin(), network.begin() + 16); + std::vector cluster(network.begin(), network.begin() + 16); while (cluster.size() != 32) cluster.push_back(randomNode()); @@ -83,17 +82,14 @@ public: for (auto const& n : network) { auto found = std::find(cluster.begin(), cluster.end(), n); - BEAST_EXPECT( - static_cast(c->member(n)) == - (found != cluster.end())); + BEAST_EXPECT(static_cast(c->member(n)) == (found != cluster.end())); } } { testcase("Membership: Non-empty cluster and all present"); - std::vector cluster( - network.begin(), network.begin() + 32); + std::vector cluster(network.begin(), network.begin() + 32); auto c = create(cluster); @@ -103,9 +99,7 @@ public: for (auto const& n : network) { auto found = std::find(cluster.begin(), cluster.end(), n); - BEAST_EXPECT( - static_cast(c->member(n)) == - (found != cluster.end())); + BEAST_EXPECT(static_cast(c->member(n)) == (found != cluster.end())); } } } @@ -181,8 +175,7 @@ public: while (network.size() != 8) network.push_back(randomNode()); - auto format = [](PublicKey const& publicKey, - char const* comment = nullptr) { + auto format = [](PublicKey const& publicKey, char const* comment = nullptr) { auto ret = toBase58(TokenType::NodePublic, publicKey); if (comment) @@ -205,8 +198,7 @@ public: s1.append(format(network[4], " Leading Whitespace")); s1.append(format(network[5], " Trailing Whitespace ")); s1.append(format(network[6], " Leading & Trailing Whitespace ")); - s1.append(format( - network[7], " Leading, Trailing & Internal Whitespace ")); + s1.append(format(network[7], " Leading, Trailing & Internal Whitespace ")); BEAST_EXPECT(c->load(s1)); diff --git a/src/test/overlay/compression_test.cpp b/src/test/overlay/compression_test.cpp index f2fe07cb33..19876809d2 100644 --- a/src/test/overlay/compression_test.cpp +++ b/src/test/overlay/compression_test.cpp @@ -65,11 +65,7 @@ public: template void - doTest( - std::shared_ptr proto, - protocol::MessageType mt, - uint16_t nbuffers, - std::string msg) + doTest(std::shared_ptr proto, protocol::MessageType mt, uint16_t nbuffers, std::string msg) { testcase("Compress/Decompress: " + msg); @@ -84,16 +80,13 @@ public: for (int i = 0; i < nbuffers; i++) { auto start = buffer.begin() + sz * i; - auto end = i < nbuffers - 1 ? (buffer.begin() + sz * (i + 1)) - : buffer.end(); + auto end = i < nbuffers - 1 ? (buffer.begin() + sz * (i + 1)) : buffer.end(); std::vector slice(start, end); - buffers.commit(boost::asio::buffer_copy( - buffers.prepare(slice.size()), boost::asio::buffer(slice))); + buffers.commit(boost::asio::buffer_copy(buffers.prepare(slice.size()), boost::asio::buffer(slice))); } boost::system::error_code ec; - auto header = - xrpl::detail::parseMessageHeader(ec, buffers.data(), buffer.size()); + auto header = xrpl::detail::parseMessageHeader(ec, buffers.data(), buffer.size()); BEAST_EXPECT(header); @@ -103,27 +96,20 @@ public: std::vector decompressed; decompressed.resize(header->uncompressed_size); - BEAST_EXPECT( - header->payload_wire_size == buffer.size() - header->header_size); + BEAST_EXPECT(header->payload_wire_size == buffer.size() - header->header_size); ZeroCopyInputStream stream(buffers.data()); stream.Skip(header->header_size); auto decompressedSize = xrpl::compression::decompress( - stream, - header->payload_wire_size, - decompressed.data(), - header->uncompressed_size); + stream, header->payload_wire_size, decompressed.data(), header->uncompressed_size); BEAST_EXPECT(decompressedSize == header->uncompressed_size); auto const proto1 = std::make_shared(); - BEAST_EXPECT( - proto1->ParseFromArray(decompressed.data(), decompressedSize)); + BEAST_EXPECT(proto1->ParseFromArray(decompressed.data(), decompressedSize)); auto uncompressed = m.getBuffer(Compressed::Off); BEAST_EXPECT(std::equal( - uncompressed.begin() + xrpl::compression::headerBytes, - uncompressed.end(), - decompressed.begin())); + uncompressed.begin() + xrpl::compression::headerBytes, uncompressed.end(), decompressed.begin())); } std::shared_ptr @@ -139,20 +125,9 @@ public: st[sfSequence] = i; st[sfPublicKey] = std::get<0>(master); st[sfSigningPubKey] = std::get<0>(signing); - st[sfDomain] = makeSlice( - std::string("example") + std::to_string(i) + - std::string(".com")); - sign( - st, - HashPrefix::manifest, - KeyType::ed25519, - std::get<1>(master), - sfMasterSignature); - sign( - st, - HashPrefix::manifest, - KeyType::ed25519, - std::get<1>(signing)); + st[sfDomain] = makeSlice(std::string("example") + std::to_string(i) + std::string(".com")); + sign(st, HashPrefix::manifest, KeyType::ed25519, std::get<1>(master), sfMasterSignature); + sign(st, HashPrefix::manifest, KeyType::ed25519, std::get<1>(signing)); Serializer s; st.add(s); auto* manifest = manifests->add_list(); @@ -191,21 +166,18 @@ public: auto toBinary = [this](std::string const& text) { auto blob = strUnHex(text); BEAST_EXPECT(blob); - return std::string{ - reinterpret_cast(blob->data()), blob->size()}; + return std::string{reinterpret_cast(blob->data()), blob->size()}; }; std::string usdTxBlob = ""; auto wsc = makeWSClient(env.app().config()); { - Json::Value jrequestUsd; - jrequestUsd[jss::secret] = toBase58(generateSeed("bob")); - jrequestUsd[jss::tx_json] = - pay("bob", "alice", bob["USD"](fund / 2)); - Json::Value jreply_usd = wsc->invoke("sign", jrequestUsd); + Json::Value requestUSD; + requestUSD[jss::secret] = toBase58(generateSeed("bob")); + requestUSD[jss::tx_json] = pay("bob", "alice", bob["USD"](fund / 2)); + Json::Value replyUSD = wsc->invoke("sign", requestUSD); - usdTxBlob = - toBinary(jreply_usd[jss::result][jss::tx_blob].asString()); + usdTxBlob = toBinary(replyUSD[jss::result][jss::tx_blob].asString()); } auto transaction = std::make_shared(); @@ -266,8 +238,7 @@ public: parentHash = ledgerHash(info); Serializer nData; xrpl::addRaw(info, nData); - ledgerData->add_nodes()->set_nodedata( - nData.getDataPtr(), nData.getLength()); + ledgerData->add_nodes()->set_nodedata(nData.getDataPtr(), nData.getLength()); } return ledgerData; @@ -278,8 +249,7 @@ public: { auto getObject = std::make_shared(); - getObject->set_type(protocol::TMGetObjectByHash_ObjectType:: - TMGetObjectByHash_ObjectType_otTRANSACTION); + getObject->set_type(protocol::TMGetObjectByHash_ObjectType::TMGetObjectByHash_ObjectType_otTRANSACTION); getObject->set_query(true); getObject->set_seq(123456789); uint256 hash(xrpl::sha512Half(123456789)); @@ -311,20 +281,14 @@ public: st[sfPublicKey] = std::get<0>(master); st[sfSigningPubKey] = std::get<0>(signing); st[sfDomain] = makeSlice(std::string("example.com")); - sign( - st, - HashPrefix::manifest, - KeyType::ed25519, - std::get<1>(master), - sfMasterSignature); + sign(st, HashPrefix::manifest, KeyType::ed25519, std::get<1>(master), sfMasterSignature); sign(st, HashPrefix::manifest, KeyType::ed25519, std::get<1>(signing)); Serializer s; st.add(s); list->set_manifest(s.data(), s.size()); list->set_version(3); STObject signature(sfSignature); - xrpl::sign( - st, HashPrefix::manifest, KeyType::ed25519, std::get<1>(signing)); + xrpl::sign(st, HashPrefix::manifest, KeyType::ed25519, std::get<1>(signing)); Serializer s1; st.add(s1); list->set_signature(s1.data(), s1.size()); @@ -344,20 +308,14 @@ public: st[sfPublicKey] = std::get<0>(master); st[sfSigningPubKey] = std::get<0>(signing); st[sfDomain] = makeSlice(std::string("example.com")); - sign( - st, - HashPrefix::manifest, - KeyType::ed25519, - std::get<1>(master), - sfMasterSignature); + sign(st, HashPrefix::manifest, KeyType::ed25519, std::get<1>(master), sfMasterSignature); sign(st, HashPrefix::manifest, KeyType::ed25519, std::get<1>(signing)); Serializer s; st.add(s); list->set_manifest(s.data(), s.size()); list->set_version(4); STObject signature(sfSignature); - xrpl::sign( - st, HashPrefix::manifest, KeyType::ed25519, std::get<1>(signing)); + xrpl::sign(st, HashPrefix::manifest, KeyType::ed25519, std::get<1>(signing)); Serializer s1; st.add(s1); auto& blob = *list->add_blobs(); @@ -390,60 +348,24 @@ public: // 1.3KB doTest(buildEndpoints(100), protocol::mtENDPOINTS, 4, "TMEndpoints100"); // 242B - doTest( - buildTransaction(*logs), - protocol::mtTRANSACTION, - 1, - "TMTransaction"); + doTest(buildTransaction(*logs), protocol::mtTRANSACTION, 1, "TMTransaction"); // 87B doTest(buildGetLedger(), protocol::mtGET_LEDGER, 1, "TMGetLedger"); // 61KB - doTest( - buildLedgerData(500, *logs), - protocol::mtLEDGER_DATA, - 10, - "TMLedgerData500"); + doTest(buildLedgerData(500, *logs), protocol::mtLEDGER_DATA, 10, "TMLedgerData500"); // 122 KB - doTest( - buildLedgerData(1000, *logs), - protocol::mtLEDGER_DATA, - 20, - "TMLedgerData1000"); + doTest(buildLedgerData(1000, *logs), protocol::mtLEDGER_DATA, 20, "TMLedgerData1000"); // 1.2MB - doTest( - buildLedgerData(10000, *logs), - protocol::mtLEDGER_DATA, - 50, - "TMLedgerData10000"); + doTest(buildLedgerData(10000, *logs), protocol::mtLEDGER_DATA, 50, "TMLedgerData10000"); // 12MB - doTest( - buildLedgerData(100000, *logs), - protocol::mtLEDGER_DATA, - 100, - "TMLedgerData100000"); + doTest(buildLedgerData(100000, *logs), protocol::mtLEDGER_DATA, 100, "TMLedgerData100000"); // 61MB - doTest( - buildLedgerData(500000, *logs), - protocol::mtLEDGER_DATA, - 100, - "TMLedgerData500000"); + doTest(buildLedgerData(500000, *logs), protocol::mtLEDGER_DATA, 100, "TMLedgerData500000"); // 7.7KB - doTest( - buildGetObjectByHash(), - protocol::mtGET_OBJECTS, - 4, - "TMGetObjectByHash"); + doTest(buildGetObjectByHash(), protocol::mtGET_OBJECTS, 4, "TMGetObjectByHash"); // 895B - doTest( - buildValidatorList(), - protocol::mtVALIDATOR_LIST, - 4, - "TMValidatorList"); - doTest( - buildValidatorListCollection(), - protocol::mtVALIDATOR_LIST_COLLECTION, - 4, - "TMValidatorListCollection"); + doTest(buildValidatorList(), protocol::mtVALIDATOR_LIST, 4, "TMValidatorList"); + doTest(buildValidatorListCollection(), protocol::mtVALIDATOR_LIST_COLLECTION, 4, "TMValidatorListCollection"); } void @@ -460,13 +382,11 @@ public: c.loadFromString(str.str()); auto env = std::make_shared(*this); env->app().config().COMPRESSION = c.COMPRESSION; - env->app().config().VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE = - c.VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE; + env->app().config().VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE = c.VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE; return env; }; auto handshake = [&](int outboundEnable, int inboundEnable) { - beast::IP::Address addr = - boost::asio::ip::make_address("172.1.1.100"); + beast::IP::Address addr = boost::asio::ip::make_address("172.1.1.100"); auto env = getEnv(outboundEnable); auto request = xrpl::makeRequest( @@ -483,25 +403,15 @@ public: auto const peerEnabled = inboundEnable && outboundEnable; // inbound is enabled if the request's header has the feature // enabled and the peer's configuration is enabled - auto const inboundEnabled = peerFeatureEnabled( - http_request, FEATURE_COMPR, "lz4", inboundEnable); + auto const inboundEnabled = peerFeatureEnabled(http_request, FEATURE_COMPR, "lz4", inboundEnable); BEAST_EXPECT(!(peerEnabled ^ inboundEnabled)); env.reset(); env = getEnv(inboundEnable); - auto http_resp = xrpl::makeResponse( - true, - http_request, - addr, - addr, - uint256{1}, - 1, - {1, 0}, - env->app()); + auto http_resp = xrpl::makeResponse(true, http_request, addr, addr, uint256{1}, 1, {1, 0}, env->app()); // outbound is enabled if the response's header has the feature // enabled and the peer's configuration is enabled - auto const outboundEnabled = peerFeatureEnabled( - http_resp, FEATURE_COMPR, "lz4", outboundEnable); + auto const outboundEnabled = peerFeatureEnabled(http_resp, FEATURE_COMPR, "lz4", outboundEnable); BEAST_EXPECT(!(peerEnabled ^ outboundEnabled)); }; handshake(1, 1); diff --git a/src/test/overlay/reduce_relay_test.cpp b/src/test/overlay/reduce_relay_test.cpp index 6af27ea8f1..9d9aef7a36 100644 --- a/src/test/overlay/reduce_relay_test.cpp +++ b/src/test/overlay/reduce_relay_test.cpp @@ -31,8 +31,7 @@ using MessageSPtr = std::shared_ptr; using LinkSPtr = std::shared_ptr; using PeerSPtr = std::shared_ptr; using PeerWPtr = std::weak_ptr; -using SquelchCB = - std::function; +using SquelchCB = std::function; using UnsquelchCB = std::function; using LinkIterCB = std::function; @@ -46,8 +45,7 @@ static constexpr std::uint32_t MAX_MESSAGES = 200000; class PeerPartial : public Peer { public: - PeerPartial() - : nodePublicKey_(derivePublicKey(KeyType::ed25519, randomSecretKey())) + PeerPartial() : nodePublicKey_(derivePublicKey(KeyType::ed25519, randomSecretKey())) { } @@ -76,8 +74,7 @@ public: return {}; } void - charge(Resource::Charge const& fee, std::string const& context = {}) - override + charge(Resource::Charge const& fee, std::string const& context = {}) override { } bool @@ -248,10 +245,7 @@ class Link using Latency = std::pair; public: - Link( - Validator& validator, - PeerSPtr peer, - Latency const& latency = {milliseconds(5), milliseconds(15)}) + Link(Validator& validator, PeerSPtr peer, Latency const& latency = {milliseconds(5), milliseconds(15)}) : validator_(validator), peer_(peer), latency_(latency), up_(true) { auto sp = peer_.lock(); @@ -350,8 +344,7 @@ public: void addPeer(PeerSPtr peer) { - links_.emplace( - std::make_pair(peer->id(), std::make_shared(*this, peer))); + links_.emplace(std::make_pair(peer->id(), std::make_shared(*this, peer))); } void @@ -374,10 +367,7 @@ public: for_links(LinkIterCB f, bool simulateSlow = false) { std::vector v; - std::transform( - links_.begin(), links_.end(), std::back_inserter(v), [](auto& kv) { - return kv.second; - }); + std::transform(links_.begin(), links_.end(), std::back_inserter(v), [](auto& kv) { return kv.second; }); std::random_device d; std::mt19937 g(d()); std::shuffle(v.begin(), v.end(), g); @@ -442,8 +432,7 @@ class PeerSim : public PeerPartial, public std::enable_shared_from_this { public: using id_t = Peer::id_t; - PeerSim(Overlay& overlay, beast::Journal journal) - : overlay_(overlay), squelch_(journal) + PeerSim(Overlay& overlay, beast::Journal journal) : overlay_(overlay), squelch_(journal) { id_ = sid_++; } @@ -487,8 +476,7 @@ public: auto validator = squelch.validatorpubkey(); PublicKey key(Slice(validator.data(), validator.size())); if (squelch.squelch()) - squelch_.addSquelch( - key, std::chrono::seconds{squelch.squelchduration()}); + squelch_.addSquelch(key, std::chrono::seconds{squelch.squelchduration()}); else squelch_.removeSquelch(key); } @@ -508,8 +496,7 @@ class OverlaySim : public Overlay, public reduce_relay::SquelchHandler public: using id_t = Peer::id_t; using clock_type = ManualClock; - OverlaySim(Application& app) - : slots_(app.logs(), *this, app.config()), logs_(app.logs()) + OverlaySim(Application& app) : slots_(app.logs(), *this, app.config()), logs_(app.logs()) { } @@ -644,13 +631,7 @@ public: return *selected.begin(); } - std::unordered_map< - id_t, - std::tuple< - reduce_relay::PeerState, - std::uint16_t, - std::uint32_t, - std::uint32_t>> + std::unordered_map> getPeers(PublicKey const& validator) { return slots_.getPeers(validator); @@ -664,10 +645,7 @@ public: private: void - squelch( - PublicKey const& validator, - Peer::id_t id, - std::uint32_t squelchDuration) const override + squelch(PublicKey const& validator, Peer::id_t id, std::uint32_t squelchDuration) const override { if (auto it = peers_.find(id); it != peers_.end()) squelch_(validator, it->second, squelchDuration); @@ -762,10 +740,7 @@ public: void enableLink(std::uint16_t validatorId, Peer::id_t peer, bool enable) { - auto it = - std::find_if(validators_.begin(), validators_.end(), [&](auto& v) { - return v.id() == validatorId; - }); + auto it = std::find_if(validators_.begin(), validators_.end(), [&](auto& v) { return v.id() == validatorId; }); assert(it != validators_.end()); if (enable) it->linkUp(peer); @@ -787,17 +762,13 @@ public: PublicKey key = v; squelch.clear_validatorpubkey(); squelch.set_validatorpubkey(key.data(), key.size()); - v.for_links({peer}, [&](Link& l, MessageSPtr) { - std::dynamic_pointer_cast(l.getPeer())->send(squelch); - }); + v.for_links( + {peer}, [&](Link& l, MessageSPtr) { std::dynamic_pointer_cast(l.getPeer())->send(squelch); }); } } void - for_rand( - std::uint32_t min, - std::uint32_t max, - std::function f) + for_rand(std::uint32_t min, std::uint32_t max, std::function f) { auto size = max - min; std::vector s(size); @@ -829,9 +800,7 @@ public: for (int m = 0; m < nMessages; ++m) { ManualClock::randAdvance(milliseconds(1800), milliseconds(2200)); - for_rand(0, nValidators, [&](std::uint32_t v) { - validators_[v].for_links(link); - }); + for_rand(0, nValidators, [&](std::uint32_t v) { validators_[v].for_links(link); }); } } @@ -862,8 +831,7 @@ public: for (auto& [_, v] : peers) { (void)_; - if (std::get(v) == - reduce_relay::PeerState::Squelched) + if (std::get(v) == reduce_relay::PeerState::Squelched) return false; } } @@ -886,20 +854,15 @@ protected: { auto peers = network_.overlay().getPeers(network_.validator(validator)); std::cout << msg << " " - << "num peers " << (int)network_.overlay().getNumPeers() - << std::endl; + << "num peers " << (int)network_.overlay().getNumPeers() << std::endl; for (auto& [k, v] : peers) - std::cout << k << ":" << (int)std::get(v) - << " "; + std::cout << k << ":" << (int)std::get(v) << " "; std::cout << std::endl; } /** Send squelch (if duration is set) or unsquelch (if duration not set) */ Peer::id_t - sendSquelch( - PublicKey const& validator, - PeerWPtr const& peerPtr, - std::optional duration) + sendSquelch(PublicKey const& validator, PeerWPtr const& peerPtr, std::optional duration) { protocol::TMSquelch squelch; bool res = duration ? true : false; @@ -938,8 +901,7 @@ protected: void random(bool log) { - std::unordered_map events{ - {LinkDown, {}}, {PeerDisconnected, {}}}; + std::unordered_map events{{LinkDown, {}}, {PeerDisconnected, {}}}; time_point lastCheck = ManualClock::now(); network_.reset(); @@ -950,16 +912,12 @@ protected: bool squelched = false; std::stringstream str; - link.send( - m, - [&](PublicKey const& key, - PeerWPtr const& peerPtr, - std::uint32_t duration) { - assert(key == validator); - auto p = sendSquelch(key, peerPtr, duration); - squelched = true; - str << p << " "; - }); + link.send(m, [&](PublicKey const& key, PeerWPtr const& peerPtr, std::uint32_t duration) { + assert(key == validator); + auto p = sendSquelch(key, peerPtr, duration); + squelched = true; + str << p << " "; + }); if (squelched) { @@ -968,20 +926,13 @@ protected: for (auto s : selected) str << s << " "; if (log) - std::cout - << (double)reduce_relay::epoch(now) - .count() / - 1000. - << " random, squelched, validator: " << validator.id() - << " peers: " << str.str() << std::endl; - auto countingState = - network_.overlay().isCountingState(validator); + std::cout << (double)reduce_relay::epoch(now).count() / 1000. + << " random, squelched, validator: " << validator.id() << " peers: " << str.str() + << std::endl; + auto countingState = network_.overlay().isCountingState(validator); BEAST_EXPECT( countingState == false && - selected.size() == - env_.app() - .config() - .VP_REDUCE_RELAY_SQUELCH_MAX_SELECTED_PEERS); + selected.size() == env_.app().config().VP_REDUCE_RELAY_SQUELCH_MAX_SELECTED_PEERS); } // Trigger Link Down or Peer Disconnect event @@ -997,19 +948,14 @@ protected: events[event].time_ = now; if (event == EventType::LinkDown) { - network_.enableLink( - validator.id(), link.peerId(), false); - events[event].isSelected_ = - network_.overlay().isSelected( - validator, link.peerId()); + network_.enableLink(validator.id(), link.peerId(), false); + events[event].isSelected_ = network_.overlay().isSelected(validator, link.peerId()); } else - events[event].isSelected_ = - network_.isSelected(link.peerId()); + events[event].isSelected_ = network_.isSelected(link.peerId()); }; auto r = rand_int(0, 1000); - if (r == (int)EventType::LinkDown || - r == (int)EventType::PeerDisconnected) + if (r == (int)EventType::LinkDown || r == (int)EventType::PeerDisconnected) { update(static_cast(r)); } @@ -1019,22 +965,18 @@ protected: { auto& event = events[EventType::PeerDisconnected]; bool allCounting = network_.allCounting(event.peer_); - network_.overlay().deletePeer( - event.peer_, - [&](PublicKey const& v, PeerWPtr const& peerPtr) { - if (event.isSelected_) - sendSquelch(v, peerPtr, {}); - event.handled_ = true; - }); + network_.overlay().deletePeer(event.peer_, [&](PublicKey const& v, PeerWPtr const& peerPtr) { + if (event.isSelected_) + sendSquelch(v, peerPtr, {}); + event.handled_ = true; + }); // Should only be unsquelched if the peer is in Selected state // If in Selected state it's possible unsquelching didn't // take place because there is no peers in Squelched state in // any of the slots where the peer is in Selected state // (allCounting is true) - bool handled = - (event.isSelected_ == false && !event.handled_) || - (event.isSelected_ == true && - (event.handled_ || allCounting)); + bool handled = (event.isSelected_ == false && !event.handled_) || + (event.isSelected_ == true && (event.handled_ || allCounting)); BEAST_EXPECT(handled); event.state_ = State::Off; event.isSelected_ = false; @@ -1058,38 +1000,28 @@ protected: bool mustHandle = false; if (event.state_ == State::On && BEAST_EXPECT(event.key_)) { - event.isSelected_ = - network_.overlay().isSelected(*event.key_, event.peer_); + event.isSelected_ = network_.overlay().isSelected(*event.key_, event.peer_); auto peers = network_.overlay().getPeers(*event.key_); - auto d = reduce_relay::epoch(now).count() - - std::get<3>(peers[event.peer_]); - mustHandle = event.isSelected_ && - d > milliseconds(reduce_relay::IDLED).count() && - network_.overlay().inState( - *event.key_, reduce_relay::PeerState::Squelched) > - 0 && + auto d = reduce_relay::epoch(now).count() - std::get<3>(peers[event.peer_]); + mustHandle = event.isSelected_ && d > milliseconds(reduce_relay::IDLED).count() && + network_.overlay().inState(*event.key_, reduce_relay::PeerState::Squelched) > 0 && peers.find(event.peer_) != peers.end(); } - network_.overlay().deleteIdlePeers( - [&](PublicKey const& v, PeerWPtr const& ptr) { - event.handled_ = true; - if (mustHandle && v == event.key_) - { - event.state_ = State::WaitReset; - sendSquelch(validator, ptr, {}); - } - }); - bool handled = - (event.handled_ && event.state_ == State::WaitReset) || - (!event.handled_ && !mustHandle); + network_.overlay().deleteIdlePeers([&](PublicKey const& v, PeerWPtr const& ptr) { + event.handled_ = true; + if (mustHandle && v == event.key_) + { + event.state_ = State::WaitReset; + sendSquelch(validator, ptr, {}); + } + }); + bool handled = (event.handled_ && event.state_ == State::WaitReset) || (!event.handled_ && !mustHandle); BEAST_EXPECT(handled); } if (event.state_ == State::WaitReset || - (event.state_ == State::On && - (now - event.time_ > (reduce_relay::IDLED + seconds(2))))) + (event.state_ == State::On && (now - event.time_ > (reduce_relay::IDLED + seconds(2))))) { - bool handled = - event.state_ == State::WaitReset || !event.handled_; + bool handled = event.state_ == State::WaitReset || !event.handled_; BEAST_EXPECT(handled); event.state_ = State::Off; event.isSelected_ = false; @@ -1106,10 +1038,8 @@ protected: // All Peer Disconnect events must be handled BEAST_EXPECT(disconnected.cnt_ == disconnected.handledCnt_); if (log) - std::cout << "link down count: " << down.cnt_ << "/" - << down.handledCnt_ - << " peer disconnect count: " << disconnected.cnt_ << "/" - << disconnected.handledCnt_; + std::cout << "link down count: " << down.cnt_ << "/" << down.handledCnt_ + << " peer disconnect count: " << disconnected.cnt_ << "/" << disconnected.handledCnt_; } bool @@ -1135,9 +1065,7 @@ protected: void testInitialRound(bool log) { - doTest("Initial Round", log, [this](bool log) { - BEAST_EXPECT(propagateAndSquelch(log)); - }); + doTest("Initial Round", log, [this](bool log) { BEAST_EXPECT(propagateAndSquelch(log)); }); } /** Receiving message from squelched peer too soon should not change the @@ -1158,9 +1086,8 @@ protected: testPeerUnsquelched(bool log) { ManualClock::advance(seconds(601)); - doTest("Peer Unsquelched", log, [this](bool log) { - BEAST_EXPECT(propagateNoSquelch(log, 2, true, true, false)); - }); + doTest( + "Peer Unsquelched", log, [this](bool log) { BEAST_EXPECT(propagateNoSquelch(log, 2, true, true, false)); }); } /** Propagate enough messages to generate one squelch event */ @@ -1171,22 +1098,14 @@ protected: network_.propagate( [&](Link& link, MessageSPtr message) { std::uint16_t squelched = 0; - link.send( - message, - [&](PublicKey const& key, - PeerWPtr const& peerPtr, - std::uint32_t duration) { - squelched++; - sendSquelch(key, peerPtr, duration); - }); + link.send(message, [&](PublicKey const& key, PeerWPtr const& peerPtr, std::uint32_t duration) { + squelched++; + sendSquelch(key, peerPtr, duration); + }); if (squelched) { BEAST_EXPECT( - squelched == - MAX_PEERS - - env_.app() - .config() - .VP_REDUCE_RELAY_SQUELCH_MAX_SELECTED_PEERS); + squelched == MAX_PEERS - env_.app().config().VP_REDUCE_RELAY_SQUELCH_MAX_SELECTED_PEERS); n++; } }, @@ -1195,9 +1114,7 @@ protected: purge, resetClock); auto selected = network_.overlay().getSelected(network_.validator(0)); - BEAST_EXPECT( - selected.size() == - env_.app().config().VP_REDUCE_RELAY_SQUELCH_MAX_SELECTED_PEERS); + BEAST_EXPECT(selected.size() == env_.app().config().VP_REDUCE_RELAY_SQUELCH_MAX_SELECTED_PEERS); BEAST_EXPECT(n == 1); // only one selection round auto res = checkCounting(network_.validator(0), false); BEAST_EXPECT(res); @@ -1206,24 +1123,15 @@ protected: /** Send fewer message so that squelch event is not generated */ bool - propagateNoSquelch( - bool log, - std::uint16_t nMessages, - bool countingState, - bool purge = true, - bool resetClock = true) + propagateNoSquelch(bool log, std::uint16_t nMessages, bool countingState, bool purge = true, bool resetClock = true) { bool squelched = false; network_.propagate( [&](Link& link, MessageSPtr message) { - link.send( - message, - [&](PublicKey const& key, - PeerWPtr const& peerPtr, - std::uint32_t duration) { - squelched = true; - BEAST_EXPECT(false); - }); + link.send(message, [&](PublicKey const& key, PeerWPtr const& peerPtr, std::uint32_t duration) { + squelched = true; + BEAST_EXPECT(false); + }); }, 1, nMessages, @@ -1256,16 +1164,8 @@ protected: BEAST_EXPECT(propagateAndSquelch(log, true, false)); auto id = network_.overlay().getSelectedPeer(network_.validator(0)); std::uint16_t unsquelched = 0; - network_.overlay().deletePeer( - id, [&](PublicKey const& key, PeerWPtr const& peer) { - unsquelched++; - }); - BEAST_EXPECT( - unsquelched == - MAX_PEERS - - env_.app() - .config() - .VP_REDUCE_RELAY_SQUELCH_MAX_SELECTED_PEERS); + network_.overlay().deletePeer(id, [&](PublicKey const& key, PeerWPtr const& peer) { unsquelched++; }); + BEAST_EXPECT(unsquelched == MAX_PEERS - env_.app().config().VP_REDUCE_RELAY_SQUELCH_MAX_SELECTED_PEERS); BEAST_EXPECT(checkCounting(network_.validator(0), true)); }); } @@ -1280,17 +1180,9 @@ protected: BEAST_EXPECT(propagateAndSquelch(log, true, false)); ManualClock::advance(reduce_relay::IDLED + seconds(1)); std::uint16_t unsquelched = 0; - network_.overlay().deleteIdlePeers( - [&](PublicKey const& key, PeerWPtr const& peer) { - unsquelched++; - }); + network_.overlay().deleteIdlePeers([&](PublicKey const& key, PeerWPtr const& peer) { unsquelched++; }); auto peers = network_.overlay().getPeers(network_.validator(0)); - BEAST_EXPECT( - unsquelched == - MAX_PEERS - - env_.app() - .config() - .VP_REDUCE_RELAY_SQUELCH_MAX_SELECTED_PEERS); + BEAST_EXPECT(unsquelched == MAX_PEERS - env_.app().config().VP_REDUCE_RELAY_SQUELCH_MAX_SELECTED_PEERS); BEAST_EXPECT(checkCounting(network_.validator(0), true)); }); } @@ -1305,15 +1197,12 @@ protected: BEAST_EXPECT(propagateAndSquelch(log, true, false)); auto peers = network_.overlay().getPeers(network_.validator(0)); auto it = std::find_if(peers.begin(), peers.end(), [&](auto it) { - return std::get(it.second) == - reduce_relay::PeerState::Squelched; + return std::get(it.second) == reduce_relay::PeerState::Squelched; }); assert(it != peers.end()); std::uint16_t unsquelched = 0; network_.overlay().deletePeer( - it->first, [&](PublicKey const& key, PeerWPtr const& peer) { - unsquelched++; - }); + it->first, [&](PublicKey const& key, PeerWPtr const& peer) { unsquelched++; }); BEAST_EXPECT(unsquelched == 0); BEAST_EXPECT(checkCounting(network_.validator(0), false)); }); @@ -1458,12 +1347,9 @@ vp_base_squelch_max_selected_peers=2 { doTest("BaseSquelchReady", log, [&](bool log) { ManualClock::reset(); - auto createSlots = [&](bool baseSquelchEnabled) - -> reduce_relay::Slots { - env_.app().config().VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE = - baseSquelchEnabled; - return reduce_relay::Slots( - env_.app().logs(), network_.overlay(), env_.app().config()); + auto createSlots = [&](bool baseSquelchEnabled) -> reduce_relay::Slots { + env_.app().config().VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE = baseSquelchEnabled; + return reduce_relay::Slots(env_.app().logs(), network_.overlay(), env_.app().config()); }; // base squelching must not be ready if squelching is disabled BEAST_EXPECT(!createSlots(false).baseSquelchReady()); @@ -1494,10 +1380,7 @@ vp_base_squelch_max_selected_peers=2 { uint256 key(i); network_.overlay().updateSlotAndSquelch( - key, - network_.validator(0), - 0, - [&](PublicKey const&, PeerWPtr, std::uint32_t) {}); + key, network_.validator(0), 0, [&](PublicKey const&, PeerWPtr, std::uint32_t) {}); } auto peers = network_.overlay().getPeers(network_.validator(0)); // first message changes Slot state to Counting and is not counted, @@ -1506,20 +1389,14 @@ vp_base_squelch_max_selected_peers=2 // add duplicate uint256 key(nMessages - 1); network_.overlay().updateSlotAndSquelch( - key, - network_.validator(0), - 0, - [&](PublicKey const&, PeerWPtr, std::uint32_t) {}); + key, network_.validator(0), 0, [&](PublicKey const&, PeerWPtr, std::uint32_t) {}); // confirm the same number of messages peers = network_.overlay().getPeers(network_.validator(0)); BEAST_EXPECT(std::get<1>(peers[0]) == (nMessages - 1)); // advance the clock ManualClock::advance(reduce_relay::IDLED + seconds(1)); network_.overlay().updateSlotAndSquelch( - key, - network_.validator(0), - 0, - [&](PublicKey const&, PeerWPtr, std::uint32_t) {}); + key, network_.validator(0), 0, [&](PublicKey const&, PeerWPtr, std::uint32_t) {}); peers = network_.overlay().getPeers(network_.validator(0)); // confirm message number increased BEAST_EXPECT(std::get<1>(peers[0]) == nMessages); @@ -1532,8 +1409,7 @@ vp_base_squelch_max_selected_peers=2 { } void - squelch(PublicKey const&, Peer::id_t, std::uint32_t duration) - const override + squelch(PublicKey const&, Peer::id_t, std::uint32_t duration) const override { if (duration > maxDuration_) maxDuration_ = duration; @@ -1554,14 +1430,12 @@ vp_base_squelch_max_selected_peers=2 auto run = [&](int npeers) { handler.maxDuration_ = 0; - reduce_relay::Slots slots( - env_.app().logs(), handler, env_.app().config()); + reduce_relay::Slots slots(env_.app().logs(), handler, env_.app().config()); // 1st message from a new peer switches the slot // to counting state and resets the counts of all peers + // MAX_MESSAGE_THRESHOLD + 1 messages to reach the threshold // and switch the slot's state to peer selection. - for (int m = 1; m <= reduce_relay::MAX_MESSAGE_THRESHOLD + 2; - m++) + for (int m = 1; m <= reduce_relay::MAX_MESSAGE_THRESHOLD + 2; m++) { for (int peer = 0; peer < npeers; peer++) { @@ -1569,11 +1443,7 @@ vp_base_squelch_max_selected_peers=2 // slot's internal hash router accept the message std::uint64_t mid = m * 1000 + peer; uint256 const message{mid}; - slots.updateSlotAndSquelch( - message, - validator, - peer, - protocol::MessageType::mtVALIDATION); + slots.updateSlotAndSquelch(message, validator, peer, protocol::MessageType::mtVALIDATION); } } // make Slot's internal hash router expire all messages @@ -1603,24 +1473,14 @@ vp_base_squelch_max_selected_peers=2 handler.maxDuration_ <= MAX_UNSQUELCH_EXPIRE_PEERS.count()); using namespace beast::unit_test::detail; if (handler.maxDuration_ <= MAX_UNSQUELCH_EXPIRE_DEFAULT.count()) - log << make_reason( - "warning: squelch duration is low", - __FILE__, - __LINE__) - << std::endl - << std::flush; + log << make_reason("warning: squelch duration is low", __FILE__, __LINE__) << std::endl << std::flush; // more than 400 is still less than MAX_UNSQUELCH_EXPIRE_PEERS run(400); BEAST_EXPECT( handler.maxDuration_ >= MIN_UNSQUELCH_EXPIRE.count() && handler.maxDuration_ <= MAX_UNSQUELCH_EXPIRE_PEERS.count()); if (handler.maxDuration_ <= MAX_UNSQUELCH_EXPIRE_DEFAULT.count()) - log << make_reason( - "warning: squelch duration is low", - __FILE__, - __LINE__) - << std::endl - << std::flush; + log << make_reason("warning: squelch duration is low", __FILE__, __LINE__) << std::endl << std::flush; }); } @@ -1636,14 +1496,12 @@ vp_base_squelch_max_selected_peers=2 << "[compression]\n" << "1\n"; c.loadFromString(str.str()); - env_.app().config().VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE = - c.VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE; + env_.app().config().VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE = c.VP_REDUCE_RELAY_BASE_SQUELCH_ENABLE; env_.app().config().COMPRESSION = c.COMPRESSION; }; auto handshake = [&](int outboundEnable, int inboundEnable) { - beast::IP::Address addr = - boost::asio::ip::make_address("172.1.1.100"); + beast::IP::Address addr = boost::asio::ip::make_address("172.1.1.100"); setEnv(outboundEnable); auto request = xrpl::makeRequest( @@ -1660,24 +1518,14 @@ vp_base_squelch_max_selected_peers=2 auto const peerEnabled = inboundEnable && outboundEnable; // inbound is enabled if the request's header has the feature // enabled and the peer's configuration is enabled - auto const inboundEnabled = peerFeatureEnabled( - http_request, FEATURE_VPRR, inboundEnable); + auto const inboundEnabled = peerFeatureEnabled(http_request, FEATURE_VPRR, inboundEnable); BEAST_EXPECT(!(peerEnabled ^ inboundEnabled)); setEnv(inboundEnable); - auto http_resp = xrpl::makeResponse( - true, - http_request, - addr, - addr, - uint256{1}, - 1, - {1, 0}, - env_.app()); + auto http_resp = xrpl::makeResponse(true, http_request, addr, addr, uint256{1}, 1, {1, 0}, env_.app()); // outbound is enabled if the response's header has the feature // enabled and the peer's configuration is enabled - auto const outboundEnabled = - peerFeatureEnabled(http_resp, FEATURE_VPRR, outboundEnable); + auto const outboundEnabled = peerFeatureEnabled(http_resp, FEATURE_VPRR, outboundEnable); BEAST_EXPECT(!(peerEnabled ^ outboundEnabled)); }; handshake(1, 1); diff --git a/src/test/overlay/short_read_test.cpp b/src/test/overlay/short_read_test.cpp index 2db35dd93e..498ecb6a27 100644 --- a/src/test/overlay/short_read_test.cpp +++ b/src/test/overlay/short_read_test.cpp @@ -36,8 +36,7 @@ class short_read_test : public beast::unit_test::suite private: using io_context_type = boost::asio::io_context; using strand_type = boost::asio::strand; - using timer_type = - boost::asio::basic_waitable_timer; + using timer_type = boost::asio::basic_waitable_timer; using acceptor_type = boost::asio::ip::tcp::acceptor; using socket_type = boost::asio::ip::tcp::socket; using stream_type = boost::asio::ssl::stream; @@ -46,9 +45,7 @@ private: using address_type = boost::asio::ip::address; io_context_type io_context_; - boost::optional> - work_; + boost::optional> work_; std::thread thread_; std::shared_ptr context_; @@ -171,10 +168,7 @@ private: , test_(server_.test_) , acceptor_( test_.io_context_, - endpoint_type( - boost::asio::ip::make_address( - test::getEnvLocalhostAddr()), - 0)) + endpoint_type(boost::asio::ip::make_address(test::getEnvLocalhostAddr()), 0)) , socket_(test_.io_context_) , strand_(boost::asio::make_strand(test_.io_context_)) { @@ -186,9 +180,7 @@ private: close() override { if (!strand_.running_in_this_thread()) - return post( - strand_, - std::bind(&Acceptor::close, shared_from_this())); + return post(strand_, std::bind(&Acceptor::close, shared_from_this())); acceptor_.close(); } @@ -197,12 +189,7 @@ private: { acceptor_.async_accept( socket_, - bind_executor( - strand_, - std::bind( - &Acceptor::on_accept, - shared_from_this(), - std::placeholders::_1))); + bind_executor(strand_, std::bind(&Acceptor::on_accept, shared_from_this(), std::placeholders::_1))); } void @@ -221,18 +208,12 @@ private: { if (ec) return fail("accept", ec); - auto const p = - std::make_shared(server_, std::move(socket_)); + auto const p = std::make_shared(server_, std::move(socket_)); server_.add(p); p->run(); acceptor_.async_accept( socket_, - bind_executor( - strand_, - std::bind( - &Acceptor::on_accept, - shared_from_this(), - std::placeholders::_1))); + bind_executor(strand_, std::bind(&Acceptor::on_accept, shared_from_this(), std::placeholders::_1))); } }; @@ -261,9 +242,7 @@ private: close() override { if (!strand_.running_in_this_thread()) - return post( - strand_, - std::bind(&Connection::close, shared_from_this())); + return post(strand_, std::bind(&Connection::close, shared_from_this())); if (socket_.is_open()) { socket_.close(); @@ -276,19 +255,11 @@ private: { timer_.expires_after(std::chrono::seconds(3)); timer_.async_wait(bind_executor( - strand_, - std::bind( - &Connection::on_timer, - shared_from_this(), - std::placeholders::_1))); + strand_, std::bind(&Connection::on_timer, shared_from_this(), std::placeholders::_1))); stream_.async_handshake( stream_type::server, bind_executor( - strand_, - std::bind( - &Connection::on_handshake, - shared_from_this(), - std::placeholders::_1))); + strand_, std::bind(&Connection::on_handshake, shared_from_this(), std::placeholders::_1))); } void @@ -297,8 +268,7 @@ private: if (socket_.is_open()) { if (ec != boost::asio::error::operation_aborted) - test_.log << "[server] " << what << ": " << ec.message() - << std::endl; + test_.log << "[server] " << what << ": " << ec.message() << std::endl; socket_.close(); timer_.cancel(); } @@ -328,10 +298,7 @@ private: bind_executor( strand_, std::bind( - &Connection::on_read, - shared_from_this(), - std::placeholders::_1, - std::placeholders::_2))); + &Connection::on_read, shared_from_this(), std::placeholders::_1, std::placeholders::_2))); #else close(); #endif @@ -344,11 +311,7 @@ private: { server_.test_.log << "[server] read: EOF" << std::endl; return stream_.async_shutdown(bind_executor( - strand_, - std::bind( - &Connection::on_shutdown, - shared_from_this(), - std::placeholders::_1))); + strand_, std::bind(&Connection::on_shutdown, shared_from_this(), std::placeholders::_1))); } if (ec) return fail("read", ec); @@ -362,10 +325,7 @@ private: bind_executor( strand_, std::bind( - &Connection::on_write, - shared_from_this(), - std::placeholders::_1, - std::placeholders::_2))); + &Connection::on_write, shared_from_this(), std::placeholders::_1, std::placeholders::_2))); } void @@ -375,11 +335,7 @@ private: if (ec) return fail("write", ec); stream_.async_shutdown(bind_executor( - strand_, - std::bind( - &Connection::on_shutdown, - shared_from_this(), - std::placeholders::_1))); + strand_, std::bind(&Connection::on_shutdown, shared_from_this(), std::placeholders::_1))); } void @@ -447,9 +403,7 @@ private: close() override { if (!strand_.running_in_this_thread()) - return post( - strand_, - std::bind(&Connection::close, shared_from_this())); + return post(strand_, std::bind(&Connection::close, shared_from_this())); if (socket_.is_open()) { socket_.close(); @@ -462,19 +416,11 @@ private: { timer_.expires_after(std::chrono::seconds(3)); timer_.async_wait(bind_executor( - strand_, - std::bind( - &Connection::on_timer, - shared_from_this(), - std::placeholders::_1))); + strand_, std::bind(&Connection::on_timer, shared_from_this(), std::placeholders::_1))); socket_.async_connect( ep, bind_executor( - strand_, - std::bind( - &Connection::on_connect, - shared_from_this(), - std::placeholders::_1))); + strand_, std::bind(&Connection::on_connect, shared_from_this(), std::placeholders::_1))); } void @@ -483,8 +429,7 @@ private: if (socket_.is_open()) { if (ec != boost::asio::error::operation_aborted) - test_.log << "[client] " << what << ": " << ec.message() - << std::endl; + test_.log << "[client] " << what << ": " << ec.message() << std::endl; socket_.close(); timer_.cancel(); } @@ -509,11 +454,7 @@ private: stream_.async_handshake( stream_type::client, bind_executor( - strand_, - std::bind( - &Connection::on_handshake, - shared_from_this(), - std::placeholders::_1))); + strand_, std::bind(&Connection::on_handshake, shared_from_this(), std::placeholders::_1))); } void @@ -530,17 +471,10 @@ private: bind_executor( strand_, std::bind( - &Connection::on_write, - shared_from_this(), - std::placeholders::_1, - std::placeholders::_2))); + &Connection::on_write, shared_from_this(), std::placeholders::_1, std::placeholders::_2))); #else stream_.async_shutdown(bind_executor( - strand_, - std::bind( - &Connection::on_shutdown, - shared_from_this(), - std::placeholders::_1))); + strand_, std::bind(&Connection::on_shutdown, shared_from_this(), std::placeholders::_1))); #endif } @@ -558,17 +492,10 @@ private: bind_executor( strand_, std::bind( - &Connection::on_read, - shared_from_this(), - std::placeholders::_1, - std::placeholders::_2))); + &Connection::on_read, shared_from_this(), std::placeholders::_1, std::placeholders::_2))); #else stream_.async_shutdown(bind_executor( - strand_, - std::bind( - &Connection::on_shutdown, - shared_from_this(), - std::placeholders::_1))); + strand_, std::bind(&Connection::on_shutdown, shared_from_this(), std::placeholders::_1))); #endif } @@ -579,11 +506,7 @@ private: return fail("read", ec); buf_.commit(bytes_transferred); stream_.async_shutdown(bind_executor( - strand_, - std::bind( - &Connection::on_shutdown, - shared_from_this(), - std::placeholders::_1))); + strand_, std::bind(&Connection::on_shutdown, shared_from_this(), std::placeholders::_1))); } void diff --git a/src/test/overlay/traffic_count_test.cpp b/src/test/overlay/traffic_count_test.cpp index a8948879d9..6516fe3843 100644 --- a/src/test/overlay/traffic_count_test.cpp +++ b/src/test/overlay/traffic_count_test.cpp @@ -21,13 +21,11 @@ public: message.set_type(protocol::TMPing::ptPING); // a known message is categorized to a proper category - auto const known = - TrafficCount::categorize(message, protocol::mtPING, false); + auto const known = TrafficCount::categorize(message, protocol::mtPING, false); BEAST_EXPECT(known == TrafficCount::category::base); // an unknown message type is categorized as unknown - auto const unknown = TrafficCount::categorize( - message, static_cast(99), false); + auto const unknown = TrafficCount::categorize(message, static_cast(99), false); BEAST_EXPECT(unknown == TrafficCount::category::unknown); } @@ -57,18 +55,12 @@ public: }); auto const counts_new = m_traffic.getCounts(); - std::for_each( - counts_new.begin(), counts_new.end(), [&](auto const& pair) { - BEAST_EXPECT( - pair.second.bytesIn.load() == tc.expectedBytesIn); - BEAST_EXPECT( - pair.second.bytesOut.load() == tc.expectedBytesOut); - BEAST_EXPECT( - pair.second.messagesIn.load() == tc.expectedMessagesIn); - BEAST_EXPECT( - pair.second.messagesOut.load() == - tc.expectedMessagesOut); - }); + std::for_each(counts_new.begin(), counts_new.end(), [&](auto const& pair) { + BEAST_EXPECT(pair.second.bytesIn.load() == tc.expectedBytesIn); + BEAST_EXPECT(pair.second.bytesOut.load() == tc.expectedBytesOut); + BEAST_EXPECT(pair.second.messagesIn.load() == tc.expectedMessagesIn); + BEAST_EXPECT(pair.second.messagesOut.load() == tc.expectedMessagesOut); + }); }; auto const testcases = { @@ -114,13 +106,10 @@ public: testcase("category-to-string"); // known category returns known string value - BEAST_EXPECT( - TrafficCount::to_string(TrafficCount::category::total) == "total"); + BEAST_EXPECT(TrafficCount::to_string(TrafficCount::category::total) == "total"); // return "unknown" for unknown categories - BEAST_EXPECT( - TrafficCount::to_string( - static_cast(1000)) == "unknown"); + BEAST_EXPECT(TrafficCount::to_string(static_cast(1000)) == "unknown"); } void diff --git a/src/test/overlay/tx_reduce_relay_test.cpp b/src/test/overlay/tx_reduce_relay_test.cpp index 7286b3fd90..b8e3300c03 100644 --- a/src/test/overlay/tx_reduce_relay_test.cpp +++ b/src/test/overlay/tx_reduce_relay_test.cpp @@ -32,11 +32,7 @@ private: testConfig(bool log) { doTest("Config Test", log, [&](bool log) { - auto test = [&](bool enable, - bool metrics, - std::uint16_t min, - std::uint16_t pct, - bool success = true) { + auto test = [&](bool enable, bool metrics, std::uint16_t min, std::uint16_t pct, bool success = true) { std::stringstream str("[reduce_relay]"); str << "[reduce_relay]\n" << "tx_enable=" << static_cast(enable) << "\n" @@ -135,47 +131,28 @@ private: boost::beast::multi_buffer read_buf_; public: - tx_reduce_relay_test() - : context_(make_SSLContext("")), protocolVersion_{1, 7} + tx_reduce_relay_test() : context_(make_SSLContext("")), protocolVersion_{1, 7} { } private: void - addPeer( - jtx::Env& env, - std::vector>& peers, - std::uint16_t& nDisabled) + addPeer(jtx::Env& env, std::vector>& peers, std::uint16_t& nDisabled) { auto& overlay = dynamic_cast(env.app().overlay()); boost::beast::http::request request; - (nDisabled == 0) - ? (void)request.insert( - "X-Protocol-Ctl", - makeFeaturesRequestHeader(false, false, true, false)) - : (void)nDisabled--; + (nDisabled == 0) ? (void)request.insert("X-Protocol-Ctl", makeFeaturesRequestHeader(false, false, true, false)) + : (void)nDisabled--; auto stream_ptr = std::make_unique( - socket_type(std::forward( - env.app().getIOContext())), - *context_); - beast::IP::Endpoint local( - boost::asio::ip::make_address("172.1.1." + std::to_string(lid_))); - beast::IP::Endpoint remote( - boost::asio::ip::make_address("172.1.1." + std::to_string(rid_))); + socket_type(std::forward(env.app().getIOContext())), *context_); + beast::IP::Endpoint local(boost::asio::ip::make_address("172.1.1." + std::to_string(lid_))); + beast::IP::Endpoint remote(boost::asio::ip::make_address("172.1.1." + std::to_string(rid_))); PublicKey key(std::get<0>(randomKeyPair(KeyType::ed25519))); auto consumer = overlay.resourceManager().newInboundEndpoint(remote); auto [slot, _] = overlay.peerFinder().new_inbound_slot(local, remote); auto const peer = std::make_shared( - env.app(), - slot, - std::move(request), - key, - protocolVersion_, - consumer, - std::move(stream_ptr), - overlay); - BEAST_EXPECT( - overlay.findPeerByPublicKey(key) == std::shared_ptr{}); + env.app(), slot, std::move(request), key, protocolVersion_, consumer, std::move(stream_ptr), overlay); + BEAST_EXPECT(overlay.findPeerByPublicKey(key) == std::shared_ptr{}); overlay.add_active(peer); BEAST_EXPECT(overlay.findPeerByPublicKey(key) == peer); peers.emplace_back(peer); // overlay stores week ptr to PeerImp @@ -218,9 +195,7 @@ private: m.set_deferred(false); m.set_status(protocol::TransactionStatus::tsNEW); env.app().overlay().relay(uint256{0}, m, toSkip); - BEAST_EXPECT( - PeerTest::sendTx_ == expectRelay && - PeerTest::queueTx_ == expectQueue); + BEAST_EXPECT(PeerTest::sendTx_ == expectRelay && PeerTest::queueTx_ == expectQueue); } } diff --git a/src/test/peerfinder/Livecache_test.cpp b/src/test/peerfinder/Livecache_test.cpp index b9487d8ce7..2c2ac01111 100644 --- a/src/test/peerfinder/Livecache_test.cpp +++ b/src/test/peerfinder/Livecache_test.cpp @@ -142,57 +142,32 @@ public: testcase("Shuffle"); Livecache<> c(clock_, journal_); for (auto i = 0; i < 100; ++i) - add(beast::IP::randomEP(true), - c, - xrpl::rand_int(Tuning::maxHops + 1)); + add(beast::IP::randomEP(true), c, xrpl::rand_int(Tuning::maxHops + 1)); using at_hop = std::vector; using all_hops = std::array; auto cmp_EP = [](Endpoint const& a, Endpoint const& b) { - return ( - b.hops < a.hops || (b.hops == a.hops && b.address < a.address)); + return (b.hops < a.hops || (b.hops == a.hops && b.address < a.address)); }; all_hops before; all_hops before_sorted; - for (auto i = std::make_pair(0, c.hops.begin()); - i.second != c.hops.end(); - ++i.first, ++i.second) + for (auto i = std::make_pair(0, c.hops.begin()); i.second != c.hops.end(); ++i.first, ++i.second) { - std::copy( - (*i.second).begin(), - (*i.second).end(), - std::back_inserter(before[i.first])); - std::copy( - (*i.second).begin(), - (*i.second).end(), - std::back_inserter(before_sorted[i.first])); - std::sort( - before_sorted[i.first].begin(), - before_sorted[i.first].end(), - cmp_EP); + std::copy((*i.second).begin(), (*i.second).end(), std::back_inserter(before[i.first])); + std::copy((*i.second).begin(), (*i.second).end(), std::back_inserter(before_sorted[i.first])); + std::sort(before_sorted[i.first].begin(), before_sorted[i.first].end(), cmp_EP); } c.hops.shuffle(); all_hops after; all_hops after_sorted; - for (auto i = std::make_pair(0, c.hops.begin()); - i.second != c.hops.end(); - ++i.first, ++i.second) + for (auto i = std::make_pair(0, c.hops.begin()); i.second != c.hops.end(); ++i.first, ++i.second) { - std::copy( - (*i.second).begin(), - (*i.second).end(), - std::back_inserter(after[i.first])); - std::copy( - (*i.second).begin(), - (*i.second).end(), - std::back_inserter(after_sorted[i.first])); - std::sort( - after_sorted[i.first].begin(), - after_sorted[i.first].end(), - cmp_EP); + std::copy((*i.second).begin(), (*i.second).end(), std::back_inserter(after[i.first])); + std::copy((*i.second).begin(), (*i.second).end(), std::back_inserter(after_sorted[i.first])); + std::sort(after_sorted[i.first].begin(), after_sorted[i.first].end(), cmp_EP); } // each hop bucket should contain the same items diff --git a/src/test/peerfinder/PeerFinder_test.cpp b/src/test/peerfinder/PeerFinder_test.cpp index 7ff1b9de01..49ddc52c9d 100644 --- a/src/test/peerfinder/PeerFinder_test.cpp +++ b/src/test/peerfinder/PeerFinder_test.cpp @@ -65,8 +65,7 @@ public: TestChecker checker; TestStopwatch clock; Logic logic(clock, store, checker, journal_); - logic.addFixedPeer( - "test", beast::IP::Endpoint::from_string("65.0.0.1:5")); + logic.addFixedPeer("test", beast::IP::Endpoint::from_string("65.0.0.1:5")); { Config c; c.autoConnect = false; @@ -81,8 +80,7 @@ public: { BEAST_EXPECT(list.size() == 1); auto const [slot, _] = logic.new_outbound_slot(list.front()); - BEAST_EXPECT(logic.onConnected( - slot, beast::IP::Endpoint::from_string("65.0.0.2:5"))); + BEAST_EXPECT(logic.onConnected(slot, beast::IP::Endpoint::from_string("65.0.0.2:5"))); logic.on_closed(slot); ++n; } @@ -103,8 +101,7 @@ public: TestChecker checker; TestStopwatch clock; Logic logic(clock, store, checker, journal_); - logic.addFixedPeer( - "test", beast::IP::Endpoint::from_string("65.0.0.1:5")); + logic.addFixedPeer("test", beast::IP::Endpoint::from_string("65.0.0.1:5")); { Config c; c.autoConnect = false; @@ -122,13 +119,10 @@ public: { BEAST_EXPECT(list.size() == 1); auto const [slot, _] = logic.new_outbound_slot(list.front()); - if (!BEAST_EXPECT(logic.onConnected( - slot, beast::IP::Endpoint::from_string("65.0.0.2:5")))) + if (!BEAST_EXPECT(logic.onConnected(slot, beast::IP::Endpoint::from_string("65.0.0.2:5")))) return; std::string s = "."; - if (!BEAST_EXPECT( - logic.activate(slot, pk, false) == - PeerFinder::Result::success)) + if (!BEAST_EXPECT(logic.activate(slot, pk, false) == PeerFinder::Result::success)) return; logic.on_closed(slot); ++n; @@ -224,18 +218,15 @@ public: } auto const local = beast::IP::Endpoint::from_string("65.0.0.2:1024"); - auto const [slot, r] = logic.new_inbound_slot( - local, beast::IP::Endpoint::from_string("55.104.0.2:1025")); + auto const [slot, r] = logic.new_inbound_slot(local, beast::IP::Endpoint::from_string("55.104.0.2:1025")); BEAST_EXPECT(slot != nullptr); BEAST_EXPECT(r == Result::success); - auto const [slot1, r1] = logic.new_inbound_slot( - local, beast::IP::Endpoint::from_string("55.104.0.2:1026")); + auto const [slot1, r1] = logic.new_inbound_slot(local, beast::IP::Endpoint::from_string("55.104.0.2:1026")); BEAST_EXPECT(slot1 != nullptr); BEAST_EXPECT(r1 == Result::success); - auto const [slot2, r2] = logic.new_inbound_slot( - local, beast::IP::Endpoint::from_string("55.104.0.2:1027")); + auto const [slot2, r2] = logic.new_inbound_slot(local, beast::IP::Endpoint::from_string("55.104.0.2:1027")); BEAST_EXPECT(r2 == Result::ipLimitExceeded); if (!BEAST_EXPECT(slot2 == nullptr)) @@ -264,13 +255,11 @@ public: PublicKey const pk1(randomKeyPair(KeyType::secp256k1).first); - auto const [slot, rSlot] = logic.new_outbound_slot( - beast::IP::Endpoint::from_string("55.104.0.2:1025")); + auto const [slot, rSlot] = logic.new_outbound_slot(beast::IP::Endpoint::from_string("55.104.0.2:1025")); BEAST_EXPECT(slot != nullptr); BEAST_EXPECT(rSlot == Result::success); - auto const [slot2, r2Slot] = logic.new_outbound_slot( - beast::IP::Endpoint::from_string("55.104.0.2:1026")); + auto const [slot2, r2Slot] = logic.new_outbound_slot(beast::IP::Endpoint::from_string("55.104.0.2:1026")); BEAST_EXPECT(slot2 != nullptr); BEAST_EXPECT(r2Slot == Result::success); @@ -280,8 +269,7 @@ public: BEAST_EXPECT(logic.activate(slot, pk1, false) == Result::success); // activating a different slot with the same node ID (pk) must fail - BEAST_EXPECT( - logic.activate(slot2, pk1, false) == Result::duplicatePeer); + BEAST_EXPECT(logic.activate(slot2, pk1, false) == Result::duplicatePeer); logic.on_closed(slot); @@ -309,13 +297,11 @@ public: PublicKey const pk1(randomKeyPair(KeyType::secp256k1).first); auto const local = beast::IP::Endpoint::from_string("65.0.0.2:1024"); - auto const [slot, rSlot] = logic.new_inbound_slot( - local, beast::IP::Endpoint::from_string("55.104.0.2:1025")); + auto const [slot, rSlot] = logic.new_inbound_slot(local, beast::IP::Endpoint::from_string("55.104.0.2:1025")); BEAST_EXPECT(slot != nullptr); BEAST_EXPECT(rSlot == Result::success); - BEAST_EXPECT( - logic.activate(slot, pk1, false) == Result::inboundDisabled); + BEAST_EXPECT(logic.activate(slot, pk1, false) == Result::inboundDisabled); { Config c; @@ -329,8 +315,7 @@ public: BEAST_EXPECT(logic.activate(slot, pk1, false) == Result::success); // creating a new inbound slot must succeed as IP Limit is not exceeded - auto const [slot2, r2Slot] = logic.new_inbound_slot( - local, beast::IP::Endpoint::from_string("55.104.0.2:1026")); + auto const [slot2, r2Slot] = logic.new_inbound_slot(local, beast::IP::Endpoint::from_string("55.104.0.2:1026")); BEAST_EXPECT(slot2 != nullptr); BEAST_EXPECT(r2Slot == Result::success); @@ -353,8 +338,7 @@ public: Logic logic(clock, store, checker, journal_); try { - logic.addFixedPeer( - "test", beast::IP::Endpoint::from_string("65.0.0.2")); + logic.addFixedPeer("test", beast::IP::Endpoint::from_string("65.0.0.2")); fail("invalid endpoint successfully added"); } catch (std::runtime_error const& e) @@ -404,21 +388,19 @@ public: if (maxPeers) { max = maxPeers.value(); - toLoad += "[peers_max]\n" + std::to_string(max) + "\n" + - "[peers_in_max]\n" + std::to_string(maxIn.value_or(0)) + - "\n" + "[peers_out_max]\n" + + toLoad += "[peers_max]\n" + std::to_string(max) + "\n" + "[peers_in_max]\n" + + std::to_string(maxIn.value_or(0)) + "\n" + "[peers_out_max]\n" + std::to_string(maxOut.value_or(0)) + "\n"; } else if (maxIn && maxOut) { - toLoad += "[peers_in_max]\n" + std::to_string(*maxIn) + "\n" + - "[peers_out_max]\n" + std::to_string(*maxOut) + "\n"; + toLoad += "[peers_in_max]\n" + std::to_string(*maxIn) + "\n" + "[peers_out_max]\n" + + std::to_string(*maxOut) + "\n"; } c.loadFromString(toLoad); BEAST_EXPECT( - (c.PEERS_MAX == max && c.PEERS_IN_MAX == 0 && - c.PEERS_OUT_MAX == 0) || + (c.PEERS_MAX == max && c.PEERS_IN_MAX == 0 && c.PEERS_OUT_MAX == 0) || (c.PEERS_IN_MAX == *maxIn && c.PEERS_OUT_MAX == *maxOut)); Config config = Config::makeConfig(c, port, false, 0); @@ -426,8 +408,7 @@ public: Counts counts; counts.onConfig(config); BEAST_EXPECT( - counts.out_max() == expectOut && counts.in_max() == expectIn && - config.ipLimit == expectIpLimit); + counts.out_max() == expectOut && counts.in_max() == expectIn && config.ipLimit == expectIpLimit); TestStore store; TestChecker checker; diff --git a/src/test/protocol/ApiVersion_test.cpp b/src/test/protocol/ApiVersion_test.cpp index 1dc8ef93f7..0b7babc764 100644 --- a/src/test/protocol/ApiVersion_test.cpp +++ b/src/test/protocol/ApiVersion_test.cpp @@ -19,13 +19,9 @@ struct ApiVersion_test : beast::unit_test::suite { testcase("API versions invariants"); - static_assert( - RPC::apiMinimumSupportedVersion <= - RPC::apiMaximumSupportedVersion); - static_assert( - RPC::apiMinimumSupportedVersion <= RPC::apiMaximumValidVersion); - static_assert( - RPC::apiMaximumSupportedVersion <= RPC::apiMaximumValidVersion); + static_assert(RPC::apiMinimumSupportedVersion <= RPC::apiMaximumSupportedVersion); + static_assert(RPC::apiMinimumSupportedVersion <= RPC::apiMaximumValidVersion); + static_assert(RPC::apiMaximumSupportedVersion <= RPC::apiMaximumValidVersion); static_assert(RPC::apiBetaVersion <= RPC::apiMaximumValidVersion); BEAST_EXPECT(true); diff --git a/src/test/protocol/BuildInfo_test.cpp b/src/test/protocol/BuildInfo_test.cpp index ae06511e85..d9810e93ea 100644 --- a/src/test/protocol/BuildInfo_test.cpp +++ b/src/test/protocol/BuildInfo_test.cpp @@ -14,29 +14,22 @@ public: auto encodedVersion = BuildInfo::encodeSoftwareVersion("1.2.3-b7"); // the first two bytes identify the particular implementation, 0x183B - BEAST_EXPECT( - (encodedVersion & 0xFFFF'0000'0000'0000LLU) == - 0x183B'0000'0000'0000LLU); + BEAST_EXPECT((encodedVersion & 0xFFFF'0000'0000'0000LLU) == 0x183B'0000'0000'0000LLU); // the next three bytes: major version, minor version, patch version, // 0x010203 - BEAST_EXPECT( - (encodedVersion & 0x0000'FFFF'FF00'0000LLU) == - 0x0000'0102'0300'0000LLU); + BEAST_EXPECT((encodedVersion & 0x0000'FFFF'FF00'0000LLU) == 0x0000'0102'0300'0000LLU); // the next two bits: { // 01 if a beta - BEAST_EXPECT( - (encodedVersion & 0x0000'0000'00C0'0000LLU) >> 22 == 0b01); + BEAST_EXPECT((encodedVersion & 0x0000'0000'00C0'0000LLU) >> 22 == 0b01); // 10 if an RC encodedVersion = BuildInfo::encodeSoftwareVersion("1.2.4-rc7"); - BEAST_EXPECT( - (encodedVersion & 0x0000'0000'00C0'0000LLU) >> 22 == 0b10); + BEAST_EXPECT((encodedVersion & 0x0000'0000'00C0'0000LLU) >> 22 == 0b10); // 11 if neither an RC nor a beta encodedVersion = BuildInfo::encodeSoftwareVersion("1.2.5"); - BEAST_EXPECT( - (encodedVersion & 0x0000'0000'00C0'0000LLU) >> 22 == 0b11); + BEAST_EXPECT((encodedVersion & 0x0000'0000'00C0'0000LLU) >> 22 == 0b11); } // the next six bits: rc/beta number (1-63) diff --git a/src/test/protocol/Hooks_test.cpp b/src/test/protocol/Hooks_test.cpp index 27f455f202..f4b33f7e4d 100644 --- a/src/test/protocol/Hooks_test.cpp +++ b/src/test/protocol/Hooks_test.cpp @@ -134,8 +134,7 @@ class Hooks_test : public beast::unit_test::suite } case STI_ACCOUNT: { - AccountID id = *parseBase58( - "rwfSjJNK2YQuN64bSWn7T2eY9FJAyAPYJT"); + AccountID id = *parseBase58("rwfSjJNK2YQuN64bSWn7T2eY9FJAyAPYJT"); dummy.setAccountID(f, id); BEAST_EXPECT(dummy.getAccountID(f) == id); BEAST_EXPECT(dummy.isFieldPresent(f)); diff --git a/src/test/protocol/InnerObjectFormats_test.cpp b/src/test/protocol/InnerObjectFormats_test.cpp index c06524b90e..7d69bb7afb 100644 --- a/src/test/protocol/InnerObjectFormats_test.cpp +++ b/src/test/protocol/InnerObjectFormats_test.cpp @@ -163,8 +163,7 @@ public: Json::Reader().parse(test.txt, req); if (RPC::contains_error(req)) { - Throw( - "Internal InnerObjectFormatsParsedJSON error. Bad JSON."); + Throw("Internal InnerObjectFormatsParsedJSON error. Bad JSON."); } STParsedJSONObject parsed("request", req); bool const noObj = !parsed.object.has_value(); diff --git a/src/test/protocol/Issue_test.cpp b/src/test/protocol/Issue_test.cpp index eec164f5b6..2321da4a6e 100644 --- a/src/test/protocol/Issue_test.cpp +++ b/src/test/protocol/Issue_test.cpp @@ -17,14 +17,6 @@ #define STL_SET_HAS_EMPLACE 0 #endif -#ifndef XRPL_ASSETS_ENABLE_STD_HASH -#if BEAST_MAC || BEAST_IOS -#define XRPL_ASSETS_ENABLE_STD_HASH 0 -#else -#define XRPL_ASSETS_ENABLE_STD_HASH 1 -#endif -#endif - namespace xrpl { class Issue_test : public beast::unit_test::suite @@ -434,12 +426,10 @@ public: // Both Books have the same domain BEAST_EXPECT(Book(a2, a3, domain1) == Book(a2, a3, domain1)); BEAST_EXPECT(Book(a2, a3, domain2) == Book(a2, a3, domain2)); - BEAST_EXPECT( - Book(a2, a3, std::nullopt) == Book(a2, a3, std::nullopt)); + BEAST_EXPECT(Book(a2, a3, std::nullopt) == Book(a2, a3, std::nullopt)); // Both Books have no domain - BEAST_EXPECT( - Book(a2, a3, std::nullopt) == Book(a2, a3, std::nullopt)); + BEAST_EXPECT(Book(a2, a3, std::nullopt) == Book(a2, a3, std::nullopt)); // Testing comparisons with >= and <= @@ -458,10 +448,8 @@ public: BEAST_EXPECT(Book(a2, a3, std::nullopt) < Book(a2, a3, domain2)); // Comparing two Books with no domains - BEAST_EXPECT( - Book(a2, a3, std::nullopt) <= Book(a2, a3, std::nullopt)); - BEAST_EXPECT( - Book(a2, a3, std::nullopt) >= Book(a2, a3, std::nullopt)); + BEAST_EXPECT(Book(a2, a3, std::nullopt) <= Book(a2, a3, std::nullopt)); + BEAST_EXPECT(Book(a2, a3, std::nullopt) >= Book(a2, a3, std::nullopt)); // Test case where domain1 is less than domain2 BEAST_EXPECT(Book(a2, a3, domain1) <= Book(a2, a3, domain2)); @@ -509,99 +497,51 @@ public: // log << std::hex << hash (Book (a3, a4)); // log << std::hex << hash (Book (a3, a4)); - BEAST_EXPECT( - hash(Book(a1, a2, std::nullopt)) == - hash(Book(a1, a2, std::nullopt))); - BEAST_EXPECT( - hash(Book(a1, a3, std::nullopt)) == - hash(Book(a1, a3, std::nullopt))); - BEAST_EXPECT( - hash(Book(a1, a4, std::nullopt)) == - hash(Book(a1, a4, std::nullopt))); - BEAST_EXPECT( - hash(Book(a2, a3, std::nullopt)) == - hash(Book(a2, a3, std::nullopt))); - BEAST_EXPECT( - hash(Book(a2, a4, std::nullopt)) == - hash(Book(a2, a4, std::nullopt))); - BEAST_EXPECT( - hash(Book(a3, a4, std::nullopt)) == - hash(Book(a3, a4, std::nullopt))); + BEAST_EXPECT(hash(Book(a1, a2, std::nullopt)) == hash(Book(a1, a2, std::nullopt))); + BEAST_EXPECT(hash(Book(a1, a3, std::nullopt)) == hash(Book(a1, a3, std::nullopt))); + BEAST_EXPECT(hash(Book(a1, a4, std::nullopt)) == hash(Book(a1, a4, std::nullopt))); + BEAST_EXPECT(hash(Book(a2, a3, std::nullopt)) == hash(Book(a2, a3, std::nullopt))); + BEAST_EXPECT(hash(Book(a2, a4, std::nullopt)) == hash(Book(a2, a4, std::nullopt))); + BEAST_EXPECT(hash(Book(a3, a4, std::nullopt)) == hash(Book(a3, a4, std::nullopt))); - BEAST_EXPECT( - hash(Book(a1, a2, std::nullopt)) != - hash(Book(a1, a3, std::nullopt))); - BEAST_EXPECT( - hash(Book(a1, a2, std::nullopt)) != - hash(Book(a1, a4, std::nullopt))); - BEAST_EXPECT( - hash(Book(a1, a2, std::nullopt)) != - hash(Book(a2, a3, std::nullopt))); - BEAST_EXPECT( - hash(Book(a1, a2, std::nullopt)) != - hash(Book(a2, a4, std::nullopt))); - BEAST_EXPECT( - hash(Book(a1, a2, std::nullopt)) != - hash(Book(a3, a4, std::nullopt))); + BEAST_EXPECT(hash(Book(a1, a2, std::nullopt)) != hash(Book(a1, a3, std::nullopt))); + BEAST_EXPECT(hash(Book(a1, a2, std::nullopt)) != hash(Book(a1, a4, std::nullopt))); + BEAST_EXPECT(hash(Book(a1, a2, std::nullopt)) != hash(Book(a2, a3, std::nullopt))); + BEAST_EXPECT(hash(Book(a1, a2, std::nullopt)) != hash(Book(a2, a4, std::nullopt))); + BEAST_EXPECT(hash(Book(a1, a2, std::nullopt)) != hash(Book(a3, a4, std::nullopt))); // Books with domain - BEAST_EXPECT( - hash(Book(a1, a2, domain1)) == hash(Book(a1, a2, domain1))); - BEAST_EXPECT( - hash(Book(a1, a3, domain1)) == hash(Book(a1, a3, domain1))); - BEAST_EXPECT( - hash(Book(a1, a4, domain1)) == hash(Book(a1, a4, domain1))); - BEAST_EXPECT( - hash(Book(a2, a3, domain1)) == hash(Book(a2, a3, domain1))); - BEAST_EXPECT( - hash(Book(a2, a4, domain1)) == hash(Book(a2, a4, domain1))); - BEAST_EXPECT( - hash(Book(a3, a4, domain1)) == hash(Book(a3, a4, domain1))); - BEAST_EXPECT( - hash(Book(a1, a2, std::nullopt)) == - hash(Book(a1, a2, std::nullopt))); + BEAST_EXPECT(hash(Book(a1, a2, domain1)) == hash(Book(a1, a2, domain1))); + BEAST_EXPECT(hash(Book(a1, a3, domain1)) == hash(Book(a1, a3, domain1))); + BEAST_EXPECT(hash(Book(a1, a4, domain1)) == hash(Book(a1, a4, domain1))); + BEAST_EXPECT(hash(Book(a2, a3, domain1)) == hash(Book(a2, a3, domain1))); + BEAST_EXPECT(hash(Book(a2, a4, domain1)) == hash(Book(a2, a4, domain1))); + BEAST_EXPECT(hash(Book(a3, a4, domain1)) == hash(Book(a3, a4, domain1))); + BEAST_EXPECT(hash(Book(a1, a2, std::nullopt)) == hash(Book(a1, a2, std::nullopt))); // Comparing Books with domain1 vs no domain - BEAST_EXPECT( - hash(Book(a1, a2, std::nullopt)) != hash(Book(a1, a2, domain1))); - BEAST_EXPECT( - hash(Book(a1, a3, std::nullopt)) != hash(Book(a1, a3, domain1))); - BEAST_EXPECT( - hash(Book(a1, a4, std::nullopt)) != hash(Book(a1, a4, domain1))); - BEAST_EXPECT( - hash(Book(a2, a3, std::nullopt)) != hash(Book(a2, a3, domain1))); - BEAST_EXPECT( - hash(Book(a2, a4, std::nullopt)) != hash(Book(a2, a4, domain1))); - BEAST_EXPECT( - hash(Book(a3, a4, std::nullopt)) != hash(Book(a3, a4, domain1))); + BEAST_EXPECT(hash(Book(a1, a2, std::nullopt)) != hash(Book(a1, a2, domain1))); + BEAST_EXPECT(hash(Book(a1, a3, std::nullopt)) != hash(Book(a1, a3, domain1))); + BEAST_EXPECT(hash(Book(a1, a4, std::nullopt)) != hash(Book(a1, a4, domain1))); + BEAST_EXPECT(hash(Book(a2, a3, std::nullopt)) != hash(Book(a2, a3, domain1))); + BEAST_EXPECT(hash(Book(a2, a4, std::nullopt)) != hash(Book(a2, a4, domain1))); + BEAST_EXPECT(hash(Book(a3, a4, std::nullopt)) != hash(Book(a3, a4, domain1))); // Books with domain1 but different Issues - BEAST_EXPECT( - hash(Book(a1, a2, domain1)) != hash(Book(a1, a3, domain1))); - BEAST_EXPECT( - hash(Book(a1, a2, domain1)) != hash(Book(a1, a4, domain1))); - BEAST_EXPECT( - hash(Book(a2, a3, domain1)) != hash(Book(a2, a4, domain1))); - BEAST_EXPECT( - hash(Book(a1, a2, domain1)) != hash(Book(a2, a3, domain1))); - BEAST_EXPECT( - hash(Book(a2, a4, domain1)) != hash(Book(a3, a4, domain1))); - BEAST_EXPECT( - hash(Book(a3, a4, domain1)) != hash(Book(a1, a4, domain1))); + BEAST_EXPECT(hash(Book(a1, a2, domain1)) != hash(Book(a1, a3, domain1))); + BEAST_EXPECT(hash(Book(a1, a2, domain1)) != hash(Book(a1, a4, domain1))); + BEAST_EXPECT(hash(Book(a2, a3, domain1)) != hash(Book(a2, a4, domain1))); + BEAST_EXPECT(hash(Book(a1, a2, domain1)) != hash(Book(a2, a3, domain1))); + BEAST_EXPECT(hash(Book(a2, a4, domain1)) != hash(Book(a3, a4, domain1))); + BEAST_EXPECT(hash(Book(a3, a4, domain1)) != hash(Book(a1, a4, domain1))); // Books with domain1 and domain2 - BEAST_EXPECT( - hash(Book(a1, a2, domain1)) != hash(Book(a1, a2, domain2))); - BEAST_EXPECT( - hash(Book(a1, a3, domain1)) != hash(Book(a1, a3, domain2))); - BEAST_EXPECT( - hash(Book(a1, a4, domain1)) != hash(Book(a1, a4, domain2))); - BEAST_EXPECT( - hash(Book(a2, a3, domain1)) != hash(Book(a2, a3, domain2))); - BEAST_EXPECT( - hash(Book(a2, a4, domain1)) != hash(Book(a2, a4, domain2))); - BEAST_EXPECT( - hash(Book(a3, a4, domain1)) != hash(Book(a3, a4, domain2))); + BEAST_EXPECT(hash(Book(a1, a2, domain1)) != hash(Book(a1, a2, domain2))); + BEAST_EXPECT(hash(Book(a1, a3, domain1)) != hash(Book(a1, a3, domain2))); + BEAST_EXPECT(hash(Book(a1, a4, domain1)) != hash(Book(a1, a4, domain2))); + BEAST_EXPECT(hash(Book(a2, a3, domain1)) != hash(Book(a2, a3, domain2))); + BEAST_EXPECT(hash(Book(a2, a4, domain1)) != hash(Book(a2, a4, domain2))); + BEAST_EXPECT(hash(Book(a3, a4, domain1)) != hash(Book(a3, a4, domain2))); } //-------------------------------------------------------------------------- diff --git a/src/test/protocol/Memo_test.cpp b/src/test/protocol/Memo_test.cpp index 706ef79fe2..3c5d3f5a38 100644 --- a/src/test/protocol/Memo_test.cpp +++ b/src/test/protocol/Memo_test.cpp @@ -35,16 +35,14 @@ public: { // Make sure that too big a memo is flagged as invalid. JTx memoSize = makeJtxWithMemo(); - memoSize.jv[sfMemos.jsonName][0u][sfMemo.jsonName] - [sfMemoData.jsonName] = std::string(2020, '0'); + memoSize.jv[sfMemos.jsonName][0u][sfMemo.jsonName][sfMemoData.jsonName] = std::string(2020, '0'); env(memoSize, rpc("invalidTransaction", "fails local checks: The memo exceeds the maximum allowed " "size.")); // This memo is just barely small enough. - memoSize.jv[sfMemos.jsonName][0u][sfMemo.jsonName] - [sfMemoData.jsonName] = std::string(2018, '1'); + memoSize.jv[sfMemos.jsonName][0u][sfMemo.jsonName][sfMemoData.jsonName] = std::string(2018, '1'); env(memoSize); } { @@ -64,9 +62,7 @@ public: { // Put an invalid field in a Memo object. JTx memoExtra = makeJtxWithMemo(); - memoExtra - .jv[sfMemos.jsonName][0u][sfMemo.jsonName][sfFlags.jsonName] = - 13; + memoExtra.jv[sfMemos.jsonName][0u][sfMemo.jsonName][sfFlags.jsonName] = 13; env(memoExtra, rpc("invalidTransaction", "fails local checks: A memo may contain only MemoType, " @@ -75,8 +71,7 @@ public: { // Put a character that is not allowed in a URL in a MemoType field. JTx memoBadChar = makeJtxWithMemo(); - memoBadChar.jv[sfMemos.jsonName][0u][sfMemo.jsonName] - [sfMemoType.jsonName] = + memoBadChar.jv[sfMemos.jsonName][0u][sfMemo.jsonName][sfMemoType.jsonName] = strHex(std::string_view("ONE subject{}; static_assert(sizeof(subject) == sizeof(subject.val)); static_assert(subject.size == subject.val.size()); - static_assert( - std::is_same_v>); + static_assert(std::is_same_v>); BEAST_EXPECT(subject.val.size() == 3); - BEAST_EXPECT( - (subject.val == - std::array{jsonNull, jsonNull, jsonNull})); + BEAST_EXPECT((subject.val == std::array{jsonNull, jsonNull, jsonNull})); subject.val[0] = obj1; subject.val[1] = obj2; @@ -61,21 +58,15 @@ struct MultiApiJson_test : beast::unit_test::suite testcase("forApiVersions, forAllApiVersions"); // Some static data for test inputs - static int const primes[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, - 29, 31, 37, 41, 43, 47, 53, 59, 61, - 67, 71, 73, 79, 83, 89, 97}; + static int const primes[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, + 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97}; static_assert(std::size(primes) > RPC::apiMaximumValidVersion); MultiApiJson<1, 3> s1{}; - static_assert( - s1.size == - RPC::apiMaximumValidVersion + 1 - - RPC::apiMinimumSupportedVersion); + static_assert(s1.size == RPC::apiMaximumValidVersion + 1 - RPC::apiMinimumSupportedVersion); int productAllVersions = 1; - for (unsigned i = RPC::apiMinimumSupportedVersion; - i <= RPC::apiMaximumValidVersion; - ++i) + for (unsigned i = RPC::apiMinimumSupportedVersion; i <= RPC::apiMaximumValidVersion; ++i) { auto const index = i - RPC::apiMinimumSupportedVersion; BEAST_EXPECT(index == s1.index(i)); @@ -85,25 +76,15 @@ struct MultiApiJson_test : beast::unit_test::suite } BEAST_EXPECT(!s1.valid(0)); BEAST_EXPECT(!s1.valid(RPC::apiMaximumValidVersion + 1)); - BEAST_EXPECT( - !s1.valid(std::numeric_limits< - decltype(RPC::apiMaximumValidVersion.value)>::max())); + BEAST_EXPECT(!s1.valid(std::numeric_limits::max())); int result = 1; - static_assert( - RPC::apiMinimumSupportedVersion + 1 <= - RPC::apiMaximumValidVersion); - forApiVersions< - RPC::apiMinimumSupportedVersion, - RPC::apiMinimumSupportedVersion + 1>( + static_assert(RPC::apiMinimumSupportedVersion + 1 <= RPC::apiMaximumValidVersion); + forApiVersions( std::as_const(s1).visit(), - [this]( - Json::Value const& json, - unsigned int version, - int* result) { + [this](Json::Value const& json, unsigned int version, int* result) { BEAST_EXPECT( - version >= RPC::apiMinimumSupportedVersion && - version <= RPC::apiMinimumSupportedVersion + 1); + version >= RPC::apiMinimumSupportedVersion && version <= RPC::apiMinimumSupportedVersion + 1); if (BEAST_EXPECT(json.isMember("value"))) { *result *= json["value"].asInt(); @@ -111,30 +92,22 @@ struct MultiApiJson_test : beast::unit_test::suite }, &result); BEAST_EXPECT( - result == - primes[RPC::apiMinimumSupportedVersion] * - primes[RPC::apiMinimumSupportedVersion + 1]); + result == primes[RPC::apiMinimumSupportedVersion] * primes[RPC::apiMinimumSupportedVersion + 1]); // Check all the values with mutable data - forAllApiVersions( - s1.visit(), [&s1, this](Json::Value& json, auto version) { - BEAST_EXPECT(s1.val[s1.index(version)] == json); - if (BEAST_EXPECT(json.isMember("value"))) - { - BEAST_EXPECT(json["value"].asInt() == primes[version]); - } - }); + forAllApiVersions(s1.visit(), [&s1, this](Json::Value& json, auto version) { + BEAST_EXPECT(s1.val[s1.index(version)] == json); + if (BEAST_EXPECT(json.isMember("value"))) + { + BEAST_EXPECT(json["value"].asInt() == primes[version]); + } + }); result = 1; forAllApiVersions( std::as_const(s1).visit(), - [this]( - Json::Value const& json, - unsigned int version, - int* result) { - BEAST_EXPECT( - version >= RPC::apiMinimumSupportedVersion && - version <= RPC::apiMaximumValidVersion); + [this](Json::Value const& json, unsigned int version, int* result) { + BEAST_EXPECT(version >= RPC::apiMinimumSupportedVersion && version <= RPC::apiMaximumValidVersion); if (BEAST_EXPECT(json.isMember("value"))) { *result *= json["value"].asInt(); @@ -163,7 +136,7 @@ struct MultiApiJson_test : beast::unit_test::suite return !requires { forAllApiVersions( std::forward(v).visit(), // - []() {}); // missing parameters + []() {}); // missing parameters }; }(std::as_const(s1))); static_assert([](auto&& v) { @@ -234,10 +207,7 @@ struct MultiApiJson_test : beast::unit_test::suite forAllApiVersions( std::forward(v).visit(), // []( - Json::Value const&, - std::integral_constant, - int, - char const*) {}, + Json::Value const&, std::integral_constant, int, char const*) {}, 0, ""); }; @@ -308,27 +278,17 @@ struct MultiApiJson_test : beast::unit_test::suite BEAST_EXPECT(x.val[1]["name2"].asString() == "bar"); // Tests of requires clause - these are expected to match - static_assert([](auto&& v) { - return requires { v.set("name", Json::nullValue); }; - }(x)); - static_assert([](auto&& v) { - return requires { v.set("name", "value"); }; - }(x)); - static_assert( - [](auto&& v) { return requires { v.set("name", true); }; }(x)); - static_assert( - [](auto&& v) { return requires { v.set("name", 42); }; }(x)); + static_assert([](auto&& v) { return requires { v.set("name", Json::nullValue); }; }(x)); + static_assert([](auto&& v) { return requires { v.set("name", "value"); }; }(x)); + static_assert([](auto&& v) { return requires { v.set("name", true); }; }(x)); + static_assert([](auto&& v) { return requires { v.set("name", 42); }; }(x)); // Tests of requires clause - these are expected NOT to match struct foo_t final { }; - static_assert([](auto&& v) { - return !requires { v.set("name", foo_t{}); }; - }(x)); - static_assert([](auto&& v) { - return !requires { v.set("name", std::nullopt); }; - }(x)); + static_assert([](auto&& v) { return !requires { v.set("name", foo_t{}); }; }(x)); + static_assert([](auto&& v) { return !requires { v.set("name", std::nullopt); }; }(x)); } { @@ -387,8 +347,7 @@ struct MultiApiJson_test : beast::unit_test::suite v.visitor( v, std::integral_constant{}, - [](Json::Value&, std::integral_constant) { - }); + [](Json::Value&, std::integral_constant) {}); }; }(s1)); BEAST_EXPECT( @@ -396,20 +355,12 @@ struct MultiApiJson_test : beast::unit_test::suite s1, std::integral_constant{}, Overload{ - [](Json::Value& v, - std::integral_constant) { - return v["value"].asInt(); - }, + [](Json::Value& v, std::integral_constant) { return v["value"].asInt(); }, [](Json::Value const&, auto) { return 0; }, [](auto, auto) { return 0; }}) == 2); static_assert([](auto&& v) { - return requires { - v.visitor( - v, - std::integral_constant{}, - [](Json::Value&) {}); - }; + return requires { v.visitor(v, std::integral_constant{}, [](Json::Value&) {}); }; }(s1)); BEAST_EXPECT( s1.visitor( @@ -425,8 +376,7 @@ struct MultiApiJson_test : beast::unit_test::suite v.visitor( v, std::integral_constant{}, - [](Json::Value const&, - std::integral_constant) {}); + [](Json::Value const&, std::integral_constant) {}); }; }(std::as_const(s1))); BEAST_EXPECT( @@ -434,20 +384,12 @@ struct MultiApiJson_test : beast::unit_test::suite std::as_const(s1), std::integral_constant{}, Overload{ - [](Json::Value const& v, - std::integral_constant) { - return v["value"].asInt(); - }, + [](Json::Value const& v, std::integral_constant) { return v["value"].asInt(); }, [](Json::Value&, auto) { return 0; }, [](auto, auto) { return 0; }}) == 3); static_assert([](auto&& v) { - return requires { - v.visitor( - v, - std::integral_constant{}, - [](Json::Value const&) {}); - }; + return requires { v.visitor(v, std::integral_constant{}, [](Json::Value const&) {}); }; }(std::as_const(s1))); BEAST_EXPECT( s1.visitor( @@ -458,25 +400,17 @@ struct MultiApiJson_test : beast::unit_test::suite [](Json::Value&) { return 0; }, [](auto...) { return 0; }}) == 3); - static_assert([](auto&& v) { - return requires { - v.visitor(v, 1, [](Json::Value&, unsigned) {}); - }; - }(s1)); + static_assert([](auto&& v) { return requires { v.visitor(v, 1, [](Json::Value&, unsigned) {}); }; }(s1)); BEAST_EXPECT( s1.visitor( s1, // 3u, Overload{ - [](Json::Value& v, unsigned) { - return v["value"].asInt(); - }, + [](Json::Value& v, unsigned) { return v["value"].asInt(); }, [](Json::Value const&, unsigned) { return 0; }, [](auto, auto) { return 0; }}) == 5); - static_assert([](auto&& v) { - return requires { v.visitor(v, 1, [](Json::Value&) {}); }; - }(s1)); + static_assert([](auto&& v) { return requires { v.visitor(v, 1, [](Json::Value&) {}); }; }(s1)); BEAST_EXPECT( s1.visitor( s1, // @@ -487,24 +421,19 @@ struct MultiApiJson_test : beast::unit_test::suite [](auto...) { return 0; }}) == 5); static_assert([](auto&& v) { - return requires { - v.visitor(v, 1, [](Json::Value const&, unsigned) {}); - }; + return requires { v.visitor(v, 1, [](Json::Value const&, unsigned) {}); }; }(std::as_const(s1))); BEAST_EXPECT( s1.visitor( std::as_const(s1), // 2u, Overload{ - [](Json::Value const& v, unsigned) { - return v["value"].asInt(); - }, + [](Json::Value const& v, unsigned) { return v["value"].asInt(); }, [](Json::Value const&, auto) { return 0; }, [](auto, auto) { return 0; }}) == 3); - static_assert([](auto&& v) { - return requires { v.visitor(v, 1, [](Json::Value const&) {}); }; - }(std::as_const(s1))); + static_assert( + [](auto&& v) { return requires { v.visitor(v, 1, [](Json::Value const&) {}); }; }(std::as_const(s1))); BEAST_EXPECT( s1.visitor( std::as_const(s1), // @@ -519,49 +448,37 @@ struct MultiApiJson_test : beast::unit_test::suite s1.visitor( s1, std::integral_constant{}, // to unsigned - [](Json::Value& v, unsigned) { - return v["value"].asInt(); - }) == 2); + [](Json::Value& v, unsigned) { return v["value"].asInt(); }) == 2); BEAST_EXPECT( s1.visitor( std::as_const(s1), std::integral_constant{}, // to unsigned - [](Json::Value const& v, unsigned) { - return v["value"].asInt(); - }) == 3); + [](Json::Value const& v, unsigned) { return v["value"].asInt(); }) == 3); BEAST_EXPECT( s1.visitor( s1, // to const std::integral_constant{}, - [](Json::Value const& v, auto) { - return v["value"].asInt(); - }) == 5); + [](Json::Value const& v, auto) { return v["value"].asInt(); }) == 5); BEAST_EXPECT( s1.visitor( s1, // to const std::integral_constant{}, - [](Json::Value const& v) { return v["value"].asInt(); }) == - 5); + [](Json::Value const& v) { return v["value"].asInt(); }) == 5); BEAST_EXPECT( s1.visitor( s1, 3, // to long - [](Json::Value& v, long) { return v["value"].asInt(); }) == - 5); + [](Json::Value& v, long) { return v["value"].asInt(); }) == 5); BEAST_EXPECT( s1.visitor( std::as_const(s1), 1, // to long - [](Json::Value const& v, long) { - return v["value"].asInt(); - }) == 2); + [](Json::Value const& v, long) { return v["value"].asInt(); }) == 2); BEAST_EXPECT( s1.visitor( s1, // to const 2, - [](Json::Value const& v, auto) { - return v["value"].asInt(); - }) == 3); + [](Json::Value const& v, auto) { return v["value"].asInt(); }) == 3); BEAST_EXPECT( s1.visitor( s1, // type deduction @@ -571,8 +488,7 @@ struct MultiApiJson_test : beast::unit_test::suite s1.visitor( s1, // to const, type deduction 2, - [](auto const& v, auto) { return v["value"].asInt(); }) == - 3); + [](auto const& v, auto) { return v["value"].asInt(); }) == 3); BEAST_EXPECT( s1.visitor( s1, // type deduction @@ -589,18 +505,14 @@ struct MultiApiJson_test : beast::unit_test::suite s1.visitor( s1, std::integral_constant{}, - [](Json::Value& v, auto ver, auto a1, auto a2) { - return ver * a1 * a2 * v["value"].asInt(); - }, + [](Json::Value& v, auto ver, auto a1, auto a2) { return ver * a1 * a2 * v["value"].asInt(); }, 5, 7) == 2 * 5 * 7 * 3); BEAST_EXPECT( s1.visitor( s1, std::integral_constant{}, - [](Json::Value& v, auto ver, auto... args) { - return ver * (1 * ... * args) * v["value"].asInt(); - }, + [](Json::Value& v, auto ver, auto... args) { return ver * (1 * ... * args) * v["value"].asInt(); }, 5, 7) == 2 * 5 * 7 * 3); @@ -642,55 +554,27 @@ struct MultiApiJson_test : beast::unit_test::suite }(s1)); // Want these to be unambiguous - static_assert([](auto&& v) { - return requires { v.visitor(v, 1, [](auto) {}); }; - }(s1)); + static_assert([](auto&& v) { return requires { v.visitor(v, 1, [](auto) {}); }; }(s1)); - static_assert([](auto&& v) { - return requires { v.visitor(v, 1, [](Json::Value&) {}); }; - }(s1)); + static_assert([](auto&& v) { return requires { v.visitor(v, 1, [](Json::Value&) {}); }; }(s1)); - static_assert([](auto&& v) { - return requires { - v.visitor(v, 1, [](Json::Value&, auto...) {}); - }; - }(s1)); + static_assert([](auto&& v) { return requires { v.visitor(v, 1, [](Json::Value&, auto...) {}); }; }(s1)); - static_assert([](auto&& v) { - return requires { v.visitor(v, 1, [](Json::Value const&) {}); }; - }(s1)); + static_assert([](auto&& v) { return requires { v.visitor(v, 1, [](Json::Value const&) {}); }; }(s1)); - static_assert([](auto&& v) { - return requires { - v.visitor(v, 1, [](Json::Value const&, auto...) {}); - }; - }(s1)); + static_assert( + [](auto&& v) { return requires { v.visitor(v, 1, [](Json::Value const&, auto...) {}); }; }(s1)); - static_assert([](auto&& v) { - return requires { v.visitor(v, 1, [](auto...) {}); }; - }(s1)); + static_assert([](auto&& v) { return requires { v.visitor(v, 1, [](auto...) {}); }; }(s1)); - static_assert([](auto&& v) { - return requires { v.visitor(v, 1, [](auto, auto...) {}); }; - }(s1)); + static_assert([](auto&& v) { return requires { v.visitor(v, 1, [](auto, auto...) {}); }; }(s1)); - static_assert([](auto&& v) { - return requires { - v.visitor(v, 1, [](auto, auto, auto...) {}); - }; - }(s1)); + static_assert([](auto&& v) { return requires { v.visitor(v, 1, [](auto, auto, auto...) {}); }; }(s1)); - static_assert([](auto&& v) { - return requires { - v.visitor(v, 1, [](auto, auto, auto...) {}, ""); - }; - }(s1)); + static_assert([](auto&& v) { return requires { v.visitor(v, 1, [](auto, auto, auto...) {}, ""); }; }(s1)); - static_assert([](auto&& v) { - return requires { - v.visitor(v, 1, [](auto, auto, auto, auto...) {}, ""); - }; - }(s1)); + static_assert( + [](auto&& v) { return requires { v.visitor(v, 1, [](auto, auto, auto, auto...) {}, ""); }; }(s1)); } { @@ -706,45 +590,33 @@ struct MultiApiJson_test : beast::unit_test::suite return requires { v.visit( std::integral_constant{}, - [](Json::Value&, std::integral_constant) { - }); + [](Json::Value&, std::integral_constant) {}); }; }(s1)); BEAST_EXPECT( s1.visit( std::integral_constant{}, Overload{ - [](Json::Value& v, - std::integral_constant) { - return v["value"].asInt(); - }, + [](Json::Value& v, std::integral_constant) { return v["value"].asInt(); }, [](Json::Value const&, auto) { return 0; }, [](auto, auto) { return 0; }}) == 2); static_assert([](auto&& v) { return requires { v.visit()( std::integral_constant{}, - [](Json::Value&, std::integral_constant) { - }); + [](Json::Value&, std::integral_constant) {}); }; }(s1)); BEAST_EXPECT( s1.visit()( std::integral_constant{}, Overload{ - [](Json::Value& v, - std::integral_constant) { - return v["value"].asInt(); - }, + [](Json::Value& v, std::integral_constant) { return v["value"].asInt(); }, [](Json::Value const&, auto) { return 0; }, [](auto, auto) { return 0; }}) == 2); static_assert([](auto&& v) { - return requires { - v.visit( - std::integral_constant{}, - [](Json::Value&) {}); - }; + return requires { v.visit(std::integral_constant{}, [](Json::Value&) {}); }; }(s1)); BEAST_EXPECT( s1.visit( @@ -754,11 +626,7 @@ struct MultiApiJson_test : beast::unit_test::suite [](Json::Value const&) { return 0; }, [](auto...) { return 0; }}) == 2); static_assert([](auto&& v) { - return requires { - v.visit()( - std::integral_constant{}, - [](Json::Value&) {}); - }; + return requires { v.visit()(std::integral_constant{}, [](Json::Value&) {}); }; }(s1)); BEAST_EXPECT( s1.visit()( @@ -772,45 +640,33 @@ struct MultiApiJson_test : beast::unit_test::suite return requires { v.visit( std::integral_constant{}, - [](Json::Value const&, - std::integral_constant) {}); + [](Json::Value const&, std::integral_constant) {}); }; }(std::as_const(s1))); BEAST_EXPECT( std::as_const(s1).visit( std::integral_constant{}, Overload{ - [](Json::Value const& v, - std::integral_constant) { - return v["value"].asInt(); - }, + [](Json::Value const& v, std::integral_constant) { return v["value"].asInt(); }, [](Json::Value&, auto) { return 0; }, [](auto, auto) { return 0; }}) == 3); static_assert([](auto&& v) { return requires { v.visit()( std::integral_constant{}, - [](Json::Value const&, - std::integral_constant) {}); + [](Json::Value const&, std::integral_constant) {}); }; }(std::as_const(s1))); BEAST_EXPECT( std::as_const(s1).visit()( std::integral_constant{}, Overload{ - [](Json::Value const& v, - std::integral_constant) { - return v["value"].asInt(); - }, + [](Json::Value const& v, std::integral_constant) { return v["value"].asInt(); }, [](Json::Value&, auto) { return 0; }, [](auto, auto) { return 0; }}) == 3); static_assert([](auto&& v) { - return requires { - v.visit( - std::integral_constant{}, - [](Json::Value const&) {}); - }; + return requires { v.visit(std::integral_constant{}, [](Json::Value const&) {}); }; }(std::as_const(s1))); BEAST_EXPECT( std::as_const(s1).visit( @@ -820,11 +676,7 @@ struct MultiApiJson_test : beast::unit_test::suite [](Json::Value&) { return 0; }, [](auto...) { return 0; }}) == 3); static_assert([](auto&& v) { - return requires { - v.visit()( - std::integral_constant{}, - [](Json::Value const&) {}); - }; + return requires { v.visit()(std::integral_constant{}, [](Json::Value const&) {}); }; }(std::as_const(s1))); BEAST_EXPECT( std::as_const(s1).visit()( @@ -834,38 +686,26 @@ struct MultiApiJson_test : beast::unit_test::suite [](Json::Value&) { return 0; }, [](auto...) { return 0; }}) == 3); - static_assert([](auto&& v) { - return requires { v.visit(1, [](Json::Value&, unsigned) {}); }; - }(s1)); + static_assert([](auto&& v) { return requires { v.visit(1, [](Json::Value&, unsigned) {}); }; }(s1)); BEAST_EXPECT( s1.visit( 3u, Overload{ - [](Json::Value& v, unsigned) { - return v["value"].asInt(); - }, + [](Json::Value& v, unsigned) { return v["value"].asInt(); }, [](Json::Value const&, unsigned) { return 0; }, [](Json::Value&, auto) { return 0; }, [](auto, auto) { return 0; }}) == 5); - static_assert([](auto&& v) { - return requires { - v.visit()(1, [](Json::Value&, unsigned) {}); - }; - }(s1)); + static_assert([](auto&& v) { return requires { v.visit()(1, [](Json::Value&, unsigned) {}); }; }(s1)); BEAST_EXPECT( s1.visit()( 3u, Overload{ - [](Json::Value& v, unsigned) { - return v["value"].asInt(); - }, + [](Json::Value& v, unsigned) { return v["value"].asInt(); }, [](Json::Value const&, unsigned) { return 0; }, [](Json::Value&, auto) { return 0; }, [](auto, auto) { return 0; }}) == 5); - static_assert([](auto&& v) { - return requires { v.visit(1, [](Json::Value&) {}); }; - }(s1)); + static_assert([](auto&& v) { return requires { v.visit(1, [](Json::Value&) {}); }; }(s1)); BEAST_EXPECT( s1.visit( 3, @@ -873,9 +713,7 @@ struct MultiApiJson_test : beast::unit_test::suite [](Json::Value& v) { return v["value"].asInt(); }, [](Json::Value const&) { return 0; }, [](auto...) { return 0; }}) == 5); - static_assert([](auto&& v) { - return requires { v.visit()(1, [](Json::Value&) {}); }; - }(s1)); + static_assert([](auto&& v) { return requires { v.visit()(1, [](Json::Value&) {}); }; }(s1)); BEAST_EXPECT( s1.visit()( 3, @@ -885,39 +723,30 @@ struct MultiApiJson_test : beast::unit_test::suite [](auto...) { return 0; }}) == 5); static_assert([](auto&& v) { - return requires { - v.visit(1, [](Json::Value const&, unsigned) {}); - }; + return requires { v.visit(1, [](Json::Value const&, unsigned) {}); }; }(std::as_const(s1))); BEAST_EXPECT( std::as_const(s1).visit( 2u, Overload{ - [](Json::Value const& v, unsigned) { - return v["value"].asInt(); - }, + [](Json::Value const& v, unsigned) { return v["value"].asInt(); }, [](Json::Value const&, auto) { return 0; }, [](Json::Value&, unsigned) { return 0; }, [](auto, auto) { return 0; }}) == 3); static_assert([](auto&& v) { - return requires { - v.visit()(1, [](Json::Value const&, unsigned) {}); - }; + return requires { v.visit()(1, [](Json::Value const&, unsigned) {}); }; }(std::as_const(s1))); BEAST_EXPECT( std::as_const(s1).visit()( 2u, Overload{ - [](Json::Value const& v, unsigned) { - return v["value"].asInt(); - }, + [](Json::Value const& v, unsigned) { return v["value"].asInt(); }, [](Json::Value const&, auto) { return 0; }, [](Json::Value&, unsigned) { return 0; }, [](auto, auto) { return 0; }}) == 3); - static_assert([](auto&& v) { - return requires { v.visit(1, [](Json::Value const&) {}); }; - }(std::as_const(s1))); + static_assert( + [](auto&& v) { return requires { v.visit(1, [](Json::Value const&) {}); }; }(std::as_const(s1))); BEAST_EXPECT( std::as_const(s1).visit( 2, @@ -925,9 +754,8 @@ struct MultiApiJson_test : beast::unit_test::suite [](Json::Value const& v) { return v["value"].asInt(); }, [](Json::Value&) { return 0; }, [](auto...) { return 0; }}) == 3); - static_assert([](auto&& v) { - return requires { v.visit()(1, [](Json::Value const&) {}); }; - }(std::as_const(s1))); + static_assert( + [](auto&& v) { return requires { v.visit()(1, [](Json::Value const&) {}); }; }(std::as_const(s1))); BEAST_EXPECT( std::as_const(s1).visit()( 2, @@ -938,112 +766,60 @@ struct MultiApiJson_test : beast::unit_test::suite // Rvalue MultivarJson visitor only binds to regular reference static_assert([](auto&& v) { - return !requires { - std::forward(v).visit(1, [](Json::Value&&) {}); - }; + return !requires { std::forward(v).visit(1, [](Json::Value&&) {}); }; }(std::move(s1))); static_assert([](auto&& v) { - return !requires { - std::forward(v).visit( - 1, [](Json::Value const&&) {}); - }; + return !requires { std::forward(v).visit(1, [](Json::Value const&&) {}); }; }(std::move(s1))); static_assert([](auto&& v) { - return requires { - std::forward(v).visit(1, [](Json::Value&) {}); - }; + return requires { std::forward(v).visit(1, [](Json::Value&) {}); }; }(std::move(s1))); static_assert([](auto&& v) { - return requires { - std::forward(v).visit( - 1, [](Json::Value const&) {}); - }; + return requires { std::forward(v).visit(1, [](Json::Value const&) {}); }; }(std::move(s1))); static_assert([](auto&& v) { - return !requires { - std::forward(v).visit()( - 1, [](Json::Value&&) {}); - }; + return !requires { std::forward(v).visit()(1, [](Json::Value&&) {}); }; }(std::move(s1))); static_assert([](auto&& v) { - return !requires { - std::forward(v).visit()( - 1, [](Json::Value const&&) {}); - }; + return !requires { std::forward(v).visit()(1, [](Json::Value const&&) {}); }; }(std::move(s1))); static_assert([](auto&& v) { - return requires { - std::forward(v).visit()( - 1, [](Json::Value&) {}); - }; + return requires { std::forward(v).visit()(1, [](Json::Value&) {}); }; }(std::move(s1))); static_assert([](auto&& v) { - return requires { - std::forward(v).visit()( - 1, [](Json::Value const&) {}); - }; + return requires { std::forward(v).visit()(1, [](Json::Value const&) {}); }; }(std::move(s1))); static_assert([](auto&& v) { - return !requires { - std::forward(v).visit( - 1, [](Json::Value const&&) {}); - }; + return !requires { std::forward(v).visit(1, [](Json::Value const&&) {}); }; }(std::move(std::as_const(s1)))); static_assert([](auto&& v) { - return requires { - std::forward(v).visit( - 1, [](Json::Value const&) {}); - }; + return requires { std::forward(v).visit(1, [](Json::Value const&) {}); }; }(std::move(std::as_const(s1)))); static_assert([](auto&& v) { - return !requires { - std::forward(v).visit()( - 1, [](Json::Value const&&) {}); - }; + return !requires { std::forward(v).visit()(1, [](Json::Value const&&) {}); }; }(std::move(std::as_const(s1)))); static_assert([](auto&& v) { - return requires { - std::forward(v).visit()( - 1, [](Json::Value const&) {}); - }; + return requires { std::forward(v).visit()(1, [](Json::Value const&) {}); }; }(std::move(std::as_const(s1)))); // Missing const static_assert([](auto&& v) { - return !requires { - std::forward(v).visit( - 1, [](Json::Value&, auto) {}); - }; + return !requires { std::forward(v).visit(1, [](Json::Value&, auto) {}); }; }(std::as_const(s1))); static_assert([](auto&& v) { - return !requires { - std::forward(v).visit()( - 1, [](Json::Value&, auto) {}); - }; + return !requires { std::forward(v).visit()(1, [](Json::Value&, auto) {}); }; }(std::as_const(s1))); // Missing parameter - static_assert([](auto&& v) { - return !requires { - std::forward(v).visit(1, []() {}); - }; - }(s1)); - static_assert([](auto&& v) { - return !requires { - std::forward(v).visit()(1, []() {}); - }; - }(s1)); + static_assert([](auto&& v) { return !requires { std::forward(v).visit(1, []() {}); }; }(s1)); + static_assert([](auto&& v) { return !requires { std::forward(v).visit()(1, []() {}); }; }(s1)); // Sanity checks static_assert([](auto&& v) { - return requires { - std::forward(v).visit(1, [](auto...) {}); - }; + return requires { std::forward(v).visit(1, [](auto...) {}); }; }(std::as_const(s1))); static_assert([](auto&& v) { - return requires { - std::forward(v).visit()(1, [](auto...) {}); - }; + return requires { std::forward(v).visit()(1, [](auto...) {}); }; }(std::as_const(s1))); } } diff --git a/src/test/protocol/PublicKey_test.cpp b/src/test/protocol/PublicKey_test.cpp index 4af21cd037..cad1e87198 100644 --- a/src/test/protocol/PublicKey_test.cpp +++ b/src/test/protocol/PublicKey_test.cpp @@ -294,11 +294,9 @@ public: // Try converting short, long and malformed data BEAST_EXPECT(!parseBase58(TokenType::NodePublic, "")); BEAST_EXPECT(!parseBase58(TokenType::NodePublic, " ")); - BEAST_EXPECT( - !parseBase58(TokenType::NodePublic, "!ty89234gh45")); + BEAST_EXPECT(!parseBase58(TokenType::NodePublic, "!ty89234gh45")); - auto const good = toBase58( - TokenType::NodePublic, derivePublicKey(keyType, randomSecretKey())); + auto const good = toBase58(TokenType::NodePublic, derivePublicKey(keyType, randomSecretKey())); // Short (non-empty) strings { @@ -368,8 +366,7 @@ public: BEAST_EXPECT((si == sj) == (i == j)); - auto const skj = - parseBase58(TokenType::NodePublic, sj); + auto const skj = parseBase58(TokenType::NodePublic, sj); BEAST_EXPECT(skj && (keys[j] == *skj)); BEAST_EXPECT((*ski == *skj) == (i == j)); @@ -384,13 +381,10 @@ public: { auto const pk1 = derivePublicKey( - KeyType::secp256k1, - generateSecretKey( - KeyType::secp256k1, generateSeed("masterpassphrase"))); + KeyType::secp256k1, generateSecretKey(KeyType::secp256k1, generateSeed("masterpassphrase"))); - auto const pk2 = parseBase58( - TokenType::NodePublic, - "n94a1u4jAz288pZLtw6yFWVbi89YamiC6JBXPVUj5zmExe5fTVg9"); + auto const pk2 = + parseBase58(TokenType::NodePublic, "n94a1u4jAz288pZLtw6yFWVbi89YamiC6JBXPVUj5zmExe5fTVg9"); BEAST_EXPECT(pk2); BEAST_EXPECT(pk1 == *pk2); @@ -402,13 +396,10 @@ public: { auto const pk1 = derivePublicKey( - KeyType::ed25519, - generateSecretKey( - KeyType::ed25519, generateSeed("masterpassphrase"))); + KeyType::ed25519, generateSecretKey(KeyType::ed25519, generateSeed("masterpassphrase"))); - auto const pk2 = parseBase58( - TokenType::NodePublic, - "nHUeeJCSY2dM71oxM8Cgjouf5ekTuev2mwDpc374aLMxzDLXNmjf"); + auto const pk2 = + parseBase58(TokenType::NodePublic, "nHUeeJCSY2dM71oxM8Cgjouf5ekTuev2mwDpc374aLMxzDLXNmjf"); BEAST_EXPECT(pk2); BEAST_EXPECT(pk1 == *pk2); @@ -423,18 +414,14 @@ public: testcase("Miscellaneous operations"); auto const pk1 = derivePublicKey( - KeyType::secp256k1, - generateSecretKey( - KeyType::secp256k1, generateSeed("masterpassphrase"))); + KeyType::secp256k1, generateSecretKey(KeyType::secp256k1, generateSeed("masterpassphrase"))); PublicKey pk2(pk1); BEAST_EXPECT(pk1 == pk2); BEAST_EXPECT(pk2 == pk1); PublicKey pk3 = derivePublicKey( - KeyType::secp256k1, - generateSecretKey( - KeyType::secp256k1, generateSeed("arbitraryPassPhrase"))); + KeyType::secp256k1, generateSecretKey(KeyType::secp256k1, generateSeed("arbitraryPassPhrase"))); // Testing the copy assignment operation of PublicKey class pk3 = pk2; BEAST_EXPECT(pk3 == pk2); diff --git a/src/test/protocol/Quality_test.cpp b/src/test/protocol/Quality_test.cpp index 840e903ed5..1dbbbfdf3d 100644 --- a/src/test/protocol/Quality_test.cpp +++ b/src/test/protocol/Quality_test.cpp @@ -16,9 +16,7 @@ public: template static STAmount - amount( - Integer integer, - std::enable_if_t::value>* = 0) + amount(Integer integer, std::enable_if_t::value>* = 0) { static_assert(std::is_integral::value, ""); return STAmount(integer, false); @@ -26,9 +24,7 @@ public: template static STAmount - amount( - Integer integer, - std::enable_if_t::value>* = 0) + amount(Integer integer, std::enable_if_t::value>* = 0) { static_assert(std::is_integral::value, ""); if (integer < 0) @@ -45,13 +41,7 @@ public: template void - ceil_in( - Quality const& q, - In1 in, - Out1 out, - Int limit, - In2 in_expected, - Out2 out_expected) + ceil_in(Quality const& q, In1 in, Out1 out, Int limit, In2 in_expected, Out2 out_expected) { auto expect_result(amounts(in_expected, out_expected)); auto actual_result(q.ceil_in(amounts(in, out), amount(limit))); @@ -61,13 +51,7 @@ public: template void - ceil_out( - Quality const& q, - In1 in, - Out1 out, - Int limit, - In2 in_expected, - Out2 out_expected) + ceil_out(Quality const& q, In1 in, Out1 out, Int limit, In2 in_expected, Out2 out_expected) { auto const expect_result(amounts(in_expected, out_expected)); auto const actual_result(q.ceil_out(amounts(in, out), amount(limit))); @@ -269,10 +253,9 @@ public: { Quality q(0x5d048191fb9130daull); // 126836389.7680090 Amounts const value( - amount(349469768), // 349.469768 XRP - raw(2755280000000000ull, -15)); // 2.75528 - STAmount const limit( - raw(4131113916555555, -16)); // .4131113916555555 + amount(349469768), // 349.469768 XRP + raw(2755280000000000ull, -15)); // 2.75528 + STAmount const limit(raw(4131113916555555, -16)); // .4131113916555555 Amounts const result(q.ceil_out(value, limit)); BEAST_EXPECT(result.in != beast::zero); } @@ -366,8 +349,7 @@ public: { testcase("operations"); - Quality const q11( - Amounts(STAmount(noIssue(), 731), STAmount(noIssue(), 731))); + Quality const q11(Amounts(STAmount(noIssue(), 731), STAmount(noIssue(), 731))); Quality qa(q11); Quality qb(q11); diff --git a/src/test/protocol/STAccount_test.cpp b/src/test/protocol/STAccount_test.cpp index d469627d51..76b633df80 100644 --- a/src/test/protocol/STAccount_test.cpp +++ b/src/test/protocol/STAccount_test.cpp @@ -63,8 +63,7 @@ struct STAccount_test : public beast::unit_test::suite Serializer s; zeroAcct.add(s); BEAST_EXPECT(s.size() == 21); - BEAST_EXPECT( - strHex(s) == "140000000000000000000000000000000000000000"); + BEAST_EXPECT(strHex(s) == "140000000000000000000000000000000000000000"); SerialIter sit(s.slice()); STAccount const deserializedZero(sit, sfAccount); BEAST_EXPECT(deserializedZero.isEquivalent(zeroAcct)); @@ -72,8 +71,7 @@ struct STAccount_test : public beast::unit_test::suite { // Construct from a VL that is not exactly 160 bits. Serializer s; - std::uint8_t const bits128[]{ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + std::uint8_t const bits128[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; s.addVL(bits128, sizeof(bits128)); SerialIter sit(s.slice()); try @@ -83,8 +81,7 @@ struct STAccount_test : public beast::unit_test::suite } catch (std::runtime_error const& ex) { - BEAST_EXPECT( - ex.what() == std::string("Invalid STAccount size")); + BEAST_EXPECT(ex.what() == std::string("Invalid STAccount size")); } } @@ -113,8 +110,7 @@ struct STAccount_test : public beast::unit_test::suite } { - auto const s = - "âabcd1rNxp4h8apvRis6mJf9Sh8C6iRxfrDWNâabcdAVâ\xc2\x80\xc2\x8f"; + auto const s = "âabcd1rNxp4h8apvRis6mJf9Sh8C6iRxfrDWNâabcdAVâ\xc2\x80\xc2\x8f"; BEAST_EXPECT(!parseBase58(s)); } } diff --git a/src/test/protocol/STAmount_test.cpp b/src/test/protocol/STAmount_test.cpp index 796ac91de1..98bcc7b1bc 100644 --- a/src/test/protocol/STAmount_test.cpp +++ b/src/test/protocol/STAmount_test.cpp @@ -35,18 +35,9 @@ public: mantissa--; if (mantissa < STAmount::cMinValue) - return { - amount.issue(), - mantissa, - amount.exponent(), - amount.negative()}; + return {amount.issue(), mantissa, amount.exponent(), amount.negative()}; - return { - amount.issue(), - mantissa, - amount.exponent(), - amount.negative(), - STAmount::unchecked{}}; + return {amount.issue(), mantissa, amount.exponent(), amount.negative(), STAmount::unchecked{}}; } if (valueDigits == 999999999) @@ -54,18 +45,9 @@ public: mantissa++; if (mantissa > STAmount::cMaxValue) - return { - amount.issue(), - mantissa, - amount.exponent(), - amount.negative()}; + return {amount.issue(), mantissa, amount.exponent(), amount.negative()}; - return { - amount.issue(), - mantissa, - amount.exponent(), - amount.negative(), - STAmount::unchecked{}}; + return {amount.issue(), mantissa, amount.exponent(), amount.negative(), STAmount::unchecked{}}; } return amount; @@ -91,9 +73,8 @@ public: if (res != cmp) { - log << "(" << num.getText() << "/" << den.getText() << ") X " - << mul.getText() << " = " << res.getText() << " not " - << cmp.getText(); + log << "(" << num.getText() << "/" << den.getText() << ") X " << mul.getText() << " = " << res.getText() + << " not " << cmp.getText(); fail("Rounding"); return; } @@ -108,14 +89,11 @@ public: BEAST_EXPECT(!prod1.native()); - STAmount prod2( - noIssue(), - static_cast(a) * static_cast(b)); + STAmount prod2(noIssue(), static_cast(a) * static_cast(b)); if (prod1 != prod2) { - log << "nn(" << aa.getFullText() << " * " << bb.getFullText() - << ") = " << prod1.getFullText() << " not " + log << "nn(" << aa.getFullText() << " * " << bb.getFullText() << ") = " << prod1.getFullText() << " not " << prod2.getFullText(); fail("Multiplication result is not exact"); } @@ -124,10 +102,7 @@ public: //-------------------------------------------------------------------------- void - testSetValue( - std::string const& value, - Issue const& issue, - bool success = true) + testSetValue(std::string const& value, Issue const& issue, bool success = true) { try { @@ -215,8 +190,7 @@ public: // VFALCO NOTE Why repeat "STAmount fail" so many times?? unexpected(serializeAndDeserialize(zeroSt) != zeroSt, "STAmount fail"); unexpected(serializeAndDeserialize(one) != one, "STAmount fail"); - unexpected( - serializeAndDeserialize(hundred) != hundred, "STAmount fail"); + unexpected(serializeAndDeserialize(hundred) != hundred, "STAmount fail"); unexpected(!zeroSt.native(), "STAmount fail"); unexpected(!hundred.native(), "STAmount fail"); unexpected(zeroSt != beast::zero, "STAmount fail"); @@ -298,8 +272,7 @@ public: STAmount zeroSt(noIssue()), one(noIssue(), 1), hundred(noIssue(), 100); unexpected(serializeAndDeserialize(zeroSt) != zeroSt, "STAmount fail"); unexpected(serializeAndDeserialize(one) != one, "STAmount fail"); - unexpected( - serializeAndDeserialize(hundred) != hundred, "STAmount fail"); + unexpected(serializeAndDeserialize(hundred) != hundred, "STAmount fail"); unexpected(zeroSt.native(), "STAmount fail"); unexpected(hundred.native(), "STAmount fail"); unexpected(zeroSt != beast::zero, "STAmount fail"); @@ -361,33 +334,19 @@ public: unexpected((hundred != hundred), "STAmount fail"); unexpected(STAmount(noIssue()).getText() != "0", "STAmount fail"); unexpected(STAmount(noIssue(), 31).getText() != "31", "STAmount fail"); + unexpected(STAmount(noIssue(), 31, 1).getText() != "310", "STAmount fail"); + unexpected(STAmount(noIssue(), 31, -1).getText() != "3.1", "STAmount fail"); + unexpected(STAmount(noIssue(), 31, -2).getText() != "0.31", "STAmount fail"); unexpected( - STAmount(noIssue(), 31, 1).getText() != "310", "STAmount fail"); + multiply(STAmount(noIssue(), 20), STAmount(3), noIssue()).getText() != "60", "STAmount multiply fail 1"); unexpected( - STAmount(noIssue(), 31, -1).getText() != "3.1", "STAmount fail"); - unexpected( - STAmount(noIssue(), 31, -2).getText() != "0.31", "STAmount fail"); - unexpected( - multiply(STAmount(noIssue(), 20), STAmount(3), noIssue()) - .getText() != "60", - "STAmount multiply fail 1"); - unexpected( - multiply(STAmount(noIssue(), 20), STAmount(3), xrpIssue()) - .getText() != "60", - "STAmount multiply fail 2"); - unexpected( - multiply(STAmount(20), STAmount(3), noIssue()).getText() != "60", - "STAmount multiply fail 3"); - unexpected( - multiply(STAmount(20), STAmount(3), xrpIssue()).getText() != "60", - "STAmount multiply fail 4"); + multiply(STAmount(noIssue(), 20), STAmount(3), xrpIssue()).getText() != "60", "STAmount multiply fail 2"); + unexpected(multiply(STAmount(20), STAmount(3), noIssue()).getText() != "60", "STAmount multiply fail 3"); + unexpected(multiply(STAmount(20), STAmount(3), xrpIssue()).getText() != "60", "STAmount multiply fail 4"); - if (divide(STAmount(noIssue(), 60), STAmount(3), noIssue()).getText() != - "20") + if (divide(STAmount(noIssue(), 60), STAmount(3), noIssue()).getText() != "20") { - log << "60/3 = " - << divide(STAmount(noIssue(), 60), STAmount(3), noIssue()) - .getText(); + log << "60/3 = " << divide(STAmount(noIssue(), 60), STAmount(3), noIssue()).getText(); fail("STAmount divide fail"); } else @@ -395,30 +354,21 @@ public: pass(); } + unexpected(divide(STAmount(noIssue(), 60), STAmount(3), xrpIssue()).getText() != "20", "STAmount divide fail"); + unexpected( - divide(STAmount(noIssue(), 60), STAmount(3), xrpIssue()) - .getText() != "20", + divide(STAmount(noIssue(), 60), STAmount(noIssue(), 3), noIssue()).getText() != "20", "STAmount divide fail"); unexpected( - divide(STAmount(noIssue(), 60), STAmount(noIssue(), 3), noIssue()) - .getText() != "20", - "STAmount divide fail"); - - unexpected( - divide(STAmount(noIssue(), 60), STAmount(noIssue(), 3), xrpIssue()) - .getText() != "20", + divide(STAmount(noIssue(), 60), STAmount(noIssue(), 3), xrpIssue()).getText() != "20", "STAmount divide fail"); STAmount a1(noIssue(), 60), a2(noIssue(), 10, -1); - unexpected( - divide(a2, a1, noIssue()) != amountFromQuality(getRate(a1, a2)), - "STAmount setRate(getRate) fail"); + unexpected(divide(a2, a1, noIssue()) != amountFromQuality(getRate(a1, a2)), "STAmount setRate(getRate) fail"); - unexpected( - divide(a1, a2, noIssue()) != amountFromQuality(getRate(a2, a1)), - "STAmount setRate(getRate) fail"); + unexpected(divide(a1, a2, noIssue()) != amountFromQuality(getRate(a2, a1)), "STAmount setRate(getRate) fail"); } //-------------------------------------------------------------------------- @@ -433,13 +383,11 @@ public: // and getNeeded unexpected( - getRate(STAmount(1), STAmount(10)) != - (((100ull - 14) << (64 - 8)) | 1000000000000000ull), + getRate(STAmount(1), STAmount(10)) != (((100ull - 14) << (64 - 8)) | 1000000000000000ull), "STAmount getRate fail 1"); unexpected( - getRate(STAmount(10), STAmount(1)) != - (((100ull - 16) << (64 - 8)) | 1000000000000000ull), + getRate(STAmount(10), STAmount(1)) != (((100ull - 16) << (64 - 8)) | 1000000000000000ull), "STAmount getRate fail 2"); unexpected( @@ -453,23 +401,19 @@ public: "STAmount getRate fail 4"); unexpected( - getRate(STAmount(noIssue(), 1), STAmount(10)) != - (((100ull - 14) << (64 - 8)) | 1000000000000000ull), + getRate(STAmount(noIssue(), 1), STAmount(10)) != (((100ull - 14) << (64 - 8)) | 1000000000000000ull), "STAmount getRate fail 5"); unexpected( - getRate(STAmount(noIssue(), 10), STAmount(1)) != - (((100ull - 16) << (64 - 8)) | 1000000000000000ull), + getRate(STAmount(noIssue(), 10), STAmount(1)) != (((100ull - 16) << (64 - 8)) | 1000000000000000ull), "STAmount getRate fail 6"); unexpected( - getRate(STAmount(1), STAmount(noIssue(), 10)) != - (((100ull - 14) << (64 - 8)) | 1000000000000000ull), + getRate(STAmount(1), STAmount(noIssue(), 10)) != (((100ull - 14) << (64 - 8)) | 1000000000000000ull), "STAmount getRate fail 7"); unexpected( - getRate(STAmount(10), STAmount(noIssue(), 1)) != - (((100ull - 16) << (64 - 8)) | 1000000000000000ull), + getRate(STAmount(10), STAmount(noIssue(), 1)) != (((100ull - 16) << (64 - 8)) | 1000000000000000ull), "STAmount getRate fail 8"); roundTest(1, 3, 3); @@ -493,19 +437,13 @@ public: testcase("underflow"); STAmount bigNative(STAmount::cMaxNative / 2); - STAmount bigValue( - noIssue(), - (STAmount::cMinValue + STAmount::cMaxValue) / 2, - STAmount::cMaxOffset - 1); - STAmount smallValue( - noIssue(), - (STAmount::cMinValue + STAmount::cMaxValue) / 2, - STAmount::cMinOffset + 1); + STAmount bigValue(noIssue(), (STAmount::cMinValue + STAmount::cMaxValue) / 2, STAmount::cMaxOffset - 1); + STAmount smallValue(noIssue(), (STAmount::cMinValue + STAmount::cMaxValue) / 2, STAmount::cMinOffset + 1); STAmount zeroSt(noIssue(), 0); - STAmount smallXsmall = multiply(smallValue, smallValue, noIssue()); + STAmount smallXSmall = multiply(smallValue, smallValue, noIssue()); - BEAST_EXPECT(smallXsmall == beast::zero); + BEAST_EXPECT(smallXSmall == beast::zero); STAmount bigDsmall = divide(smallValue, bigValue, noIssue()); @@ -600,13 +538,10 @@ public: } { - BEAST_EXPECT( - amountFromJson(sfNumber, Json::Value(42)) == XRPAmount(42)); - BEAST_EXPECT( - amountFromJson(sfNumber, Json::Value(-42)) == XRPAmount(-42)); + BEAST_EXPECT(amountFromJson(sfNumber, Json::Value(42)) == XRPAmount(42)); + BEAST_EXPECT(amountFromJson(sfNumber, Json::Value(-42)) == XRPAmount(-42)); - BEAST_EXPECT( - amountFromJson(sfNumber, Json::UInt(42)) == XRPAmount(42)); + BEAST_EXPECT(amountFromJson(sfNumber, Json::UInt(42)) == XRPAmount(42)); BEAST_EXPECT(amountFromJson(sfNumber, "-123") == XRPAmount(-123)); @@ -614,29 +549,22 @@ public: BEAST_EXPECT(amountFromJson(sfNumber, "-123") == XRPAmount(-123)); BEAST_EXPECT(amountFromJson(sfNumber, "3.14e2") == XRPAmount(314)); - BEAST_EXPECT( - amountFromJson(sfNumber, "-3.14e2") == XRPAmount(-314)); + BEAST_EXPECT(amountFromJson(sfNumber, "-3.14e2") == XRPAmount(-314)); BEAST_EXPECT(amountFromJson(sfNumber, "0") == XRPAmount(0)); BEAST_EXPECT(amountFromJson(sfNumber, "-0") == XRPAmount(0)); constexpr auto imin = std::numeric_limits::min(); BEAST_EXPECT(amountFromJson(sfNumber, imin) == XRPAmount(imin)); - BEAST_EXPECT( - amountFromJson(sfNumber, std::to_string(imin)) == - XRPAmount(imin)); + BEAST_EXPECT(amountFromJson(sfNumber, std::to_string(imin)) == XRPAmount(imin)); constexpr auto imax = std::numeric_limits::max(); BEAST_EXPECT(amountFromJson(sfNumber, imax) == XRPAmount(imax)); - BEAST_EXPECT( - amountFromJson(sfNumber, std::to_string(imax)) == - XRPAmount(imax)); + BEAST_EXPECT(amountFromJson(sfNumber, std::to_string(imax)) == XRPAmount(imax)); constexpr auto umax = std::numeric_limits::max(); BEAST_EXPECT(amountFromJson(sfNumber, umax) == XRPAmount(umax)); - BEAST_EXPECT( - amountFromJson(sfNumber, std::to_string(umax)) == - XRPAmount(umax)); + BEAST_EXPECT(amountFromJson(sfNumber, std::to_string(umax)) == XRPAmount(umax)); // XRP does not handle fractional part try @@ -646,8 +574,7 @@ public: } catch (std::runtime_error const& e) { - std::string const expected = - "XRP and MPT must be specified as integral amount."; + std::string const expected = "XRP and MPT must be specified as integral amount."; BEAST_EXPECT(e.what() == expected); } @@ -659,8 +586,7 @@ public: } catch (std::runtime_error const& e) { - std::string const expected = - "XRP and MPT must be specified as integral amount."; + std::string const expected = "XRP and MPT must be specified as integral amount."; BEAST_EXPECT(e.what() == expected); } @@ -716,8 +642,7 @@ public: } catch (std::runtime_error const& e) { - std::string const expected = - "XRP may not be specified with a null Json value"; + std::string const expected = "XRP may not be specified with a null Json value"; BEAST_EXPECT(e.what() == expected); } @@ -804,8 +729,7 @@ public: Issue const usd{Currency(0x5553440000000000), AccountID(0x4985601)}; Issue const xrp{xrpIssue()}; - for (std::uint64_t drops = 100000000000000000; drops != 1; - drops = drops / 10) + for (std::uint64_t drops = 100000000000000000; drops != 1; drops = drops / 10) { auto const t = amountFromString(xrp, std::to_string(drops)); auto const s = t.xrp(); @@ -837,8 +761,7 @@ public: Issue const usd{Currency(0x5553440000000000), AccountID(0x4985601)}; Issue const xrp{xrpIssue()}; - for (std::uint64_t dollars = 10000000000; dollars != 1; - dollars = dollars / 10) + for (std::uint64_t dollars = 10000000000; dollars != 1; dollars = dollars / 10) { auto const t = amountFromString(usd, std::to_string(dollars)); auto const s = t.iou(); @@ -1021,8 +944,7 @@ public: // Overflow check for max MPT amounts { - STAmount amt1( - mpt, std::numeric_limits::max()); + STAmount amt1(mpt, std::numeric_limits::max()); STAmount amt2(mpt, 1); BEAST_EXPECT(canAdd(amt1, amt2) == false); } @@ -1194,8 +1116,7 @@ public: // Overflow check for max positive MPT amounts (should fail) { - STAmount amt1( - mpt, std::numeric_limits::max()); + STAmount amt1(mpt, std::numeric_limits::max()); STAmount amt2(mpt, -2); BEAST_EXPECT(canSubtract(amt1, amt2) == false); } diff --git a/src/test/protocol/STInteger_test.cpp b/src/test/protocol/STInteger_test.cpp index 73b4ca39ef..74340d53ea 100644 --- a/src/test/protocol/STInteger_test.cpp +++ b/src/test/protocol/STInteger_test.cpp @@ -21,9 +21,7 @@ struct STInteger_test : public beast::unit_test::suite // there is some special handling for sfTransactionResult STUInt8 tr(sfTransactionResult, 0); BEAST_EXPECT(tr.value() == 0); - BEAST_EXPECT( - tr.getText() == - "The transaction was applied. Only final in a validated ledger."); + BEAST_EXPECT(tr.getText() == "The transaction was applied. Only final in a validated ledger."); BEAST_EXPECT(tr.getSType() == STI_UINT8); BEAST_EXPECT(tr.getJson(JsonOptions::none) == "tesSUCCESS"); @@ -101,8 +99,7 @@ struct STInteger_test : public beast::unit_test::suite BEAST_EXPECT(u64_2.value() == 0xFFFFFFFFFFFFFFFFull); BEAST_EXPECT(u64_2.getText() == "18446744073709551615"); BEAST_EXPECT(u64_2.getSType() == STI_UINT64); - BEAST_EXPECT( - u64_2.getJson(JsonOptions::none) == "18446744073709551615"); + BEAST_EXPECT(u64_2.getJson(JsonOptions::none) == "18446744073709551615"); } void diff --git a/src/test/protocol/STIssue_test.cpp b/src/test/protocol/STIssue_test.cpp index d64722712b..cfd047e752 100644 --- a/src/test/protocol/STIssue_test.cpp +++ b/src/test/protocol/STIssue_test.cpp @@ -123,12 +123,8 @@ public: BEAST_EXPECT(STIssue(sfAsset, asset1) != asset3); BEAST_EXPECT(STIssue(sfAsset, asset1) == asset1); BEAST_EXPECT(STIssue(sfAsset, asset1).getText() == "XRP"); - BEAST_EXPECT( - STIssue(sfAsset, asset2).getText() == - "USD/rG1QQv2nh2gr7RCZ1P8YYcBUKCCN633jCn"); - BEAST_EXPECT( - STIssue(sfAsset, asset3).getText() == - "000000000000000000000000000000000000000000000002"); + BEAST_EXPECT(STIssue(sfAsset, asset2).getText() == "USD/rG1QQv2nh2gr7RCZ1P8YYcBUKCCN633jCn"); + BEAST_EXPECT(STIssue(sfAsset, asset3).getText() == "000000000000000000000000000000000000000000000002"); } void diff --git a/src/test/protocol/STNumber_test.cpp b/src/test/protocol/STNumber_test.cpp index 4e7a8388ee..a1a94accaa 100644 --- a/src/test/protocol/STNumber_test.cpp +++ b/src/test/protocol/STNumber_test.cpp @@ -40,16 +40,11 @@ struct STNumber_test : public beast::unit_test::suite } std::initializer_list const mantissas = { - std::numeric_limits::min(), - -1, - 0, - 1, - std::numeric_limits::max()}; + std::numeric_limits::min(), -1, 0, 1, std::numeric_limits::max()}; for (std::int64_t mantissa : mantissas) testCombo(Number{mantissa}); - std::initializer_list const exponents = { - Number::minExponent, -1, 0, 1, Number::maxExponent - 1}; + std::initializer_list const exponents = {Number::minExponent, -1, 0, 1, Number::maxExponent - 1}; for (std::int32_t exponent : exponents) testCombo(Number{123, exponent}); @@ -63,126 +58,71 @@ struct STNumber_test : public beast::unit_test::suite } { - BEAST_EXPECT( - numberFromJson(sfNumber, Json::Value(42)) == - STNumber(sfNumber, 42)); - BEAST_EXPECT( - numberFromJson(sfNumber, Json::Value(-42)) == - STNumber(sfNumber, -42)); + BEAST_EXPECT(numberFromJson(sfNumber, Json::Value(42)) == STNumber(sfNumber, 42)); + BEAST_EXPECT(numberFromJson(sfNumber, Json::Value(-42)) == STNumber(sfNumber, -42)); - BEAST_EXPECT( - numberFromJson(sfNumber, Json::UInt(42)) == - STNumber(sfNumber, 42)); + BEAST_EXPECT(numberFromJson(sfNumber, Json::UInt(42)) == STNumber(sfNumber, 42)); - BEAST_EXPECT( - numberFromJson(sfNumber, "-123") == STNumber(sfNumber, -123)); + BEAST_EXPECT(numberFromJson(sfNumber, "-123") == STNumber(sfNumber, -123)); - BEAST_EXPECT( - numberFromJson(sfNumber, "123") == STNumber(sfNumber, 123)); - BEAST_EXPECT( - numberFromJson(sfNumber, "-123") == STNumber(sfNumber, -123)); + BEAST_EXPECT(numberFromJson(sfNumber, "123") == STNumber(sfNumber, 123)); + BEAST_EXPECT(numberFromJson(sfNumber, "-123") == STNumber(sfNumber, -123)); - BEAST_EXPECT( - numberFromJson(sfNumber, "3.14") == - STNumber(sfNumber, Number(314, -2))); - BEAST_EXPECT( - numberFromJson(sfNumber, "-3.14") == - STNumber(sfNumber, -Number(314, -2))); - BEAST_EXPECT( - numberFromJson(sfNumber, "3.14e2") == STNumber(sfNumber, 314)); - BEAST_EXPECT( - numberFromJson(sfNumber, "-3.14e2") == - STNumber(sfNumber, -314)); + BEAST_EXPECT(numberFromJson(sfNumber, "3.14") == STNumber(sfNumber, Number(314, -2))); + BEAST_EXPECT(numberFromJson(sfNumber, "-3.14") == STNumber(sfNumber, -Number(314, -2))); + BEAST_EXPECT(numberFromJson(sfNumber, "3.14e2") == STNumber(sfNumber, 314)); + BEAST_EXPECT(numberFromJson(sfNumber, "-3.14e2") == STNumber(sfNumber, -314)); - BEAST_EXPECT( - numberFromJson(sfNumber, "1000e-2") == STNumber(sfNumber, 10)); - BEAST_EXPECT( - numberFromJson(sfNumber, "-1000e-2") == - STNumber(sfNumber, -10)); + BEAST_EXPECT(numberFromJson(sfNumber, "1000e-2") == STNumber(sfNumber, 10)); + BEAST_EXPECT(numberFromJson(sfNumber, "-1000e-2") == STNumber(sfNumber, -10)); - BEAST_EXPECT( - numberFromJson(sfNumber, "0") == STNumber(sfNumber, 0)); - BEAST_EXPECT( - numberFromJson(sfNumber, "0.0") == STNumber(sfNumber, 0)); - BEAST_EXPECT( - numberFromJson(sfNumber, "0.000") == STNumber(sfNumber, 0)); - BEAST_EXPECT( - numberFromJson(sfNumber, "-0") == STNumber(sfNumber, 0)); - BEAST_EXPECT( - numberFromJson(sfNumber, "-0.0") == STNumber(sfNumber, 0)); - BEAST_EXPECT( - numberFromJson(sfNumber, "-0.000") == STNumber(sfNumber, 0)); - BEAST_EXPECT( - numberFromJson(sfNumber, "0e6") == STNumber(sfNumber, 0)); - BEAST_EXPECT( - numberFromJson(sfNumber, "0.0e6") == STNumber(sfNumber, 0)); - BEAST_EXPECT( - numberFromJson(sfNumber, "0.000e6") == STNumber(sfNumber, 0)); - BEAST_EXPECT( - numberFromJson(sfNumber, "-0e6") == STNumber(sfNumber, 0)); - BEAST_EXPECT( - numberFromJson(sfNumber, "-0.0e6") == STNumber(sfNumber, 0)); - BEAST_EXPECT( - numberFromJson(sfNumber, "-0.000e6") == STNumber(sfNumber, 0)); + BEAST_EXPECT(numberFromJson(sfNumber, "0") == STNumber(sfNumber, 0)); + BEAST_EXPECT(numberFromJson(sfNumber, "0.0") == STNumber(sfNumber, 0)); + BEAST_EXPECT(numberFromJson(sfNumber, "0.000") == STNumber(sfNumber, 0)); + BEAST_EXPECT(numberFromJson(sfNumber, "-0") == STNumber(sfNumber, 0)); + BEAST_EXPECT(numberFromJson(sfNumber, "-0.0") == STNumber(sfNumber, 0)); + BEAST_EXPECT(numberFromJson(sfNumber, "-0.000") == STNumber(sfNumber, 0)); + BEAST_EXPECT(numberFromJson(sfNumber, "0e6") == STNumber(sfNumber, 0)); + BEAST_EXPECT(numberFromJson(sfNumber, "0.0e6") == STNumber(sfNumber, 0)); + BEAST_EXPECT(numberFromJson(sfNumber, "0.000e6") == STNumber(sfNumber, 0)); + BEAST_EXPECT(numberFromJson(sfNumber, "-0e6") == STNumber(sfNumber, 0)); + BEAST_EXPECT(numberFromJson(sfNumber, "-0.0e6") == STNumber(sfNumber, 0)); + BEAST_EXPECT(numberFromJson(sfNumber, "-0.000e6") == STNumber(sfNumber, 0)); { NumberRoundModeGuard mg(Number::towards_zero); // maxint64 9,223,372,036,854,775,807 - auto const maxInt = - std::to_string(std::numeric_limits::max()); + auto const maxInt = std::to_string(std::numeric_limits::max()); // minint64 -9,223,372,036,854,775,808 - auto const minInt = - std::to_string(std::numeric_limits::min()); + auto const minInt = std::to_string(std::numeric_limits::min()); if (Number::getMantissaScale() == MantissaRange::small) { BEAST_EXPECT( - numberFromJson(sfNumber, maxInt) == - STNumber(sfNumber, Number{9'223'372'036'854'775, 3})); + numberFromJson(sfNumber, maxInt) == STNumber(sfNumber, Number{9'223'372'036'854'775, 3})); BEAST_EXPECT( - numberFromJson(sfNumber, minInt) == - STNumber(sfNumber, Number{-9'223'372'036'854'775, 3})); + numberFromJson(sfNumber, minInt) == STNumber(sfNumber, Number{-9'223'372'036'854'775, 3})); } else { BEAST_EXPECT( - numberFromJson(sfNumber, maxInt) == - STNumber( - sfNumber, Number{9'223'372'036'854'775'807, 0})); + numberFromJson(sfNumber, maxInt) == STNumber(sfNumber, Number{9'223'372'036'854'775'807, 0})); BEAST_EXPECT( numberFromJson(sfNumber, minInt) == - STNumber( - sfNumber, - Number{ - true, - 9'223'372'036'854'775'808ULL, - 0, - Number::normalized{}})); + STNumber(sfNumber, Number{true, 9'223'372'036'854'775'808ULL, 0, Number::normalized{}})); } } constexpr auto imin = std::numeric_limits::min(); - BEAST_EXPECT( - numberFromJson(sfNumber, imin) == - STNumber(sfNumber, Number(imin, 0))); - BEAST_EXPECT( - numberFromJson(sfNumber, std::to_string(imin)) == - STNumber(sfNumber, Number(imin, 0))); + BEAST_EXPECT(numberFromJson(sfNumber, imin) == STNumber(sfNumber, Number(imin, 0))); + BEAST_EXPECT(numberFromJson(sfNumber, std::to_string(imin)) == STNumber(sfNumber, Number(imin, 0))); constexpr auto imax = std::numeric_limits::max(); - BEAST_EXPECT( - numberFromJson(sfNumber, imax) == - STNumber(sfNumber, Number(imax, 0))); - BEAST_EXPECT( - numberFromJson(sfNumber, std::to_string(imax)) == - STNumber(sfNumber, Number(imax, 0))); + BEAST_EXPECT(numberFromJson(sfNumber, imax) == STNumber(sfNumber, Number(imax, 0))); + BEAST_EXPECT(numberFromJson(sfNumber, std::to_string(imax)) == STNumber(sfNumber, Number(imax, 0))); constexpr auto umax = std::numeric_limits::max(); - BEAST_EXPECT( - numberFromJson(sfNumber, umax) == - STNumber(sfNumber, Number(umax, 0))); - BEAST_EXPECT( - numberFromJson(sfNumber, std::to_string(umax)) == - STNumber(sfNumber, Number(umax, 0))); + BEAST_EXPECT(numberFromJson(sfNumber, umax) == STNumber(sfNumber, Number(umax, 0))); + BEAST_EXPECT(numberFromJson(sfNumber, std::to_string(umax)) == STNumber(sfNumber, Number(umax, 0))); // Obvious non-numbers tested here try diff --git a/src/test/protocol/STObject_test.cpp b/src/test/protocol/STObject_test.cpp index c01297b4e1..861a1ab967 100644 --- a/src/test/protocol/STObject_test.cpp +++ b/src/test/protocol/STObject_test.cpp @@ -13,8 +13,7 @@ public: unexpected(sfGeneric.isUseful(), "sfGeneric must not be useful"); { // Try to put sfGeneric in an SOTemplate. - except( - [&]() { SOTemplate elements{{sfGeneric, soeREQUIRED}}; }); + except([&]() { SOTemplate elements{{sfGeneric, soeREQUIRED}}; }); } unexpected(sfInvalid.isUseful(), "sfInvalid must not be useful"); @@ -32,8 +31,7 @@ public: } { // Try to put sfInvalid in an SOTemplate. - except( - [&]() { SOTemplate elements{{sfInvalid, soeREQUIRED}}; }); + except([&]() { SOTemplate elements{{sfInvalid, soeREQUIRED}}; }); } { // Try to put the same SField into an SOTemplate twice. @@ -63,21 +61,15 @@ public: STObject object1(elements, sfTestObject); STObject object2(object1); - unexpected( - object1.getSerializer() != object2.getSerializer(), - "STObject error 1"); + unexpected(object1.getSerializer() != object2.getSerializer(), "STObject error 1"); - unexpected( - object1.isFieldPresent(sfTestH256) || - !object1.isFieldPresent(sfTestVL), - "STObject error"); + unexpected(object1.isFieldPresent(sfTestH256) || !object1.isFieldPresent(sfTestVL), "STObject error"); object1.makeFieldPresent(sfTestH256); unexpected(!object1.isFieldPresent(sfTestH256), "STObject Error 2"); - unexpected( - object1.getFieldH256(sfTestH256) != uint256(), "STObject error 3"); + unexpected(object1.getFieldH256(sfTestH256) != uint256(), "STObject error 3"); if (object1.getSerializer() == object2.getSerializer()) { @@ -96,9 +88,7 @@ public: unexpected(object1.getFlags() != 0, "STObject error 6"); - unexpected( - object1.getSerializer() != object2.getSerializer(), - "STObject error 7"); + unexpected(object1.getSerializer() != object2.getSerializer(), "STObject error 7"); STObject copy(object1); @@ -106,15 +96,11 @@ public: unexpected(copy.isFieldPresent(sfTestH256), "STObject error 9"); - unexpected( - object1.getSerializer() != copy.getSerializer(), - "STObject error 10"); + unexpected(object1.getSerializer() != copy.getSerializer(), "STObject error 10"); copy.setFieldU32(sfTestU32, 1); - unexpected( - object1.getSerializer() == copy.getSerializer(), - "STObject error 11"); + unexpected(object1.getSerializer() == copy.getSerializer(), "STObject error 11"); for (int i = 0; i < 1000; i++) { @@ -339,11 +325,7 @@ public: { STObject st(sfGeneric); auto const v = ~st[~sf1Outer]; - static_assert( - std::is_same< - std::decay_t, - std::optional>::value, - ""); + static_assert(std::is_same, std::optional>::value, ""); } // UDT scalar fields @@ -397,8 +379,7 @@ public: { STObject st(sfGeneric); BEAST_EXPECT(!st[~sf5]); - auto const kp = generateKeyPair( - KeyType::secp256k1, generateSeed("masterpassphrase")); + auto const kp = generateKeyPair(KeyType::secp256k1, generateSeed("masterpassphrase")); st[sf5] = kp.first; st[~sf5] = std::nullopt; } @@ -418,11 +399,7 @@ public: BEAST_EXPECT(cst[~sf]->size() == 2); BEAST_EXPECT(cst[sf][0] == 1); BEAST_EXPECT(cst[sf][1] == 2); - static_assert( - std::is_same< - decltype(cst[sfIndexes]), - std::vector const&>::value, - ""); + static_assert(std::is_same const&>::value, ""); } // Default by reference field @@ -467,8 +444,7 @@ public: try { - std::array const payload{ - {0xe9, 0x12, 0xab, 0xcd, 0x12, 0xfe, 0xdc}}; + std::array const payload{{0xe9, 0x12, 0xab, 0xcd, 0x12, 0xfe, 0xdc}}; SerialIter sit{makeSlice(payload)}; auto obj = std::make_shared(sit, sfMetadata); BEAST_EXPECT(!obj); diff --git a/src/test/protocol/STParsedJSON_test.cpp b/src/test/protocol/STParsedJSON_test.cpp index 9c3a08243b..0ef7878cdc 100644 --- a/src/test/protocol/STParsedJSON_test.cpp +++ b/src/test/protocol/STParsedJSON_test.cpp @@ -260,9 +260,7 @@ class STParsedJSON_test : public beast::unit_test::suite STParsedJSONObject obj("Test", j); BEAST_EXPECT(obj.object.has_value()); BEAST_EXPECT(obj.object->isFieldPresent(sfIndexNext)); - BEAST_EXPECT( - obj.object->getFieldU64(sfIndexNext) == - 18446744073709551615ull); + BEAST_EXPECT(obj.object->getFieldU64(sfIndexNext) == 18446744073709551615ull); } // Test min value for uint64 @@ -338,24 +336,8 @@ class STParsedJSON_test : public beast::unit_test::suite BEAST_EXPECT(obj.object->isFieldPresent(sfEmailHash)); BEAST_EXPECT(obj.object->getFieldH128(sfEmailHash).size() == 16); std::array expected = { - 0x01, - 0x23, - 0x45, - 0x67, - 0x89, - 0xAB, - 0xCD, - 0xEF, - 0x01, - 0x23, - 0x45, - 0x67, - 0x89, - 0xAB, - 0xCD, - 0xEF}; - BEAST_EXPECT( - obj.object->getFieldH128(sfEmailHash) == uint128{expected}); + 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF}; + BEAST_EXPECT(obj.object->getFieldH128(sfEmailHash) == uint128{expected}); } // Valid lowercase hex string for UInt128 @@ -377,8 +359,7 @@ class STParsedJSON_test : public beast::unit_test::suite BEAST_EXPECT(obj.object->isFieldPresent(sfEmailHash)); auto const& h128 = obj.object->getFieldH128(sfEmailHash); BEAST_EXPECT(h128.size() == 16); - bool allZero = std::all_of( - h128.begin(), h128.end(), [](auto b) { return b == 0; }); + bool allZero = std::all_of(h128.begin(), h128.end(), [](auto b) { return b == 0; }); BEAST_EXPECT(allZero); } @@ -441,14 +422,10 @@ class STParsedJSON_test : public beast::unit_test::suite STParsedJSONObject obj("Test", j); BEAST_EXPECT(obj.object.has_value()); BEAST_EXPECT(obj.object->isFieldPresent(sfTakerPaysCurrency)); - BEAST_EXPECT( - obj.object->getFieldH160(sfTakerPaysCurrency).size() == 20); - std::array expected = { - 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0x01, 0x23, - 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0x01, 0x23, 0x45, 0x67}; - BEAST_EXPECT( - obj.object->getFieldH160(sfTakerPaysCurrency) == - uint160{expected}); + BEAST_EXPECT(obj.object->getFieldH160(sfTakerPaysCurrency).size() == 20); + std::array expected = {0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0x01, 0x23, + 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0x01, 0x23, 0x45, 0x67}; + BEAST_EXPECT(obj.object->getFieldH160(sfTakerPaysCurrency) == uint160{expected}); } // Valid lowercase hex string for UInt160 { @@ -457,8 +434,7 @@ class STParsedJSON_test : public beast::unit_test::suite STParsedJSONObject obj("Test", j); BEAST_EXPECT(obj.object.has_value()); BEAST_EXPECT(obj.object->isFieldPresent(sfTakerPaysCurrency)); - BEAST_EXPECT( - obj.object->getFieldH160(sfTakerPaysCurrency).size() == 20); + BEAST_EXPECT(obj.object->getFieldH160(sfTakerPaysCurrency).size() == 20); } // Empty string for UInt160 (should be valid, all zero) @@ -470,8 +446,7 @@ class STParsedJSON_test : public beast::unit_test::suite BEAST_EXPECT(obj.object->isFieldPresent(sfTakerPaysCurrency)); auto const& h160 = obj.object->getFieldH160(sfTakerPaysCurrency); BEAST_EXPECT(h160.size() == 20); - bool allZero = std::all_of( - h160.begin(), h160.end(), [](auto b) { return b == 0; }); + bool allZero = std::all_of(h160.begin(), h160.end(), [](auto b) { return b == 0; }); BEAST_EXPECT(allZero); } @@ -494,8 +469,7 @@ class STParsedJSON_test : public beast::unit_test::suite // Hex string too long for UInt160 (should fail) { Json::Value j; - j[sfTakerPaysCurrency] = - "0123456789ABCDEF0123456789ABCDEF0123456789"; + j[sfTakerPaysCurrency] = "0123456789ABCDEF0123456789ABCDEF0123456789"; STParsedJSONObject obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -523,32 +497,24 @@ class STParsedJSON_test : public beast::unit_test::suite testcase("UInt192"); { Json::Value j; - j[sfMPTokenIssuanceID] = - "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"; + j[sfMPTokenIssuanceID] = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"; STParsedJSONObject obj("Test", j); BEAST_EXPECT(obj.object.has_value()); BEAST_EXPECT(obj.object->isFieldPresent(sfMPTokenIssuanceID)); - BEAST_EXPECT( - obj.object->getFieldH192(sfMPTokenIssuanceID).size() == 24); - std::array expected = { - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; - BEAST_EXPECT( - obj.object->getFieldH192(sfMPTokenIssuanceID) == - uint192{expected}); + BEAST_EXPECT(obj.object->getFieldH192(sfMPTokenIssuanceID).size() == 24); + std::array expected = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; + BEAST_EXPECT(obj.object->getFieldH192(sfMPTokenIssuanceID) == uint192{expected}); } // Valid lowercase hex string for UInt192 { Json::Value j; - j[sfMPTokenIssuanceID] = - "ffffffffffffffffffffffffffffffffffffffffffffffff"; + j[sfMPTokenIssuanceID] = "ffffffffffffffffffffffffffffffffffffffffffffffff"; STParsedJSONObject obj("Test", j); BEAST_EXPECT(obj.object.has_value()); BEAST_EXPECT(obj.object->isFieldPresent(sfMPTokenIssuanceID)); - BEAST_EXPECT( - obj.object->getFieldH192(sfMPTokenIssuanceID).size() == 24); + BEAST_EXPECT(obj.object->getFieldH192(sfMPTokenIssuanceID).size() == 24); } // Empty string for UInt192 (should be valid, all zero) @@ -560,16 +526,14 @@ class STParsedJSON_test : public beast::unit_test::suite BEAST_EXPECT(obj.object->isFieldPresent(sfMPTokenIssuanceID)); auto const& h192 = obj.object->getFieldH192(sfMPTokenIssuanceID); BEAST_EXPECT(h192.size() == 24); - bool allZero = std::all_of( - h192.begin(), h192.end(), [](auto b) { return b == 0; }); + bool allZero = std::all_of(h192.begin(), h192.end(), [](auto b) { return b == 0; }); BEAST_EXPECT(allZero); } // Odd-length hex string for UInt192 (should fail) { Json::Value j; - j[sfMPTokenIssuanceID] = - "0123456789ABCDEF0123456789ABCDEF0123456789ABCDE"; + j[sfMPTokenIssuanceID] = "0123456789ABCDEF0123456789ABCDEF0123456789ABCDE"; STParsedJSONObject obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -593,8 +557,7 @@ class STParsedJSON_test : public beast::unit_test::suite // Hex string too long for UInt192 (should fail) { Json::Value j; - j[sfMPTokenIssuanceID] = - "0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF00"; + j[sfMPTokenIssuanceID] = "0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF00"; STParsedJSONObject obj("Test", j); BEAST_EXPECT(!obj.object.has_value()); } @@ -630,13 +593,10 @@ class STParsedJSON_test : public beast::unit_test::suite BEAST_EXPECT(obj.object.has_value()); BEAST_EXPECT(obj.object->isFieldPresent(sfLedgerHash)); BEAST_EXPECT(obj.object->getFieldH256(sfLedgerHash).size() == 32); - std::array expected = { - 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, - 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, - 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, - 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF}; - BEAST_EXPECT( - obj.object->getFieldH256(sfLedgerHash) == uint256{expected}); + std::array expected = {0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0x01, 0x23, 0x45, + 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, + 0xCD, 0xEF, 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF}; + BEAST_EXPECT(obj.object->getFieldH256(sfLedgerHash) == uint256{expected}); } // Valid lowercase hex string for UInt256 { @@ -659,8 +619,7 @@ class STParsedJSON_test : public beast::unit_test::suite BEAST_EXPECT(obj.object->isFieldPresent(sfLedgerHash)); auto const& h256 = obj.object->getFieldH256(sfLedgerHash); BEAST_EXPECT(h256.size() == 32); - bool allZero = std::all_of( - h256.begin(), h256.end(), [](auto b) { return b == 0; }); + bool allZero = std::all_of(h256.begin(), h256.end(), [](auto b) { return b == 0; }); BEAST_EXPECT(allZero); } @@ -750,9 +709,7 @@ class STParsedJSON_test : public beast::unit_test::suite STParsedJSONObject obj("Test", j); BEAST_EXPECT(obj.object.has_value()); if (BEAST_EXPECT(obj.object->isFieldPresent(sfLoanScale))) - BEAST_EXPECT( - obj.object->getFieldI32(sfLoanScale) == - static_cast(maxUInt32)); + BEAST_EXPECT(obj.object->getFieldI32(sfLoanScale) == static_cast(maxUInt32)); } // Test with string value @@ -762,8 +719,7 @@ class STParsedJSON_test : public beast::unit_test::suite STParsedJSONObject obj("Test", j); BEAST_EXPECT(obj.object.has_value()); if (BEAST_EXPECT(obj.object->isFieldPresent(sfLoanScale))) - BEAST_EXPECT( - obj.object->getFieldI32(sfLoanScale) == 2147483647u); + BEAST_EXPECT(obj.object->getFieldI32(sfLoanScale) == 2147483647u); } // Test with string negative value @@ -987,8 +943,7 @@ class STParsedJSON_test : public beast::unit_test::suite BEAST_EXPECT(obj.object->isFieldPresent(sfAccount)); auto const& acct = obj.object->getAccountID(sfAccount); BEAST_EXPECT(acct.size() == 20); - BEAST_EXPECT( - toBase58(acct) == "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"); + BEAST_EXPECT(toBase58(acct) == "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"); } // Valid hex string for AccountID @@ -1172,9 +1127,7 @@ class STParsedJSON_test : public beast::unit_test::suite STParsedJSONObject obj("Test", j); BEAST_EXPECT(obj.object.has_value()); BEAST_EXPECT(obj.object->isFieldPresent(sfAmount)); - BEAST_EXPECT( - obj.object->getFieldAmount(sfAmount) == - STAmount(100000000000000000ull)); + BEAST_EXPECT(obj.object->getFieldAmount(sfAmount) == STAmount(100000000000000000ull)); } // Test with int value for Amount @@ -1184,8 +1137,7 @@ class STParsedJSON_test : public beast::unit_test::suite STParsedJSONObject obj("Test", j); BEAST_EXPECT(obj.object.has_value()); BEAST_EXPECT(obj.object->isFieldPresent(sfAmount)); - BEAST_EXPECT( - obj.object->getFieldAmount(sfAmount) == STAmount(4294967295u)); + BEAST_EXPECT(obj.object->getFieldAmount(sfAmount) == STAmount(4294967295u)); } // Test with decimal string for Amount (should fail) @@ -1245,15 +1197,9 @@ class STParsedJSON_test : public beast::unit_test::suite BEAST_EXPECT(!ps.empty()); BEAST_EXPECT(ps.size() == 1); BEAST_EXPECT(ps[0].size() == 1); - BEAST_EXPECT( - ps[0][0].getAccountID() == - parseBase58( - "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")); + BEAST_EXPECT(ps[0][0].getAccountID() == parseBase58("rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")); BEAST_EXPECT(to_string(ps[0][0].getCurrency()) == "USD"); - BEAST_EXPECT( - ps[0][0].getIssuerID() == - parseBase58( - "rPT1Sjq2YGrBMTttX4GZHjKu9dyfzbpAYe")); + BEAST_EXPECT(ps[0][0].getIssuerID() == parseBase58("rPT1Sjq2YGrBMTttX4GZHjKu9dyfzbpAYe")); } } @@ -1428,10 +1374,7 @@ class STParsedJSON_test : public beast::unit_test::suite BEAST_EXPECT(issue.currency.size() == 20); BEAST_EXPECT(to_string(issue.currency) == "USD"); BEAST_EXPECT(issue.account.size() == 20); - BEAST_EXPECT( - issue.account == - parseBase58( - "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")); + BEAST_EXPECT(issue.account == parseBase58("rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")); } } @@ -1457,8 +1400,7 @@ class STParsedJSON_test : public beast::unit_test::suite { Json::Value j; Json::Value issueJson(Json::objectValue); - issueJson["mpt_issuance_id"] = - "0000000000000000000000004D5054494431323334234234"; + issueJson["mpt_issuance_id"] = "0000000000000000000000004D5054494431323334234234"; j[sfAsset] = issueJson; STParsedJSONObject obj("Test", j); if (BEAST_EXPECT(obj.object.has_value())) @@ -1567,10 +1509,8 @@ class STParsedJSON_test : public beast::unit_test::suite { BEAST_EXPECT(obj.object->isFieldPresent(sfXChainBridge)); auto const& bridgeField = (*obj.object)[sfXChainBridge]; - BEAST_EXPECT( - bridgeField->lockingChainIssue().currency.size() == 20); - BEAST_EXPECT( - bridgeField->issuingChainIssue().currency.size() == 20); + BEAST_EXPECT(bridgeField->lockingChainIssue().currency.size() == 20); + BEAST_EXPECT(bridgeField->issuingChainIssue().currency.size() == 20); } } @@ -1579,12 +1519,10 @@ class STParsedJSON_test : public beast::unit_test::suite Json::Value j; Json::Value bridge(Json::objectValue); Json::Value issuingChainIssue(Json::objectValue); - issuingChainIssue["currency"] = - "0123456789ABCDEF01230123456789ABCDEF0123"; + issuingChainIssue["currency"] = "0123456789ABCDEF01230123456789ABCDEF0123"; issuingChainIssue["issuer"] = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; Json::Value lockingChainIssue(Json::objectValue); - lockingChainIssue["currency"] = - "0123456789ABCDEF01230123456789ABCDEF0123"; + lockingChainIssue["currency"] = "0123456789ABCDEF01230123456789ABCDEF0123"; lockingChainIssue["issuer"] = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; bridge["LockingChainIssue"] = lockingChainIssue; bridge["IssuingChainIssue"] = issuingChainIssue; @@ -1596,10 +1534,8 @@ class STParsedJSON_test : public beast::unit_test::suite { BEAST_EXPECT(obj.object->isFieldPresent(sfXChainBridge)); auto const& bridgeField = (*obj.object)[sfXChainBridge]; - BEAST_EXPECT( - bridgeField->lockingChainIssue().currency.size() == 20); - BEAST_EXPECT( - bridgeField->issuingChainIssue().currency.size() == 20); + BEAST_EXPECT(bridgeField->lockingChainIssue().currency.size() == 20); + BEAST_EXPECT(bridgeField->issuingChainIssue().currency.size() == 20); } } @@ -1749,9 +1685,7 @@ class STParsedJSON_test : public beast::unit_test::suite STParsedJSONObject obj("Test", j); BEAST_EXPECT(obj.object.has_value()); BEAST_EXPECT(obj.object->isFieldPresent(sfNumber)); - BEAST_EXPECT( - obj.object->getFieldNumber(sfNumber).value() == - Number(12345, 0)); + BEAST_EXPECT(obj.object->getFieldNumber(sfNumber).value() == Number(12345, 0)); } // Valid uint value for STNumber @@ -1761,9 +1695,7 @@ class STParsedJSON_test : public beast::unit_test::suite STParsedJSONObject obj("Test", j); BEAST_EXPECT(obj.object.has_value()); BEAST_EXPECT(obj.object->isFieldPresent(sfNumber)); - BEAST_EXPECT( - obj.object->getFieldNumber(sfNumber).value() == - Number(12345, 0)); + BEAST_EXPECT(obj.object->getFieldNumber(sfNumber).value() == Number(12345, 0)); } // Valid string integer value for STNumber @@ -1773,9 +1705,7 @@ class STParsedJSON_test : public beast::unit_test::suite STParsedJSONObject obj("Test", j); BEAST_EXPECT(obj.object.has_value()); BEAST_EXPECT(obj.object->isFieldPresent(sfNumber)); - BEAST_EXPECT( - obj.object->getFieldNumber(sfNumber).value() == - Number(67890, 0)); + BEAST_EXPECT(obj.object->getFieldNumber(sfNumber).value() == Number(67890, 0)); } // Valid negative integer value for STNumber @@ -1785,8 +1715,7 @@ class STParsedJSON_test : public beast::unit_test::suite STParsedJSONObject obj("Test", j); BEAST_EXPECT(obj.object.has_value()); BEAST_EXPECT(obj.object->isFieldPresent(sfNumber)); - BEAST_EXPECT( - obj.object->getFieldNumber(sfNumber).value() == Number(-42, 0)); + BEAST_EXPECT(obj.object->getFieldNumber(sfNumber).value() == Number(-42, 0)); } // Valid string negative integer value for STNumber @@ -1796,9 +1725,7 @@ class STParsedJSON_test : public beast::unit_test::suite STParsedJSONObject obj("Test", j); BEAST_EXPECT(obj.object.has_value()); BEAST_EXPECT(obj.object->isFieldPresent(sfNumber)); - BEAST_EXPECT( - obj.object->getFieldNumber(sfNumber).value() == - Number(-123, 0)); + BEAST_EXPECT(obj.object->getFieldNumber(sfNumber).value() == Number(-123, 0)); } // Valid floating point value for STNumber @@ -1809,9 +1736,7 @@ class STParsedJSON_test : public beast::unit_test::suite if (BEAST_EXPECT(obj.object.has_value())) { BEAST_EXPECT(obj.object->isFieldPresent(sfNumber)); - BEAST_EXPECT( - obj.object->getFieldNumber(sfNumber).value() == - Number(314159, -5)); + BEAST_EXPECT(obj.object->getFieldNumber(sfNumber).value() == Number(314159, -5)); } } @@ -1861,8 +1786,7 @@ class STParsedJSON_test : public beast::unit_test::suite STParsedJSONObject obj("Test", j); BEAST_EXPECT(obj.object.has_value()); BEAST_EXPECT(obj.object->isFieldPresent(sfTransactionMetaData)); - auto const& result = - obj.object->peekFieldObject(sfTransactionMetaData); + auto const& result = obj.object->peekFieldObject(sfTransactionMetaData); BEAST_EXPECT(result.getFieldU8(sfTransactionResult) == 1); } @@ -2063,8 +1987,7 @@ class STParsedJSON_test : public beast::unit_test::suite catch (std::runtime_error& e) { std::string what(e.what()); - unexpected( - what.find("First level children of `Template`") != 0); + unexpected(what.find("First level children of `Template`") != 0); } } } @@ -2089,20 +2012,17 @@ class STParsedJSON_test : public beast::unit_test::suite STParsedJSONObject parsed("test", jv); if (BEAST_EXPECT(parsed.object)) { - std::string const& serialized( - to_string(parsed.object->getJson(JsonOptions::none))); + std::string const& serialized(to_string(parsed.object->getJson(JsonOptions::none))); BEAST_EXPECT(serialized == goodJson); } } } { - std::string const goodJson( - R"({"CloseResolution":19,"Method":"250",)" - R"("TransactionResult":"tecFROZEN"})"); - std::string const expectedJson( - R"({"CloseResolution":19,"Method":250,)" - R"("TransactionResult":"tecFROZEN"})"); + std::string const goodJson(R"({"CloseResolution":19,"Method":"250",)" + R"("TransactionResult":"tecFROZEN"})"); + std::string const expectedJson(R"({"CloseResolution":19,"Method":250,)" + R"("TransactionResult":"tecFROZEN"})"); Json::Value jv; if (BEAST_EXPECT(parseJSONString(goodJson, jv))) @@ -2113,20 +2033,17 @@ class STParsedJSON_test : public beast::unit_test::suite STParsedJSONObject parsed("test", jv); if (BEAST_EXPECT(parsed.object)) { - std::string const& serialized( - to_string(parsed.object->getJson(JsonOptions::none))); + std::string const& serialized(to_string(parsed.object->getJson(JsonOptions::none))); BEAST_EXPECT(serialized == expectedJson); } } } { - std::string const goodJson( - R"({"CloseResolution":"19","Method":"250",)" - R"("TransactionResult":"tecFROZEN"})"); - std::string const expectedJson( - R"({"CloseResolution":19,"Method":250,)" - R"("TransactionResult":"tecFROZEN"})"); + std::string const goodJson(R"({"CloseResolution":"19","Method":"250",)" + R"("TransactionResult":"tecFROZEN"})"); + std::string const expectedJson(R"({"CloseResolution":19,"Method":250,)" + R"("TransactionResult":"tecFROZEN"})"); Json::Value jv; if (BEAST_EXPECT(parseJSONString(goodJson, jv))) @@ -2137,8 +2054,7 @@ class STParsedJSON_test : public beast::unit_test::suite STParsedJSONObject parsed("test", jv); if (BEAST_EXPECT(parsed.object)) { - std::string const& serialized( - to_string(parsed.object->getJson(JsonOptions::none))); + std::string const& serialized(to_string(parsed.object->getJson(JsonOptions::none))); BEAST_EXPECT(serialized == expectedJson); } } @@ -2155,9 +2071,7 @@ class STParsedJSON_test : public beast::unit_test::suite BEAST_EXPECT(!parsed.object); BEAST_EXPECT(parsed.error); BEAST_EXPECT(parsed.error[jss::error] == "invalidParams"); - BEAST_EXPECT( - parsed.error[jss::error_message] == - "Field 'test.TransactionResult' is out of range."); + BEAST_EXPECT(parsed.error[jss::error_message] == "Field 'test.TransactionResult' is out of range."); } } @@ -2172,16 +2086,13 @@ class STParsedJSON_test : public beast::unit_test::suite BEAST_EXPECT(!parsed.object); BEAST_EXPECT(parsed.error); BEAST_EXPECT(parsed.error[jss::error] == "invalidParams"); - BEAST_EXPECT( - parsed.error[jss::error_message] == - "Field 'test.Method' has bad type."); + BEAST_EXPECT(parsed.error[jss::error_message] == "Field 'test.Method' has bad type."); } } { - std::string const json( - R"({"CloseResolution":19,"Method":3294967296,)" - R"("TransactionResult":"tesSUCCESS"})"); + std::string const json(R"({"CloseResolution":19,"Method":3294967296,)" + R"("TransactionResult":"tesSUCCESS"})"); Json::Value jv; if (BEAST_EXPECT(parseJSONString(json, jv))) @@ -2190,9 +2101,7 @@ class STParsedJSON_test : public beast::unit_test::suite BEAST_EXPECT(!parsed.object); BEAST_EXPECT(parsed.error); BEAST_EXPECT(parsed.error[jss::error] == "invalidParams"); - BEAST_EXPECT( - parsed.error[jss::error_message] == - "Field 'test.Method' is out of range."); + BEAST_EXPECT(parsed.error[jss::error_message] == "Field 'test.Method' is out of range."); } } @@ -2207,16 +2116,13 @@ class STParsedJSON_test : public beast::unit_test::suite BEAST_EXPECT(!parsed.object); BEAST_EXPECT(parsed.error); BEAST_EXPECT(parsed.error[jss::error] == "invalidParams"); - BEAST_EXPECT( - parsed.error[jss::error_message] == - "Field 'test.CloseResolution' is out of range."); + BEAST_EXPECT(parsed.error[jss::error_message] == "Field 'test.CloseResolution' is out of range."); } } { - std::string const json( - R"({"CloseResolution":19,"Method":3.141592653,)" - R"("TransactionResult":"tesSUCCESS"})"); + std::string const json(R"({"CloseResolution":19,"Method":3.141592653,)" + R"("TransactionResult":"tesSUCCESS"})"); Json::Value jv; if (BEAST_EXPECT(parseJSONString(json, jv))) @@ -2225,18 +2131,15 @@ class STParsedJSON_test : public beast::unit_test::suite BEAST_EXPECT(!parsed.object); BEAST_EXPECT(parsed.error); BEAST_EXPECT(parsed.error[jss::error] == "invalidParams"); - BEAST_EXPECT( - parsed.error[jss::error_message] == - "Field 'test.Method' has bad type."); + BEAST_EXPECT(parsed.error[jss::error_message] == "Field 'test.Method' has bad type."); } } { std::string const goodJson(R"({"CloseResolution":19,"Method":250,)" R"("TransferFee":"65535"})"); - std::string const expectedJson( - R"({"CloseResolution":19,"Method":250,)" - R"("TransferFee":65535})"); + std::string const expectedJson(R"({"CloseResolution":19,"Method":250,)" + R"("TransferFee":65535})"); Json::Value jv; if (BEAST_EXPECT(parseJSONString(goodJson, jv))) @@ -2244,8 +2147,7 @@ class STParsedJSON_test : public beast::unit_test::suite STParsedJSONObject parsed("test", jv); if (BEAST_EXPECT(parsed.object)) { - std::string const& serialized( - to_string(parsed.object->getJson(JsonOptions::none))); + std::string const& serialized(to_string(parsed.object->getJson(JsonOptions::none))); BEAST_EXPECT(serialized == expectedJson); } } @@ -2262,9 +2164,7 @@ class STParsedJSON_test : public beast::unit_test::suite BEAST_EXPECT(!parsed.object); BEAST_EXPECT(parsed.error); BEAST_EXPECT(parsed.error[jss::error] == "invalidParams"); - BEAST_EXPECT( - parsed.error[jss::error_message] == - "Field 'test.TransferFee' has invalid data."); + BEAST_EXPECT(parsed.error[jss::error_message] == "Field 'test.TransferFee' has invalid data."); } } @@ -2279,9 +2179,7 @@ class STParsedJSON_test : public beast::unit_test::suite BEAST_EXPECT(!parsed.object); BEAST_EXPECT(parsed.error); BEAST_EXPECT(parsed.error[jss::error] == "invalidParams"); - BEAST_EXPECT( - parsed.error[jss::error_message] == - "Field 'test.TransferFee' has invalid data."); + BEAST_EXPECT(parsed.error[jss::error_message] == "Field 'test.TransferFee' has invalid data."); } } @@ -2296,9 +2194,7 @@ class STParsedJSON_test : public beast::unit_test::suite BEAST_EXPECT(!parsed.object); BEAST_EXPECT(parsed.error); BEAST_EXPECT(parsed.error[jss::error] == "invalidParams"); - BEAST_EXPECT( - parsed.error[jss::error_message] == - "Field 'test.TransferFee' has bad type."); + BEAST_EXPECT(parsed.error[jss::error_message] == "Field 'test.TransferFee' has bad type."); } } } diff --git a/src/test/protocol/STTx_test.cpp b/src/test/protocol/STTx_test.cpp index 1899b786f9..853ff35635 100644 --- a/src/test/protocol/STTx_test.cpp +++ b/src/test/protocol/STTx_test.cpp @@ -21,8 +21,7 @@ namespace xrpl { inline bool matches(char const* string, char const* regex) { - return std::regex_search( - string, std::basic_regex(regex, std::regex_constants::icase)); + return std::regex_search(string, std::basic_regex(regex, std::regex_constants::icase)); } class STTx_test : public beast::unit_test::suite @@ -48,1323 +47,814 @@ public: { testcase("Malformed serialized form"); - constexpr unsigned char payload1[] = { - 0x0a, 0xff, 0xff, 0xff, 0xff, 0x63, 0x63, 0x63, 0x63, 0x63, - 0x63, 0x63, 0x63, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, - 0x1b, 0x1b, 0x29, 0x1b, 0x1b, 0x1b, 0x1b, 0xef, 0xef, 0xef, - 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef}; + constexpr unsigned char payload1[] = {0x0a, 0xff, 0xff, 0xff, 0xff, 0x63, 0x63, 0x63, 0x63, 0x63, + 0x63, 0x63, 0x63, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, + 0x1b, 0x1b, 0x29, 0x1b, 0x1b, 0x1b, 0x1b, 0xef, 0xef, 0xef, + 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef}; constexpr unsigned char payload2[] = { - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, - 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, - 0xff, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0x3b, 0x3b, - 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0x29, 0xe7, 0x12, 0x12, - 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xff, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, - 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xe7, - 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, - 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, - 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, - 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, - 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, - 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xf4, - 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, - 0x12, 0x12, 0x12, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0x27, 0xdf, 0xff, - 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, - 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, - 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, - 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0xe7, 0xe7, 0xe7, - 0xe7, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, - 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, - 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0x3b, 0x3b, 0x3b, - 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0x29, 0xe7, 0x12, 0x12, 0x12, - 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, - 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, - 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, - 0x2b, 0x3b, 0x18, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, - 0x12, 0x12, 0x12, 0x12, 0x12, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, - 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xe7, 0xe7, - 0x29, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, - 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, - 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, - 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, - 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, - 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, 0xff, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0x27, 0xdf, - 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, - 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, - 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, - 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, - 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, - 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, - 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, - 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, - 0xdf, 0xff, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0x3b, - 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, - 0x12, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0x29, 0xe7, 0x12, - 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, - 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, - 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, - 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0x3b, 0x3b, 0x3b, - 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, - 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, - 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xe7, 0xe7, 0x29, 0xe7, - 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, - 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, - 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, - 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0x27, 0xdf, 0xff, 0xff, - 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, - 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, - 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, - 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, - 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xf4, - 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, - 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0xe7, 0xe7, 0xe7, 0xe7, - 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, - 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, - 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, - 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, - 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, - 0x12, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, - 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, - 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, - 0x3b, 0x27, 0xdf, 0xff, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, - 0x18, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x12, 0x12, - 0x12, 0x12, 0x12, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0x29, - 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, - 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, - 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, - 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, - 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0x3b, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, - 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, - 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, - 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, - 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0x2b, 0x3b, 0x18, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, - 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xe7, 0xe7, 0x29, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, - 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, - 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, - 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, - 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, - 0x12, 0x12, 0x12, 0x12, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, - 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, - 0x27, 0xdf, 0xff, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, - 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x12, 0x12, 0x12, - 0x12, 0x12, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, - 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xe7, 0xe7, 0x29, 0xe7, 0x12, - 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, - 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, - 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, - 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, - 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, - 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, - 0x3b, 0x26, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, - 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, - 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, - 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, - 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, - 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, - 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, - 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, - 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, - 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, - 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, - 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, - 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, - 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xe7, - 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, - 0xe7, 0xe7, 0xe7, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, - 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, - 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, - 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, - 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xe7, 0x27, - 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, - 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, - 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0x3b, 0x3b, 0x3b, - 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, - 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xe7, 0xe7, 0x29, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, - 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, - 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, - 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, - 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, - 0x12, 0x12, 0x12, 0x12, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, - 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, - 0x27, 0xdf, 0xff, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, - 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x12, 0x12, 0x12, - 0x12, 0x12, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, - 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xe7, 0xe7, 0x29, 0xe7, 0x12, - 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, - 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, - 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, - 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, - 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, - 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, - 0x3b, 0x26, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, - 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, - 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, - 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, - 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, - 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, - 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, - 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, - 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, - 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, - 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, - 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, - 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0x14, - 0x14, 0x14, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, - 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, - 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, - 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, - 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, - 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, - 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, - 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, - 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, - 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0x3b, 0x3b, 0x3b, - 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0x29, 0xe7, 0x12, 0x12, 0x12, - 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, - 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xe7, 0x27, 0xdf, - 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, - 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xda, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, - 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0x3b, 0x3b, 0x3b, 0x3b, - 0x29, 0x2b, 0x3b, 0x18, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, - 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xe7, 0xe7, 0x29, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, - 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, - 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, - 0x3b, 0x3b, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, - 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0x3b, 0x3b, 0x3b, - 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, - 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xe7, 0xe7, 0x29, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, - 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, - 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, - 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, - 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, - 0x12, 0x12, 0x12, 0x12, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, - 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, - 0x27, 0xdf, 0xff, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, - 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x12, 0x12, 0x12, - 0x12, 0x12, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0x29, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0xe7, 0xe7, - 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, - 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, - 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0xe7, 0xe7, 0xef, 0xff, - 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, - 0x12, 0x12, 0x12, 0x12, 0x12, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0x27, - 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, - 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, - 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, - 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, - 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, 0xff, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, - 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, - 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, - 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0x3b, 0x3b, 0x3b, - 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0x3b, 0x3b, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, - 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0xe7, 0xe7, - 0xe7, 0xe7, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, - 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, - 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, - 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, - 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0x12, 0x12, 0x12, 0x12, 0x12, - 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0xff, 0xef, - 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0x3b, 0x3b, - 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x7f, - 0x3b, 0x3b, 0xef, 0xfd, 0xf1, 0xff, 0xf1, 0xff, 0xf1, 0xfb, 0xef, - 0xfd, 0xf1, 0xff, 0xf1, 0xfd, 0xf1, 0xfb, 0xf1, 0xfd, 0xf1, 0xef, - 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xff, - 0xff, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0xff, 0xef, 0xff, 0x01, 0x00, 0xfd, 0xf1, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, - 0xef, 0x3b, 0x3b, 0x43, 0x3b, 0x3b, 0xff, 0x3b, 0x12, 0xf1, 0x12, - 0x12, 0x12, 0xff}; + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, + 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, + 0x3b, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0x29, 0xe7, 0x12, + 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, + 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, + 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, + 0xff, 0xe7, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, + 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, + 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, + 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, + 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, + 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, + 0x26, 0xdf, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, + 0x12, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, + 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, + 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0x3b, 0x3b, 0x3b, + 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0x29, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, + 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, + 0x12, 0x12, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, + 0xff, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x12, + 0x12, 0x12, 0x12, 0x12, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, + 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xe7, 0xe7, 0x29, 0xe7, 0x12, 0x12, 0x12, + 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, + 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, + 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, 0xff, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, + 0xe7, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, + 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, + 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, + 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, + 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, + 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xe7, 0xe7, 0x29, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, + 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, + 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, + 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0x3b, 0x3b, 0x3b, 0x3b, + 0x29, 0x2b, 0x3b, 0x18, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, + 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xe7, 0xe7, 0x29, 0xe7, 0x12, + 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, + 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, + 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, + 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, + 0xe7, 0xe7, 0xe7, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, + 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, + 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, + 0x12, 0x12, 0x12, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, + 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, + 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0xe7, 0xe7, + 0xe7, 0xe7, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, + 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, + 0x3b, 0x18, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xe7, 0xe7, 0x29, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, + 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, + 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xe7, 0x27, 0xdf, 0xff, 0xff, + 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, + 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0x2b, 0x3b, 0x18, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0x29, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, + 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, + 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, + 0x12, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, + 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x12, 0x12, + 0x12, 0x12, 0x12, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, + 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xe7, 0xe7, 0x29, 0xe7, 0x12, 0x12, 0x12, 0x12, + 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, + 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, + 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, + 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, + 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, + 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, + 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, + 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, + 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, + 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, + 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, + 0xe7, 0xe7, 0xe7, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, + 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, + 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, + 0x3b, 0x18, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xe7, 0xe7, 0x29, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, + 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, + 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0x3b, 0x3b, + 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, + 0x12, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, + 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xe7, 0xe7, 0x29, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, + 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, + 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, + 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0x27, + 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, + 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, + 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, + 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0xe7, 0xe7, + 0xe7, 0xe7, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, + 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, + 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0x27, 0xdf, + 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0x14, 0x14, 0x14, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, + 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, + 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, + 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, + 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0x67, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, + 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, + 0xdf, 0xff, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, + 0x12, 0x12, 0x12, 0x12, 0x12, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0x29, 0xe7, 0x12, 0x12, 0x12, 0x12, + 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, + 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, + 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xda, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, + 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, + 0x2b, 0x3b, 0x18, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xe7, 0xe7, 0x29, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, + 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, + 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, + 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x12, 0x12, + 0x12, 0x12, 0x12, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0x29, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, + 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, + 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, + 0xe7, 0x12, 0x12, 0x12, 0x12, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, + 0x3b, 0x27, 0xdf, 0xff, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, + 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0x29, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0xe7, 0xe7, 0xef, + 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0xe7, 0xe7, + 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, + 0x12, 0x12, 0x12, 0x12, 0x12, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, + 0xe7, 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, + 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, + 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xf4, 0xef, 0x3b, 0x15, 0x15, 0x15, 0x15, + 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x3b, 0x3b, + 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, + 0xdf, 0xff, 0x3b, 0x3b, 0x3b, 0x3b, 0x29, 0x2b, 0x3b, 0x18, 0x3b, 0x3b, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xed, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0x3b, 0x3b, 0x12, 0x12, 0x12, + 0x12, 0x12, 0x12, 0x12, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, + 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, + 0xe7, 0xff, 0xe7, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, + 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x26, 0xdf, + 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xec, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, + 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, + 0xff, 0xef, 0xff, 0x12, 0x12, 0x12, 0x12, 0x12, 0x3b, 0x3b, 0x3b, 0x27, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xef, + 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, 0xef, 0xff, 0xef, 0xff, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xff, + 0xe7, 0x3b, 0x3b, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0xff, + 0xef, 0xef, 0xff, 0xef, 0xef, 0xff, 0xef, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, + 0x3b, 0x7f, 0x3b, 0x3b, 0xef, 0xfd, 0xf1, 0xff, 0xf1, 0xff, 0xf1, 0xfb, 0xef, 0xfd, 0xf1, 0xff, 0xf1, 0xfd, + 0xf1, 0xfb, 0xf1, 0xfd, 0xf1, 0xef, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0x01, 0x00, 0xfd, 0xf1, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xef, 0xff, 0xef, 0xff, 0xef, 0xff, 0xef, 0x3b, 0x3b, 0x43, + 0x3b, 0x3b, 0xff, 0x3b, 0x12, 0xf1, 0x12, 0x12, 0x12, 0xff}; constexpr unsigned char payload3[] = { - 0x12, 0x00, 0x65, 0x24, 0x00, 0x00, 0x00, 0x00, 0x20, 0x1e, 0x00, - 0x4f, 0x00, 0x00, 0x20, 0x1f, 0x03, 0xf6, 0x00, 0x00, 0x20, 0x20, - 0x00, 0x00, 0x00, 0x00, 0x35, 0x00, 0x59, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x68, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, - 0x73, 0x00, 0x81, 0x14, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x65, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0xe5, 0xfe, 0xf3, 0xe7, 0xe5, 0x65, 0x24, 0x00, 0x00, 0x00, 0x00, - 0x20, 0x1e, 0x00, 0x6f, 0x00, 0x00, 0x20, 0x1f, 0x03, 0xf6, 0x00, - 0x00, 0x20, 0x20, 0x00, 0x00, 0x00, 0x00, 0x35, 0x00, 0x59, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x68, 0x40, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x02, 0x00, 0x12, 0x00, 0x65, 0x24, 0x00, 0x00, 0x00, 0x00, - 0x20, 0x1e, 0x00, 0x4f, 0x00, 0x00, 0x20, 0x1f, 0x03, 0xf6, 0x00, - 0x00, 0x20, 0x20, 0x00, 0x00, 0x00, 0x00, 0x35, 0x24, 0x59, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x68, 0x40, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x02, 0x00, 0x54, 0x72, 0x61, 0x6e, 0x00, 0x10, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x65, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0xe5, 0xfe, 0xf3, 0xe7, 0xe5, 0x65, 0x24, 0x00, - 0x00, 0x00, 0x00, 0x20, 0x1e, 0x00, 0x6f, 0x00, 0x00, 0x20, 0xf6, - 0x00, 0x00, 0x03, 0x1f, 0x20, 0x20, 0x00, 0x00, 0x00, 0x00, 0x35, - 0x00, 0x59, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x68, 0x40, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x73, 0x00, 0x81, 0x14, 0x00, - 0x10, 0x00, 0x73, 0x00, 0x81, 0x14, 0x00, 0x10, 0x00, 0x00, 0x00, - 0x00, 0x26, 0x00, 0x00, 0x00, 0x00, 0xe5, 0xfe}; + 0x12, 0x00, 0x65, 0x24, 0x00, 0x00, 0x00, 0x00, 0x20, 0x1e, 0x00, 0x4f, 0x00, 0x00, 0x20, 0x1f, 0x03, 0xf6, + 0x00, 0x00, 0x20, 0x20, 0x00, 0x00, 0x00, 0x00, 0x35, 0x00, 0x59, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x68, + 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x73, 0x00, 0x81, 0x14, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x65, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe5, 0xfe, 0xf3, 0xe7, 0xe5, 0x65, + 0x24, 0x00, 0x00, 0x00, 0x00, 0x20, 0x1e, 0x00, 0x6f, 0x00, 0x00, 0x20, 0x1f, 0x03, 0xf6, 0x00, 0x00, 0x20, + 0x20, 0x00, 0x00, 0x00, 0x00, 0x35, 0x00, 0x59, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x68, 0x40, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x02, 0x00, 0x12, 0x00, 0x65, 0x24, 0x00, 0x00, 0x00, 0x00, 0x20, 0x1e, 0x00, 0x4f, 0x00, + 0x00, 0x20, 0x1f, 0x03, 0xf6, 0x00, 0x00, 0x20, 0x20, 0x00, 0x00, 0x00, 0x00, 0x35, 0x24, 0x59, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x68, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x54, 0x72, 0x61, 0x6e, 0x00, + 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x65, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe5, + 0xfe, 0xf3, 0xe7, 0xe5, 0x65, 0x24, 0x00, 0x00, 0x00, 0x00, 0x20, 0x1e, 0x00, 0x6f, 0x00, 0x00, 0x20, 0xf6, + 0x00, 0x00, 0x03, 0x1f, 0x20, 0x20, 0x00, 0x00, 0x00, 0x00, 0x35, 0x00, 0x59, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x68, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x73, 0x00, 0x81, 0x14, 0x00, 0x10, 0x00, 0x73, + 0x00, 0x81, 0x14, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x26, 0x00, 0x00, 0x00, 0x00, 0xe5, 0xfe}; constexpr unsigned char payload4[] = { - 0x12, 0x00, 0x65, 0x24, 0x00, 0x00, 0x00, 0x00, 0x20, 0x1e, 0x00, - 0x4f, 0x00, 0x00, 0x20, 0x1f, 0x03, 0xf6, 0x00, 0x00, 0x20, 0x20, - 0x00, 0x00, 0x00, 0x00, 0x35, 0x00, 0x59, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x68, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, - 0x73, 0x00, 0x81, 0x14, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x65, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0xe5, 0xfe, 0xf3, 0xe7, 0xe5, 0x65, 0x24, 0x00, 0x00, 0x00, 0x00, - 0x20, 0x1e, 0x00, 0x6f, 0x00, 0x00, 0x00, 0x20, 0x1f, 0x03, 0xf6, - 0x00, 0x00, 0x20, 0x20, 0x00, 0x00, 0x00, 0x00, 0x35, 0x00, 0x59, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x68, 0x40, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x02, 0x00, 0x12, 0x00, 0x65, 0x24, 0x00, 0x00, 0x00, - 0x00, 0x20, 0x1e, 0x00, 0x4f, 0x00, 0x00, 0x20, 0x1f, 0x03, 0xf6, - 0x00, 0x00, 0x20, 0x20, 0x00, 0x00, 0x00, 0x00, 0x35, 0x24, 0x59, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x68, 0x40, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x02, 0x00, 0x54, 0x72, 0x61, 0x6e, 0x00, 0x10, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x65, 0x24, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0xe5, 0xfe, 0xf3, 0xe7, 0xe5, 0x65, 0x24, - 0x00, 0x00, 0x00, 0x00, 0x20, 0x1e, 0x00, 0x6f, 0x00, 0x00, 0x20, - 0xf6, 0x00, 0x00, 0x03, 0x1f, 0x20, 0x20, 0x00, 0x00, 0x00, 0x00, - 0x35, 0x00, 0x59, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x68, 0x40, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x73, 0x00, 0x81, 0x14, - 0x00, 0x10, 0x00, 0x73, 0x00, 0x81, 0x14, 0x00, 0x10, 0x00, 0x00, - 0x00, 0x00, 0x26, 0x00, 0x00, 0x00, 0x00, 0xe5, 0xfe}; + 0x12, 0x00, 0x65, 0x24, 0x00, 0x00, 0x00, 0x00, 0x20, 0x1e, 0x00, 0x4f, 0x00, 0x00, 0x20, 0x1f, 0x03, 0xf6, + 0x00, 0x00, 0x20, 0x20, 0x00, 0x00, 0x00, 0x00, 0x35, 0x00, 0x59, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x68, + 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x73, 0x00, 0x81, 0x14, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x65, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe5, 0xfe, 0xf3, 0xe7, 0xe5, 0x65, + 0x24, 0x00, 0x00, 0x00, 0x00, 0x20, 0x1e, 0x00, 0x6f, 0x00, 0x00, 0x00, 0x20, 0x1f, 0x03, 0xf6, 0x00, 0x00, + 0x20, 0x20, 0x00, 0x00, 0x00, 0x00, 0x35, 0x00, 0x59, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x68, 0x40, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x12, 0x00, 0x65, 0x24, 0x00, 0x00, 0x00, 0x00, 0x20, 0x1e, 0x00, 0x4f, + 0x00, 0x00, 0x20, 0x1f, 0x03, 0xf6, 0x00, 0x00, 0x20, 0x20, 0x00, 0x00, 0x00, 0x00, 0x35, 0x24, 0x59, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x68, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x54, 0x72, 0x61, 0x6e, + 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x65, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xe5, 0xfe, 0xf3, 0xe7, 0xe5, 0x65, 0x24, 0x00, 0x00, 0x00, 0x00, 0x20, 0x1e, 0x00, 0x6f, 0x00, 0x00, 0x20, + 0xf6, 0x00, 0x00, 0x03, 0x1f, 0x20, 0x20, 0x00, 0x00, 0x00, 0x00, 0x35, 0x00, 0x59, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x68, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x73, 0x00, 0x81, 0x14, 0x00, 0x10, 0x00, + 0x73, 0x00, 0x81, 0x14, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x26, 0x00, 0x00, 0x00, 0x00, 0xe5, 0xfe}; // Construct an STObject with 11 levels of object nesting so the // maximum nesting level exception is thrown. @@ -1379,14 +869,12 @@ public: // Make an STObject that nests objects ten levels deep. There's // a minimum transaction size we must meet, so include a hash256. uint256 const hash{42u}; - auto inner = - std::make_unique(recurse, sfTransactionMetaData); + auto inner = std::make_unique(recurse, sfTransactionMetaData); inner->setFieldH256(sfTransactionHash, hash); for (int i = 1; i < 10; ++i) { - auto outer = - std::make_unique(recurse, sfTransactionMetaData); + auto outer = std::make_unique(recurse, sfTransactionMetaData); outer->set(std::move(inner)); outer->setFieldH256(sfTransactionHash, hash); inner = std::move(outer); @@ -1422,10 +910,7 @@ public: } catch (std::runtime_error const& ex) { - BEAST_EXPECT( - std::strcmp( - ex.what(), "Maximum nesting depth of STVar exceeded") == - 0); + BEAST_EXPECT(std::strcmp(ex.what(), "Maximum nesting depth of STVar exceeded") == 0); } } { @@ -1488,10 +973,7 @@ public: } catch (std::runtime_error const& ex) { - BEAST_EXPECT( - std::strcmp( - ex.what(), "Maximum nesting depth of STVar exceeded") == - 0); + BEAST_EXPECT(std::strcmp(ex.what(), "Maximum nesting depth of STVar exceeded") == 0); } } @@ -1529,8 +1011,7 @@ public: } catch (std::exception const& ex) { - BEAST_EXPECT( - strcmp(ex.what(), "Duplicate field detected") == 0); + BEAST_EXPECT(strcmp(ex.what(), "Duplicate field detected") == 0); } } @@ -1580,8 +1061,7 @@ public: } catch (std::exception const& ex) { - BEAST_EXPECT( - strcmp(ex.what(), "gFID: uncommon name out of range 0") == 0); + BEAST_EXPECT(strcmp(ex.what(), "gFID: uncommon name out of range 0") == 0); } try @@ -1614,8 +1094,7 @@ public: Rules const defaultRules{presets}; BEAST_EXPECT(!defaultRules.enabled(featureAMM)); - unexpected( - !j.checkSign(defaultRules), "Transaction fails signature test"); + unexpected(!j.checkSign(defaultRules), "Transaction fails signature test"); Serializer rawTxn; j.add(rawTxn); @@ -1640,8 +1119,7 @@ public: if (STObject(j) != parsed.object) { log << "ORIG: " << j.getJson(JsonOptions::none) << '\n' - << "BUILT " << parsed.object->getJson(JsonOptions::none) - << std::endl; + << "BUILT " << parsed.object->getJson(JsonOptions::none) << std::endl; fail("Built a different transaction"); } else @@ -1669,8 +1147,7 @@ public: payment.setFieldAmount(sfAmount, STAmount(10000000000ull)); payment.setFieldAmount(sfFee, STAmount(10ull)); payment.setFieldU32(sfSequence, 1); - payment.setFieldVL( - sfSigningPubKey, Slice(kp1.first.data(), kp1.first.size())); + payment.setFieldVL(sfSigningPubKey, Slice(kp1.first.data(), kp1.first.size())); return payment; }; { @@ -1700,8 +1177,7 @@ public: { got = err.what(); } - BEAST_EXPECT( - got == "Field 'Paths' may not be explicitly set to default."); + BEAST_EXPECT(got == "Field 'Paths' may not be explicitly set to default."); } { // Make a Payment with an extra "SignerWeight" field. @@ -1717,8 +1193,7 @@ public: { got = err.what(); } - BEAST_EXPECT( - got == "Field 'SignerWeight' found in disallowed location."); + BEAST_EXPECT(got == "Field 'SignerWeight' found in disallowed location."); } { // Make a Payment that is missing the required Fee field. @@ -1776,31 +1251,30 @@ public: // the bad ones. // This lambda contains the bulk of the test code. - auto testMalformedSigningAccount = - [this, &txn](STObject const& signer, bool expectPass) { - // Create SigningAccounts array. - STArray signers(sfSigners, 1); - signers.push_back(signer); + auto testMalformedSigningAccount = [this, &txn](STObject const& signer, bool expectPass) { + // Create SigningAccounts array. + STArray signers(sfSigners, 1); + signers.push_back(signer); - // Insert signers into transaction. - STTx tempTxn(txn); - tempTxn.setFieldArray(sfSigners, signers); + // Insert signers into transaction. + STTx tempTxn(txn); + tempTxn.setFieldArray(sfSigners, signers); - Serializer rawTxn; - tempTxn.add(rawTxn); - SerialIter sit(rawTxn.slice()); - bool serialized = false; - try - { - STTx copy(sit); - serialized = true; - } - catch (std::exception const&) - { - ; // If it threw then serialization failed. - } - BEAST_EXPECT(serialized == expectPass); - }; + Serializer rawTxn; + tempTxn.add(rawTxn); + SerialIter sit(rawTxn.slice()); + bool serialized = false; + try + { + STTx copy(sit); + serialized = true; + } + catch (std::exception const&) + { + ; // If it threw then serialization failed. + } + BEAST_EXPECT(serialized == expectPass); + }; { // Test case 1. Make a valid Signer object. diff --git a/src/test/protocol/STValidation_test.cpp b/src/test/protocol/STValidation_test.cpp index 3530d2f34a..0c0951fde2 100644 --- a/src/test/protocol/STValidation_test.cpp +++ b/src/test/protocol/STValidation_test.cpp @@ -14,146 +14,109 @@ class STValidation_test : public beast::unit_test::suite { // No public key: static constexpr std::uint8_t payload1[] = { - 0x22, 0x80, 0x00, 0x00, 0x01, 0x26, 0x03, 0x4B, 0xEA, 0x97, 0x29, 0x26, - 0x47, 0x31, 0x1A, 0x3A, 0x4E, 0x69, 0x6B, 0x2B, 0x54, 0x69, 0x66, 0x66, - 0x51, 0x53, 0x1F, 0x1A, 0x4E, 0xBB, 0x43, 0x19, 0x69, 0x16, 0xF8, 0x3E, - 0xEA, 0x5C, 0x77, 0x94, 0x08, 0x19, 0x0B, 0x4B, 0x40, 0x8C, 0xDE, 0xB8, - 0x79, 0x39, 0xF3, 0x9D, 0x66, 0x7B, 0x12, 0xCA, 0x97, 0x50, 0x17, 0x21, - 0x0B, 0xAB, 0xBC, 0x8C, 0xB7, 0xFB, 0x45, 0x49, 0xED, 0x1E, 0x07, 0xB4, - 0xFB, 0xC5, 0xF2, 0xFB, 0x67, 0x2D, 0x18, 0xA6, 0x43, 0x35, 0x28, 0xEB, - 0xD9, 0x06, 0x3E, 0xB3, 0x8B, 0xC2, 0xE0, 0x76, 0x47, 0x30, 0x45, 0x02, - 0x21, 0x00, 0xAF, 0x1D, 0x17, 0xA2, 0x12, 0x7B, 0xA4, 0x6B, 0x40, 0xBD, - 0x58, 0x76, 0x39, 0x3F, 0xF4, 0x49, 0x6B, 0x25, 0xA1, 0xAD, 0xB7, 0x36, - 0xFB, 0x64, 0x4C, 0x05, 0x21, 0x0C, 0x43, 0x02, 0xE5, 0xEE, 0x02, 0x20, - 0x26, 0x01, 0x7C, 0x5F, 0x69, 0xDA, 0xD1, 0xC3, 0x28, 0xED, 0x80, 0x05, - 0x36, 0x86, 0x8B, 0x1B, 0x22, 0xE4, 0x8E, 0x09, 0x11, 0x52, 0x28, 0x5A, - 0x48, 0x8F, 0x98, 0x7A, 0x5A, 0x10, 0x74, 0xCC}; + 0x22, 0x80, 0x00, 0x00, 0x01, 0x26, 0x03, 0x4B, 0xEA, 0x97, 0x29, 0x26, 0x47, 0x31, 0x1A, 0x3A, 0x4E, + 0x69, 0x6B, 0x2B, 0x54, 0x69, 0x66, 0x66, 0x51, 0x53, 0x1F, 0x1A, 0x4E, 0xBB, 0x43, 0x19, 0x69, 0x16, + 0xF8, 0x3E, 0xEA, 0x5C, 0x77, 0x94, 0x08, 0x19, 0x0B, 0x4B, 0x40, 0x8C, 0xDE, 0xB8, 0x79, 0x39, 0xF3, + 0x9D, 0x66, 0x7B, 0x12, 0xCA, 0x97, 0x50, 0x17, 0x21, 0x0B, 0xAB, 0xBC, 0x8C, 0xB7, 0xFB, 0x45, 0x49, + 0xED, 0x1E, 0x07, 0xB4, 0xFB, 0xC5, 0xF2, 0xFB, 0x67, 0x2D, 0x18, 0xA6, 0x43, 0x35, 0x28, 0xEB, 0xD9, + 0x06, 0x3E, 0xB3, 0x8B, 0xC2, 0xE0, 0x76, 0x47, 0x30, 0x45, 0x02, 0x21, 0x00, 0xAF, 0x1D, 0x17, 0xA2, + 0x12, 0x7B, 0xA4, 0x6B, 0x40, 0xBD, 0x58, 0x76, 0x39, 0x3F, 0xF4, 0x49, 0x6B, 0x25, 0xA1, 0xAD, 0xB7, + 0x36, 0xFB, 0x64, 0x4C, 0x05, 0x21, 0x0C, 0x43, 0x02, 0xE5, 0xEE, 0x02, 0x20, 0x26, 0x01, 0x7C, 0x5F, + 0x69, 0xDA, 0xD1, 0xC3, 0x28, 0xED, 0x80, 0x05, 0x36, 0x86, 0x8B, 0x1B, 0x22, 0xE4, 0x8E, 0x09, 0x11, + 0x52, 0x28, 0x5A, 0x48, 0x8F, 0x98, 0x7A, 0x5A, 0x10, 0x74, 0xCC}; // Short public key: static constexpr std::uint8_t payload2[] = { - 0x22, 0x80, 0x00, 0x00, 0x01, 0x26, 0x03, 0x4B, 0xEA, 0x97, 0x29, 0x26, - 0x47, 0x31, 0x1A, 0x51, 0x53, 0x1F, 0x1A, 0x4E, 0xBB, 0x43, 0x19, 0x69, - 0x16, 0xF8, 0x3E, 0xEA, 0x5C, 0x77, 0x94, 0x08, 0x19, 0x0B, 0x4B, 0x40, - 0x8C, 0xDE, 0xB8, 0x79, 0x39, 0xF3, 0x9D, 0x66, 0x7B, 0x12, 0xCA, 0x97, - 0x50, 0x17, 0x21, 0x0B, 0xAB, 0xBC, 0x8C, 0xB7, 0xFB, 0x45, 0x49, 0xED, - 0x1E, 0x07, 0xB4, 0xFB, 0xC5, 0xF2, 0xFB, 0x67, 0x2D, 0x18, 0xA6, 0x43, - 0x35, 0x28, 0xEB, 0xD9, 0x06, 0x3E, 0xB3, 0x8B, 0xC2, 0xE0, 0x73, 0x20, - 0x02, 0x9D, 0x19, 0xFB, 0x09, 0x40, 0xE5, 0xC0, 0xD8, 0x58, 0x73, 0xFA, - 0x71, 0x19, 0x99, 0x94, 0x4A, 0x68, 0x7D, 0x12, 0x9D, 0xA5, 0xC3, 0x3E, - 0x92, 0x8C, 0x27, 0x51, 0xFC, 0x1B, 0x31, 0xEB, 0x76, 0x46, 0x30, 0x44, - 0x02, 0x20, 0x34, 0x89, 0xA3, 0xBF, 0xA9, 0x97, 0x13, 0xBC, 0x87, 0x61, - 0xC5, 0x2B, 0x7F, 0xAA, 0xE9, 0x31, 0x4C, 0xCD, 0x6F, 0x57, 0x68, 0x70, - 0xC8, 0xDC, 0x58, 0x76, 0x91, 0x2F, 0x70, 0x2F, 0xD0, 0x78, 0x02, 0x20, - 0x7E, 0x57, 0x9D, 0xCA, 0x11, 0xF1, 0x3B, 0xA0, 0x39, 0x38, 0x37, 0x40, - 0xC5, 0xC8, 0xFE, 0xC1, 0xFC, 0xE9, 0xE7, 0x84, 0x6C, 0x2D, 0x47, 0x6E, + 0x22, 0x80, 0x00, 0x00, 0x01, 0x26, 0x03, 0x4B, 0xEA, 0x97, 0x29, 0x26, 0x47, 0x31, 0x1A, 0x51, 0x53, 0x1F, + 0x1A, 0x4E, 0xBB, 0x43, 0x19, 0x69, 0x16, 0xF8, 0x3E, 0xEA, 0x5C, 0x77, 0x94, 0x08, 0x19, 0x0B, 0x4B, 0x40, + 0x8C, 0xDE, 0xB8, 0x79, 0x39, 0xF3, 0x9D, 0x66, 0x7B, 0x12, 0xCA, 0x97, 0x50, 0x17, 0x21, 0x0B, 0xAB, 0xBC, + 0x8C, 0xB7, 0xFB, 0x45, 0x49, 0xED, 0x1E, 0x07, 0xB4, 0xFB, 0xC5, 0xF2, 0xFB, 0x67, 0x2D, 0x18, 0xA6, 0x43, + 0x35, 0x28, 0xEB, 0xD9, 0x06, 0x3E, 0xB3, 0x8B, 0xC2, 0xE0, 0x73, 0x20, 0x02, 0x9D, 0x19, 0xFB, 0x09, 0x40, + 0xE5, 0xC0, 0xD8, 0x58, 0x73, 0xFA, 0x71, 0x19, 0x99, 0x94, 0x4A, 0x68, 0x7D, 0x12, 0x9D, 0xA5, 0xC3, 0x3E, + 0x92, 0x8C, 0x27, 0x51, 0xFC, 0x1B, 0x31, 0xEB, 0x76, 0x46, 0x30, 0x44, 0x02, 0x20, 0x34, 0x89, 0xA3, 0xBF, + 0xA9, 0x97, 0x13, 0xBC, 0x87, 0x61, 0xC5, 0x2B, 0x7F, 0xAA, 0xE9, 0x31, 0x4C, 0xCD, 0x6F, 0x57, 0x68, 0x70, + 0xC8, 0xDC, 0x58, 0x76, 0x91, 0x2F, 0x70, 0x2F, 0xD0, 0x78, 0x02, 0x20, 0x7E, 0x57, 0x9D, 0xCA, 0x11, 0xF1, + 0x3B, 0xA0, 0x39, 0x38, 0x37, 0x40, 0xC5, 0xC8, 0xFE, 0xC1, 0xFC, 0xE9, 0xE7, 0x84, 0x6C, 0x2D, 0x47, 0x6E, 0xD7, 0xFF, 0x83, 0x9D, 0xEF, 0x7D, 0xF7, 0x6A}; // Long public key: static constexpr std::uint8_t payload3[] = { - 0x22, 0x80, 0x00, 0x00, 0x01, 0x26, 0x03, 0x4B, 0xEA, 0x97, 0x29, 0x26, - 0x47, 0x31, 0x1A, 0x51, 0x53, 0x1F, 0x1A, 0x4E, 0xBB, 0x43, 0x19, 0x69, - 0x16, 0xF8, 0x3E, 0xEA, 0x5C, 0x77, 0x94, 0x08, 0x19, 0x0B, 0x4B, 0x40, - 0x8C, 0xDE, 0xB8, 0x79, 0x39, 0xF3, 0x9D, 0x66, 0x7B, 0x12, 0xCA, 0x97, - 0x50, 0x17, 0x21, 0x0B, 0xAB, 0xBC, 0x8C, 0xB7, 0xFB, 0x45, 0x49, 0xED, - 0x1E, 0x07, 0xB4, 0xFB, 0xC5, 0xF2, 0xFB, 0x67, 0x2D, 0x18, 0xA6, 0x43, - 0x35, 0x28, 0xEB, 0xD9, 0x06, 0x3E, 0xB3, 0x8B, 0xC2, 0xE0, 0x73, 0x22, - 0x02, 0x9D, 0x19, 0xFB, 0x09, 0x40, 0xE5, 0xC0, 0xD8, 0x58, 0x73, 0xFA, - 0x71, 0x19, 0x99, 0x94, 0x4A, 0x68, 0x7D, 0x12, 0x9D, 0xA5, 0xC3, 0x3E, - 0x92, 0x8C, 0x27, 0x51, 0xFC, 0x1B, 0x31, 0xEB, 0x32, 0x78, 0x76, 0x46, - 0x30, 0x44, 0x02, 0x20, 0x3C, 0xAB, 0xEE, 0x36, 0xD8, 0xF3, 0x74, 0x5F, - 0x50, 0x28, 0x66, 0x17, 0x57, 0x26, 0x6A, 0xBD, 0x9A, 0x19, 0x08, 0xAA, - 0x65, 0x94, 0x0B, 0xDF, 0x24, 0x20, 0x44, 0x99, 0x05, 0x8C, 0xB7, 0x3D, - 0x02, 0x20, 0x79, 0x66, 0xE6, 0xCC, 0xA2, 0x5E, 0x15, 0xFE, 0x18, 0x4B, - 0xB2, 0xA8, 0x01, 0x3A, 0xD6, 0x63, 0x54, 0x08, 0x1B, 0xDA, 0xD0, 0x04, + 0x22, 0x80, 0x00, 0x00, 0x01, 0x26, 0x03, 0x4B, 0xEA, 0x97, 0x29, 0x26, 0x47, 0x31, 0x1A, 0x51, 0x53, 0x1F, + 0x1A, 0x4E, 0xBB, 0x43, 0x19, 0x69, 0x16, 0xF8, 0x3E, 0xEA, 0x5C, 0x77, 0x94, 0x08, 0x19, 0x0B, 0x4B, 0x40, + 0x8C, 0xDE, 0xB8, 0x79, 0x39, 0xF3, 0x9D, 0x66, 0x7B, 0x12, 0xCA, 0x97, 0x50, 0x17, 0x21, 0x0B, 0xAB, 0xBC, + 0x8C, 0xB7, 0xFB, 0x45, 0x49, 0xED, 0x1E, 0x07, 0xB4, 0xFB, 0xC5, 0xF2, 0xFB, 0x67, 0x2D, 0x18, 0xA6, 0x43, + 0x35, 0x28, 0xEB, 0xD9, 0x06, 0x3E, 0xB3, 0x8B, 0xC2, 0xE0, 0x73, 0x22, 0x02, 0x9D, 0x19, 0xFB, 0x09, 0x40, + 0xE5, 0xC0, 0xD8, 0x58, 0x73, 0xFA, 0x71, 0x19, 0x99, 0x94, 0x4A, 0x68, 0x7D, 0x12, 0x9D, 0xA5, 0xC3, 0x3E, + 0x92, 0x8C, 0x27, 0x51, 0xFC, 0x1B, 0x31, 0xEB, 0x32, 0x78, 0x76, 0x46, 0x30, 0x44, 0x02, 0x20, 0x3C, 0xAB, + 0xEE, 0x36, 0xD8, 0xF3, 0x74, 0x5F, 0x50, 0x28, 0x66, 0x17, 0x57, 0x26, 0x6A, 0xBD, 0x9A, 0x19, 0x08, 0xAA, + 0x65, 0x94, 0x0B, 0xDF, 0x24, 0x20, 0x44, 0x99, 0x05, 0x8C, 0xB7, 0x3D, 0x02, 0x20, 0x79, 0x66, 0xE6, 0xCC, + 0xA2, 0x5E, 0x15, 0xFE, 0x18, 0x4B, 0xB2, 0xA8, 0x01, 0x3A, 0xD6, 0x63, 0x54, 0x08, 0x1B, 0xDA, 0xD0, 0x04, 0xEF, 0x4C, 0x73, 0xB3, 0xFF, 0xFE, 0xA9, 0x8E, 0x92, 0xE8}; // Ed25519 public key: static constexpr std::uint8_t payload4[] = { - 0x22, 0x80, 0x00, 0x00, 0x01, 0x26, 0x03, 0x4B, 0xEA, 0x97, 0x29, 0x26, - 0x47, 0x31, 0x1A, 0x51, 0x53, 0x1F, 0x1A, 0x4E, 0xBB, 0x43, 0x19, 0x69, - 0x16, 0xF8, 0x3E, 0xEA, 0x5C, 0x77, 0x94, 0x08, 0x19, 0x0B, 0x4B, 0x40, - 0x8C, 0xDE, 0xB8, 0x79, 0x39, 0xF3, 0x9D, 0x66, 0x7B, 0x12, 0xCA, 0x97, - 0x50, 0x17, 0x21, 0x0B, 0xAB, 0xBC, 0x8C, 0xB7, 0xFB, 0x45, 0x49, 0xED, - 0x1E, 0x07, 0xB4, 0xFB, 0xC5, 0xF2, 0xFB, 0x67, 0x2D, 0x18, 0xA6, 0x43, - 0x35, 0x28, 0xEB, 0xD9, 0x06, 0x3E, 0xB3, 0x8B, 0xC2, 0xE0, 0x73, 0x21, - 0xED, 0x04, 0x8B, 0x9A, 0x31, 0x5E, 0xC7, 0x33, 0xC0, 0x15, 0x3B, 0x67, - 0x04, 0x73, 0x7A, 0x91, 0x3D, 0xEF, 0x57, 0x1D, 0xAD, 0xEC, 0x57, 0xE5, - 0x91, 0x5D, 0x55, 0xD9, 0x32, 0x9D, 0x45, 0x12, 0x85, 0x76, 0x40, 0x52, - 0x07, 0xF9, 0x0D, 0x18, 0x2B, 0xB7, 0xAF, 0x5D, 0x43, 0xF8, 0xF9, 0xC5, - 0xAD, 0xF9, 0xBA, 0x33, 0x23, 0xC0, 0x2F, 0x95, 0xFF, 0x36, 0x94, 0xD8, - 0x99, 0x99, 0xE0, 0x66, 0xF8, 0xB6, 0x27, 0x22, 0xFD, 0x29, 0x39, 0x30, - 0x39, 0xAB, 0x93, 0xDB, 0x9D, 0x2C, 0xE5, 0xF0, 0x4C, 0xB7, 0x30, 0xFD, - 0xC7, 0xD3, 0x21, 0xC9, 0x4E, 0x0D, 0x8A, 0x1B, 0xB2, 0x89, 0x97, 0x10, - 0x7E, 0x84, 0x09}; + 0x22, 0x80, 0x00, 0x00, 0x01, 0x26, 0x03, 0x4B, 0xEA, 0x97, 0x29, 0x26, 0x47, 0x31, 0x1A, 0x51, 0x53, + 0x1F, 0x1A, 0x4E, 0xBB, 0x43, 0x19, 0x69, 0x16, 0xF8, 0x3E, 0xEA, 0x5C, 0x77, 0x94, 0x08, 0x19, 0x0B, + 0x4B, 0x40, 0x8C, 0xDE, 0xB8, 0x79, 0x39, 0xF3, 0x9D, 0x66, 0x7B, 0x12, 0xCA, 0x97, 0x50, 0x17, 0x21, + 0x0B, 0xAB, 0xBC, 0x8C, 0xB7, 0xFB, 0x45, 0x49, 0xED, 0x1E, 0x07, 0xB4, 0xFB, 0xC5, 0xF2, 0xFB, 0x67, + 0x2D, 0x18, 0xA6, 0x43, 0x35, 0x28, 0xEB, 0xD9, 0x06, 0x3E, 0xB3, 0x8B, 0xC2, 0xE0, 0x73, 0x21, 0xED, + 0x04, 0x8B, 0x9A, 0x31, 0x5E, 0xC7, 0x33, 0xC0, 0x15, 0x3B, 0x67, 0x04, 0x73, 0x7A, 0x91, 0x3D, 0xEF, + 0x57, 0x1D, 0xAD, 0xEC, 0x57, 0xE5, 0x91, 0x5D, 0x55, 0xD9, 0x32, 0x9D, 0x45, 0x12, 0x85, 0x76, 0x40, + 0x52, 0x07, 0xF9, 0x0D, 0x18, 0x2B, 0xB7, 0xAF, 0x5D, 0x43, 0xF8, 0xF9, 0xC5, 0xAD, 0xF9, 0xBA, 0x33, + 0x23, 0xC0, 0x2F, 0x95, 0xFF, 0x36, 0x94, 0xD8, 0x99, 0x99, 0xE0, 0x66, 0xF8, 0xB6, 0x27, 0x22, 0xFD, + 0x29, 0x39, 0x30, 0x39, 0xAB, 0x93, 0xDB, 0x9D, 0x2C, 0xE5, 0xF0, 0x4C, 0xB7, 0x30, 0xFD, 0xC7, 0xD3, + 0x21, 0xC9, 0x4E, 0x0D, 0x8A, 0x1B, 0xB2, 0x89, 0x97, 0x10, 0x7E, 0x84, 0x09}; // No ledger sequence: static constexpr std::uint8_t payload5[] = { - 0x22, 0x80, 0x00, 0x00, 0x01, 0x29, 0x26, 0x47, 0x31, 0x1A, 0x51, 0x53, - 0x1F, 0x1A, 0x4E, 0xBB, 0x43, 0x19, 0x69, 0x16, 0xF8, 0x3E, 0xEA, 0x5C, - 0x77, 0x94, 0x08, 0x19, 0x0B, 0x4B, 0x40, 0x8C, 0xDE, 0xB8, 0x79, 0x39, - 0xF3, 0x9D, 0x66, 0x7B, 0x12, 0xCA, 0x97, 0x50, 0x17, 0x21, 0x0B, 0xAB, - 0xBC, 0x8C, 0xB7, 0xFB, 0x45, 0x49, 0xED, 0x1E, 0x07, 0xB4, 0xFB, 0xC5, - 0xF2, 0xFB, 0x67, 0x2D, 0x18, 0xA6, 0x43, 0x35, 0x28, 0xEB, 0xD9, 0x06, - 0x3E, 0xB3, 0x8B, 0xC2, 0xE0, 0x73, 0x21, 0x02, 0x9D, 0x19, 0xFB, 0x09, - 0x40, 0xE5, 0xC0, 0xD8, 0x58, 0x73, 0xFA, 0x71, 0x19, 0x99, 0x94, 0x4A, - 0x68, 0x7D, 0x12, 0x9D, 0xA5, 0xC3, 0x3E, 0x92, 0x8C, 0x27, 0x51, 0xFC, - 0x1B, 0x31, 0xEB, 0x32, 0x76, 0x47, 0x30, 0x45, 0x02, 0x21, 0x00, 0x83, - 0xB3, 0x1B, 0xE9, 0x03, 0x8F, 0x4A, 0x92, 0x8B, 0x9B, 0x51, 0xEF, 0x79, - 0xED, 0xA1, 0x4A, 0x58, 0x9B, 0x20, 0xCF, 0x89, 0xC4, 0x75, 0x99, 0x5F, - 0x6D, 0x79, 0x51, 0x79, 0x07, 0xF9, 0x93, 0x02, 0x20, 0x39, 0xA6, 0x0C, - 0x77, 0x68, 0x84, 0x50, 0xDB, 0xDA, 0x64, 0x32, 0x74, 0xEC, 0x63, 0x48, - 0x48, 0x96, 0xB5, 0x94, 0x57, 0x55, 0x8D, 0x7D, 0xD8, 0x25, 0x78, 0xD1, - 0xEA, 0x5F, 0xD9, 0xC7, 0xAA}; + 0x22, 0x80, 0x00, 0x00, 0x01, 0x29, 0x26, 0x47, 0x31, 0x1A, 0x51, 0x53, 0x1F, 0x1A, 0x4E, 0xBB, 0x43, + 0x19, 0x69, 0x16, 0xF8, 0x3E, 0xEA, 0x5C, 0x77, 0x94, 0x08, 0x19, 0x0B, 0x4B, 0x40, 0x8C, 0xDE, 0xB8, + 0x79, 0x39, 0xF3, 0x9D, 0x66, 0x7B, 0x12, 0xCA, 0x97, 0x50, 0x17, 0x21, 0x0B, 0xAB, 0xBC, 0x8C, 0xB7, + 0xFB, 0x45, 0x49, 0xED, 0x1E, 0x07, 0xB4, 0xFB, 0xC5, 0xF2, 0xFB, 0x67, 0x2D, 0x18, 0xA6, 0x43, 0x35, + 0x28, 0xEB, 0xD9, 0x06, 0x3E, 0xB3, 0x8B, 0xC2, 0xE0, 0x73, 0x21, 0x02, 0x9D, 0x19, 0xFB, 0x09, 0x40, + 0xE5, 0xC0, 0xD8, 0x58, 0x73, 0xFA, 0x71, 0x19, 0x99, 0x94, 0x4A, 0x68, 0x7D, 0x12, 0x9D, 0xA5, 0xC3, + 0x3E, 0x92, 0x8C, 0x27, 0x51, 0xFC, 0x1B, 0x31, 0xEB, 0x32, 0x76, 0x47, 0x30, 0x45, 0x02, 0x21, 0x00, + 0x83, 0xB3, 0x1B, 0xE9, 0x03, 0x8F, 0x4A, 0x92, 0x8B, 0x9B, 0x51, 0xEF, 0x79, 0xED, 0xA1, 0x4A, 0x58, + 0x9B, 0x20, 0xCF, 0x89, 0xC4, 0x75, 0x99, 0x5F, 0x6D, 0x79, 0x51, 0x79, 0x07, 0xF9, 0x93, 0x02, 0x20, + 0x39, 0xA6, 0x0C, 0x77, 0x68, 0x84, 0x50, 0xDB, 0xDA, 0x64, 0x32, 0x74, 0xEC, 0x63, 0x48, 0x48, 0x96, + 0xB5, 0x94, 0x57, 0x55, 0x8D, 0x7D, 0xD8, 0x25, 0x78, 0xD1, 0xEA, 0x5F, 0xD9, 0xC7, 0xAA}; // No sign time: static constexpr std::uint8_t payload6[] = { - 0x22, 0x80, 0x00, 0x00, 0x01, 0x26, 0x03, 0x4B, 0xEA, 0x97, 0x51, 0x53, - 0x1F, 0x1A, 0x4E, 0xBB, 0x43, 0x19, 0x69, 0x16, 0xF8, 0x3E, 0xEA, 0x5C, - 0x77, 0x94, 0x08, 0x19, 0x0B, 0x4B, 0x40, 0x8C, 0xDE, 0xB8, 0x79, 0x39, - 0xF3, 0x9D, 0x66, 0x7B, 0x12, 0xCA, 0x97, 0x50, 0x17, 0x21, 0x0B, 0xAB, - 0xBC, 0x8C, 0xB7, 0xFB, 0x45, 0x49, 0xED, 0x1E, 0x07, 0xB4, 0xFB, 0xC5, - 0xF2, 0xFB, 0x67, 0x2D, 0x18, 0xA6, 0x43, 0x35, 0x28, 0xEB, 0xD9, 0x06, - 0x3E, 0xB3, 0x8B, 0xC2, 0xE0, 0x73, 0x21, 0x02, 0x9D, 0x19, 0xFB, 0x09, - 0x40, 0xE5, 0xC0, 0xD8, 0x58, 0x73, 0xFA, 0x71, 0x19, 0x99, 0x94, 0x4A, - 0x68, 0x7D, 0x12, 0x9D, 0xA5, 0xC3, 0x3E, 0x92, 0x8C, 0x27, 0x51, 0xFC, - 0x1B, 0x31, 0xEB, 0x32, 0x76, 0x47, 0x30, 0x45, 0x02, 0x21, 0x00, 0xDD, - 0xB0, 0x59, 0x9A, 0x02, 0x3E, 0xF2, 0x44, 0xCE, 0x1D, 0xA8, 0x99, 0x06, - 0xF3, 0x8A, 0x4B, 0xEB, 0x95, 0x42, 0x63, 0x6A, 0x6C, 0x04, 0x30, 0x7F, - 0x62, 0x78, 0x3A, 0x89, 0xB0, 0x3F, 0x22, 0x02, 0x20, 0x4E, 0x6A, 0x55, - 0x63, 0x8A, 0x19, 0xED, 0xFE, 0x70, 0x34, 0xD1, 0x30, 0xED, 0x7C, 0xAF, - 0xB2, 0x78, 0xBB, 0x15, 0x6C, 0x42, 0x3E, 0x19, 0x5D, 0xEA, 0xC5, 0x5E, - 0x23, 0xE2, 0x14, 0x80, 0x54}; + 0x22, 0x80, 0x00, 0x00, 0x01, 0x26, 0x03, 0x4B, 0xEA, 0x97, 0x51, 0x53, 0x1F, 0x1A, 0x4E, 0xBB, 0x43, + 0x19, 0x69, 0x16, 0xF8, 0x3E, 0xEA, 0x5C, 0x77, 0x94, 0x08, 0x19, 0x0B, 0x4B, 0x40, 0x8C, 0xDE, 0xB8, + 0x79, 0x39, 0xF3, 0x9D, 0x66, 0x7B, 0x12, 0xCA, 0x97, 0x50, 0x17, 0x21, 0x0B, 0xAB, 0xBC, 0x8C, 0xB7, + 0xFB, 0x45, 0x49, 0xED, 0x1E, 0x07, 0xB4, 0xFB, 0xC5, 0xF2, 0xFB, 0x67, 0x2D, 0x18, 0xA6, 0x43, 0x35, + 0x28, 0xEB, 0xD9, 0x06, 0x3E, 0xB3, 0x8B, 0xC2, 0xE0, 0x73, 0x21, 0x02, 0x9D, 0x19, 0xFB, 0x09, 0x40, + 0xE5, 0xC0, 0xD8, 0x58, 0x73, 0xFA, 0x71, 0x19, 0x99, 0x94, 0x4A, 0x68, 0x7D, 0x12, 0x9D, 0xA5, 0xC3, + 0x3E, 0x92, 0x8C, 0x27, 0x51, 0xFC, 0x1B, 0x31, 0xEB, 0x32, 0x76, 0x47, 0x30, 0x45, 0x02, 0x21, 0x00, + 0xDD, 0xB0, 0x59, 0x9A, 0x02, 0x3E, 0xF2, 0x44, 0xCE, 0x1D, 0xA8, 0x99, 0x06, 0xF3, 0x8A, 0x4B, 0xEB, + 0x95, 0x42, 0x63, 0x6A, 0x6C, 0x04, 0x30, 0x7F, 0x62, 0x78, 0x3A, 0x89, 0xB0, 0x3F, 0x22, 0x02, 0x20, + 0x4E, 0x6A, 0x55, 0x63, 0x8A, 0x19, 0xED, 0xFE, 0x70, 0x34, 0xD1, 0x30, 0xED, 0x7C, 0xAF, 0xB2, 0x78, + 0xBB, 0x15, 0x6C, 0x42, 0x3E, 0x19, 0x5D, 0xEA, 0xC5, 0x5E, 0x23, 0xE2, 0x14, 0x80, 0x54}; // No signature field: static constexpr std::uint8_t payload7[] = { - 0x22, 0x80, 0x00, 0x00, 0x01, 0x26, 0x03, 0x4B, 0xEA, 0x97, 0x29, 0x26, - 0x47, 0x31, 0x1A, 0x51, 0x53, 0x1F, 0x1A, 0x4E, 0xBB, 0x43, 0x19, 0x69, - 0x16, 0xF8, 0x3E, 0xEA, 0x5C, 0x77, 0x94, 0x08, 0x19, 0x0B, 0x4B, 0x40, - 0x8C, 0xDE, 0xB8, 0x79, 0x39, 0xF3, 0x9D, 0x66, 0x7B, 0x12, 0xCA, 0x97, - 0x50, 0x17, 0x21, 0x0B, 0xAB, 0xBC, 0x8C, 0xB7, 0xFB, 0x45, 0x49, 0xED, - 0x1E, 0x07, 0xB4, 0xFB, 0xC5, 0xF2, 0xFB, 0x67, 0x2D, 0x18, 0xA6, 0x43, - 0x35, 0x28, 0xEB, 0xD9, 0x06, 0x3E, 0xB3, 0x8B, 0xC2, 0xE0, 0x73, 0x21, - 0x02, 0x9D, 0x19, 0xFB, 0x09, 0x40, 0xE5, 0xC0, 0xD8, 0x58, 0x73, 0xFA, - 0x71, 0x19, 0x99, 0x94, 0x4A, 0x68, 0x7D, 0x12, 0x9D, 0xA5, 0xC3, 0x3E, - 0x92, 0x8C, 0x27, 0x51, 0xFC, 0x1B, 0x31, 0xEB, 0x32}; + 0x22, 0x80, 0x00, 0x00, 0x01, 0x26, 0x03, 0x4B, 0xEA, 0x97, 0x29, 0x26, 0x47, 0x31, 0x1A, 0x51, 0x53, + 0x1F, 0x1A, 0x4E, 0xBB, 0x43, 0x19, 0x69, 0x16, 0xF8, 0x3E, 0xEA, 0x5C, 0x77, 0x94, 0x08, 0x19, 0x0B, + 0x4B, 0x40, 0x8C, 0xDE, 0xB8, 0x79, 0x39, 0xF3, 0x9D, 0x66, 0x7B, 0x12, 0xCA, 0x97, 0x50, 0x17, 0x21, + 0x0B, 0xAB, 0xBC, 0x8C, 0xB7, 0xFB, 0x45, 0x49, 0xED, 0x1E, 0x07, 0xB4, 0xFB, 0xC5, 0xF2, 0xFB, 0x67, + 0x2D, 0x18, 0xA6, 0x43, 0x35, 0x28, 0xEB, 0xD9, 0x06, 0x3E, 0xB3, 0x8B, 0xC2, 0xE0, 0x73, 0x21, 0x02, + 0x9D, 0x19, 0xFB, 0x09, 0x40, 0xE5, 0xC0, 0xD8, 0x58, 0x73, 0xFA, 0x71, 0x19, 0x99, 0x94, 0x4A, 0x68, + 0x7D, 0x12, 0x9D, 0xA5, 0xC3, 0x3E, 0x92, 0x8C, 0x27, 0x51, 0xFC, 0x1B, 0x31, 0xEB, 0x32}; // Good: static constexpr std::uint8_t payload8[] = { - 0x22, 0x80, 0x00, 0x00, 0x01, 0x26, 0x03, 0x4B, 0xEA, 0x97, 0x29, 0x26, - 0x47, 0x31, 0x1A, 0x51, 0x53, 0x1F, 0x1A, 0x4E, 0xBB, 0x43, 0x19, 0x69, - 0x16, 0xF8, 0x3E, 0xEA, 0x5C, 0x77, 0x94, 0x08, 0x19, 0x0B, 0x4B, 0x40, - 0x8C, 0xDE, 0xB8, 0x79, 0x39, 0xF3, 0x9D, 0x66, 0x7B, 0x12, 0xCA, 0x97, - 0x50, 0x17, 0x21, 0x0B, 0xAB, 0xBC, 0x8C, 0xB7, 0xFB, 0x45, 0x49, 0xED, - 0x1E, 0x07, 0xB4, 0xFB, 0xC5, 0xF2, 0xFB, 0x67, 0x2D, 0x18, 0xA6, 0x43, - 0x35, 0x28, 0xEB, 0xD9, 0x06, 0x3E, 0xB3, 0x8B, 0xC2, 0xE0, 0x73, 0x21, - 0x02, 0x9D, 0x19, 0xFB, 0x09, 0x40, 0xE5, 0xC0, 0xD8, 0x58, 0x73, 0xFA, - 0x71, 0x19, 0x99, 0x94, 0x4A, 0x68, 0x7D, 0x12, 0x9D, 0xA5, 0xC3, 0x3E, - 0x92, 0x8C, 0x27, 0x51, 0xFC, 0x1B, 0x31, 0xEB, 0x32, 0x76, 0x47, 0x30, - 0x45, 0x02, 0x21, 0x00, 0xDD, 0x29, 0xDC, 0xAC, 0x82, 0x5E, 0xF9, 0xE2, - 0x2D, 0x26, 0x03, 0x95, 0xC2, 0x11, 0x3A, 0x2A, 0x83, 0xEE, 0xA0, 0x2B, - 0x9F, 0x2A, 0x51, 0xBD, 0x6B, 0xF7, 0x83, 0xCE, 0x4A, 0x7C, 0x52, 0x29, - 0x02, 0x20, 0x52, 0x45, 0xB9, 0x07, 0x57, 0xEF, 0xB2, 0x6C, 0x69, 0xC5, - 0x47, 0xCA, 0xE2, 0x76, 0x00, 0xFC, 0x35, 0x46, 0x5D, 0x19, 0x64, 0xCE, + 0x22, 0x80, 0x00, 0x00, 0x01, 0x26, 0x03, 0x4B, 0xEA, 0x97, 0x29, 0x26, 0x47, 0x31, 0x1A, 0x51, 0x53, 0x1F, + 0x1A, 0x4E, 0xBB, 0x43, 0x19, 0x69, 0x16, 0xF8, 0x3E, 0xEA, 0x5C, 0x77, 0x94, 0x08, 0x19, 0x0B, 0x4B, 0x40, + 0x8C, 0xDE, 0xB8, 0x79, 0x39, 0xF3, 0x9D, 0x66, 0x7B, 0x12, 0xCA, 0x97, 0x50, 0x17, 0x21, 0x0B, 0xAB, 0xBC, + 0x8C, 0xB7, 0xFB, 0x45, 0x49, 0xED, 0x1E, 0x07, 0xB4, 0xFB, 0xC5, 0xF2, 0xFB, 0x67, 0x2D, 0x18, 0xA6, 0x43, + 0x35, 0x28, 0xEB, 0xD9, 0x06, 0x3E, 0xB3, 0x8B, 0xC2, 0xE0, 0x73, 0x21, 0x02, 0x9D, 0x19, 0xFB, 0x09, 0x40, + 0xE5, 0xC0, 0xD8, 0x58, 0x73, 0xFA, 0x71, 0x19, 0x99, 0x94, 0x4A, 0x68, 0x7D, 0x12, 0x9D, 0xA5, 0xC3, 0x3E, + 0x92, 0x8C, 0x27, 0x51, 0xFC, 0x1B, 0x31, 0xEB, 0x32, 0x76, 0x47, 0x30, 0x45, 0x02, 0x21, 0x00, 0xDD, 0x29, + 0xDC, 0xAC, 0x82, 0x5E, 0xF9, 0xE2, 0x2D, 0x26, 0x03, 0x95, 0xC2, 0x11, 0x3A, 0x2A, 0x83, 0xEE, 0xA0, 0x2B, + 0x9F, 0x2A, 0x51, 0xBD, 0x6B, 0xF7, 0x83, 0xCE, 0x4A, 0x7C, 0x52, 0x29, 0x02, 0x20, 0x52, 0x45, 0xB9, 0x07, + 0x57, 0xEF, 0xB2, 0x6C, 0x69, 0xC5, 0x47, 0xCA, 0xE2, 0x76, 0x00, 0xFC, 0x35, 0x46, 0x5D, 0x19, 0x64, 0xCE, 0xCA, 0x88, 0xA1, 0x2A, 0x20, 0xCF, 0x3C, 0xF9, 0xCE, 0xCF}; public: @@ -166,8 +129,7 @@ public: { SerialIter sit{payload8}; - auto val = std::make_shared( - sit, [](PublicKey const& pk) { return calcNodeID(pk); }, true); + auto val = std::make_shared(sit, [](PublicKey const& pk) { return calcNodeID(pk); }, true); BEAST_EXPECT(val); BEAST_EXPECT(val->isFieldPresent(sfLedgerSequence)); @@ -187,55 +149,49 @@ public: try { SerialIter sit{payload1}; - auto val = std::make_shared( - sit, [](PublicKey const& pk) { return calcNodeID(pk); }, false); + auto val = + std::make_shared(sit, [](PublicKey const& pk) { return calcNodeID(pk); }, false); fail("An exception should have been thrown"); } catch (std::exception const& ex) { - BEAST_EXPECT( - strcmp( - ex.what(), - "Field 'SigningPubKey' is required but missing.") == 0); + BEAST_EXPECT(strcmp(ex.what(), "Field 'SigningPubKey' is required but missing.") == 0); } try { SerialIter sit{payload2}; - auto val = std::make_shared( - sit, [](PublicKey const& pk) { return calcNodeID(pk); }, false); + auto val = + std::make_shared(sit, [](PublicKey const& pk) { return calcNodeID(pk); }, false); fail("An exception should have been thrown"); } catch (std::exception const& ex) { - BEAST_EXPECT( - strcmp(ex.what(), "Invalid public key in validation") == 0); + BEAST_EXPECT(strcmp(ex.what(), "Invalid public key in validation") == 0); } try { SerialIter sit{payload3}; - auto val = std::make_shared( - sit, [](PublicKey const& pk) { return calcNodeID(pk); }, false); + auto val = + std::make_shared(sit, [](PublicKey const& pk) { return calcNodeID(pk); }, false); fail("An exception should have been thrown"); } catch (std::exception const& ex) { - BEAST_EXPECT( - strcmp(ex.what(), "Invalid public key in validation") == 0); + BEAST_EXPECT(strcmp(ex.what(), "Invalid public key in validation") == 0); } try { SerialIter sit{payload4}; - auto val = std::make_shared( - sit, [](PublicKey const& pk) { return calcNodeID(pk); }, false); + auto val = + std::make_shared(sit, [](PublicKey const& pk) { return calcNodeID(pk); }, false); fail("An exception should have been thrown"); } catch (std::exception const& ex) { - BEAST_EXPECT( - strcmp(ex.what(), "Invalid public key in validation") == 0); + BEAST_EXPECT(strcmp(ex.what(), "Invalid public key in validation") == 0); } testcase("Deserialization: Missing Fields"); @@ -243,48 +199,36 @@ public: try { SerialIter sit{payload5}; - auto val = std::make_shared( - sit, [](PublicKey const& pk) { return calcNodeID(pk); }, false); + auto val = std::make_shared(sit, [](PublicKey const& pk) { return calcNodeID(pk); }, false); fail("Expected exception not thrown from validation"); } catch (std::exception const& ex) { - BEAST_EXPECT( - strcmp( - ex.what(), - "Field 'LedgerSequence' is required but missing.") == 0); + BEAST_EXPECT(strcmp(ex.what(), "Field 'LedgerSequence' is required but missing.") == 0); } try { SerialIter sit{payload6}; - auto val = std::make_shared( - sit, [](PublicKey const& pk) { return calcNodeID(pk); }, false); + auto val = std::make_shared(sit, [](PublicKey const& pk) { return calcNodeID(pk); }, false); fail("Expected exception not thrown from validation"); } catch (std::exception const& ex) { - BEAST_EXPECT( - strcmp( - ex.what(), - "Field 'SigningTime' is required but missing.") == 0); + BEAST_EXPECT(strcmp(ex.what(), "Field 'SigningTime' is required but missing.") == 0); } try { SerialIter sit{payload7}; - auto val = std::make_shared( - sit, [](PublicKey const& pk) { return calcNodeID(pk); }, false); + auto val = std::make_shared(sit, [](PublicKey const& pk) { return calcNodeID(pk); }, false); fail("Expected exception not thrown from validation"); } catch (std::exception const& ex) { - BEAST_EXPECT( - strcmp( - ex.what(), "Field 'Signature' is required but missing.") == - 0); + BEAST_EXPECT(strcmp(ex.what(), "Field 'Signature' is required but missing.") == 0); } testcase("Deserialization: Corrupted Data / Fuzzing"); @@ -307,14 +251,10 @@ public: { SerialIter sit{makeSlice(v2)}; - auto val = std::make_shared( - sit, - [](PublicKey const& pk) { return calcNodeID(pk); }, - true); + auto val = + std::make_shared(sit, [](PublicKey const& pk) { return calcNodeID(pk); }, true); - fail( - "Mutated validation signature checked out: offset=" + - std::to_string(i)); + fail("Mutated validation signature checked out: offset=" + std::to_string(i)); } catch (std::exception const&) { diff --git a/src/test/protocol/SecretKey_test.cpp b/src/test/protocol/SecretKey_test.cpp index e7bdcc1916..60081c8251 100644 --- a/src/test/protocol/SecretKey_test.cpp +++ b/src/test/protocol/SecretKey_test.cpp @@ -31,38 +31,29 @@ public: { testcase("secp256k1: canonicality"); - std::array const digestData{ - 0x34, 0xC1, 0x90, 0x28, 0xC8, 0x0D, 0x21, 0xF3, 0xF4, 0x8C, 0x93, - 0x54, 0x89, 0x5F, 0x8D, 0x5B, 0xF0, 0xD5, 0xEE, 0x7F, 0xF4, 0x57, - 0x64, 0x7C, 0xF6, 0x55, 0xF5, 0x53, 0x0A, 0x30, 0x22, 0xA7}; + std::array const digestData{0x34, 0xC1, 0x90, 0x28, 0xC8, 0x0D, 0x21, 0xF3, 0xF4, 0x8C, 0x93, + 0x54, 0x89, 0x5F, 0x8D, 0x5B, 0xF0, 0xD5, 0xEE, 0x7F, 0xF4, 0x57, + 0x64, 0x7C, 0xF6, 0x55, 0xF5, 0x53, 0x0A, 0x30, 0x22, 0xA7}; - std::array const pkData{ - 0x02, 0x50, 0x96, 0xEB, 0x12, 0xD3, 0xE9, 0x24, 0x23, 0x4E, 0x71, - 0x62, 0x36, 0x9C, 0x11, 0xD8, 0xBF, 0x87, 0x7E, 0xDA, 0x23, 0x87, - 0x78, 0xE7, 0xA3, 0x1F, 0xF0, 0xAA, 0xC5, 0xD0, 0xDB, 0xCF, 0x37}; + std::array const pkData{0x02, 0x50, 0x96, 0xEB, 0x12, 0xD3, 0xE9, 0x24, 0x23, 0x4E, 0x71, + 0x62, 0x36, 0x9C, 0x11, 0xD8, 0xBF, 0x87, 0x7E, 0xDA, 0x23, 0x87, + 0x78, 0xE7, 0xA3, 0x1F, 0xF0, 0xAA, 0xC5, 0xD0, 0xDB, 0xCF, 0x37}; - std::array const skData{ - 0xAA, 0x92, 0x14, 0x17, 0xE7, 0xE5, 0xC2, 0x99, 0xDA, 0x4E, 0xEC, - 0x16, 0xD1, 0xCA, 0xA9, 0x2F, 0x19, 0xB1, 0x9F, 0x2A, 0x68, 0x51, - 0x1F, 0x68, 0xEC, 0x73, 0xBB, 0xB2, 0xF5, 0x23, 0x6F, 0x3D}; + std::array const skData{0xAA, 0x92, 0x14, 0x17, 0xE7, 0xE5, 0xC2, 0x99, 0xDA, 0x4E, 0xEC, + 0x16, 0xD1, 0xCA, 0xA9, 0x2F, 0x19, 0xB1, 0x9F, 0x2A, 0x68, 0x51, + 0x1F, 0x68, 0xEC, 0x73, 0xBB, 0xB2, 0xF5, 0x23, 0x6F, 0x3D}; std::array const sig{ - 0x30, 0x45, 0x02, 0x21, 0x00, 0xB4, 0x9D, 0x07, 0xF0, 0xE9, 0x34, - 0xBA, 0x46, 0x8C, 0x0E, 0xFC, 0x78, 0x11, 0x77, 0x91, 0x40, 0x8D, - 0x1F, 0xB8, 0xB6, 0x3A, 0x64, 0x92, 0xAD, 0x39, 0x5A, 0xC2, 0xF3, - 0x60, 0xF2, 0x46, 0x60, 0x02, 0x20, 0x50, 0x87, 0x39, 0xDB, 0x0A, - 0x2E, 0xF8, 0x16, 0x76, 0xE3, 0x9F, 0x45, 0x9C, 0x8B, 0xBB, 0x07, - 0xA0, 0x9C, 0x3E, 0x9F, 0x9B, 0xEB, 0x69, 0x62, 0x94, 0xD5, 0x24, - 0xD4, 0x79, 0xD6, 0x27, 0x40}; + 0x30, 0x45, 0x02, 0x21, 0x00, 0xB4, 0x9D, 0x07, 0xF0, 0xE9, 0x34, 0xBA, 0x46, 0x8C, 0x0E, 0xFC, 0x78, 0x11, + 0x77, 0x91, 0x40, 0x8D, 0x1F, 0xB8, 0xB6, 0x3A, 0x64, 0x92, 0xAD, 0x39, 0x5A, 0xC2, 0xF3, 0x60, 0xF2, 0x46, + 0x60, 0x02, 0x20, 0x50, 0x87, 0x39, 0xDB, 0x0A, 0x2E, 0xF8, 0x16, 0x76, 0xE3, 0x9F, 0x45, 0x9C, 0x8B, 0xBB, + 0x07, 0xA0, 0x9C, 0x3E, 0x9F, 0x9B, 0xEB, 0x69, 0x62, 0x94, 0xD5, 0x24, 0xD4, 0x79, 0xD6, 0x27, 0x40}; std::array const non{ - 0x30, 0x46, 0x02, 0x21, 0x00, 0xB4, 0x9D, 0x07, 0xF0, 0xE9, 0x34, - 0xBA, 0x46, 0x8C, 0x0E, 0xFC, 0x78, 0x11, 0x77, 0x91, 0x40, 0x8D, - 0x1F, 0xB8, 0xB6, 0x3A, 0x64, 0x92, 0xAD, 0x39, 0x5A, 0xC2, 0xF3, - 0x60, 0xF2, 0x46, 0x60, 0x02, 0x21, 0x00, 0xAF, 0x78, 0xC6, 0x24, - 0xF5, 0xD1, 0x07, 0xE9, 0x89, 0x1C, 0x60, 0xBA, 0x63, 0x74, 0x44, - 0xF7, 0x1A, 0x12, 0x9E, 0x47, 0x13, 0x5D, 0x36, 0xD9, 0x2A, 0xFD, - 0x39, 0xB8, 0x56, 0x60, 0x1A, 0x01}; + 0x30, 0x46, 0x02, 0x21, 0x00, 0xB4, 0x9D, 0x07, 0xF0, 0xE9, 0x34, 0xBA, 0x46, 0x8C, 0x0E, 0xFC, 0x78, 0x11, + 0x77, 0x91, 0x40, 0x8D, 0x1F, 0xB8, 0xB6, 0x3A, 0x64, 0x92, 0xAD, 0x39, 0x5A, 0xC2, 0xF3, 0x60, 0xF2, 0x46, + 0x60, 0x02, 0x21, 0x00, 0xAF, 0x78, 0xC6, 0x24, 0xF5, 0xD1, 0x07, 0xE9, 0x89, 0x1C, 0x60, 0xBA, 0x63, 0x74, + 0x44, 0xF7, 0x1A, 0x12, 0x9E, 0x47, 0x13, 0x5D, 0x36, 0xD9, 0x2A, 0xFD, 0x39, 0xB8, 0x56, 0x60, 0x1A, 0x01}; auto const digest = uint256::fromVoid(digestData.data()); @@ -152,8 +143,7 @@ public: // swaps the smallest and largest elements in buffer std::iter_swap( - std::min_element(badData.begin(), badData.end()), - std::max_element(badData.begin(), badData.end())); + std::min_element(badData.begin(), badData.end()), std::max_element(badData.begin(), badData.end())); // Wrong data: should fail BEAST_EXPECT(!verify(pk, makeSlice(badData), sig)); @@ -178,24 +168,20 @@ public: // Ensure that parsing some well-known secret keys works { - auto const sk1 = generateSecretKey( - KeyType::secp256k1, generateSeed("masterpassphrase")); + auto const sk1 = generateSecretKey(KeyType::secp256k1, generateSeed("masterpassphrase")); - auto const sk2 = parseBase58( - TokenType::NodePrivate, - "pnen77YEeUd4fFKG7iycBWcwKpTaeFRkW2WFostaATy1DSupwXe"); + auto const sk2 = + parseBase58(TokenType::NodePrivate, "pnen77YEeUd4fFKG7iycBWcwKpTaeFRkW2WFostaATy1DSupwXe"); BEAST_EXPECT(sk2); BEAST_EXPECT(sk1 == *sk2); } { - auto const sk1 = generateSecretKey( - KeyType::ed25519, generateSeed("masterpassphrase")); + auto const sk1 = generateSecretKey(KeyType::ed25519, generateSeed("masterpassphrase")); - auto const sk2 = parseBase58( - TokenType::NodePrivate, - "paKv46LztLqK3GaKz1rG2nQGN6M4JLyRtxFBYFTw4wAVHtGys36"); + auto const sk2 = + parseBase58(TokenType::NodePrivate, "paKv46LztLqK3GaKz1rG2nQGN6M4JLyRtxFBYFTw4wAVHtGys36"); BEAST_EXPECT(sk2); BEAST_EXPECT(sk1 == *sk2); @@ -204,8 +190,7 @@ public: // Try converting short, long and malformed data BEAST_EXPECT(!parseBase58(TokenType::NodePrivate, "")); BEAST_EXPECT(!parseBase58(TokenType::NodePrivate, " ")); - BEAST_EXPECT(!parseBase58( - TokenType::NodePrivate, "!35gty9mhju8nfjl")); + BEAST_EXPECT(!parseBase58(TokenType::NodePrivate, "!35gty9mhju8nfjl")); auto const good = toBase58(TokenType::NodePrivate, randomSecretKey()); @@ -219,8 +204,7 @@ public: while (!s.empty()) { s.erase(r(s) % s.size(), 1); - BEAST_EXPECT( - !parseBase58(TokenType::NodePrivate, s)); + BEAST_EXPECT(!parseBase58(TokenType::NodePrivate, s)); } } @@ -239,8 +223,7 @@ public: { auto s = good; s[i % s.size()] = c; - BEAST_EXPECT( - !parseBase58(TokenType::NodePrivate, s)); + BEAST_EXPECT(!parseBase58(TokenType::NodePrivate, s)); } } @@ -251,8 +234,7 @@ public: for (auto c : std::string("ansrJqtv7")) { s[0] = c; - BEAST_EXPECT( - !parseBase58(TokenType::NodePrivate, s)); + BEAST_EXPECT(!parseBase58(TokenType::NodePrivate, s)); } } @@ -280,8 +262,7 @@ public: BEAST_EXPECT((si == sj) == (i == j)); - auto const skj = - parseBase58(TokenType::NodePrivate, sj); + auto const skj = parseBase58(TokenType::NodePrivate, sj); BEAST_EXPECT(skj && keys[j] == *skj); BEAST_EXPECT((*ski == *skj) == (i == j)); @@ -299,8 +280,7 @@ public: auto const id = parseBase58(test.addr); BEAST_EXPECT(id); - auto kp = - generateKeyPair(KeyType::secp256k1, Seed{makeSlice(test.seed)}); + auto kp = generateKeyPair(KeyType::secp256k1, Seed{makeSlice(test.seed)}); BEAST_EXPECT(kp.first == PublicKey{makeSlice(test.pubkey)}); BEAST_EXPECT(kp.second == SecretKey{makeSlice(test.seckey)}); @@ -318,8 +298,7 @@ public: auto const id = parseBase58(test.addr); BEAST_EXPECT(id); - auto kp = - generateKeyPair(KeyType::ed25519, Seed{makeSlice(test.seed)}); + auto kp = generateKeyPair(KeyType::ed25519, Seed{makeSlice(test.seed)}); BEAST_EXPECT(kp.first == PublicKey{makeSlice(test.pubkey)}); BEAST_EXPECT(kp.second == SecretKey{makeSlice(test.seckey)}); diff --git a/src/test/protocol/Seed_test.cpp b/src/test/protocol/Seed_test.cpp index d33f397921..d6b200cca8 100644 --- a/src/test/protocol/Seed_test.cpp +++ b/src/test/protocol/Seed_test.cpp @@ -14,11 +14,7 @@ class Seed_test : public beast::unit_test::suite static bool equal(Seed const& lhs, Seed const& rhs) { - return std::equal( - lhs.data(), - lhs.data() + lhs.size(), - rhs.data(), - rhs.data() + rhs.size()); + return std::equal(lhs.data(), lhs.data() + lhs.size(), rhs.data(), rhs.data() + rhs.size()); } public: @@ -62,15 +58,9 @@ public: testPassphrase() { testcase("generation from passphrase"); - BEAST_EXPECT( - testPassphrase("masterpassphrase") == - "snoPBrXtMeMyMHUVTgbuqAfg1SUTb"); - BEAST_EXPECT( - testPassphrase("Non-Random Passphrase") == - "snMKnVku798EnBwUfxeSD8953sLYA"); - BEAST_EXPECT( - testPassphrase("cookies excitement hand public") == - "sspUXGrmjQhq6mgc24jiRuevZiwKT"); + BEAST_EXPECT(testPassphrase("masterpassphrase") == "snoPBrXtMeMyMHUVTgbuqAfg1SUTb"); + BEAST_EXPECT(testPassphrase("Non-Random Passphrase") == "snMKnVku798EnBwUfxeSD8953sLYA"); + BEAST_EXPECT(testPassphrase("cookies excitement hand public") == "sspUXGrmjQhq6mgc24jiRuevZiwKT"); } void @@ -115,20 +105,14 @@ public: { testcase("Node keypair generation & signing (secp256k1)"); - auto const secretKey = generateSecretKey( - KeyType::secp256k1, generateSeed("masterpassphrase")); - auto const publicKey = - derivePublicKey(KeyType::secp256k1, secretKey); + auto const secretKey = generateSecretKey(KeyType::secp256k1, generateSeed("masterpassphrase")); + auto const publicKey = derivePublicKey(KeyType::secp256k1, secretKey); BEAST_EXPECT( - toBase58(TokenType::NodePublic, publicKey) == - "n94a1u4jAz288pZLtw6yFWVbi89YamiC6JBXPVUj5zmExe5fTVg9"); + toBase58(TokenType::NodePublic, publicKey) == "n94a1u4jAz288pZLtw6yFWVbi89YamiC6JBXPVUj5zmExe5fTVg9"); BEAST_EXPECT( - toBase58(TokenType::NodePrivate, secretKey) == - "pnen77YEeUd4fFKG7iycBWcwKpTaeFRkW2WFostaATy1DSupwXe"); - BEAST_EXPECT( - to_string(calcNodeID(publicKey)) == - "7E59C17D50F5959C7B158FEC95C8F815BF653DC8"); + toBase58(TokenType::NodePrivate, secretKey) == "pnen77YEeUd4fFKG7iycBWcwKpTaeFRkW2WFostaATy1DSupwXe"); + BEAST_EXPECT(to_string(calcNodeID(publicKey)) == "7E59C17D50F5959C7B158FEC95C8F815BF653DC8"); auto sig = sign(publicKey, secretKey, makeSlice(message1)); BEAST_EXPECT(sig.size() != 0); @@ -140,9 +124,7 @@ public: // Verify with incorrect public key { auto const otherPublicKey = derivePublicKey( - KeyType::secp256k1, - generateSecretKey( - KeyType::secp256k1, generateSeed("otherpassphrase"))); + KeyType::secp256k1, generateSecretKey(KeyType::secp256k1, generateSeed("otherpassphrase"))); BEAST_EXPECT(!verify(otherPublicKey, makeSlice(message1), sig)); } @@ -160,19 +142,14 @@ public: { testcase("Node keypair generation & signing (ed25519)"); - auto const secretKey = generateSecretKey( - KeyType::ed25519, generateSeed("masterpassphrase")); + auto const secretKey = generateSecretKey(KeyType::ed25519, generateSeed("masterpassphrase")); auto const publicKey = derivePublicKey(KeyType::ed25519, secretKey); BEAST_EXPECT( - toBase58(TokenType::NodePublic, publicKey) == - "nHUeeJCSY2dM71oxM8Cgjouf5ekTuev2mwDpc374aLMxzDLXNmjf"); + toBase58(TokenType::NodePublic, publicKey) == "nHUeeJCSY2dM71oxM8Cgjouf5ekTuev2mwDpc374aLMxzDLXNmjf"); BEAST_EXPECT( - toBase58(TokenType::NodePrivate, secretKey) == - "paKv46LztLqK3GaKz1rG2nQGN6M4JLyRtxFBYFTw4wAVHtGys36"); - BEAST_EXPECT( - to_string(calcNodeID(publicKey)) == - "AA066C988C712815CC37AF71472B7CBBBD4E2A0A"); + toBase58(TokenType::NodePrivate, secretKey) == "paKv46LztLqK3GaKz1rG2nQGN6M4JLyRtxFBYFTw4wAVHtGys36"); + BEAST_EXPECT(to_string(calcNodeID(publicKey)) == "AA066C988C712815CC37AF71472B7CBBBD4E2A0A"); auto sig = sign(publicKey, secretKey, makeSlice(message1)); BEAST_EXPECT(sig.size() != 0); @@ -184,9 +161,7 @@ public: // Verify with incorrect public key { auto const otherPublicKey = derivePublicKey( - KeyType::ed25519, - generateSecretKey( - KeyType::ed25519, generateSeed("otherpassphrase"))); + KeyType::ed25519, generateSecretKey(KeyType::ed25519, generateSeed("otherpassphrase"))); BEAST_EXPECT(!verify(otherPublicKey, makeSlice(message1), sig)); } @@ -204,18 +179,13 @@ public: { testcase("Account keypair generation & signing (secp256k1)"); - auto const [pk, sk] = generateKeyPair( - KeyType::secp256k1, generateSeed("masterpassphrase")); + auto const [pk, sk] = generateKeyPair(KeyType::secp256k1, generateSeed("masterpassphrase")); + BEAST_EXPECT(toBase58(calcAccountID(pk)) == "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"); BEAST_EXPECT( - toBase58(calcAccountID(pk)) == - "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"); + toBase58(TokenType::AccountPublic, pk) == "aBQG8RQAzjs1eTKFEAQXr2gS4utcDiEC9wmi7pfUPTi27VCahwgw"); BEAST_EXPECT( - toBase58(TokenType::AccountPublic, pk) == - "aBQG8RQAzjs1eTKFEAQXr2gS4utcDiEC9wmi7pfUPTi27VCahwgw"); - BEAST_EXPECT( - toBase58(TokenType::AccountSecret, sk) == - "p9JfM6HHi64m6mvB6v5k7G2b1cXzGmYiCNJf6GHPKvFTWdeRVjh"); + toBase58(TokenType::AccountSecret, sk) == "p9JfM6HHi64m6mvB6v5k7G2b1cXzGmYiCNJf6GHPKvFTWdeRVjh"); auto sig = sign(pk, sk, makeSlice(message1)); BEAST_EXPECT(sig.size() != 0); @@ -226,11 +196,9 @@ public: // Verify with incorrect public key { - auto const otherKeyPair = generateKeyPair( - KeyType::secp256k1, generateSeed("otherpassphrase")); + auto const otherKeyPair = generateKeyPair(KeyType::secp256k1, generateSeed("otherpassphrase")); - BEAST_EXPECT( - !verify(otherKeyPair.first, makeSlice(message1), sig)); + BEAST_EXPECT(!verify(otherKeyPair.first, makeSlice(message1), sig)); } // Correct public key but wrong signature @@ -246,18 +214,13 @@ public: { testcase("Account keypair generation & signing (ed25519)"); - auto const [pk, sk] = generateKeyPair( - KeyType::ed25519, generateSeed("masterpassphrase")); + auto const [pk, sk] = generateKeyPair(KeyType::ed25519, generateSeed("masterpassphrase")); + BEAST_EXPECT(to_string(calcAccountID(pk)) == "rGWrZyQqhTp9Xu7G5Pkayo7bXjH4k4QYpf"); BEAST_EXPECT( - to_string(calcAccountID(pk)) == - "rGWrZyQqhTp9Xu7G5Pkayo7bXjH4k4QYpf"); + toBase58(TokenType::AccountPublic, pk) == "aKGheSBjmCsKJVuLNKRAKpZXT6wpk2FCuEZAXJupXgdAxX5THCqR"); BEAST_EXPECT( - toBase58(TokenType::AccountPublic, pk) == - "aKGheSBjmCsKJVuLNKRAKpZXT6wpk2FCuEZAXJupXgdAxX5THCqR"); - BEAST_EXPECT( - toBase58(TokenType::AccountSecret, sk) == - "pwDQjwEhbUBmPuEjFpEG75bFhv2obkCB7NxQsfFxM7xGHBMVPu9"); + toBase58(TokenType::AccountSecret, sk) == "pwDQjwEhbUBmPuEjFpEG75bFhv2obkCB7NxQsfFxM7xGHBMVPu9"); auto sig = sign(pk, sk, makeSlice(message1)); BEAST_EXPECT(sig.size() != 0); @@ -268,11 +231,9 @@ public: // Verify with incorrect public key { - auto const otherKeyPair = generateKeyPair( - KeyType::ed25519, generateSeed("otherpassphrase")); + auto const otherKeyPair = generateKeyPair(KeyType::ed25519, generateSeed("otherpassphrase")); - BEAST_EXPECT( - !verify(otherKeyPair.first, makeSlice(message1), sig)); + BEAST_EXPECT(!verify(otherKeyPair.first, makeSlice(message1), sig)); } // Correct public key but wrong signature @@ -296,35 +257,25 @@ public: auto const node1 = randomKeyPair(KeyType::secp256k1); - BEAST_EXPECT( - !parseGenericSeed(toBase58(TokenType::NodePublic, node1.first))); - BEAST_EXPECT( - !parseGenericSeed(toBase58(TokenType::NodePrivate, node1.second))); + BEAST_EXPECT(!parseGenericSeed(toBase58(TokenType::NodePublic, node1.first))); + BEAST_EXPECT(!parseGenericSeed(toBase58(TokenType::NodePrivate, node1.second))); auto const node2 = randomKeyPair(KeyType::ed25519); - BEAST_EXPECT( - !parseGenericSeed(toBase58(TokenType::NodePublic, node2.first))); - BEAST_EXPECT( - !parseGenericSeed(toBase58(TokenType::NodePrivate, node2.second))); + BEAST_EXPECT(!parseGenericSeed(toBase58(TokenType::NodePublic, node2.first))); + BEAST_EXPECT(!parseGenericSeed(toBase58(TokenType::NodePrivate, node2.second))); auto const account1 = generateKeyPair(KeyType::secp256k1, randomSeed()); - BEAST_EXPECT( - !parseGenericSeed(toBase58(calcAccountID(account1.first)))); - BEAST_EXPECT(!parseGenericSeed( - toBase58(TokenType::AccountPublic, account1.first))); - BEAST_EXPECT(!parseGenericSeed( - toBase58(TokenType::AccountSecret, account1.second))); + BEAST_EXPECT(!parseGenericSeed(toBase58(calcAccountID(account1.first)))); + BEAST_EXPECT(!parseGenericSeed(toBase58(TokenType::AccountPublic, account1.first))); + BEAST_EXPECT(!parseGenericSeed(toBase58(TokenType::AccountSecret, account1.second))); auto const account2 = generateKeyPair(KeyType::ed25519, randomSeed()); - BEAST_EXPECT( - !parseGenericSeed(toBase58(calcAccountID(account2.first)))); - BEAST_EXPECT(!parseGenericSeed( - toBase58(TokenType::AccountPublic, account2.first))); - BEAST_EXPECT(!parseGenericSeed( - toBase58(TokenType::AccountSecret, account2.second))); + BEAST_EXPECT(!parseGenericSeed(toBase58(calcAccountID(account2.first)))); + BEAST_EXPECT(!parseGenericSeed(toBase58(TokenType::AccountPublic, account2.first))); + BEAST_EXPECT(!parseGenericSeed(toBase58(TokenType::AccountSecret, account2.second))); } void diff --git a/src/test/protocol/SeqProxy_test.cpp b/src/test/protocol/SeqProxy_test.cpp index d922dd1182..0e91680c8c 100644 --- a/src/test/protocol/SeqProxy_test.cpp +++ b/src/test/protocol/SeqProxy_test.cpp @@ -13,32 +13,28 @@ struct SeqProxy_test : public beast::unit_test::suite expectValues(SeqProxy seqProx, std::uint32_t value, SeqProxy::Type type) { bool const expectSeq{type == SeqProxy::seq}; - return (seqProx.value() == value) && (seqProx.isSeq() == expectSeq) && - (seqProx.isTicket() == !expectSeq); + return (seqProx.value() == value) && (seqProx.isSeq() == expectSeq) && (seqProx.isTicket() == !expectSeq); } // Exercise all SeqProxy comparison operators expecting lhs < rhs. static constexpr bool expectLt(SeqProxy lhs, SeqProxy rhs) { - return (lhs < rhs) && (lhs <= rhs) && (!(lhs == rhs)) && (lhs != rhs) && - (!(lhs >= rhs)) && (!(lhs > rhs)); + return (lhs < rhs) && (lhs <= rhs) && (!(lhs == rhs)) && (lhs != rhs) && (!(lhs >= rhs)) && (!(lhs > rhs)); } // Exercise all SeqProxy comparison operators expecting lhs == rhs. static constexpr bool expectEq(SeqProxy lhs, SeqProxy rhs) { - return (!(lhs < rhs)) && (lhs <= rhs) && (lhs == rhs) && - (!(lhs != rhs)) && (lhs >= rhs) && (!(lhs > rhs)); + return (!(lhs < rhs)) && (lhs <= rhs) && (lhs == rhs) && (!(lhs != rhs)) && (lhs >= rhs) && (!(lhs > rhs)); } // Exercise all SeqProxy comparison operators expecting lhs > rhs. static constexpr bool expectGt(SeqProxy lhs, SeqProxy rhs) { - return (!(lhs < rhs)) && (!(lhs <= rhs)) && (!(lhs == rhs)) && - (lhs != rhs) && (lhs >= rhs) && (lhs > rhs); + return (!(lhs < rhs)) && (!(lhs <= rhs)) && (!(lhs == rhs)) && (lhs != rhs) && (lhs >= rhs) && (lhs > rhs); } // Verify streaming. @@ -52,8 +48,7 @@ struct SeqProxy_test : public beast::unit_test::suite ss << seqProx; std::string str{ss.str()}; - return str.find(type) == 0 && str[type.size()] == ' ' && - str.find(value) == (type.size() + 1); + return str.find(type) == 0 && str[type.size()] == ' ' && str.find(value) == (type.size() + 1); } void @@ -62,8 +57,7 @@ struct SeqProxy_test : public beast::unit_test::suite // While SeqProxy supports values of zero, they are not // expected in the wild. Nevertheless they are tested here. // But so are values of 1, which are expected to occur in the wild. - static constexpr std::uint32_t uintMax{ - std::numeric_limits::max()}; + static constexpr std::uint32_t uintMax{std::numeric_limits::max()}; static constexpr SeqProxy::Type seq{SeqProxy::seq}; static constexpr SeqProxy::Type ticket{SeqProxy::ticket}; diff --git a/src/test/protocol/Serializer_test.cpp b/src/test/protocol/Serializer_test.cpp index c5b56c3029..cd34446fa8 100644 --- a/src/test/protocol/Serializer_test.cpp +++ b/src/test/protocol/Serializer_test.cpp @@ -12,11 +12,7 @@ struct Serializer_test : public beast::unit_test::suite { { std::initializer_list const values = { - std::numeric_limits::min(), - -1, - 0, - 1, - std::numeric_limits::max()}; + std::numeric_limits::min(), -1, 0, 1, std::numeric_limits::max()}; for (std::int32_t value : values) { Serializer s; @@ -28,11 +24,7 @@ struct Serializer_test : public beast::unit_test::suite } { std::initializer_list const values = { - std::numeric_limits::min(), - -1, - 0, - 1, - std::numeric_limits::max()}; + std::numeric_limits::min(), -1, 0, 1, std::numeric_limits::max()}; for (std::int64_t value : values) { Serializer s; diff --git a/src/test/protocol/TER_test.cpp b/src/test/protocol/TER_test.cpp index 56b3b08051..6dce46ed6b 100644 --- a/src/test/protocol/TER_test.cpp +++ b/src/test/protocol/TER_test.cpp @@ -14,8 +14,7 @@ struct TER_test : public beast::unit_test::suite for (auto i = -400; i < 400; ++i) { TER t = TER::fromInt(i); - auto inRange = isTelLocal(t) || isTemMalformed(t) || - isTefFailure(t) || isTerRetry(t) || isTesSuccess(t) || + auto inRange = isTelLocal(t) || isTemMalformed(t) || isTefFailure(t) || isTerRetry(t) || isTesSuccess(t) || isTecClaim(t); std::string token, text; @@ -49,36 +48,21 @@ struct TER_test : public beast::unit_test::suite // unless they are the same types. using To_t = std::decay_t(tup))>; using From_t = std::decay_t(tup))>; + static_assert(std::is_same::value == std::is_convertible::value, "Convert err"); static_assert( - std::is_same::value == - std::is_convertible::value, - "Convert err"); + std::is_same::value == std::is_constructible::value, "Construct err"); static_assert( - std::is_same::value == - std::is_constructible::value, - "Construct err"); - static_assert( - std::is_same::value == - std::is_assignable::value, - "Assign err"); + std::is_same::value == std::is_assignable::value, "Assign err"); // Assignment or conversion from integer to type should never work. - static_assert( - !std::is_convertible::value, "Convert err"); - static_assert( - !std::is_constructible::value, "Construct err"); - static_assert( - !std::is_assignable::value, "Assign err"); + static_assert(!std::is_convertible::value, "Convert err"); + static_assert(!std::is_constructible::value, "Construct err"); + static_assert(!std::is_assignable::value, "Assign err"); } }; // Fast iteration over the tuple. - template < - std::size_t I1, - std::size_t I2, - template - class Func, - typename Tup> + template class Func, typename Tup> std::enable_if_t testIterate(Tup const& tup, beast::unit_test::suite& s) { @@ -88,12 +72,7 @@ struct TER_test : public beast::unit_test::suite } // Slow iteration over the tuple. - template < - std::size_t I1, - std::size_t I2, - template - class Func, - typename Tup> + template class Func, typename Tup> std::enable_if_t testIterate(Tup const& tup, beast::unit_test::suite& s) { @@ -103,12 +82,7 @@ struct TER_test : public beast::unit_test::suite } // Finish iteration over the tuple. - template < - std::size_t I1, - std::size_t I2, - template - class Func, - typename Tup> + template class Func, typename Tup> std::enable_if_t testIterate(Tup const& tup, beast::unit_test::suite& s) { @@ -123,15 +97,9 @@ struct TER_test : public beast::unit_test::suite // are not valid. // Examples of each kind of enum. - static auto const terEnums = std::make_tuple( - telLOCAL_ERROR, - temMALFORMED, - tefFAILURE, - terRETRY, - tesSUCCESS, - tecCLAIM); - static int const hiIndex{ - std::tuple_size::value - 1}; + static auto const terEnums = + std::make_tuple(telLOCAL_ERROR, temMALFORMED, tefFAILURE, terRETRY, tesSUCCESS, tecCLAIM); + static int const hiIndex{std::tuple_size::value - 1}; // Verify that enums cannot be converted to other enum types. testIterate(terEnums, *this); @@ -140,12 +108,9 @@ struct TER_test : public beast::unit_test::suite auto isConvertible = [](auto from, auto to) { using From_t = std::decay_t; using To_t = std::decay_t; - static_assert( - std::is_convertible::value, "Convert err"); - static_assert( - std::is_constructible::value, "Construct err"); - static_assert( - std::is_assignable::value, "Assign err"); + static_assert(std::is_convertible::value, "Convert err"); + static_assert(std::is_constructible::value, "Construct err"); + static_assert(std::is_assignable::value, "Assign err"); }; // Verify the right types convert to NotTEC. @@ -161,12 +126,9 @@ struct TER_test : public beast::unit_test::suite auto notConvertible = [](auto from, auto to) { using To_t = std::decay_t; using From_t = std::decay_t; - static_assert( - !std::is_convertible::value, "Convert err"); - static_assert( - !std::is_constructible::value, "Construct err"); - static_assert( - !std::is_assignable::value, "Assign err"); + static_assert(!std::is_convertible::value, "Convert err"); + static_assert(!std::is_constructible::value, "Construct err"); + static_assert(!std::is_assignable::value, "Assign err"); }; // Verify types that shouldn't convert to NotTEC. @@ -208,29 +170,17 @@ struct TER_test : public beast::unit_test::suite auto const lhs = std::get(tup); auto const rhs = std::get(tup); - static_assert( - std::is_same::value, - "== err"); + static_assert(std::is_same::value, "== err"); - static_assert( - std::is_same::value, - "!= err"); + static_assert(std::is_same::value, "!= err"); - static_assert( - std::is_same::value, - "< err"); + static_assert(std::is_same::value, "< err"); - static_assert( - std::is_same::value, - "<= err"); + static_assert(std::is_same::value, "<= err"); - static_assert( - std::is_same(lhs, rhs)), bool>::value, - "> err"); + static_assert(std::is_same(lhs, rhs)), bool>::value, "> err"); - static_assert( - std::is_same=(lhs, rhs)), bool>::value, - ">= err"); + static_assert(std::is_same=(lhs, rhs)), bool>::value, ">= err"); // Make sure a sampling of TER types exhibit the expected behavior // for all comparison operators. diff --git a/src/test/resource/Logic_test.cpp b/src/test/resource/Logic_test.cpp index 0e520d4983..f3e44e8b32 100644 --- a/src/test/resource/Logic_test.cpp +++ b/src/test/resource/Logic_test.cpp @@ -17,16 +17,14 @@ namespace Resource { class ResourceManager_test : public beast::unit_test::suite { public: - class TestLogic : private boost::base_from_member, - public Logic + class TestLogic : private boost::base_from_member, public Logic { private: using clock_type = boost::base_from_member; public: - explicit TestLogic(beast::Journal journal) - : Logic(beast::insight::NullCollector::New(), member, journal) + explicit TestLogic(beast::Journal journal) : Logic(beast::insight::NullCollector::New(), member, journal) { } @@ -55,8 +53,7 @@ public: { Gossip::Item item; item.balance = 100 + rand_int(499); - beast::IP::AddressV4::bytes_type d = { - {192, 0, 2, static_cast(v + i)}}; + beast::IP::AddressV4::bytes_type d = {{192, 0, 2, static_cast(v + i)}}; item.address = beast::IP::Endpoint{beast::IP::AddressV4{d}}; gossip.items.push_back(item); } @@ -75,16 +72,11 @@ public: TestLogic logic(j); Charge const fee(dropThreshold + 1); - beast::IP::Endpoint const addr( - beast::IP::Endpoint::from_string("192.0.2.2")); + beast::IP::Endpoint const addr(beast::IP::Endpoint::from_string("192.0.2.2")); std::function ep = limited - ? std::bind( - &TestLogic::newInboundEndpoint, &logic, std::placeholders::_1) - : std::bind( - &TestLogic::newUnlimitedEndpoint, - &logic, - std::placeholders::_1); + ? std::bind(&TestLogic::newInboundEndpoint, &logic, std::placeholders::_1) + : std::bind(&TestLogic::newUnlimitedEndpoint, &logic, std::placeholders::_1); { Consumer c(ep(addr)); @@ -222,34 +214,28 @@ public: TestLogic logic(j); { - beast::IP::Endpoint address( - beast::IP::Endpoint::from_string("192.0.2.1")); + beast::IP::Endpoint address(beast::IP::Endpoint::from_string("192.0.2.1")); Consumer c(logic.newInboundEndpoint(address)); Charge fee(1000); - JLOG(j.info()) << "Charging " << c.to_string() << " " << fee - << " per second"; + JLOG(j.info()) << "Charging " << c.to_string() << " " << fee << " per second"; c.charge(fee); for (int i = 0; i < 128; ++i) { - JLOG(j.info()) << "Time= " - << logic.clock().now().time_since_epoch().count() + JLOG(j.info()) << "Time= " << logic.clock().now().time_since_epoch().count() << ", Balance = " << c.balance(); logic.advance(); } } { - beast::IP::Endpoint address( - beast::IP::Endpoint::from_string("192.0.2.2")); + beast::IP::Endpoint address(beast::IP::Endpoint::from_string("192.0.2.2")); Consumer c(logic.newInboundEndpoint(address)); Charge fee(1000); - JLOG(j.info()) << "Charging " << c.to_string() << " " << fee - << " per second"; + JLOG(j.info()) << "Charging " << c.to_string() << " " << fee << " per second"; for (int i = 0; i < 128; ++i) { c.charge(fee); - JLOG(j.info()) << "Time= " - << logic.clock().now().time_since_epoch().count() + JLOG(j.info()) << "Time= " << logic.clock().now().time_since_epoch().count() << ", Balance = " << c.balance(); logic.advance(); } diff --git a/src/test/rpc/AMMInfo_test.cpp b/src/test/rpc/AMMInfo_test.cpp index c76fa15eb7..cf515d7c84 100644 --- a/src/test/rpc/AMMInfo_test.cpp +++ b/src/test/rpc/AMMInfo_test.cpp @@ -21,8 +21,7 @@ public: Account const bogie("bogie"); enum TestAccount { None, Alice, Bogie }; - auto accountId = [&](AMM const& ammAlice, - TestAccount v) -> std::optional { + auto accountId = [&](AMM const& ammAlice, TestAccount v) -> std::optional { if (v == Alice) return ammAlice.ammAccount(); else if (v == Bogie) @@ -35,8 +34,7 @@ public: testAMM([&](AMM& ammAlice, Env&) { Account const gw("gw"); auto const USD = gw["USD"]; - auto const jv = - ammAlice.ammRpcInfo({}, {}, USD.issue(), USD.issue()); + auto const jv = ammAlice.ammRpcInfo({}, {}, USD.issue(), USD.issue()); BEAST_EXPECT(jv[jss::error_message] == "Account not found."); }); @@ -46,11 +44,7 @@ public: BEAST_EXPECT(jv[jss::error_message] == "Account malformed."); }); - std::vector, - std::optional, - TestAccount, - bool>> const invalidParams = { + std::vector, std::optional, TestAccount, bool>> const invalidParams = { {xrpIssue(), std::nullopt, None, false}, {std::nullopt, USD.issue(), None, false}, {xrpIssue(), std::nullopt, Alice, false}, @@ -63,12 +57,7 @@ public: for (auto const& [iss1, iss2, acct, ignoreParams] : invalidParams) { auto const jv = ammAlice.ammRpcInfo( - std::nullopt, - std::nullopt, - iss1, - iss2, - accountId(ammAlice, acct), - ignoreParams); + std::nullopt, std::nullopt, iss1, iss2, accountId(ammAlice, acct), ignoreParams); BEAST_EXPECT(jv[jss::error_message] == "Invalid parameters."); } }); @@ -106,60 +95,38 @@ public: // Invalid AMM account id testAMM([&](AMM& ammAlice, Env&) { - auto const jv = ammAlice.ammRpcInfo( - std::nullopt, - std::nullopt, - std::nullopt, - std::nullopt, - bogie.id()); + auto const jv = ammAlice.ammRpcInfo(std::nullopt, std::nullopt, std::nullopt, std::nullopt, bogie.id()); BEAST_EXPECT(jv[jss::error_message] == "Account malformed."); }); - std::vector, - std::optional, - TestAccount, - bool>> const invalidParamsBadAccount = { - {xrpIssue(), std::nullopt, None, false}, - {std::nullopt, USD.issue(), None, false}, - {xrpIssue(), std::nullopt, Bogie, false}, - {std::nullopt, USD.issue(), Bogie, false}, - {xrpIssue(), USD.issue(), Bogie, false}, - {std::nullopt, std::nullopt, None, true}}; + std::vector, std::optional, TestAccount, bool>> const + invalidParamsBadAccount = { + {xrpIssue(), std::nullopt, None, false}, + {std::nullopt, USD.issue(), None, false}, + {xrpIssue(), std::nullopt, Bogie, false}, + {std::nullopt, USD.issue(), Bogie, false}, + {xrpIssue(), USD.issue(), Bogie, false}, + {std::nullopt, std::nullopt, None, true}}; // Invalid parameters *and* invalid AMM account, default API version testAMM([&](AMM& ammAlice, Env&) { - for (auto const& [iss1, iss2, acct, ignoreParams] : - invalidParamsBadAccount) + for (auto const& [iss1, iss2, acct, ignoreParams] : invalidParamsBadAccount) { auto const jv = ammAlice.ammRpcInfo( - std::nullopt, - std::nullopt, - iss1, - iss2, - accountId(ammAlice, acct), - ignoreParams); + std::nullopt, std::nullopt, iss1, iss2, accountId(ammAlice, acct), ignoreParams); BEAST_EXPECT(jv[jss::error_message] == "Invalid parameters."); } }); // Invalid parameters *and* invalid AMM account, API version 3 testAMM([&](AMM& ammAlice, Env&) { - for (auto const& [iss1, iss2, acct, ignoreParams] : - invalidParamsBadAccount) + for (auto const& [iss1, iss2, acct, ignoreParams] : invalidParamsBadAccount) { auto const jv = ammAlice.ammRpcInfo( - std::nullopt, - std::nullopt, - iss1, - iss2, - accountId(ammAlice, acct), - ignoreParams, - 3); + std::nullopt, std::nullopt, iss1, iss2, accountId(ammAlice, acct), ignoreParams, 3); BEAST_EXPECT( jv[jss::error_message] == - (acct == Bogie ? std::string("Account malformed.") - : std::string("Invalid parameters."))); + (acct == Bogie ? std::string("Account malformed.") : std::string("Invalid parameters."))); } }); } @@ -171,15 +138,9 @@ public: using namespace jtx; testAMM([&](AMM& ammAlice, Env&) { + BEAST_EXPECT(ammAlice.expectAmmRpcInfo(XRP(10000), USD(10000), IOUAmount{10000000, 0})); BEAST_EXPECT(ammAlice.expectAmmRpcInfo( - XRP(10000), USD(10000), IOUAmount{10000000, 0})); - BEAST_EXPECT(ammAlice.expectAmmRpcInfo( - XRP(10000), - USD(10000), - IOUAmount{10000000, 0}, - std::nullopt, - std::nullopt, - ammAlice.ammAccount())); + XRP(10000), USD(10000), IOUAmount{10000000, 0}, std::nullopt, std::nullopt, ammAlice.ammAccount())); }); } @@ -191,8 +152,7 @@ public: using namespace jtx; testAMM( [&](AMM& ammAlice, Env& env) { - BEAST_EXPECT(ammAlice.expectAmmRpcInfo( - XRP(10000), USD(10000), IOUAmount{10000000, 0})); + BEAST_EXPECT(ammAlice.expectAmmRpcInfo(XRP(10000), USD(10000), IOUAmount{10000000, 0})); std::unordered_map votes; votes.insert({alice.human(), 0}); for (int i = 0; i < 7; ++i) @@ -210,8 +170,7 @@ public: Account ed("ed"); Account bill("bill"); env.fund(XRP(1000), bob, ed, bill); - env(ammAlice.bid( - {.bidMin = 100, .authAccounts = {carol, bob, ed, bill}})); + env(ammAlice.bid({.bidMin = 100, .authAccounts = {carol, bob, ed, bill}})); if (!features[fixAMMv1_3]) BEAST_EXPECT(ammAlice.expectAmmRpcInfo( XRP(80000), @@ -232,13 +191,10 @@ public: { std::unordered_set authAccounts = { carol.human(), bob.human(), ed.human(), bill.human()}; - auto const ammInfo = i ? ammAlice.ammRpcInfo() - : ammAlice.ammRpcInfo( - std::nullopt, - std::nullopt, - std::nullopt, - std::nullopt, - ammAlice.ammAccount()); + auto const ammInfo = i + ? ammAlice.ammRpcInfo() + : ammAlice.ammRpcInfo( + std::nullopt, std::nullopt, std::nullopt, std::nullopt, ammAlice.ammAccount()); auto const& amm = ammInfo[jss::amm]; try { @@ -248,12 +204,9 @@ public: for (std::uint8_t i = 0; i < 8; ++i) { if (!BEAST_EXPECT( - votes[voteSlots[i][jss::account] - .asString()] == - voteSlots[i][jss::trading_fee] - .asUInt() && - voteSlots[i][jss::vote_weight].asUInt() == - 12500)) + votes[voteSlots[i][jss::account].asString()] == + voteSlots[i][jss::trading_fee].asUInt() && + voteSlots[i][jss::vote_weight].asUInt() == 12500)) return; votes.erase(voteSlots[i][jss::account].asString()); } @@ -265,27 +218,20 @@ public: auto const auctionSlot = amm[jss::auction_slot]; for (std::uint8_t i = 0; i < 4; ++i) { - if (!BEAST_EXPECT(authAccounts.contains( - auctionSlot[jss::auth_accounts][i] - [jss::account] - .asString()))) + if (!BEAST_EXPECT( + authAccounts.contains(auctionSlot[jss::auth_accounts][i][jss::account].asString()))) return; - authAccounts.erase( - auctionSlot[jss::auth_accounts][i][jss::account] - .asString()); + authAccounts.erase(auctionSlot[jss::auth_accounts][i][jss::account].asString()); } if (!BEAST_EXPECT(authAccounts.empty())) return; BEAST_EXPECT( - auctionSlot[jss::account].asString() == - alice.human() && + auctionSlot[jss::account].asString() == alice.human() && auctionSlot[jss::discounted_fee].asUInt() == 17 && - auctionSlot[jss::price][jss::value].asString() == - "5600" && + auctionSlot[jss::price][jss::value].asString() == "5600" && auctionSlot[jss::price][jss::currency].asString() == to_string(ammAlice.lptIssue().currency) && - auctionSlot[jss::price][jss::issuer].asString() == - to_string(ammAlice.lptIssue().account)); + auctionSlot[jss::price][jss::issuer].asString() == to_string(ammAlice.lptIssue().account)); } catch (std::exception const& e) { @@ -308,8 +254,7 @@ public: env.close(); auto test = [&](bool freeze) { auto const info = ammAlice.ammRpcInfo(); - BEAST_EXPECT( - info[jss::amm][jss::asset2_frozen].asBool() == freeze); + BEAST_EXPECT(info[jss::amm][jss::asset2_frozen].asBool() == freeze); }; test(true); env(fclear(gw, asfGlobalFreeze)); @@ -325,14 +270,8 @@ public: testcase("Invalid amm field"); testAMM([&](AMM& amm, Env&) { - auto const resp = amm.ammRpcInfo( - std::nullopt, - jss::validated.c_str(), - std::nullopt, - std::nullopt, - gw); - BEAST_EXPECT( - resp.isMember("error") && resp["error"] == "actNotFound"); + auto const resp = amm.ammRpcInfo(std::nullopt, jss::validated.c_str(), std::nullopt, std::nullopt, gw); + BEAST_EXPECT(resp.isMember("error") && resp["error"] == "actNotFound"); }); } diff --git a/src/test/rpc/AccountCurrencies_test.cpp b/src/test/rpc/AccountCurrencies_test.cpp index b1417735be..f467b50adc 100644 --- a/src/test/rpc/AccountCurrencies_test.cpp +++ b/src/test/rpc/AccountCurrencies_test.cpp @@ -23,20 +23,15 @@ class AccountCurrencies_test : public beast::unit_test::suite Json::Value params; params[jss::account] = Account{"bob"}.human(); params[jss::ledger_hash] = 1; - auto const result = env.rpc( - "json", "account_currencies", to_string(params))[jss::result]; + auto const result = env.rpc("json", "account_currencies", to_string(params))[jss::result]; BEAST_EXPECT(result[jss::error] == "invalidParams"); - BEAST_EXPECT( - result[jss::error_message] == - "Invalid field 'ledger_hash', not hex string."); + BEAST_EXPECT(result[jss::error_message] == "Invalid field 'ledger_hash', not hex string."); } { // missing account field - auto const result = - env.rpc("json", "account_currencies", "{}")[jss::result]; + auto const result = env.rpc("json", "account_currencies", "{}")[jss::result]; BEAST_EXPECT(result[jss::error] == "invalidParams"); - BEAST_EXPECT( - result[jss::error_message] == "Missing field 'account'."); + BEAST_EXPECT(result[jss::error_message] == "Missing field 'account'."); } { @@ -44,13 +39,9 @@ class AccountCurrencies_test : public beast::unit_test::suite auto testInvalidAccountParam = [&](auto const& param) { Json::Value params; params[jss::account] = param; - auto jrr = env.rpc( - "json", - "account_currencies", - to_string(params))[jss::result]; + auto jrr = env.rpc("json", "account_currencies", to_string(params))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); - BEAST_EXPECT( - jrr[jss::error_message] == "Invalid field 'account'."); + BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'account'."); }; testInvalidAccountParam(1); @@ -66,13 +57,9 @@ class AccountCurrencies_test : public beast::unit_test::suite auto testInvalidIdentParam = [&](auto const& param) { Json::Value params; params[jss::ident] = param; - auto jrr = env.rpc( - "json", - "account_currencies", - to_string(params))[jss::result]; + auto jrr = env.rpc("json", "account_currencies", to_string(params))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); - BEAST_EXPECT( - jrr[jss::error_message] == "Invalid field 'ident'."); + BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'ident'."); }; testInvalidIdentParam(1); @@ -85,10 +72,8 @@ class AccountCurrencies_test : public beast::unit_test::suite { Json::Value params; - params[jss::account] = - "llIIOO"; // these are invalid in bitcoin alphabet - auto const result = env.rpc( - "json", "account_currencies", to_string(params))[jss::result]; + params[jss::account] = "llIIOO"; // these are invalid in bitcoin alphabet + auto const result = env.rpc("json", "account_currencies", to_string(params))[jss::result]; BEAST_EXPECT(result[jss::error] == "actMalformed"); BEAST_EXPECT(result[jss::error_message] == "Account malformed."); } @@ -97,8 +82,7 @@ class AccountCurrencies_test : public beast::unit_test::suite // Cannot use a seed as account Json::Value params; params[jss::account] = "Bob"; - auto const result = env.rpc( - "json", "account_currencies", to_string(params))[jss::result]; + auto const result = env.rpc("json", "account_currencies", to_string(params))[jss::result]; BEAST_EXPECT(result[jss::error] == "actMalformed"); BEAST_EXPECT(result[jss::error_message] == "Account malformed."); } @@ -106,8 +90,7 @@ class AccountCurrencies_test : public beast::unit_test::suite { // ask for nonexistent account Json::Value params; params[jss::account] = Account{"bob"}.human(); - auto const result = env.rpc( - "json", "account_currencies", to_string(params))[jss::result]; + auto const result = env.rpc("json", "account_currencies", to_string(params))[jss::result]; BEAST_EXPECT(result[jss::error] == "actNotFound"); BEAST_EXPECT(result[jss::error_message] == "Account not found."); } @@ -135,20 +118,14 @@ class AccountCurrencies_test : public beast::unit_test::suite Json::Value params; params[jss::account] = alice.human(); - auto result = env.rpc( - "json", "account_currencies", to_string(params))[jss::result]; + auto result = env.rpc("json", "account_currencies", to_string(params))[jss::result]; - auto arrayCheck = - [&result]( - Json::StaticString const& fld, - std::vector> const& expected) -> bool { - bool stat = result.isMember(fld) && result[fld].isArray() && - result[fld].size() == expected.size(); + auto arrayCheck = [&result]( + Json::StaticString const& fld, std::vector> const& expected) -> bool { + bool stat = result.isMember(fld) && result[fld].isArray() && result[fld].size() == expected.size(); for (size_t i = 0; stat && i < expected.size(); ++i) { - stat &= - (to_string(expected[i].value().currency) == - result[fld][i].asString()); + stat &= (to_string(expected[i].value().currency) == result[fld][i].asString()); } return stat; }; @@ -161,8 +138,7 @@ class AccountCurrencies_test : public beast::unit_test::suite env(pay(gw, alice, c.value()(50))); // send_currencies should be populated now - result = env.rpc( - "json", "account_currencies", to_string(params))[jss::result]; + result = env.rpc("json", "account_currencies", to_string(params))[jss::result]; BEAST_EXPECT(arrayCheck(jss::receive_currencies, gwCurrencies)); BEAST_EXPECT(arrayCheck(jss::send_currencies, gwCurrencies)); @@ -171,10 +147,8 @@ class AccountCurrencies_test : public beast::unit_test::suite env(trust(alice, gw["USD"](100), tfSetFreeze)); result = env.rpc("account_lines", alice.human()); for (auto const& l : result[jss::lines]) - BEAST_EXPECT( - l[jss::freeze].asBool() == (l[jss::currency] == "USD")); - result = env.rpc( - "json", "account_currencies", to_string(params))[jss::result]; + BEAST_EXPECT(l[jss::freeze].asBool() == (l[jss::currency] == "USD")); + result = env.rpc("json", "account_currencies", to_string(params))[jss::result]; BEAST_EXPECT(arrayCheck(jss::receive_currencies, gwCurrencies)); BEAST_EXPECT(arrayCheck(jss::send_currencies, gwCurrencies)); // clear the freeze @@ -183,10 +157,8 @@ class AccountCurrencies_test : public beast::unit_test::suite // make a payment that exhausts the trustline from alice to gw for USA env(pay(gw, alice, gw["USA"](50))); // USA should now be missing from receive_currencies - result = env.rpc( - "json", "account_currencies", to_string(params))[jss::result]; - decltype(gwCurrencies) gwCurrenciesNoUSA( - gwCurrencies.begin() + 1, gwCurrencies.end()); + result = env.rpc("json", "account_currencies", to_string(params))[jss::result]; + decltype(gwCurrencies) gwCurrenciesNoUSA(gwCurrencies.begin() + 1, gwCurrencies.end()); BEAST_EXPECT(arrayCheck(jss::receive_currencies, gwCurrenciesNoUSA)); BEAST_EXPECT(arrayCheck(jss::send_currencies, gwCurrencies)); @@ -194,8 +166,7 @@ class AccountCurrencies_test : public beast::unit_test::suite // so that send_currencies for alice will now omit USA env(trust(gw, alice["USA"](100))); env(pay(alice, gw, alice["USA"](200))); - result = env.rpc( - "json", "account_currencies", to_string(params))[jss::result]; + result = env.rpc("json", "account_currencies", to_string(params))[jss::result]; BEAST_EXPECT(arrayCheck(jss::receive_currencies, gwCurrencies)); BEAST_EXPECT(arrayCheck(jss::send_currencies, gwCurrenciesNoUSA)); } diff --git a/src/test/rpc/AccountInfo_test.cpp b/src/test/rpc/AccountInfo_test.cpp index 6370884124..bdc8e63e3d 100644 --- a/src/test/rpc/AccountInfo_test.cpp +++ b/src/test/rpc/AccountInfo_test.cpp @@ -20,9 +20,7 @@ public: { // account_info with no account. auto const info = env.rpc("json", "account_info", "{ }"); - BEAST_EXPECT( - info[jss::result][jss::error_message] == - "Missing field 'account'."); + BEAST_EXPECT(info[jss::result][jss::error_message] == "Missing field 'account'."); } { // account_info with a malformed account string. @@ -31,31 +29,23 @@ public: "account_info", "{\"account\": " "\"n94JNrQYkDrpt62bbSR7nVEhdyAvcJXRAsjEkFYyqRkh9SUTYEqV\"}"); - BEAST_EXPECT( - info[jss::result][jss::error_code] == rpcACT_MALFORMED); - BEAST_EXPECT( - info[jss::result][jss::error_message] == "Account malformed."); + BEAST_EXPECT(info[jss::result][jss::error_code] == rpcACT_MALFORMED); + BEAST_EXPECT(info[jss::result][jss::error_message] == "Account malformed."); } { // account_info with an account that's not in the ledger. Account const bogie{"bogie"}; Json::Value params; params[jss::account] = bogie.human(); - auto const info = - env.rpc("json", "account_info", to_string(params)); - BEAST_EXPECT( - info[jss::result][jss::error_code] == rpcACT_NOT_FOUND); - BEAST_EXPECT( - info[jss::result][jss::error_message] == "Account not found."); + auto const info = env.rpc("json", "account_info", to_string(params)); + BEAST_EXPECT(info[jss::result][jss::error_code] == rpcACT_NOT_FOUND); + BEAST_EXPECT(info[jss::result][jss::error_message] == "Account not found."); } { // Cannot use a seed as account - auto const info = - env.rpc("json", "account_info", R"({"account": "foo"})"); - BEAST_EXPECT( - info[jss::result][jss::error_code] == rpcACT_MALFORMED); - BEAST_EXPECT( - info[jss::result][jss::error_message] == "Account malformed."); + auto const info = env.rpc("json", "account_info", R"({"account": "foo"})"); + BEAST_EXPECT(info[jss::result][jss::error_code] == rpcACT_MALFORMED); + BEAST_EXPECT(info[jss::result][jss::error_message] == "Account malformed."); } { // Cannot pass a non-string into the `account` param @@ -63,11 +53,9 @@ public: auto testInvalidAccountParam = [&](auto const& param) { Json::Value params; params[jss::account] = param; - auto jrr = env.rpc( - "json", "account_info", to_string(params))[jss::result]; + auto jrr = env.rpc("json", "account_info", to_string(params))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); - BEAST_EXPECT( - jrr[jss::error_message] == "Invalid field 'account'."); + BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'account'."); }; testInvalidAccountParam(1); @@ -83,11 +71,9 @@ public: auto testInvalidIdentParam = [&](auto const& param) { Json::Value params; params[jss::ident] = param; - auto jrr = env.rpc( - "json", "account_info", to_string(params))[jss::result]; + auto jrr = env.rpc("json", "account_info", to_string(params))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); - BEAST_EXPECT( - jrr[jss::error_message] == "Invalid field 'ident'."); + BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'ident'."); }; testInvalidIdentParam(1); @@ -119,21 +105,14 @@ public: // Alice has no SignerList yet. { // account_info without the "signer_lists" argument. - auto const info = - env.rpc("json", "account_info", to_string(withoutSigners)); - BEAST_EXPECT( - info.isMember(jss::result) && - info[jss::result].isMember(jss::account_data)); - BEAST_EXPECT(!info[jss::result][jss::account_data].isMember( - jss::signer_lists)); + auto const info = env.rpc("json", "account_info", to_string(withoutSigners)); + BEAST_EXPECT(info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); + BEAST_EXPECT(!info[jss::result][jss::account_data].isMember(jss::signer_lists)); } { // account_info with the "signer_lists" argument. - auto const info = - env.rpc("json", "account_info", to_string(withSigners)); - BEAST_EXPECT( - info.isMember(jss::result) && - info[jss::result].isMember(jss::account_data)); + auto const info = env.rpc("json", "account_info", to_string(withSigners)); + BEAST_EXPECT(info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); auto const& data = info[jss::result][jss::account_data]; BEAST_EXPECT(data.isMember(jss::signer_lists)); auto const& signerLists = data[jss::signer_lists]; @@ -148,21 +127,14 @@ public: env(smallSigners); { // account_info without the "signer_lists" argument. - auto const info = - env.rpc("json", "account_info", to_string(withoutSigners)); - BEAST_EXPECT( - info.isMember(jss::result) && - info[jss::result].isMember(jss::account_data)); - BEAST_EXPECT(!info[jss::result][jss::account_data].isMember( - jss::signer_lists)); + auto const info = env.rpc("json", "account_info", to_string(withoutSigners)); + BEAST_EXPECT(info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); + BEAST_EXPECT(!info[jss::result][jss::account_data].isMember(jss::signer_lists)); } { // account_info with the "signer_lists" argument. - auto const info = - env.rpc("json", "account_info", to_string(withSigners)); - BEAST_EXPECT( - info.isMember(jss::result) && - info[jss::result].isMember(jss::account_data)); + auto const info = env.rpc("json", "account_info", to_string(withSigners)); + BEAST_EXPECT(info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); auto const& data = info[jss::result][jss::account_data]; BEAST_EXPECT(data.isMember(jss::signer_lists)); auto const& signerLists = data[jss::signer_lists]; @@ -202,11 +174,8 @@ public: env(bigSigners); { // account_info with the "signer_lists" argument. - auto const info = - env.rpc("json", "account_info", to_string(withSigners)); - BEAST_EXPECT( - info.isMember(jss::result) && - info[jss::result].isMember(jss::account_data)); + auto const info = env.rpc("json", "account_info", to_string(withSigners)); + BEAST_EXPECT(info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); auto const& data = info[jss::result][jss::account_data]; BEAST_EXPECT(data.isMember(jss::signer_lists)); auto const& signerLists = data[jss::signer_lists]; @@ -246,22 +215,19 @@ public: withSigners[jss::account] = alice.human(); withSigners[jss::signer_lists] = true; - auto const withSignersAsString = std::string("{ ") + - "\"api_version\": 2, \"account\": \"" + alice.human() + "\", " + - "\"signer_lists\": asdfggh }"; + auto const withSignersAsString = std::string("{ ") + "\"api_version\": 2, \"account\": \"" + alice.human() + + "\", " + "\"signer_lists\": asdfggh }"; // Alice has no SignerList yet. { // account_info without the "signer_lists" argument. - auto const info = - env.rpc("json", "account_info", to_string(withoutSigners)); + auto const info = env.rpc("json", "account_info", to_string(withoutSigners)); BEAST_EXPECT(info.isMember(jss::result)); BEAST_EXPECT(!info[jss::result].isMember(jss::signer_lists)); } { // account_info with the "signer_lists" argument. - auto const info = - env.rpc("json", "account_info", to_string(withSigners)); + auto const info = env.rpc("json", "account_info", to_string(withSigners)); BEAST_EXPECT(info.isMember(jss::result)); auto const& data = info[jss::result]; BEAST_EXPECT(data.isMember(jss::signer_lists)); @@ -277,15 +243,13 @@ public: env(smallSigners); { // account_info without the "signer_lists" argument. - auto const info = - env.rpc("json", "account_info", to_string(withoutSigners)); + auto const info = env.rpc("json", "account_info", to_string(withoutSigners)); BEAST_EXPECT(info.isMember(jss::result)); BEAST_EXPECT(!info[jss::result].isMember(jss::signer_lists)); } { // account_info with the "signer_lists" argument. - auto const info = - env.rpc("json", "account_info", to_string(withSigners)); + auto const info = env.rpc("json", "account_info", to_string(withSigners)); BEAST_EXPECT(info.isMember(jss::result)); auto const& data = info[jss::result]; BEAST_EXPECT(data.isMember(jss::signer_lists)); @@ -302,8 +266,7 @@ public: } { // account_info with "signer_lists" as not bool should error out - auto const info = - env.rpc("json", "account_info", withSignersAsString); + auto const info = env.rpc("json", "account_info", withSignersAsString); BEAST_EXPECT(info[jss::status] == "error"); BEAST_EXPECT(info[jss::error] == "invalidParams"); } @@ -333,8 +296,7 @@ public: env(bigSigners); { // account_info with the "signer_lists" argument. - auto const info = - env.rpc("json", "account_info", to_string(withSigners)); + auto const info = env.rpc("json", "account_info", to_string(withSigners)); BEAST_EXPECT(info.isMember(jss::result)); auto const& data = info[jss::result]; BEAST_EXPECT(data.isMember(jss::signer_lists)); @@ -387,65 +349,42 @@ public: { // account_info without the "signer_lists" argument. auto const info = env.rpc("json2", withoutSigners); - BEAST_EXPECT( - info.isMember(jss::result) && - info[jss::result].isMember(jss::account_data)); - BEAST_EXPECT(!info[jss::result][jss::account_data].isMember( - jss::signer_lists)); - BEAST_EXPECT( - info.isMember(jss::jsonrpc) && info[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - info.isMember(jss::ripplerpc) && info[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); + BEAST_EXPECT(!info[jss::result][jss::account_data].isMember(jss::signer_lists)); + BEAST_EXPECT(info.isMember(jss::jsonrpc) && info[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(info.isMember(jss::ripplerpc) && info[jss::ripplerpc] == "2.0"); BEAST_EXPECT(info.isMember(jss::id) && info[jss::id] == 5); } { // account_info with the "signer_lists" argument. auto const info = env.rpc("json2", withSigners); - BEAST_EXPECT( - info.isMember(jss::result) && - info[jss::result].isMember(jss::account_data)); + BEAST_EXPECT(info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); auto const& data = info[jss::result][jss::account_data]; BEAST_EXPECT(data.isMember(jss::signer_lists)); auto const& signerLists = data[jss::signer_lists]; BEAST_EXPECT(signerLists.isArray()); BEAST_EXPECT(signerLists.size() == 0); - BEAST_EXPECT( - info.isMember(jss::jsonrpc) && info[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - info.isMember(jss::ripplerpc) && info[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(info.isMember(jss::jsonrpc) && info[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(info.isMember(jss::ripplerpc) && info[jss::ripplerpc] == "2.0"); BEAST_EXPECT(info.isMember(jss::id) && info[jss::id] == 6); } { // Do both of the above as a batch job - auto const info = env.rpc( - "json2", '[' + withoutSigners + ", " + withSigners + ']'); - BEAST_EXPECT( - info[0u].isMember(jss::result) && - info[0u][jss::result].isMember(jss::account_data)); - BEAST_EXPECT(!info[0u][jss::result][jss::account_data].isMember( - jss::signer_lists)); - BEAST_EXPECT( - info[0u].isMember(jss::jsonrpc) && - info[0u][jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - info[0u].isMember(jss::ripplerpc) && - info[0u][jss::ripplerpc] == "2.0"); + auto const info = env.rpc("json2", '[' + withoutSigners + ", " + withSigners + ']'); + BEAST_EXPECT(info[0u].isMember(jss::result) && info[0u][jss::result].isMember(jss::account_data)); + BEAST_EXPECT(!info[0u][jss::result][jss::account_data].isMember(jss::signer_lists)); + BEAST_EXPECT(info[0u].isMember(jss::jsonrpc) && info[0u][jss::jsonrpc] == "2.0"); + BEAST_EXPECT(info[0u].isMember(jss::ripplerpc) && info[0u][jss::ripplerpc] == "2.0"); BEAST_EXPECT(info[0u].isMember(jss::id) && info[0u][jss::id] == 5); - BEAST_EXPECT( - info[1u].isMember(jss::result) && - info[1u][jss::result].isMember(jss::account_data)); + BEAST_EXPECT(info[1u].isMember(jss::result) && info[1u][jss::result].isMember(jss::account_data)); auto const& data = info[1u][jss::result][jss::account_data]; BEAST_EXPECT(data.isMember(jss::signer_lists)); auto const& signerLists = data[jss::signer_lists]; BEAST_EXPECT(signerLists.isArray()); BEAST_EXPECT(signerLists.size() == 0); - BEAST_EXPECT( - info[1u].isMember(jss::jsonrpc) && - info[1u][jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - info[1u].isMember(jss::ripplerpc) && - info[1u][jss::ripplerpc] == "2.0"); + BEAST_EXPECT(info[1u].isMember(jss::jsonrpc) && info[1u][jss::jsonrpc] == "2.0"); + BEAST_EXPECT(info[1u].isMember(jss::ripplerpc) && info[1u][jss::ripplerpc] == "2.0"); BEAST_EXPECT(info[1u].isMember(jss::id) && info[1u][jss::id] == 6); } @@ -457,23 +396,16 @@ public: { // account_info without the "signer_lists" argument. auto const info = env.rpc("json2", withoutSigners); - BEAST_EXPECT( - info.isMember(jss::result) && - info[jss::result].isMember(jss::account_data)); - BEAST_EXPECT(!info[jss::result][jss::account_data].isMember( - jss::signer_lists)); - BEAST_EXPECT( - info.isMember(jss::jsonrpc) && info[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - info.isMember(jss::ripplerpc) && info[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); + BEAST_EXPECT(!info[jss::result][jss::account_data].isMember(jss::signer_lists)); + BEAST_EXPECT(info.isMember(jss::jsonrpc) && info[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(info.isMember(jss::ripplerpc) && info[jss::ripplerpc] == "2.0"); BEAST_EXPECT(info.isMember(jss::id) && info[jss::id] == 5); } { // account_info with the "signer_lists" argument. auto const info = env.rpc("json2", withSigners); - BEAST_EXPECT( - info.isMember(jss::result) && - info[jss::result].isMember(jss::account_data)); + BEAST_EXPECT(info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); auto const& data = info[jss::result][jss::account_data]; BEAST_EXPECT(data.isMember(jss::signer_lists)); auto const& signerLists = data[jss::signer_lists]; @@ -486,10 +418,8 @@ public: BEAST_EXPECT(signerEntries.size() == 1); auto const& entry0 = signerEntries[0u][sfSignerEntry.jsonName]; BEAST_EXPECT(entry0[sfSignerWeight.jsonName] == 3); - BEAST_EXPECT( - info.isMember(jss::jsonrpc) && info[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - info.isMember(jss::ripplerpc) && info[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(info.isMember(jss::jsonrpc) && info[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(info.isMember(jss::ripplerpc) && info[jss::ripplerpc] == "2.0"); BEAST_EXPECT(info.isMember(jss::id) && info[jss::id] == 6); } @@ -519,9 +449,7 @@ public: { // account_info with the "signer_lists" argument. auto const info = env.rpc("json2", withSigners); - BEAST_EXPECT( - info.isMember(jss::result) && - info[jss::result].isMember(jss::account_data)); + BEAST_EXPECT(info.isMember(jss::result) && info[jss::result].isMember(jss::account_data)); auto const& data = info[jss::result][jss::account_data]; BEAST_EXPECT(data.isMember(jss::signer_lists)); auto const& signerLists = data[jss::signer_lists]; @@ -539,10 +467,8 @@ public: BEAST_EXPECT(entry.isMember(sfAccount.jsonName)); BEAST_EXPECT(entry[sfSignerWeight.jsonName] == 1); } - BEAST_EXPECT( - info.isMember(jss::jsonrpc) && info[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - info.isMember(jss::ripplerpc) && info[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(info.isMember(jss::jsonrpc) && info[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(info.isMember(jss::ripplerpc) && info[jss::ripplerpc] == "2.0"); BEAST_EXPECT(info.isMember(jss::id) && info[jss::id] == 6); } } @@ -558,33 +484,27 @@ public: Account const bob{"bob"}; env.fund(XRP(1000), alice, bob); - auto getAccountFlag = [&env]( - std::string_view fName, - Account const& account) { + auto getAccountFlag = [&env](std::string_view fName, Account const& account) { Json::Value params; params[jss::account] = account.human(); - auto const info = - env.rpc("json", "account_info", to_string(params)); + auto const info = env.rpc("json", "account_info", to_string(params)); std::optional res; if (info[jss::result][jss::status] == "success" && info[jss::result][jss::account_flags].isMember(fName.data())) - res.emplace(info[jss::result][jss::account_flags][fName.data()] - .asBool()); + res.emplace(info[jss::result][jss::account_flags][fName.data()].asBool()); return res; }; - static constexpr std:: - array, 7> - asFlags{ - {{"defaultRipple", asfDefaultRipple}, - {"depositAuth", asfDepositAuth}, - {"disallowIncomingXRP", asfDisallowXRP}, - {"globalFreeze", asfGlobalFreeze}, - {"noFreeze", asfNoFreeze}, - {"requireAuthorization", asfRequireAuth}, - {"requireDestinationTag", asfRequireDest}}}; + static constexpr std::array, 7> asFlags{ + {{"defaultRipple", asfDefaultRipple}, + {"depositAuth", asfDepositAuth}, + {"disallowIncomingXRP", asfDisallowXRP}, + {"globalFreeze", asfGlobalFreeze}, + {"noFreeze", asfNoFreeze}, + {"requireAuthorization", asfRequireAuth}, + {"requireDestinationTag", asfRequireDest}}}; for (auto& asf : asFlags) { @@ -605,15 +525,11 @@ public: BEAST_EXPECT(f2.value()); } - static constexpr std:: - array, 4> - disallowIncomingFlags{ - {{"disallowIncomingCheck", asfDisallowIncomingCheck}, - {"disallowIncomingNFTokenOffer", - asfDisallowIncomingNFTokenOffer}, - {"disallowIncomingPayChan", asfDisallowIncomingPayChan}, - {"disallowIncomingTrustline", - asfDisallowIncomingTrustline}}}; + static constexpr std::array, 4> disallowIncomingFlags{ + {{"disallowIncomingCheck", asfDisallowIncomingCheck}, + {"disallowIncomingNFTokenOffer", asfDisallowIncomingNFTokenOffer}, + {"disallowIncomingPayChan", asfDisallowIncomingPayChan}, + {"disallowIncomingTrustline", asfDisallowIncomingTrustline}}}; for (auto& asf : disallowIncomingFlags) { @@ -634,48 +550,41 @@ public: BEAST_EXPECT(f2.value()); } - static constexpr std::pair - allowTrustLineClawbackFlag{ - "allowTrustLineClawback", asfAllowTrustLineClawback}; + static constexpr std::pair allowTrustLineClawbackFlag{ + "allowTrustLineClawback", asfAllowTrustLineClawback}; if (features[featureClawback]) { // must use bob's account because alice has noFreeze set - auto const f1 = - getAccountFlag(allowTrustLineClawbackFlag.first, bob); + auto const f1 = getAccountFlag(allowTrustLineClawbackFlag.first, bob); BEAST_EXPECT(f1.has_value()); BEAST_EXPECT(!f1.value()); // Set allowTrustLineClawback env(fset(bob, allowTrustLineClawbackFlag.second)); env.close(); - auto const f2 = - getAccountFlag(allowTrustLineClawbackFlag.first, bob); + auto const f2 = getAccountFlag(allowTrustLineClawbackFlag.first, bob); BEAST_EXPECT(f2.has_value()); BEAST_EXPECT(f2.value()); } else { - BEAST_EXPECT( - !getAccountFlag(allowTrustLineClawbackFlag.first, bob)); + BEAST_EXPECT(!getAccountFlag(allowTrustLineClawbackFlag.first, bob)); } - static constexpr std::pair - allowTrustLineLockingFlag{ - "allowTrustLineLocking", asfAllowTrustLineLocking}; + static constexpr std::pair allowTrustLineLockingFlag{ + "allowTrustLineLocking", asfAllowTrustLineLocking}; if (features[featureTokenEscrow]) { - auto const f1 = - getAccountFlag(allowTrustLineLockingFlag.first, bob); + auto const f1 = getAccountFlag(allowTrustLineLockingFlag.first, bob); BEAST_EXPECT(f1.has_value()); BEAST_EXPECT(!f1.value()); // Set allowTrustLineLocking env(fset(bob, allowTrustLineLockingFlag.second)); env.close(); - auto const f2 = - getAccountFlag(allowTrustLineLockingFlag.first, bob); + auto const f2 = getAccountFlag(allowTrustLineLockingFlag.first, bob); BEAST_EXPECT(f2.has_value()); BEAST_EXPECT(f2.value()); } diff --git a/src/test/rpc/AccountLines_test.cpp b/src/test/rpc/AccountLines_test.cpp index 6d9b75a44e..1f5f190cfa 100644 --- a/src/test/rpc/AccountLines_test.cpp +++ b/src/test/rpc/AccountLines_test.cpp @@ -22,30 +22,24 @@ public: // account_lines with no account. auto const lines = env.rpc("json", "account_lines", "{ }"); BEAST_EXPECT( - lines[jss::result][jss::error_message] == - RPC::missing_field_error(jss::account)[jss::error_message]); + lines[jss::result][jss::error_message] == RPC::missing_field_error(jss::account)[jss::error_message]); } { // account_lines with a malformed account. Json::Value params; - params[jss::account] = - "n9MJkEKHDhy5eTLuHUQeAAjo382frHNbFK4C8hcwN4nwM2SrLdBj"; - auto const lines = - env.rpc("json", "account_lines", to_string(params)); + params[jss::account] = "n9MJkEKHDhy5eTLuHUQeAAjo382frHNbFK4C8hcwN4nwM2SrLdBj"; + auto const lines = env.rpc("json", "account_lines", to_string(params)); BEAST_EXPECT( - lines[jss::result][jss::error_message] == - RPC::make_error(rpcACT_MALFORMED)[jss::error_message]); + lines[jss::result][jss::error_message] == RPC::make_error(rpcACT_MALFORMED)[jss::error_message]); } { // test account non-string auto testInvalidAccountParam = [&](auto const& param) { Json::Value params; params[jss::account] = param; - auto jrr = env.rpc( - "json", "account_lines", to_string(params))[jss::result]; + auto jrr = env.rpc("json", "account_lines", to_string(params))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); - BEAST_EXPECT( - jrr[jss::error_message] == "Invalid field 'account'."); + BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'account'."); }; testInvalidAccountParam(1); @@ -60,11 +54,9 @@ public: // account_lines on an unfunded account. Json::Value params; params[jss::account] = alice.human(); - auto const lines = - env.rpc("json", "account_lines", to_string(params)); + auto const lines = env.rpc("json", "account_lines", to_string(params)); BEAST_EXPECT( - lines[jss::result][jss::error_message] == - RPC::make_error(rpcACT_NOT_FOUND)[jss::error_message]); + lines[jss::result][jss::error_message] == RPC::make_error(rpcACT_NOT_FOUND)[jss::error_message]); } env.fund(XRP(10000), alice); env.close(); @@ -75,8 +67,7 @@ public: // alice is funded but has no lines. An empty array is returned. Json::Value params; params[jss::account] = alice.human(); - auto const lines = - env.rpc("json", "account_lines", to_string(params)); + auto const lines = env.rpc("json", "account_lines", to_string(params)); BEAST_EXPECT(lines[jss::result][jss::lines].isArray()); BEAST_EXPECT(lines[jss::result][jss::lines].size() == 0); } @@ -85,21 +76,17 @@ public: Json::Value params; params[jss::account] = alice.human(); params[jss::ledger_index] = "nonsense"; - auto const lines = - env.rpc("json", "account_lines", to_string(params)); + auto const lines = env.rpc("json", "account_lines", to_string(params)); BEAST_EXPECT( - lines[jss::result][jss::error_message] == - "Invalid field 'ledger_index', not string or number."); + lines[jss::result][jss::error_message] == "Invalid field 'ledger_index', not string or number."); } { // Specify a different ledger that doesn't exist. Json::Value params; params[jss::account] = alice.human(); params[jss::ledger_index] = 50000; - auto const lines = - env.rpc("json", "account_lines", to_string(params)); - BEAST_EXPECT( - lines[jss::result][jss::error_message] == "ledgerNotFound"); + auto const lines = env.rpc("json", "account_lines", to_string(params)); + BEAST_EXPECT(lines[jss::result][jss::error_message] == "ledgerNotFound"); } // Create trust lines to share with alice. Account const gw1{"gw1"}; @@ -109,8 +96,7 @@ public: for (char c = 0; c <= ('Z' - 'A'); ++c) { // gw1 currencies have names "YAA" -> "YAZ". - gw1Currencies.push_back( - gw1[std::string("YA") + static_cast('A' + c)]); + gw1Currencies.push_back(gw1[std::string("YA") + static_cast('A' + c)]); IOU const& gw1Currency = gw1Currencies.back(); // Establish trust lines. @@ -134,8 +120,7 @@ public: for (char c = 0; c <= ('Z' - 'A'); ++c) { // gw2 currencies have names "ZAA" -> "ZAZ". - gw2Currencies.push_back( - gw2[std::string("ZA") + static_cast('A' + c)]); + gw2Currencies.push_back(gw2[std::string("ZA") + static_cast('A' + c)]); IOU const& gw2Currency = gw2Currencies.back(); // Establish trust lines. @@ -146,27 +131,19 @@ public: env.close(); // Set flags on gw2 trust lines so we can look for them. - env(trust( - alice, - gw2Currency(0), - gw2, - tfSetNoRipple | tfSetFreeze | tfSetDeepFreeze)); + env(trust(alice, gw2Currency(0), gw2, tfSetNoRipple | tfSetFreeze | tfSetDeepFreeze)); } env.close(); LedgerHeader const ledger58Info = env.closed()->header(); BEAST_EXPECT(ledger58Info.seq == 58); // A re-usable test for historic ledgers. - auto testAccountLinesHistory = [this, &env]( - Account const& account, - LedgerHeader const& info, - int count) { + auto testAccountLinesHistory = [this, &env](Account const& account, LedgerHeader const& info, int count) { // Get account_lines by ledger index. Json::Value paramsSeq; paramsSeq[jss::account] = account.human(); paramsSeq[jss::ledger_index] = info.seq; - auto const linesSeq = - env.rpc("json", "account_lines", to_string(paramsSeq)); + auto const linesSeq = env.rpc("json", "account_lines", to_string(paramsSeq)); BEAST_EXPECT(linesSeq[jss::result][jss::lines].isArray()); BEAST_EXPECT(linesSeq[jss::result][jss::lines].size() == count); @@ -174,8 +151,7 @@ public: Json::Value paramsHash; paramsHash[jss::account] = account.human(); paramsHash[jss::ledger_hash] = to_string(info.hash); - auto const linesHash = - env.rpc("json", "account_lines", to_string(paramsHash)); + auto const linesHash = env.rpc("json", "account_lines", to_string(paramsHash)); BEAST_EXPECT(linesHash[jss::result][jss::lines].isArray()); BEAST_EXPECT(linesHash[jss::result][jss::lines].size() == count); }; @@ -195,8 +171,7 @@ public: params[jss::account] = alice.human(); params[jss::ledger_hash] = to_string(ledger4Info.hash); params[jss::ledger_index] = ledger58Info.seq; - auto const lines = env.rpc( - "json", "account_lines", to_string(params))[jss::result]; + auto const lines = env.rpc("json", "account_lines", to_string(params))[jss::result]; BEAST_EXPECT(lines[jss::error] == "invalidParams"); BEAST_EXPECT( lines[jss::error_message] == @@ -208,19 +183,15 @@ public: Json::Value params; params[jss::account] = alice.human(); params[jss::ledger_index] = Json::objectValue; - auto const lines = env.rpc( - "json", "account_lines", to_string(params))[jss::result]; + auto const lines = env.rpc("json", "account_lines", to_string(params))[jss::result]; BEAST_EXPECT(lines[jss::error] == "invalidParams"); - BEAST_EXPECT( - lines[jss::error_message] == - "Invalid field 'ledger_index', not string or number."); + BEAST_EXPECT(lines[jss::error_message] == "Invalid field 'ledger_index', not string or number."); } { // alice should have 52 trust lines in the current ledger. Json::Value params; params[jss::account] = alice.human(); - auto const lines = - env.rpc("json", "account_lines", to_string(params)); + auto const lines = env.rpc("json", "account_lines", to_string(params)); BEAST_EXPECT(lines[jss::result][jss::lines].isArray()); BEAST_EXPECT(lines[jss::result][jss::lines].size() == 52); } @@ -229,8 +200,7 @@ public: Json::Value params; params[jss::account] = alice.human(); params[jss::peer] = gw1.human(); - auto const lines = - env.rpc("json", "account_lines", to_string(params)); + auto const lines = env.rpc("json", "account_lines", to_string(params)); BEAST_EXPECT(lines[jss::result][jss::lines].isArray()); BEAST_EXPECT(lines[jss::result][jss::lines].size() == 26); @@ -242,32 +212,26 @@ public: // Use a malformed peer. Json::Value params; params[jss::account] = alice.human(); - params[jss::peer] = - "n9MJkEKHDhy5eTLuHUQeAAjo382frHNbFK4C8hcwN4nwM2SrLdBj"; - auto const lines = - env.rpc("json", "account_lines", to_string(params)); + params[jss::peer] = "n9MJkEKHDhy5eTLuHUQeAAjo382frHNbFK4C8hcwN4nwM2SrLdBj"; + auto const lines = env.rpc("json", "account_lines", to_string(params)); BEAST_EXPECT( - lines[jss::result][jss::error_message] == - RPC::make_error(rpcACT_MALFORMED)[jss::error_message]); + lines[jss::result][jss::error_message] == RPC::make_error(rpcACT_MALFORMED)[jss::error_message]); } { // A negative limit should fail. Json::Value params; params[jss::account] = alice.human(); params[jss::limit] = -1; - auto const lines = - env.rpc("json", "account_lines", to_string(params)); + auto const lines = env.rpc("json", "account_lines", to_string(params)); BEAST_EXPECT( - lines[jss::result][jss::error_message] == - RPC::expected_field_message(jss::limit, "unsigned integer")); + lines[jss::result][jss::error_message] == RPC::expected_field_message(jss::limit, "unsigned integer")); } { // Limit the response to 1 trust line. Json::Value paramsA; paramsA[jss::account] = alice.human(); paramsA[jss::limit] = 1; - auto const linesA = - env.rpc("json", "account_lines", to_string(paramsA)); + auto const linesA = env.rpc("json", "account_lines", to_string(paramsA)); BEAST_EXPECT(linesA[jss::result][jss::lines].isArray()); BEAST_EXPECT(linesA[jss::result][jss::lines].size() == 1); @@ -276,8 +240,7 @@ public: Json::Value paramsB; paramsB[jss::account] = alice.human(); paramsB[jss::marker] = marker; - auto const linesB = - env.rpc("json", "account_lines", to_string(paramsB)); + auto const linesB = env.rpc("json", "account_lines", to_string(paramsB)); BEAST_EXPECT(linesB[jss::result][jss::lines].isArray()); BEAST_EXPECT(linesB[jss::result][jss::lines].size() == 51); @@ -286,8 +249,7 @@ public: paramsC[jss::account] = alice.human(); paramsC[jss::limit] = 3; paramsC[jss::marker] = marker; - auto const linesC = - env.rpc("json", "account_lines", to_string(paramsC)); + auto const linesC = env.rpc("json", "account_lines", to_string(paramsC)); BEAST_EXPECT(linesC[jss::result][jss::lines].isArray()); BEAST_EXPECT(linesC[jss::result][jss::lines].size() == 3); @@ -296,22 +258,17 @@ public: Json::Value paramsD; paramsD[jss::account] = alice.human(); paramsD[jss::marker] = marker; - auto const linesD = - env.rpc("json", "account_lines", to_string(paramsD)); + auto const linesD = env.rpc("json", "account_lines", to_string(paramsD)); BEAST_EXPECT( - linesD[jss::result][jss::error_message] == - RPC::make_error(rpcINVALID_PARAMS)[jss::error_message]); + linesD[jss::result][jss::error_message] == RPC::make_error(rpcINVALID_PARAMS)[jss::error_message]); } { // A non-string marker should also fail. Json::Value params; params[jss::account] = alice.human(); params[jss::marker] = true; - auto const lines = - env.rpc("json", "account_lines", to_string(params)); - BEAST_EXPECT( - lines[jss::result][jss::error_message] == - RPC::expected_field_message(jss::marker, "string")); + auto const lines = env.rpc("json", "account_lines", to_string(params)); + BEAST_EXPECT(lines[jss::result][jss::error_message] == RPC::expected_field_message(jss::marker, "string")); } { // Check that the flags we expect from alice to gw2 are present. @@ -319,8 +276,7 @@ public: params[jss::account] = alice.human(); params[jss::limit] = 10; params[jss::peer] = gw2.human(); - auto const lines = - env.rpc("json", "account_lines", to_string(params)); + auto const lines = env.rpc("json", "account_lines", to_string(params)); auto const& line = lines[jss::result][jss::lines][0u]; BEAST_EXPECT(line[jss::freeze].asBool() == true); BEAST_EXPECT(line[jss::deep_freeze].asBool() == true); @@ -333,8 +289,7 @@ public: paramsA[jss::account] = gw2.human(); paramsA[jss::limit] = 1; paramsA[jss::peer] = alice.human(); - auto const linesA = - env.rpc("json", "account_lines", to_string(paramsA)); + auto const linesA = env.rpc("json", "account_lines", to_string(paramsA)); auto const& lineA = linesA[jss::result][jss::lines][0u]; BEAST_EXPECT(lineA[jss::freeze_peer].asBool() == true); BEAST_EXPECT(lineA[jss::deep_freeze_peer].asBool() == true); @@ -349,8 +304,7 @@ public: paramsB[jss::limit] = 25; paramsB[jss::marker] = marker; paramsB[jss::peer] = alice.human(); - auto const linesB = - env.rpc("json", "account_lines", to_string(paramsB)); + auto const linesB = env.rpc("json", "account_lines", to_string(paramsB)); BEAST_EXPECT(linesB[jss::result][jss::lines].isArray()); BEAST_EXPECT(linesB[jss::result][jss::lines].size() == 25); BEAST_EXPECT(!linesB[jss::result].isMember(jss::marker)); @@ -393,10 +347,8 @@ public: Json::Value aliceObjectsParams; aliceObjectsParams[jss::account] = alice.human(); aliceObjectsParams[jss::limit] = 10; - Json::Value const aliceObjects = - env.rpc("json", "account_objects", to_string(aliceObjectsParams)); - Json::Value const& aliceSignerList = - aliceObjects[jss::result][jss::account_objects][0u]; + Json::Value const aliceObjects = env.rpc("json", "account_objects", to_string(aliceObjectsParams)); + Json::Value const& aliceSignerList = aliceObjects[jss::result][jss::account_objects][0u]; if (!(aliceSignerList[sfLedgerEntryType.jsonName] == jss::SignerList)) { fail( @@ -412,33 +364,28 @@ public: Json::Value aliceLines1Params; aliceLines1Params[jss::account] = alice.human(); aliceLines1Params[jss::limit] = 1; - auto const aliceLines1 = - env.rpc("json", "account_lines", to_string(aliceLines1Params)); + auto const aliceLines1 = env.rpc("json", "account_lines", to_string(aliceLines1Params)); BEAST_EXPECT(aliceLines1[jss::result].isMember(jss::marker)); // Verify that the marker points at the signer list. - std::string const aliceMarker = - aliceLines1[jss::result][jss::marker].asString(); - std::string const markerIndex = - aliceMarker.substr(0, aliceMarker.find(',')); + std::string const aliceMarker = aliceLines1[jss::result][jss::marker].asString(); + std::string const markerIndex = aliceMarker.substr(0, aliceMarker.find(',')); BEAST_EXPECT(markerIndex == aliceSignerList[jss::index].asString()); // When we fetch Alice's remaining lines we should find one and no more. Json::Value aliceLines2Params; aliceLines2Params[jss::account] = alice.human(); aliceLines2Params[jss::marker] = aliceMarker; - auto const aliceLines2 = - env.rpc("json", "account_lines", to_string(aliceLines2Params)); + auto const aliceLines2 = env.rpc("json", "account_lines", to_string(aliceLines2Params)); BEAST_EXPECT(aliceLines2[jss::result][jss::lines].size() == 1); BEAST_EXPECT(!aliceLines2[jss::result].isMember(jss::marker)); - // Get account lines for beckys account, using alices SignerList as a + // Get account lines for becky's account, using alice's SignerList as a // marker. This should cause an error. Json::Value beckyLinesParams; beckyLinesParams[jss::account] = becky.human(); beckyLinesParams[jss::marker] = aliceMarker; - auto const beckyLines = - env.rpc("json", "account_lines", to_string(beckyLinesParams)); + auto const beckyLines = env.rpc("json", "account_lines", to_string(beckyLinesParams)); BEAST_EXPECT(beckyLines[jss::result].isMember(jss::error_message)); } @@ -493,10 +440,8 @@ public: Json::Value linesBegParams; linesBegParams[jss::account] = alice.human(); linesBegParams[jss::limit] = 2; - auto const linesBeg = - env.rpc("json", "account_lines", to_string(linesBegParams)); - BEAST_EXPECT( - linesBeg[jss::result][jss::lines][0u][jss::currency] == "USD"); + auto const linesBeg = env.rpc("json", "account_lines", to_string(linesBegParams)); + BEAST_EXPECT(linesBeg[jss::result][jss::lines][0u][jss::currency] == "USD"); BEAST_EXPECT(linesBeg[jss::result].isMember(jss::marker)); // alice pays 100 EUR to cheri. @@ -508,11 +453,9 @@ public: Json::Value linesEndParams; linesEndParams[jss::account] = alice.human(); linesEndParams[jss::marker] = linesBeg[jss::result][jss::marker]; - auto const linesEnd = - env.rpc("json", "account_lines", to_string(linesEndParams)); + auto const linesEnd = env.rpc("json", "account_lines", to_string(linesEndParams)); BEAST_EXPECT( - linesEnd[jss::result][jss::error_message] == - RPC::make_error(rpcINVALID_PARAMS)[jss::error_message]); + linesEnd[jss::result][jss::error_message] == RPC::make_error(rpcINVALID_PARAMS)[jss::error_message]); } void @@ -570,48 +513,32 @@ public: env.close(); // Escrow, in each direction - env(escrow::create(alice, becky, XRP(1000)), - escrow::finish_time(env.now() + 1s)); - env(escrow::create(becky, alice, XRP(1000)), - escrow::finish_time(env.now() + 1s)); + env(escrow::create(alice, becky, XRP(1000)), escrow::finish_time(env.now() + 1s)); + env(escrow::create(becky, alice, XRP(1000)), escrow::finish_time(env.now() + 1s)); // Pay channels, in each direction env(payChan(alice, becky, XRP(1000), 100s, alice.pk())); env(payChan(becky, alice, XRP(1000), 100s, becky.pk())); // Mint NFTs, for each account - uint256 const aliceNFtokenID = - token::getNextID(env, alice, 0, tfTransferable); + uint256 const aliceNFtokenID = token::getNextID(env, alice, 0, tfTransferable); env(token::mint(alice, 0), txflags(tfTransferable)); - uint256 const beckyNFtokenID = - token::getNextID(env, becky, 0, tfTransferable); + uint256 const beckyNFtokenID = token::getNextID(env, becky, 0, tfTransferable); env(token::mint(becky, 0), txflags(tfTransferable)); // NFT Offers, for each other's NFTs - env(token::createOffer(alice, beckyNFtokenID, drops(1)), - token::owner(becky)); - env(token::createOffer(becky, aliceNFtokenID, drops(1)), - token::owner(alice)); + env(token::createOffer(alice, beckyNFtokenID, drops(1)), token::owner(becky)); + env(token::createOffer(becky, aliceNFtokenID, drops(1)), token::owner(alice)); - env(token::createOffer(becky, beckyNFtokenID, drops(1)), - txflags(tfSellNFToken), - token::destination(alice)); - env(token::createOffer(alice, aliceNFtokenID, drops(1)), - txflags(tfSellNFToken), - token::destination(becky)); + env(token::createOffer(becky, beckyNFtokenID, drops(1)), txflags(tfSellNFToken), token::destination(alice)); + env(token::createOffer(alice, aliceNFtokenID, drops(1)), txflags(tfSellNFToken), token::destination(becky)); - env(token::createOffer(gw1, beckyNFtokenID, drops(1)), - token::owner(becky), - token::destination(alice)); - env(token::createOffer(gw1, aliceNFtokenID, drops(1)), - token::owner(alice), - token::destination(becky)); + env(token::createOffer(gw1, beckyNFtokenID, drops(1)), token::owner(becky), token::destination(alice)); + env(token::createOffer(gw1, aliceNFtokenID, drops(1)), token::owner(alice), token::destination(becky)); - env(token::createOffer(becky, beckyNFtokenID, drops(1)), - txflags(tfSellNFToken)); - env(token::createOffer(alice, aliceNFtokenID, drops(1)), - txflags(tfSellNFToken)); + env(token::createOffer(becky, beckyNFtokenID, drops(1)), txflags(tfSellNFToken)); + env(token::createOffer(alice, aliceNFtokenID, drops(1)), txflags(tfSellNFToken)); // Checks, in each direction env(check::create(alice, becky, XRP(50))); @@ -640,9 +567,7 @@ public: // Now make repeated calls to `account_lines` with a limit of 1. // That should iterate all of alice's relevant objects, even though // the list will be empty for most calls. - auto getNextLine = [](Env& env, - Account const& alice, - std::optional const marker) { + auto getNextLine = [](Env& env, Account const& alice, std::optional const marker) { Json::Value params(Json::objectValue); params[jss::account] = alice.human(); params[jss::limit] = 1; @@ -658,17 +583,11 @@ public: constexpr std::size_t expectedNFTs = 1; std::size_t foundLines = 0; - auto hasMarker = [](auto const& aliceLines) { - return aliceLines[jss::result].isMember(jss::marker); - }; - auto marker = [](auto const& aliceLines) { - return aliceLines[jss::result][jss::marker].asString(); - }; + auto hasMarker = [](auto const& aliceLines) { return aliceLines[jss::result].isMember(jss::marker); }; + auto marker = [](auto const& aliceLines) { return aliceLines[jss::result][jss::marker].asString(); }; auto checkLines = [](auto const& aliceLines) { - return aliceLines.isMember(jss::result) && - !aliceLines[jss::result].isMember(jss::error_message) && - aliceLines[jss::result].isMember(jss::lines) && - aliceLines[jss::result][jss::lines].isArray() && + return aliceLines.isMember(jss::result) && !aliceLines[jss::result].isMember(jss::error_message) && + aliceLines[jss::result].isMember(jss::lines) && aliceLines[jss::result][jss::lines].isArray() && aliceLines[jss::result][jss::lines].size() <= 1; }; @@ -691,39 +610,28 @@ public: Json::Value aliceObjectsParams2; aliceObjectsParams2[jss::account] = alice.human(); aliceObjectsParams2[jss::limit] = 200; - Json::Value const aliceObjects = env.rpc( - "json", "account_objects", to_string(aliceObjectsParams2)); + Json::Value const aliceObjects = env.rpc("json", "account_objects", to_string(aliceObjectsParams2)); BEAST_EXPECT(aliceObjects.isMember(jss::result)); - BEAST_EXPECT( - !aliceObjects[jss::result].isMember(jss::error_message)); - BEAST_EXPECT( - aliceObjects[jss::result].isMember(jss::account_objects)); - BEAST_EXPECT( - aliceObjects[jss::result][jss::account_objects].isArray()); + BEAST_EXPECT(!aliceObjects[jss::result].isMember(jss::error_message)); + BEAST_EXPECT(aliceObjects[jss::result].isMember(jss::account_objects)); + BEAST_EXPECT(aliceObjects[jss::result][jss::account_objects].isArray()); // account_objects does not currently return NFTPages. If // that ever changes, without also changing account_lines, // this test will need to be updated. - BEAST_EXPECT( - aliceObjects[jss::result][jss::account_objects].size() == - iterations + expectedNFTs); + BEAST_EXPECT(aliceObjects[jss::result][jss::account_objects].size() == iterations + expectedNFTs); // If ledger object association ever changes, for whatever // reason, this test will need to be updated. - BEAST_EXPECTS( - iterations == expectedIterations, std::to_string(iterations)); + BEAST_EXPECTS(iterations == expectedIterations, std::to_string(iterations)); // Get becky's objects just to confirm that they're symmetrical Json::Value beckyObjectsParams; beckyObjectsParams[jss::account] = becky.human(); beckyObjectsParams[jss::limit] = 200; - Json::Value const beckyObjects = env.rpc( - "json", "account_objects", to_string(beckyObjectsParams)); + Json::Value const beckyObjects = env.rpc("json", "account_objects", to_string(beckyObjectsParams)); BEAST_EXPECT(beckyObjects.isMember(jss::result)); - BEAST_EXPECT( - !beckyObjects[jss::result].isMember(jss::error_message)); - BEAST_EXPECT( - beckyObjects[jss::result].isMember(jss::account_objects)); - BEAST_EXPECT( - beckyObjects[jss::result][jss::account_objects].isArray()); + BEAST_EXPECT(!beckyObjects[jss::result].isMember(jss::error_message)); + BEAST_EXPECT(beckyObjects[jss::result].isMember(jss::account_objects)); + BEAST_EXPECT(beckyObjects[jss::result][jss::account_objects].isArray()); // becky should have the same number of objects as alice, except the // 2 tickets that only alice created. BEAST_EXPECT( @@ -747,11 +655,8 @@ public: request[jss::jsonrpc] = "2.0"; request[jss::ripplerpc] = "2.0"; auto const lines = env.rpc("json2", to_string(request)); - BEAST_EXPECT( - lines.isMember(jss::jsonrpc) && lines[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - lines.isMember(jss::ripplerpc) && - lines[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(lines.isMember(jss::jsonrpc) && lines[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(lines.isMember(jss::ripplerpc) && lines[jss::ripplerpc] == "2.0"); } { // account_lines with no account. @@ -761,21 +666,15 @@ public: request[jss::ripplerpc] = "2.0"; request[jss::id] = 5; auto const lines = env.rpc("json2", to_string(request)); - BEAST_EXPECT( - lines[jss::error][jss::message] == - RPC::missing_field_error(jss::account)[jss::error_message]); - BEAST_EXPECT( - lines.isMember(jss::jsonrpc) && lines[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - lines.isMember(jss::ripplerpc) && - lines[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(lines[jss::error][jss::message] == RPC::missing_field_error(jss::account)[jss::error_message]); + BEAST_EXPECT(lines.isMember(jss::jsonrpc) && lines[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(lines.isMember(jss::ripplerpc) && lines[jss::ripplerpc] == "2.0"); BEAST_EXPECT(lines.isMember(jss::id) && lines[jss::id] == 5); } { // account_lines with a malformed account. Json::Value params; - params[jss::account] = - "n9MJkEKHDhy5eTLuHUQeAAjo382frHNbFK4C8hcwN4nwM2SrLdBj"; + params[jss::account] = "n9MJkEKHDhy5eTLuHUQeAAjo382frHNbFK4C8hcwN4nwM2SrLdBj"; Json::Value request; request[jss::method] = "account_lines"; request[jss::jsonrpc] = "2.0"; @@ -783,14 +682,9 @@ public: request[jss::id] = 5; request[jss::params] = params; auto const lines = env.rpc("json2", to_string(request)); - BEAST_EXPECT( - lines[jss::error][jss::message] == - RPC::make_error(rpcACT_MALFORMED)[jss::error_message]); - BEAST_EXPECT( - lines.isMember(jss::jsonrpc) && lines[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - lines.isMember(jss::ripplerpc) && - lines[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(lines[jss::error][jss::message] == RPC::make_error(rpcACT_MALFORMED)[jss::error_message]); + BEAST_EXPECT(lines.isMember(jss::jsonrpc) && lines[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(lines.isMember(jss::ripplerpc) && lines[jss::ripplerpc] == "2.0"); BEAST_EXPECT(lines.isMember(jss::id) && lines[jss::id] == 5); } Account const alice{"alice"}; @@ -805,14 +699,9 @@ public: request[jss::id] = 5; request[jss::params] = params; auto const lines = env.rpc("json2", to_string(request)); - BEAST_EXPECT( - lines[jss::error][jss::message] == - RPC::make_error(rpcACT_NOT_FOUND)[jss::error_message]); - BEAST_EXPECT( - lines.isMember(jss::jsonrpc) && lines[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - lines.isMember(jss::ripplerpc) && - lines[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(lines[jss::error][jss::message] == RPC::make_error(rpcACT_NOT_FOUND)[jss::error_message]); + BEAST_EXPECT(lines.isMember(jss::jsonrpc) && lines[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(lines.isMember(jss::ripplerpc) && lines[jss::ripplerpc] == "2.0"); BEAST_EXPECT(lines.isMember(jss::id) && lines[jss::id] == 5); } env.fund(XRP(10000), alice); @@ -833,11 +722,8 @@ public: auto const lines = env.rpc("json2", to_string(request)); BEAST_EXPECT(lines[jss::result][jss::lines].isArray()); BEAST_EXPECT(lines[jss::result][jss::lines].size() == 0); - BEAST_EXPECT( - lines.isMember(jss::jsonrpc) && lines[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - lines.isMember(jss::ripplerpc) && - lines[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(lines.isMember(jss::jsonrpc) && lines[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(lines.isMember(jss::ripplerpc) && lines[jss::ripplerpc] == "2.0"); BEAST_EXPECT(lines.isMember(jss::id) && lines[jss::id] == 5); } { @@ -852,14 +738,9 @@ public: request[jss::id] = 5; request[jss::params] = params; auto const lines = env.rpc("json2", to_string(request)); - BEAST_EXPECT( - lines[jss::error][jss::message] == - "Invalid field 'ledger_index', not string or number."); - BEAST_EXPECT( - lines.isMember(jss::jsonrpc) && lines[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - lines.isMember(jss::ripplerpc) && - lines[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(lines[jss::error][jss::message] == "Invalid field 'ledger_index', not string or number."); + BEAST_EXPECT(lines.isMember(jss::jsonrpc) && lines[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(lines.isMember(jss::ripplerpc) && lines[jss::ripplerpc] == "2.0"); BEAST_EXPECT(lines.isMember(jss::id) && lines[jss::id] == 5); } { @@ -875,11 +756,8 @@ public: request[jss::params] = params; auto const lines = env.rpc("json2", to_string(request)); BEAST_EXPECT(lines[jss::error][jss::message] == "ledgerNotFound"); - BEAST_EXPECT( - lines.isMember(jss::jsonrpc) && lines[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - lines.isMember(jss::ripplerpc) && - lines[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(lines.isMember(jss::jsonrpc) && lines[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(lines.isMember(jss::ripplerpc) && lines[jss::ripplerpc] == "2.0"); BEAST_EXPECT(lines.isMember(jss::id) && lines[jss::id] == 5); } // Create trust lines to share with alice. @@ -890,8 +768,7 @@ public: for (char c = 0; c <= ('Z' - 'A'); ++c) { // gw1 currencies have names "YAA" -> "YAZ". - gw1Currencies.push_back( - gw1[std::string("YA") + static_cast('A' + c)]); + gw1Currencies.push_back(gw1[std::string("YA") + static_cast('A' + c)]); IOU const& gw1Currency = gw1Currencies.back(); // Establish trust lines. @@ -915,8 +792,7 @@ public: for (char c = 0; c <= ('Z' - 'A'); ++c) { // gw2 currencies have names "ZAA" -> "ZAZ". - gw2Currencies.push_back( - gw2[std::string("ZA") + static_cast('A' + c)]); + gw2Currencies.push_back(gw2[std::string("ZA") + static_cast('A' + c)]); IOU const& gw2Currency = gw2Currencies.back(); // Establish trust lines. @@ -927,21 +803,14 @@ public: env.close(); // Set flags on gw2 trust lines so we can look for them. - env(trust( - alice, - gw2Currency(0), - gw2, - tfSetNoRipple | tfSetFreeze | tfSetDeepFreeze)); + env(trust(alice, gw2Currency(0), gw2, tfSetNoRipple | tfSetFreeze | tfSetDeepFreeze)); } env.close(); LedgerHeader const ledger58Info = env.closed()->header(); BEAST_EXPECT(ledger58Info.seq == 58); // A re-usable test for historic ledgers. - auto testAccountLinesHistory = [this, &env]( - Account const& account, - LedgerHeader const& info, - int count) { + auto testAccountLinesHistory = [this, &env](Account const& account, LedgerHeader const& info, int count) { // Get account_lines by ledger index. Json::Value paramsSeq; paramsSeq[jss::account] = account.human(); @@ -955,12 +824,8 @@ public: auto const linesSeq = env.rpc("json2", to_string(requestSeq)); BEAST_EXPECT(linesSeq[jss::result][jss::lines].isArray()); BEAST_EXPECT(linesSeq[jss::result][jss::lines].size() == count); - BEAST_EXPECT( - linesSeq.isMember(jss::jsonrpc) && - linesSeq[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - linesSeq.isMember(jss::ripplerpc) && - linesSeq[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(linesSeq.isMember(jss::jsonrpc) && linesSeq[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(linesSeq.isMember(jss::ripplerpc) && linesSeq[jss::ripplerpc] == "2.0"); BEAST_EXPECT(linesSeq.isMember(jss::id) && linesSeq[jss::id] == 5); // Get account_lines by ledger hash. @@ -976,14 +841,9 @@ public: auto const linesHash = env.rpc("json2", to_string(requestHash)); BEAST_EXPECT(linesHash[jss::result][jss::lines].isArray()); BEAST_EXPECT(linesHash[jss::result][jss::lines].size() == count); - BEAST_EXPECT( - linesHash.isMember(jss::jsonrpc) && - linesHash[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - linesHash.isMember(jss::ripplerpc) && - linesHash[jss::ripplerpc] == "2.0"); - BEAST_EXPECT( - linesHash.isMember(jss::id) && linesHash[jss::id] == 5); + BEAST_EXPECT(linesHash.isMember(jss::jsonrpc) && linesHash[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(linesHash.isMember(jss::ripplerpc) && linesHash[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(linesHash.isMember(jss::id) && linesHash[jss::id] == 5); }; // Alice should have no trust lines in ledger 3. @@ -1014,11 +874,8 @@ public: lines[jss::error][jss::message] == "Exactly one of 'ledger_hash' or 'ledger_index' can be " "specified."); - BEAST_EXPECT( - lines.isMember(jss::jsonrpc) && lines[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - lines.isMember(jss::ripplerpc) && - lines[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(lines.isMember(jss::jsonrpc) && lines[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(lines.isMember(jss::ripplerpc) && lines[jss::ripplerpc] == "2.0"); BEAST_EXPECT(lines.isMember(jss::id) && lines[jss::id] == 5); } { @@ -1034,11 +891,8 @@ public: auto const lines = env.rpc("json2", to_string(request)); BEAST_EXPECT(lines[jss::result][jss::lines].isArray()); BEAST_EXPECT(lines[jss::result][jss::lines].size() == 52); - BEAST_EXPECT( - lines.isMember(jss::jsonrpc) && lines[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - lines.isMember(jss::ripplerpc) && - lines[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(lines.isMember(jss::jsonrpc) && lines[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(lines.isMember(jss::ripplerpc) && lines[jss::ripplerpc] == "2.0"); BEAST_EXPECT(lines.isMember(jss::id) && lines[jss::id] == 5); } { @@ -1055,19 +909,15 @@ public: auto const lines = env.rpc("json2", to_string(request)); BEAST_EXPECT(lines[jss::result][jss::lines].isArray()); BEAST_EXPECT(lines[jss::result][jss::lines].size() == 26); - BEAST_EXPECT( - lines.isMember(jss::jsonrpc) && lines[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - lines.isMember(jss::ripplerpc) && - lines[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(lines.isMember(jss::jsonrpc) && lines[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(lines.isMember(jss::ripplerpc) && lines[jss::ripplerpc] == "2.0"); BEAST_EXPECT(lines.isMember(jss::id) && lines[jss::id] == 5); } { // Use a malformed peer. Json::Value params; params[jss::account] = alice.human(); - params[jss::peer] = - "n9MJkEKHDhy5eTLuHUQeAAjo382frHNbFK4C8hcwN4nwM2SrLdBj"; + params[jss::peer] = "n9MJkEKHDhy5eTLuHUQeAAjo382frHNbFK4C8hcwN4nwM2SrLdBj"; Json::Value request; request[jss::method] = "account_lines"; request[jss::jsonrpc] = "2.0"; @@ -1075,14 +925,9 @@ public: request[jss::id] = 5; request[jss::params] = params; auto const lines = env.rpc("json2", to_string(request)); - BEAST_EXPECT( - lines[jss::error][jss::message] == - RPC::make_error(rpcACT_MALFORMED)[jss::error_message]); - BEAST_EXPECT( - lines.isMember(jss::jsonrpc) && lines[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - lines.isMember(jss::ripplerpc) && - lines[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(lines[jss::error][jss::message] == RPC::make_error(rpcACT_MALFORMED)[jss::error_message]); + BEAST_EXPECT(lines.isMember(jss::jsonrpc) && lines[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(lines.isMember(jss::ripplerpc) && lines[jss::ripplerpc] == "2.0"); BEAST_EXPECT(lines.isMember(jss::id) && lines[jss::id] == 5); } { @@ -1098,13 +943,9 @@ public: request[jss::params] = params; auto const lines = env.rpc("json2", to_string(request)); BEAST_EXPECT( - lines[jss::error][jss::message] == - RPC::expected_field_message(jss::limit, "unsigned integer")); - BEAST_EXPECT( - lines.isMember(jss::jsonrpc) && lines[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - lines.isMember(jss::ripplerpc) && - lines[jss::ripplerpc] == "2.0"); + lines[jss::error][jss::message] == RPC::expected_field_message(jss::limit, "unsigned integer")); + BEAST_EXPECT(lines.isMember(jss::jsonrpc) && lines[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(lines.isMember(jss::ripplerpc) && lines[jss::ripplerpc] == "2.0"); BEAST_EXPECT(lines.isMember(jss::id) && lines[jss::id] == 5); } { @@ -1121,11 +962,8 @@ public: auto const linesA = env.rpc("json2", to_string(requestA)); BEAST_EXPECT(linesA[jss::result][jss::lines].isArray()); BEAST_EXPECT(linesA[jss::result][jss::lines].size() == 1); - BEAST_EXPECT( - linesA.isMember(jss::jsonrpc) && linesA[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - linesA.isMember(jss::ripplerpc) && - linesA[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(linesA.isMember(jss::jsonrpc) && linesA[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(linesA.isMember(jss::ripplerpc) && linesA[jss::ripplerpc] == "2.0"); BEAST_EXPECT(linesA.isMember(jss::id) && linesA[jss::id] == 5); // Pick up from where the marker left off. We should get 51. @@ -1142,11 +980,8 @@ public: auto const linesB = env.rpc("json2", to_string(requestB)); BEAST_EXPECT(linesB[jss::result][jss::lines].isArray()); BEAST_EXPECT(linesB[jss::result][jss::lines].size() == 51); - BEAST_EXPECT( - linesB.isMember(jss::jsonrpc) && linesB[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - linesB.isMember(jss::ripplerpc) && - linesB[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(linesB.isMember(jss::jsonrpc) && linesB[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(linesB.isMember(jss::ripplerpc) && linesB[jss::ripplerpc] == "2.0"); BEAST_EXPECT(linesB.isMember(jss::id) && linesB[jss::id] == 5); // Go again from where the marker left off, but set a limit of 3. @@ -1163,11 +998,8 @@ public: auto const linesC = env.rpc("json2", to_string(requestC)); BEAST_EXPECT(linesC[jss::result][jss::lines].isArray()); BEAST_EXPECT(linesC[jss::result][jss::lines].size() == 3); - BEAST_EXPECT( - linesC.isMember(jss::jsonrpc) && linesC[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - linesC.isMember(jss::ripplerpc) && - linesC[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(linesC.isMember(jss::jsonrpc) && linesC[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(linesC.isMember(jss::ripplerpc) && linesC[jss::ripplerpc] == "2.0"); BEAST_EXPECT(linesC.isMember(jss::id) && linesC[jss::id] == 5); // Mess with the marker so it becomes bad and check for the error. @@ -1182,14 +1014,9 @@ public: requestD[jss::id] = 5; requestD[jss::params] = paramsD; auto const linesD = env.rpc("json2", to_string(requestD)); - BEAST_EXPECT( - linesD[jss::error][jss::message] == - RPC::make_error(rpcINVALID_PARAMS)[jss::error_message]); - BEAST_EXPECT( - linesD.isMember(jss::jsonrpc) && linesD[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - linesD.isMember(jss::ripplerpc) && - linesD[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(linesD[jss::error][jss::message] == RPC::make_error(rpcINVALID_PARAMS)[jss::error_message]); + BEAST_EXPECT(linesD.isMember(jss::jsonrpc) && linesD[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(linesD.isMember(jss::ripplerpc) && linesD[jss::ripplerpc] == "2.0"); BEAST_EXPECT(linesD.isMember(jss::id) && linesD[jss::id] == 5); } { @@ -1204,14 +1031,9 @@ public: request[jss::id] = 5; request[jss::params] = params; auto const lines = env.rpc("json2", to_string(request)); - BEAST_EXPECT( - lines[jss::error][jss::message] == - RPC::expected_field_message(jss::marker, "string")); - BEAST_EXPECT( - lines.isMember(jss::jsonrpc) && lines[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - lines.isMember(jss::ripplerpc) && - lines[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(lines[jss::error][jss::message] == RPC::expected_field_message(jss::marker, "string")); + BEAST_EXPECT(lines.isMember(jss::jsonrpc) && lines[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(lines.isMember(jss::ripplerpc) && lines[jss::ripplerpc] == "2.0"); BEAST_EXPECT(lines.isMember(jss::id) && lines[jss::id] == 5); } { @@ -1232,11 +1054,8 @@ public: BEAST_EXPECT(line[jss::deep_freeze].asBool() == true); BEAST_EXPECT(line[jss::no_ripple].asBool() == true); BEAST_EXPECT(line[jss::peer_authorized].asBool() == true); - BEAST_EXPECT( - lines.isMember(jss::jsonrpc) && lines[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - lines.isMember(jss::ripplerpc) && - lines[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(lines.isMember(jss::jsonrpc) && lines[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(lines.isMember(jss::ripplerpc) && lines[jss::ripplerpc] == "2.0"); BEAST_EXPECT(lines.isMember(jss::id) && lines[jss::id] == 5); } { @@ -1257,11 +1076,8 @@ public: BEAST_EXPECT(lineA[jss::deep_freeze_peer].asBool() == true); BEAST_EXPECT(lineA[jss::no_ripple_peer].asBool() == true); BEAST_EXPECT(lineA[jss::authorized].asBool() == true); - BEAST_EXPECT( - linesA.isMember(jss::jsonrpc) && linesA[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - linesA.isMember(jss::ripplerpc) && - linesA[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(linesA.isMember(jss::jsonrpc) && linesA[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(linesA.isMember(jss::ripplerpc) && linesA[jss::ripplerpc] == "2.0"); BEAST_EXPECT(linesA.isMember(jss::id) && linesA[jss::id] == 5); // Continue from the returned marker to make sure that works. @@ -1282,11 +1098,8 @@ public: BEAST_EXPECT(linesB[jss::result][jss::lines].isArray()); BEAST_EXPECT(linesB[jss::result][jss::lines].size() == 25); BEAST_EXPECT(!linesB[jss::result].isMember(jss::marker)); - BEAST_EXPECT( - linesB.isMember(jss::jsonrpc) && linesB[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - linesB.isMember(jss::ripplerpc) && - linesB[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(linesB.isMember(jss::jsonrpc) && linesB[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(linesB.isMember(jss::ripplerpc) && linesB[jss::ripplerpc] == "2.0"); BEAST_EXPECT(linesB.isMember(jss::id) && linesB[jss::id] == 5); } } @@ -1351,14 +1164,10 @@ public: linesBegRequest[jss::id] = 5; linesBegRequest[jss::params] = linesBegParams; auto const linesBeg = env.rpc("json2", to_string(linesBegRequest)); - BEAST_EXPECT( - linesBeg[jss::result][jss::lines][0u][jss::currency] == "USD"); + BEAST_EXPECT(linesBeg[jss::result][jss::lines][0u][jss::currency] == "USD"); BEAST_EXPECT(linesBeg[jss::result].isMember(jss::marker)); - BEAST_EXPECT( - linesBeg.isMember(jss::jsonrpc) && linesBeg[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - linesBeg.isMember(jss::ripplerpc) && - linesBeg[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(linesBeg.isMember(jss::jsonrpc) && linesBeg[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(linesBeg.isMember(jss::ripplerpc) && linesBeg[jss::ripplerpc] == "2.0"); BEAST_EXPECT(linesBeg.isMember(jss::id) && linesBeg[jss::id] == 5); // alice pays 100 USD to cheri. @@ -1377,14 +1186,9 @@ public: linesEndRequest[jss::id] = 5; linesEndRequest[jss::params] = linesEndParams; auto const linesEnd = env.rpc("json2", to_string(linesEndRequest)); - BEAST_EXPECT( - linesEnd[jss::error][jss::message] == - RPC::make_error(rpcINVALID_PARAMS)[jss::error_message]); - BEAST_EXPECT( - linesEnd.isMember(jss::jsonrpc) && linesEnd[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - linesEnd.isMember(jss::ripplerpc) && - linesEnd[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(linesEnd[jss::error][jss::message] == RPC::make_error(rpcINVALID_PARAMS)[jss::error_message]); + BEAST_EXPECT(linesEnd.isMember(jss::jsonrpc) && linesEnd[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(linesEnd.isMember(jss::ripplerpc) && linesEnd[jss::ripplerpc] == "2.0"); BEAST_EXPECT(linesEnd.isMember(jss::id) && linesEnd[jss::id] == 5); } diff --git a/src/test/rpc/AccountObjects_test.cpp b/src/test/rpc/AccountObjects_test.cpp index 4f3e1817e1..0dec2bde7f 100644 --- a/src/test/rpc/AccountObjects_test.cpp +++ b/src/test/rpc/AccountObjects_test.cpp @@ -17,7 +17,7 @@ namespace xrpl { namespace test { -static char const* bobs_account_objects[] = { +static char const* bob_account_objects[] = { R"json({ "Account" : "rPMh7Pi9ct699iZUTWaytJUoHcJ7cgyziK", "BookDirectory" : "50AD0A9E54D2B381288D535EB724E4275FFBF41580D28A925D038D7EA4C68000", @@ -110,20 +110,16 @@ public: { Json::Value params; auto resp = env.rpc("json", "account_objects", to_string(params)); - BEAST_EXPECT( - resp[jss::result][jss::error_message] == - "Missing field 'account'."); + BEAST_EXPECT(resp[jss::result][jss::error_message] == "Missing field 'account'."); } // test account non-string { auto testInvalidAccountParam = [&](auto const& param) { Json::Value params; params[jss::account] = param; - auto jrr = env.rpc( - "json", "account_objects", to_string(params))[jss::result]; + auto jrr = env.rpc("json", "account_objects", to_string(params))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); - BEAST_EXPECT( - jrr[jss::error_message] == "Invalid field 'account'."); + BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'account'."); }; testInvalidAccountParam(1); @@ -136,19 +132,16 @@ public: // test error on malformed account string. { Json::Value params; - params[jss::account] = - "n94JNrQYkDrpt62bbSR7nVEhdyAvcJXRAsjEkFYyqRkh9SUTYEqV"; + params[jss::account] = "n94JNrQYkDrpt62bbSR7nVEhdyAvcJXRAsjEkFYyqRkh9SUTYEqV"; auto resp = env.rpc("json", "account_objects", to_string(params)); - BEAST_EXPECT( - resp[jss::result][jss::error_message] == "Account malformed."); + BEAST_EXPECT(resp[jss::result][jss::error_message] == "Account malformed."); } // test error on account that's not in the ledger. { Json::Value params; params[jss::account] = Account{"bogie"}.human(); auto resp = env.rpc("json", "account_objects", to_string(params)); - BEAST_EXPECT( - resp[jss::result][jss::error_message] == "Account not found."); + BEAST_EXPECT(resp[jss::result][jss::error_message] == "Account not found."); } Account const bob{"bob"}; // test error on large ledger_index. @@ -157,8 +150,7 @@ public: params[jss::account] = bob.human(); params[jss::ledger_index] = 10; auto resp = env.rpc("json", "account_objects", to_string(params)); - BEAST_EXPECT( - resp[jss::result][jss::error_message] == "ledgerNotFound"); + BEAST_EXPECT(resp[jss::result][jss::error_message] == "ledgerNotFound"); } env.fund(XRP(1000), bob); @@ -168,9 +160,7 @@ public: params[jss::account] = bob.human(); params[jss::type] = 10; auto resp = env.rpc("json", "account_objects", to_string(params)); - BEAST_EXPECT( - resp[jss::result][jss::error_message] == - "Invalid field 'type', not string."); + BEAST_EXPECT(resp[jss::result][jss::error_message] == "Invalid field 'type', not string."); } // test error on type param not a valid type { @@ -178,9 +168,7 @@ public: params[jss::account] = bob.human(); params[jss::type] = "expedited"; auto resp = env.rpc("json", "account_objects", to_string(params)); - BEAST_EXPECT( - resp[jss::result][jss::error_message] == - "Invalid field 'type'."); + BEAST_EXPECT(resp[jss::result][jss::error_message] == "Invalid field 'type'."); } // test error on limit -ve { @@ -188,9 +176,7 @@ public: params[jss::account] = bob.human(); params[jss::limit] = -1; auto resp = env.rpc("json", "account_objects", to_string(params)); - BEAST_EXPECT( - resp[jss::result][jss::error_message] == - "Invalid field 'limit', not unsigned integer."); + BEAST_EXPECT(resp[jss::result][jss::error_message] == "Invalid field 'limit', not unsigned integer."); } // test errors on marker { @@ -210,39 +196,27 @@ public: std::string mark = to_string(resume_marker); params[jss::marker] = 10; resp = env.rpc("json", "account_objects", to_string(params)); - BEAST_EXPECT( - resp[jss::result][jss::error_message] == - "Invalid field 'marker', not string."); + BEAST_EXPECT(resp[jss::result][jss::error_message] == "Invalid field 'marker', not string."); params[jss::marker] = "This is a string with no comma"; resp = env.rpc("json", "account_objects", to_string(params)); - BEAST_EXPECT( - resp[jss::result][jss::error_message] == - "Invalid field 'marker'."); + BEAST_EXPECT(resp[jss::result][jss::error_message] == "Invalid field 'marker'."); params[jss::marker] = "This string has a comma, but is not hex"; resp = env.rpc("json", "account_objects", to_string(params)); - BEAST_EXPECT( - resp[jss::result][jss::error_message] == - "Invalid field 'marker'."); + BEAST_EXPECT(resp[jss::result][jss::error_message] == "Invalid field 'marker'."); params[jss::marker] = std::string(&mark[1U], 64); resp = env.rpc("json", "account_objects", to_string(params)); - BEAST_EXPECT( - resp[jss::result][jss::error_message] == - "Invalid field 'marker'."); + BEAST_EXPECT(resp[jss::result][jss::error_message] == "Invalid field 'marker'."); params[jss::marker] = std::string(&mark[1U], 65); resp = env.rpc("json", "account_objects", to_string(params)); - BEAST_EXPECT( - resp[jss::result][jss::error_message] == - "Invalid field 'marker'."); + BEAST_EXPECT(resp[jss::result][jss::error_message] == "Invalid field 'marker'."); params[jss::marker] = std::string(&mark[1U], 65) + "not hex"; resp = env.rpc("json", "account_objects", to_string(params)); - BEAST_EXPECT( - resp[jss::result][jss::error_message] == - "Invalid field 'marker'."); + BEAST_EXPECT(resp[jss::result][jss::error_message] == "Invalid field 'marker'."); // Should this be an error? // A hex digit is absent from the end of marker. @@ -280,7 +254,7 @@ public: Json::Value bobj[4]; for (int i = 0; i < 4; ++i) - Json::Reader{}.parse(bobs_account_objects[i], bobj[i]); + Json::Reader{}.parse(bob_account_objects[i], bobj[i]); // test 'unstepped' // i.e. request account objects without explicit limit/marker paging @@ -323,8 +297,7 @@ public: params[jss::limit] = 1; for (int i = 0; i < 4; ++i) { - auto resp = - env.rpc("json", "account_objects", to_string(params)); + auto resp = env.rpc("json", "account_objects", to_string(params)); auto& aobjs = resp[jss::result][jss::account_objects]; BEAST_EXPECT(aobjs.size() == 1); auto& aobj = aobjs[0U]; @@ -405,8 +378,7 @@ public: BEAST_EXPECT(!resp.isMember(jss::marker)); Json::Value& aobjs = resp[jss::result][jss::account_objects]; BEAST_EXPECT(aobjs.size() == 1); - BEAST_EXPECT( - aobjs[0u][sfLedgerEntryType.jsonName] == jss::NFTokenPage); + BEAST_EXPECT(aobjs[0u][sfLedgerEntryType.jsonName] == jss::NFTokenPage); BEAST_EXPECT(aobjs[0u][sfNFTokens.jsonName].size() == 1); } // test stepped one-at-a-time with limit=1, resume from prev marker @@ -415,8 +387,7 @@ public: params[jss::account] = bob.human(); params[jss::limit] = 1; - Json::Value resp = - env.rpc("json", "account_objects", to_string(params)); + Json::Value resp = env.rpc("json", "account_objects", to_string(params)); Json::Value& aobjs = resp[jss::result][jss::account_objects]; BEAST_EXPECT(aobjs.size() == 1); auto& aobj = aobjs[0U]; @@ -456,8 +427,7 @@ public: BEAST_EXPECT(!resp.isMember(jss::marker)); Json::Value& aobjs = resp[jss::result][jss::account_objects]; BEAST_EXPECT(aobjs.size() == 1); - BEAST_EXPECT( - aobjs[0u][sfLedgerEntryType.jsonName] == jss::NFTokenPage); + BEAST_EXPECT(aobjs[0u][sfLedgerEntryType.jsonName] == jss::NFTokenPage); BEAST_EXPECT(aobjs[0u][sfNFTokens.jsonName].size() == 1); } // test stepped one-at-a-time with limit=1, resume from prev marker @@ -467,8 +437,7 @@ public: params[jss::limit] = 1; for (int i = 0; i < 5; ++i) { - Json::Value resp = - env.rpc("json", "account_objects", to_string(params)); + Json::Value resp = env.rpc("json", "account_objects", to_string(params)); Json::Value& aobjs = resp[jss::result][jss::account_objects]; BEAST_EXPECT(aobjs.size() == 1); auto& aobj = aobjs[0U]; @@ -522,8 +491,7 @@ public: params[jss::limit] = 1; for (int i = 0; i < 6; ++i) { - Json::Value resp = - env.rpc("json", "account_objects", to_string(params)); + Json::Value resp = env.rpc("json", "account_objects", to_string(params)); Json::Value& aobjs = resp[jss::result][jss::account_objects]; BEAST_EXPECT(aobjs.size() == 1); auto& aobj = aobjs[0U]; @@ -558,8 +526,7 @@ public: Account const gw{"gateway"}; auto const USD = gw["USD"]; - auto const features = testable_amendments() | featureXChainBridge | - featurePermissionedDomains; + auto const features = testable_amendments() | featureXChainBridge | featurePermissionedDomains; Env env(*this, features); // Make a lambda we can use to get "account_objects" easily. @@ -589,8 +556,7 @@ public: // Make a lambda that checks if the response has error for invalid type auto acctObjsTypeIsInvalid = [](Json::Value const& resp) { return resp[jss::result].isMember(jss::error) && - resp[jss::result][jss::error_message] == - "Invalid field \'type\'."; + resp[jss::result][jss::error_message] == "Invalid field \'type\'."; }; env.fund(XRP(10000), gw, alice); @@ -631,8 +597,7 @@ public: auto const& nftPage = resp[jss::result][jss::account_objects][0u]; BEAST_EXPECT(nftPage[sfNFTokens.jsonName].size() == 1); BEAST_EXPECT( - nftPage[sfNFTokens.jsonName][0u][sfNFToken.jsonName] - [sfNFTokenID.jsonName] == to_string(nftID)); + nftPage[sfNFTokens.jsonName][0u][sfNFToken.jsonName][sfNFTokenID.jsonName] == to_string(nftID)); } // Set up a trust line so we can find it. @@ -647,8 +612,7 @@ public: auto const& state = resp[jss::result][jss::account_objects][0u]; BEAST_EXPECT(state[sfBalance.jsonName][jss::value].asInt() == -5); - BEAST_EXPECT( - state[sfHighLimit.jsonName][jss::value].asUInt() == 1000); + BEAST_EXPECT(state[sfHighLimit.jsonName][jss::value].asUInt() == 1000); } // gw writes a check for USD(10) to alice. env(check::create(gw, alice, USD(10))); @@ -682,8 +646,7 @@ public: jvEscrow[jss::Account] = gw.human(); jvEscrow[jss::Destination] = gw.human(); jvEscrow[jss::Amount] = XRP(100).value().getJson(JsonOptions::none); - jvEscrow[sfFinishAfter.jsonName] = - env.now().time_since_epoch().count() + 1; + jvEscrow[sfFinishAfter.jsonName] = env.now().time_since_epoch().count() + 1; env(jvEscrow); env.close(); } @@ -711,30 +674,22 @@ public: Json::Value const resp = acctObjs(gw, jss::permissioned_domain); BEAST_EXPECT(acctObjsIsSize(resp, 1)); - auto const& permissionedDomain = - resp[jss::result][jss::account_objects][0u]; - BEAST_EXPECT( - permissionedDomain.isMember(jss::Owner) && - (permissionedDomain[jss::Owner] == gw.human())); + auto const& permissionedDomain = resp[jss::result][jss::account_objects][0u]; + BEAST_EXPECT(permissionedDomain.isMember(jss::Owner) && (permissionedDomain[jss::Owner] == gw.human())); bool const check1 = BEAST_EXPECT( permissionedDomain.isMember(jss::AcceptedCredentials) && permissionedDomain[jss::AcceptedCredentials].isArray() && (permissionedDomain[jss::AcceptedCredentials].size() == 1) && - (permissionedDomain[jss::AcceptedCredentials][0u].isMember( - jss::Credential))); + (permissionedDomain[jss::AcceptedCredentials][0u].isMember(jss::Credential))); if (check1) { - auto const& credential = - permissionedDomain[jss::AcceptedCredentials][0u] - [jss::Credential]; + auto const& credential = permissionedDomain[jss::AcceptedCredentials][0u][jss::Credential]; BEAST_EXPECT( - credential.isMember(sfIssuer.jsonName) && - (credential[sfIssuer.jsonName] == issuer.human())); + credential.isMember(sfIssuer.jsonName) && (credential[sfIssuer.jsonName] == issuer.human())); BEAST_EXPECT( credential.isMember(sfCredentialType.jsonName) && - (credential[sfCredentialType.jsonName] == - strHex(credentialType1))); + (credential[sfCredentialType.jsonName] == strHex(credentialType1))); } } @@ -752,30 +707,17 @@ public: return scEnv.rpc("json", "account_objects", to_string(params)); }; - Json::Value const resp = - scEnvAcctObjs(Account::master, jss::bridge); + Json::Value const resp = scEnvAcctObjs(Account::master, jss::bridge); BEAST_EXPECT(acctObjsIsSize(resp, 1)); - auto const& acct_bridge = - resp[jss::result][jss::account_objects][0u]; - BEAST_EXPECT( - acct_bridge[sfAccount.jsonName] == Account::master.human()); - BEAST_EXPECT( - acct_bridge[sfLedgerEntryType.getJsonName()] == "Bridge"); - BEAST_EXPECT( - acct_bridge[sfXChainClaimID.getJsonName()].asUInt() == 0); - BEAST_EXPECT( - acct_bridge[sfXChainAccountClaimCount.getJsonName()].asUInt() == - 0); - BEAST_EXPECT( - acct_bridge[sfXChainAccountCreateCount.getJsonName()] - .asUInt() == 0); - BEAST_EXPECT( - acct_bridge[sfMinAccountCreateAmount.getJsonName()].asUInt() == - 20000000); - BEAST_EXPECT( - acct_bridge[sfSignatureReward.getJsonName()].asUInt() == - 1000000); + auto const& acct_bridge = resp[jss::result][jss::account_objects][0u]; + BEAST_EXPECT(acct_bridge[sfAccount.jsonName] == Account::master.human()); + BEAST_EXPECT(acct_bridge[sfLedgerEntryType.getJsonName()] == "Bridge"); + BEAST_EXPECT(acct_bridge[sfXChainClaimID.getJsonName()].asUInt() == 0); + BEAST_EXPECT(acct_bridge[sfXChainAccountClaimCount.getJsonName()].asUInt() == 0); + BEAST_EXPECT(acct_bridge[sfXChainAccountCreateCount.getJsonName()].asUInt() == 0); + BEAST_EXPECT(acct_bridge[sfMinAccountCreateAmount.getJsonName()].asUInt() == 20000000); + BEAST_EXPECT(acct_bridge[sfSignatureReward.getJsonName()].asUInt() == 1000000); BEAST_EXPECT(acct_bridge[sfXChainBridge.getJsonName()] == x.jvb); } { @@ -785,8 +727,7 @@ public: Env scEnv(*this, envconfig(), features); x.createScBridgeObjects(scEnv); - scEnv( - xchain_create_claim_id(x.scAlice, x.jvb, x.reward, x.mcAlice)); + scEnv(xchain_create_claim_id(x.scAlice, x.jvb, x.reward, x.mcAlice)); scEnv.close(); scEnv(xchain_create_claim_id(x.scBob, x.jvb, x.reward, x.mcBob)); scEnv.close(); @@ -801,28 +742,21 @@ public: { // Find the xchain sequence number for Andrea. - Json::Value const resp = - scEnvAcctObjs(x.scAlice, jss::xchain_owned_claim_id); + Json::Value const resp = scEnvAcctObjs(x.scAlice, jss::xchain_owned_claim_id); BEAST_EXPECT(acctObjsIsSize(resp, 1)); - auto const& xchain_seq = - resp[jss::result][jss::account_objects][0u]; - BEAST_EXPECT( - xchain_seq[sfAccount.jsonName] == x.scAlice.human()); - BEAST_EXPECT( - xchain_seq[sfXChainClaimID.getJsonName()].asUInt() == 1); + auto const& xchain_seq = resp[jss::result][jss::account_objects][0u]; + BEAST_EXPECT(xchain_seq[sfAccount.jsonName] == x.scAlice.human()); + BEAST_EXPECT(xchain_seq[sfXChainClaimID.getJsonName()].asUInt() == 1); } { // and the one for Bob - Json::Value const resp = - scEnvAcctObjs(x.scBob, jss::xchain_owned_claim_id); + Json::Value const resp = scEnvAcctObjs(x.scBob, jss::xchain_owned_claim_id); BEAST_EXPECT(acctObjsIsSize(resp, 1)); - auto const& xchain_seq = - resp[jss::result][jss::account_objects][0u]; + auto const& xchain_seq = resp[jss::result][jss::account_objects][0u]; BEAST_EXPECT(xchain_seq[sfAccount.jsonName] == x.scBob.human()); - BEAST_EXPECT( - xchain_seq[sfXChainClaimID.getJsonName()].asUInt() == 2); + BEAST_EXPECT(xchain_seq[sfXChainClaimID.getJsonName()].asUInt() == 2); } } { @@ -836,16 +770,7 @@ public: // account (Account::master) to collect the signatures until a // quorum is reached scEnv(test::jtx::create_account_attestation( - x.scAttester, - x.jvb, - x.mcCarol, - amt, - x.reward, - x.payees[0], - true, - 1, - x.scuAlice, - x.signers[0])); + x.scAttester, x.jvb, x.mcCarol, amt, x.reward, x.payees[0], true, 1, x.scuAlice, x.signers[0])); scEnv.close(); auto scEnvAcctObjs = [&](Account const& acct, char const* type) { @@ -858,19 +783,12 @@ public: { // Find the xchain_create_account_claim_id - Json::Value const resp = scEnvAcctObjs( - Account::master, jss::xchain_owned_create_account_claim_id); + Json::Value const resp = scEnvAcctObjs(Account::master, jss::xchain_owned_create_account_claim_id); BEAST_EXPECT(acctObjsIsSize(resp, 1)); - auto const& xchain_create_account_claim_id = - resp[jss::result][jss::account_objects][0u]; - BEAST_EXPECT( - xchain_create_account_claim_id[sfAccount.jsonName] == - Account::master.human()); - BEAST_EXPECT( - xchain_create_account_claim_id[sfXChainAccountCreateCount - .getJsonName()] - .asUInt() == 1); + auto const& xchain_create_account_claim_id = resp[jss::result][jss::account_objects][0u]; + BEAST_EXPECT(xchain_create_account_claim_id[sfAccount.jsonName] == Account::master.human()); + BEAST_EXPECT(xchain_create_account_claim_id[sfXChainAccountCreateCount.getJsonName()].asUInt() == 1); } } @@ -894,8 +812,7 @@ public: jvPayChan[jss::TransactionType] = jss::PaymentChannelCreate; jvPayChan[jss::Account] = gw.human(); jvPayChan[jss::Destination] = alice.human(); - jvPayChan[jss::Amount] = - XRP(300).value().getJson(JsonOptions::none); + jvPayChan[jss::Amount] = XRP(300).value().getJson(JsonOptions::none); jvPayChan[sfSettleDelay.jsonName] = 24 * 60 * 60; jvPayChan[sfPublicKey.jsonName] = strHex(gw.pk().slice()); env(jvPayChan); @@ -909,8 +826,7 @@ public: auto const& payChan = resp[jss::result][jss::account_objects][0u]; BEAST_EXPECT(payChan[sfAccount.jsonName] == gw.human()); BEAST_EXPECT(payChan[sfAmount.jsonName].asUInt() == 300'000'000); - BEAST_EXPECT( - payChan[sfSettleDelay.jsonName].asUInt() == 24 * 60 * 60); + BEAST_EXPECT(payChan[sfSettleDelay.jsonName].asUInt() == 24 * 60 * 60); } { @@ -939,11 +855,9 @@ public: Json::Value const resp = acctObjs(gw, jss::signer_list); BEAST_EXPECT(acctObjsIsSize(resp, 1)); - auto const& signerList = - resp[jss::result][jss::account_objects][0u]; + auto const& signerList = resp[jss::result][jss::account_objects][0u]; BEAST_EXPECT(signerList[sfSignerQuorum.jsonName] == 6); - auto const& entry = signerList[sfSignerEntries.jsonName][0u] - [sfSignerEntry.jsonName]; + auto const& entry = signerList[sfSignerEntries.jsonName][0u][sfSignerEntry.jsonName]; BEAST_EXPECT(entry[sfAccount.jsonName] == alice.human()); BEAST_EXPECT(entry[sfSignerWeight.jsonName].asUInt() == 7); } @@ -983,8 +897,7 @@ public: return v; }(); - std::uint32_t const expectedAccountObjects{ - static_cast(std::size(expectedLedgerTypes))}; + std::uint32_t const expectedAccountObjects{static_cast(std::size(expectedLedgerTypes))}; if (BEAST_EXPECT(acctObjsIsSize(resp, expectedAccountObjects))) { @@ -993,8 +906,7 @@ public: gotLedgerTypes.reserve(expectedAccountObjects); for (std::uint32_t i = 0; i < expectedAccountObjects; ++i) { - gotLedgerTypes.push_back( - aobjs[i]["LedgerEntryType"].asString()); + gotLedgerTypes.push_back(aobjs[i]["LedgerEntryType"].asString()); } std::sort(gotLedgerTypes.begin(), gotLedgerTypes.end()); BEAST_EXPECT(gotLedgerTypes == expectedLedgerTypes); @@ -1017,19 +929,15 @@ public: } { // Make a lambda to get the types - auto getTypes = [&](Json::Value const& resp, - std::vector& typesOut) { + auto getTypes = [&](Json::Value const& resp, std::vector& typesOut) { auto const objs = resp[jss::result][jss::account_objects]; for (auto const& obj : resp[jss::result][jss::account_objects]) - typesOut.push_back( - obj[sfLedgerEntryType.fieldName].asString()); + typesOut.push_back(obj[sfLedgerEntryType.fieldName].asString()); std::sort(typesOut.begin(), typesOut.end()); }; // Make a lambda we can use to check the number of fetched // account objects and their ledger type - auto expectObjects = - [&](Json::Value const& resp, - std::vector const& types) -> bool { + auto expectObjects = [&](Json::Value const& resp, std::vector const& types) -> bool { if (!acctObjsIsSize(resp, types.size())) return false; std::vector typesOut; @@ -1043,36 +951,24 @@ public: auto const lines = getAccountLines(env, amm.ammAccount()); BEAST_EXPECT(lines[jss::lines].size() == 3); // request AMM only, doesn't depend on the limit - BEAST_EXPECT( - acctObjsIsSize(acctObjs(amm.ammAccount(), jss::amm), 1)); + BEAST_EXPECT(acctObjsIsSize(acctObjs(amm.ammAccount(), jss::amm), 1)); // request first two objects auto resp = acctObjs(amm.ammAccount(), std::nullopt, 2); std::vector typesOut; getTypes(resp, typesOut); // request next two objects - resp = acctObjs( - amm.ammAccount(), - std::nullopt, - 10, - resp[jss::result][jss::marker].asString()); + resp = acctObjs(amm.ammAccount(), std::nullopt, 10, resp[jss::result][jss::marker].asString()); getTypes(resp, typesOut); BEAST_EXPECT( (typesOut == std::vector{ - jss::AMM.c_str(), - jss::RippleState.c_str(), - jss::RippleState.c_str(), - jss::RippleState.c_str()})); + jss::AMM.c_str(), jss::RippleState.c_str(), jss::RippleState.c_str(), jss::RippleState.c_str()})); // filter by state: there are three trustlines resp = acctObjs(amm.ammAccount(), jss::state, 10); - BEAST_EXPECT(expectObjects( - resp, - {jss::RippleState.c_str(), - jss::RippleState.c_str(), - jss::RippleState.c_str()})); - // AMM account doesn't own offers BEAST_EXPECT( - acctObjsIsSize(acctObjs(amm.ammAccount(), jss::offer), 0)); + expectObjects(resp, {jss::RippleState.c_str(), jss::RippleState.c_str(), jss::RippleState.c_str()})); + // AMM account doesn't own offers + BEAST_EXPECT(acctObjsIsSize(acctObjs(amm.ammAccount(), jss::offer), 0)); // gw account doesn't own AMM object BEAST_EXPECT(acctObjsIsSize(acctObjs(gw, jss::amm), 0)); } @@ -1125,8 +1021,7 @@ public: Json::Value params; params[jss::account] = bob.human(); params[jss::ledger_index] = "validated"; - Json::Value const resp = - env.rpc("json", "account_nfts", to_string(params)); + Json::Value const resp = env.rpc("json", "account_nfts", to_string(params)); Json::Value const& nfts = resp[jss::result][jss::account_nfts]; for (Json::Value const& nft : nfts) tokenIDs.push_back(nft["NFTokenID"]); @@ -1135,23 +1030,20 @@ public: // this lambda function is used to check if the account_nfts method // returns the correct token information. lastIndex is used to query the // last marker. - auto compareNFTs = [&tokenIDs, &env, &bob]( - unsigned const limit, unsigned const lastIndex) { + auto compareNFTs = [&tokenIDs, &env, &bob](unsigned const limit, unsigned const lastIndex) { Json::Value params; params[jss::account] = bob.human(); params[jss::limit] = limit; params[jss::marker] = tokenIDs[lastIndex]; params[jss::ledger_index] = "validated"; - Json::Value const resp = - env.rpc("json", "account_nfts", to_string(params)); + Json::Value const resp = env.rpc("json", "account_nfts", to_string(params)); if (resp[jss::result].isMember(jss::error)) return false; Json::Value const& nfts = resp[jss::result][jss::account_nfts]; - unsigned const nftsCount = tokenIDs.size() - lastIndex - 1 < limit - ? tokenIDs.size() - lastIndex - 1 - : limit; + unsigned const nftsCount = + tokenIDs.size() - lastIndex - 1 < limit ? tokenIDs.size() - lastIndex - 1 : limit; if (nfts.size() != nftsCount) return false; @@ -1172,26 +1064,22 @@ public: BEAST_EXPECT(compareNFTs(4, 7)); // lambda that holds common code for invalid cases. - auto testInvalidMarker = [&env, &bob]( - auto marker, char const* errorMessage) { + auto testInvalidMarker = [&env, &bob](auto marker, char const* errorMessage) { Json::Value params; params[jss::account] = bob.human(); params[jss::limit] = 4; params[jss::ledger_index] = jss::validated; params[jss::marker] = marker; - Json::Value const resp = - env.rpc("json", "account_nfts", to_string(params)); + Json::Value const resp = env.rpc("json", "account_nfts", to_string(params)); return resp[jss::result][jss::error_message] == errorMessage; }; // test an invalid marker that is not a string - BEAST_EXPECT( - testInvalidMarker(17, "Invalid field \'marker\', not string.")); + BEAST_EXPECT(testInvalidMarker(17, "Invalid field \'marker\', not string.")); // test an invalid marker that has a non-hex character BEAST_EXPECT(testInvalidMarker( - "00000000F51DFC2A09D62CBBA1DFBDD4691DAC96AD98B900000000000000000G", - "Invalid field \'marker\'.")); + "00000000F51DFC2A09D62CBBA1DFBDD4691DAC96AD98B900000000000000000G", "Invalid field \'marker\'.")); // this lambda function is used to create some fake marker using given // taxon and sequence because we want to test some unassociated markers @@ -1202,20 +1090,17 @@ public: std::uint16_t flags = 0, std::uint16_t fee = 0) { // the marker has the exact same format as an NFTokenID - return to_string(NFTokenMint::createNFTokenID( - flags, fee, issuer, nft::toTaxon(taxon), tokenSeq)); + return to_string(NFTokenMint::createNFTokenID(flags, fee, issuer, nft::toTaxon(taxon), tokenSeq)); }; // test an unassociated marker which does not exist in the NFTokenIDs - BEAST_EXPECT(testInvalidMarker( - createFakeNFTMarker(bob.id(), 0x000000000, 0x00000000), - "Invalid field \'marker\'.")); + BEAST_EXPECT( + testInvalidMarker(createFakeNFTMarker(bob.id(), 0x000000000, 0x00000000), "Invalid field \'marker\'.")); // test an unassociated marker which exceeds the maximum value of the // existing NFTokenID - BEAST_EXPECT(testInvalidMarker( - createFakeNFTMarker(bob.id(), 0xFFFFFFFF, 0xFFFFFFFF), - "Invalid field \'marker\'.")); + BEAST_EXPECT( + testInvalidMarker(createFakeNFTMarker(bob.id(), 0xFFFFFFFF, 0xFFFFFFFF), "Invalid field \'marker\'.")); } void @@ -1231,11 +1116,9 @@ public: auto testInvalidAccountParam = [&](auto const& param) { Json::Value params; params[jss::account] = param; - auto jrr = env.rpc( - "json", "account_nfts", to_string(params))[jss::result]; + auto jrr = env.rpc("json", "account_nfts", to_string(params))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); - BEAST_EXPECT( - jrr[jss::error_message] == "Invalid field 'account'."); + BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'account'."); }; testInvalidAccountParam(1); @@ -1306,10 +1189,8 @@ public: params[jss::limit] = limit; params[jss::ledger_index] = jss::validated; params[jss::marker] = marker; - Json::Value const resp = - env.rpc("json", "account_objects", to_string(params)); - return resp[jss::result][jss::error_message] == - "Invalid field \'marker\'."; + Json::Value const resp = env.rpc("json", "account_objects", to_string(params)); + return resp[jss::result][jss::error_message] == "Invalid field \'marker\'."; }; auto const markerStr = marker.asString(); @@ -1395,8 +1276,7 @@ public: auto resp = env.rpc("json", "account_objects", to_string(params)); auto& accountObjects = resp[jss::result][jss::account_objects]; BEAST_EXPECT(!resp[jss::result].isMember(jss::error)); - BEAST_EXPECT( - accountObjects.size() == accountObjectSize - limit * 2); + BEAST_EXPECT(accountObjects.size() == accountObjectSize - limit * 2); BEAST_EXPECT(!resp[jss::result].isMember(jss::marker)); } diff --git a/src/test/rpc/AccountOffers_test.cpp b/src/test/rpc/AccountOffers_test.cpp index 2c03239bd8..ffa1d70992 100644 --- a/src/test/rpc/AccountOffers_test.cpp +++ b/src/test/rpc/AccountOffers_test.cpp @@ -12,8 +12,7 @@ public: static bool checkMarker(Json::Value const& val) { - return val.isMember(jss::marker) && val[jss::marker].isString() && - val[jss::marker].asString().size() > 0; + return val.isMember(jss::marker) && val[jss::marker].isString() && val[jss::marker].asString().size() > 0; } void @@ -44,8 +43,7 @@ public: } // make non-limited RPC call - auto const jro_nl = - env.rpc("account_offers", bob.human())[jss::result][jss::offers]; + auto const jro_nl = env.rpc("account_offers", bob.human())[jss::result][jss::offers]; BEAST_EXPECT(checkArraySize(jro_nl, offer_count)); // now make a low-limit query, should get "corrected" @@ -54,8 +52,7 @@ public: Json::Value jvParams; jvParams[jss::account] = bob.human(); jvParams[jss::limit] = 1u; - auto const jrr_l = env.rpc( - "json", "account_offers", jvParams.toStyledString())[jss::result]; + auto const jrr_l = env.rpc("json", "account_offers", jvParams.toStyledString())[jss::result]; auto const& jro_l = jrr_l[jss::offers]; BEAST_EXPECT(checkMarker(jrr_l)); // 9u is the expected size, since one account object is a trustline @@ -65,8 +62,7 @@ public: void testSequential(bool asAdmin) { - testcase( - std::string("Sequential - ") + (asAdmin ? "admin" : "non-admin")); + testcase(std::string("Sequential - ") + (asAdmin ? "admin" : "non-admin")); using namespace jtx; Env env{*this, asAdmin ? envconfig() : envconfig(no_admin)}; @@ -88,8 +84,7 @@ public: env(offer(bob, XRP(30), USD_gw(6))); // make the RPC call - auto const jroOuter = - env.rpc("account_offers", bob.human())[jss::result][jss::offers]; + auto const jroOuter = env.rpc("account_offers", bob.human())[jss::result][jss::offers]; if (BEAST_EXPECT(checkArraySize(jroOuter, 3u))) { // Note that the returned offers are sorted by index, not by @@ -98,22 +93,19 @@ public: // if the sequence numbers or the account IDs change. BEAST_EXPECT(jroOuter[0u][jss::quality] == "100000000"); BEAST_EXPECT(jroOuter[0u][jss::taker_gets][jss::currency] == "USD"); - BEAST_EXPECT( - jroOuter[0u][jss::taker_gets][jss::issuer] == gw.human()); + BEAST_EXPECT(jroOuter[0u][jss::taker_gets][jss::issuer] == gw.human()); BEAST_EXPECT(jroOuter[0u][jss::taker_gets][jss::value] == "2"); BEAST_EXPECT(jroOuter[0u][jss::taker_pays] == "200000000"); BEAST_EXPECT(jroOuter[1u][jss::quality] == "100000000"); BEAST_EXPECT(jroOuter[1u][jss::taker_gets][jss::currency] == "USD"); - BEAST_EXPECT( - jroOuter[1u][jss::taker_gets][jss::issuer] == bob.human()); + BEAST_EXPECT(jroOuter[1u][jss::taker_gets][jss::issuer] == bob.human()); BEAST_EXPECT(jroOuter[1u][jss::taker_gets][jss::value] == "1"); BEAST_EXPECT(jroOuter[1u][jss::taker_pays] == "100000000"); BEAST_EXPECT(jroOuter[2u][jss::quality] == "5000000"); BEAST_EXPECT(jroOuter[2u][jss::taker_gets][jss::currency] == "USD"); - BEAST_EXPECT( - jroOuter[2u][jss::taker_gets][jss::issuer] == gw.human()); + BEAST_EXPECT(jroOuter[2u][jss::taker_gets][jss::issuer] == gw.human()); BEAST_EXPECT(jroOuter[2u][jss::taker_gets][jss::value] == "6"); BEAST_EXPECT(jroOuter[2u][jss::taker_pays] == "30000000"); } @@ -123,10 +115,7 @@ public: Json::Value jvParams; jvParams[jss::account] = bob.human(); jvParams[jss::limit] = 1u; - auto const jrr_l_1 = env.rpc( - "json", - "account_offers", - jvParams.toStyledString())[jss::result]; + auto const jrr_l_1 = env.rpc("json", "account_offers", jvParams.toStyledString())[jss::result]; auto const& jro_l_1 = jrr_l_1[jss::offers]; // there is a difference in the validation of the limit param // between admin and non-admin requests. with admin requests, the @@ -134,19 +123,14 @@ public: // non-admin there are pre-configured limit ranges applied. That's // why we have different BEAST_EXPECT()s here for the two scenarios BEAST_EXPECT(checkArraySize(jro_l_1, asAdmin ? 1u : 3u)); - BEAST_EXPECT( - asAdmin ? checkMarker(jrr_l_1) - : (!jrr_l_1.isMember(jss::marker))); + BEAST_EXPECT(asAdmin ? checkMarker(jrr_l_1) : (!jrr_l_1.isMember(jss::marker))); if (asAdmin) { BEAST_EXPECT(jroOuter[0u] == jro_l_1[0u]); // second item...with previous marker passed jvParams[jss::marker] = jrr_l_1[jss::marker]; - auto const jrr_l_2 = env.rpc( - "json", - "account_offers", - jvParams.toStyledString())[jss::result]; + auto const jrr_l_2 = env.rpc("json", "account_offers", jvParams.toStyledString())[jss::result]; auto const& jro_l_2 = jrr_l_2[jss::offers]; BEAST_EXPECT(checkMarker(jrr_l_2)); BEAST_EXPECT(checkArraySize(jro_l_2, 1u)); @@ -155,10 +139,7 @@ public: // last item...with previous marker passed jvParams[jss::marker] = jrr_l_2[jss::marker]; jvParams[jss::limit] = 10u; - auto const jrr_l_3 = env.rpc( - "json", - "account_offers", - jvParams.toStyledString())[jss::result]; + auto const jrr_l_3 = env.rpc("json", "account_offers", jvParams.toStyledString())[jss::result]; auto const& jro_l_3 = jrr_l_3[jss::offers]; BEAST_EXPECT(!jrr_l_3.isMember(jss::marker)); BEAST_EXPECT(checkArraySize(jro_l_3, 1u)); @@ -174,10 +155,7 @@ public: Json::Value jvParams; jvParams[jss::account] = bob.human(); jvParams[jss::limit] = 0u; - auto const jrr = env.rpc( - "json", - "account_offers", - jvParams.toStyledString())[jss::result]; + auto const jrr = env.rpc("json", "account_offers", jvParams.toStyledString())[jss::result]; BEAST_EXPECT(jrr.isMember(jss::error_message)); } } @@ -210,11 +188,9 @@ public: auto testInvalidAccountParam = [&](auto const& param) { Json::Value params; params[jss::account] = param; - auto jrr = env.rpc( - "json", "account_offers", to_string(params))[jss::result]; + auto jrr = env.rpc("json", "account_offers", to_string(params))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); - BEAST_EXPECT( - jrr[jss::error_message] == "Invalid field 'account'."); + BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'account'."); }; testInvalidAccountParam(1); @@ -229,10 +205,7 @@ public: // empty string account Json::Value jvParams; jvParams[jss::account] = ""; - auto const jrr = env.rpc( - "json", - "account_offers", - jvParams.toStyledString())[jss::result]; + auto const jrr = env.rpc("json", "account_offers", jvParams.toStyledString())[jss::result]; BEAST_EXPECT(jrr[jss::error] == "actMalformed"); BEAST_EXPECT(jrr[jss::status] == "error"); BEAST_EXPECT(jrr[jss::error_message] == "Account malformed."); @@ -240,8 +213,7 @@ public: { // bogus account value - auto const jrr = env.rpc( - "account_offers", Account("bogus").human())[jss::result]; + auto const jrr = env.rpc("account_offers", Account("bogus").human())[jss::result]; BEAST_EXPECT(jrr[jss::error] == "actNotFound"); BEAST_EXPECT(jrr[jss::status] == "error"); BEAST_EXPECT(jrr[jss::error_message] == "Account not found."); @@ -252,15 +224,10 @@ public: Json::Value jvParams; jvParams[jss::account] = bob.human(); jvParams[jss::limit] = "0"; // NOT an integer - auto const jrr = env.rpc( - "json", - "account_offers", - jvParams.toStyledString())[jss::result]; + auto const jrr = env.rpc("json", "account_offers", jvParams.toStyledString())[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); BEAST_EXPECT(jrr[jss::status] == "error"); - BEAST_EXPECT( - jrr[jss::error_message] == - "Invalid field 'limit', not unsigned integer."); + BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'limit', not unsigned integer."); } { @@ -268,15 +235,10 @@ public: Json::Value jvParams; jvParams[jss::account] = bob.human(); jvParams[jss::marker] = "NOT_A_MARKER"; - auto const jrr = env.rpc( - "json", - "account_offers", - jvParams.toStyledString())[jss::result]; + auto const jrr = env.rpc("json", "account_offers", jvParams.toStyledString())[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); BEAST_EXPECT(jrr[jss::status] == "error"); - BEAST_EXPECTS( - jrr[jss::error_message] == "Invalid field 'marker'.", - jrr.toStyledString()); + BEAST_EXPECTS(jrr[jss::error_message] == "Invalid field 'marker'.", jrr.toStyledString()); } { @@ -284,15 +246,10 @@ public: Json::Value jvParams; jvParams[jss::account] = bob.human(); jvParams[jss::marker] = 1; - auto const jrr = env.rpc( - "json", - "account_offers", - jvParams.toStyledString())[jss::result]; + auto const jrr = env.rpc("json", "account_offers", jvParams.toStyledString())[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); BEAST_EXPECT(jrr[jss::status] == "error"); - BEAST_EXPECT( - jrr[jss::error_message] == - "Invalid field 'marker', not string."); + BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'marker', not string."); } { @@ -300,10 +257,7 @@ public: Json::Value jvParams; jvParams[jss::account] = bob.human(); jvParams[jss::ledger_index] = 10u; - auto const jrr = env.rpc( - "json", - "account_offers", - jvParams.toStyledString())[jss::result]; + auto const jrr = env.rpc("json", "account_offers", jvParams.toStyledString())[jss::result]; BEAST_EXPECT(jrr[jss::error] == "lgrNotFound"); BEAST_EXPECT(jrr[jss::status] == "error"); BEAST_EXPECT(jrr[jss::error_message] == "ledgerNotFound"); diff --git a/src/test/rpc/AccountSet_test.cpp b/src/test/rpc/AccountSet_test.cpp index 40ef4acba7..2e238773f9 100644 --- a/src/test/rpc/AccountSet_test.cpp +++ b/src/test/rpc/AccountSet_test.cpp @@ -44,12 +44,9 @@ public: env(regkey(alice, alie)); env.close(); - auto testFlags = [this, &alice, &alie, &env]( - std::initializer_list goodFlags) { + auto testFlags = [this, &alice, &alie, &env](std::initializer_list goodFlags) { std::uint32_t const orig_flags = (*env.le(alice))[sfFlags]; - for (std::uint32_t flag{1u}; - flag < std::numeric_limits::digits; - ++flag) + for (std::uint32_t flag{1u}; flag < std::numeric_limits::digits; ++flag) { if (flag == asfNoFreeze) { @@ -66,10 +63,8 @@ public: continue; } - if (flag == asfDisallowIncomingCheck || - flag == asfDisallowIncomingPayChan || - flag == asfDisallowIncomingNFTokenOffer || - flag == asfDisallowIncomingTrustline) + if (flag == asfDisallowIncomingCheck || flag == asfDisallowIncomingPayChan || + flag == asfDisallowIncomingNFTokenOffer || flag == asfDisallowIncomingTrustline) { // These flags are part of the DisallowIncoming amendment // and are tested elsewhere @@ -88,8 +83,7 @@ public: continue; } - if (std::find(goodFlags.begin(), goodFlags.end(), flag) != - goodFlags.end()) + if (std::find(goodFlags.begin(), goodFlags.end(), flag) != goodFlags.end()) { // Good flag env.require(nflags(alice, flag)); @@ -200,8 +194,7 @@ public: std::size_t const maxLength = 256; for (std::size_t len = maxLength - 1; len <= maxLength + 1; ++len) { - std::string domain2 = - std::string(len - domain.length() - 1, 'a') + "." + domain; + std::string domain2 = std::string(len - domain.length() - 1, 'a') + "." + domain; BEAST_EXPECT(domain2.length() == len); @@ -233,9 +226,7 @@ public: auto const rkp = randomKeyPair(KeyType::ed25519); jt[sfMessageKey.fieldName] = strHex(rkp.first.slice()); env(jt); - BEAST_EXPECT( - strHex((*env.le(alice))[sfMessageKey]) == - strHex(rkp.first.slice())); + BEAST_EXPECT(strHex((*env.le(alice))[sfMessageKey]) == strHex(rkp.first.slice())); jt[sfMessageKey.fieldName] = ""; env(jt); @@ -257,8 +248,7 @@ public: env.fund(XRP(10000), alice); auto jt = noop(alice); - std::string const locator = - "9633EC8AF54F16B5286DB1D7B519EF49EEFC050C0C8AC4384F1D88ACD1BFDF05"; + std::string const locator = "9633EC8AF54F16B5286DB1D7B519EF49EEFC050C0C8AC4384F1D88ACD1BFDF05"; jt[sfWalletLocator.fieldName] = locator; env(jt); BEAST_EXPECT(to_string((*env.le(alice))[sfWalletLocator]) == locator); @@ -302,9 +292,7 @@ public: testcase("TransferRate"); using namespace test::jtx; - auto doTests = [this]( - FeatureBitset const& features, - std::initializer_list testData) { + auto doTests = [this](FeatureBitset const& features, std::initializer_list testData) { Env env(*this, features); Account const alice("alice"); @@ -319,9 +307,7 @@ public: if (!(*env.le(alice))[~sfTransferRate]) BEAST_EXPECT(r.get == 1.0); else - BEAST_EXPECT( - *(*env.le(alice))[~sfTransferRate] == - r.get * QUALITY_ONE); + BEAST_EXPECT(*(*env.le(alice))[~sfTransferRate] == r.get * QUALITY_ONE); } }; @@ -349,8 +335,7 @@ public: auto const USD = gw["USD"]; // Test gateway with a variety of allowed transfer rates - for (double transferRate = 1.0; transferRate <= 2.0; - transferRate += 0.03125) + for (double transferRate = 1.0; transferRate <= 2.0; transferRate += 0.03125) { Env env(*this); env.fund(XRP(10000), gw, alice, bob); @@ -362,8 +347,7 @@ public: auto const amount = USD(1); Rate const rate(transferRate * QUALITY_ONE); - auto const amountWithRate = - toAmount(multiply(amount.value(), rate)); + auto const amountWithRate = toAmount(multiply(amount.value(), rate)); env(pay(gw, alice, USD(10))); env.close(); @@ -412,25 +396,22 @@ public: // Note that we're bypassing almost all of the ledger's safety // checks with this modify() call. If you call close() between // here and the end of the test all the effort will be lost. - env.app().openLedger().modify( - [&gw, transferRate](OpenView& view, beast::Journal j) { - // Get the account root we want to hijack. - auto const sle = view.read(keylet::account(gw.id())); - if (!sle) - return false; // This would be really surprising! + env.app().openLedger().modify([&gw, transferRate](OpenView& view, beast::Journal j) { + // Get the account root we want to hijack. + auto const sle = view.read(keylet::account(gw.id())); + if (!sle) + return false; // This would be really surprising! - // We'll insert a replacement for the account root - // with the higher (currently invalid) transfer rate. - auto replacement = std::make_shared(*sle, sle->key()); - (*replacement)[sfTransferRate] = - static_cast(transferRate * QUALITY_ONE); - view.rawReplace(replacement); - return true; - }); + // We'll insert a replacement for the account root + // with the higher (currently invalid) transfer rate. + auto replacement = std::make_shared(*sle, sle->key()); + (*replacement)[sfTransferRate] = static_cast(transferRate * QUALITY_ONE); + view.rawReplace(replacement); + return true; + }); auto const amount = USD(1); - auto const amountWithRate = toAmount( - multiply(amount.value(), Rate(transferRate * QUALITY_ONE))); + auto const amountWithRate = toAmount(multiply(amount.value(), Rate(transferRate * QUALITY_ONE))); env(pay(gw, alice, USD(10))); env(pay(alice, bob, amount), sendmax(USD(10))); @@ -478,9 +459,7 @@ public: jt[sfFlags.fieldName] = tfAccountSetMask; env(jt, ter(temINVALID_FLAG)); - env(fset(alice, asfDisableMaster), - sig(alice), - ter(tecNO_ALTERNATIVE_KEY)); + env(fset(alice, asfDisableMaster), sig(alice), ter(tecNO_ALTERNATIVE_KEY)); } void diff --git a/src/test/rpc/AccountTx_test.cpp b/src/test/rpc/AccountTx_test.cpp index 36d29236d1..3cc9dbc77c 100644 --- a/src/test/rpc/AccountTx_test.cpp +++ b/src/test/rpc/AccountTx_test.cpp @@ -52,38 +52,26 @@ class AccountTx_test : public beast::unit_test::suite checkSanity(Json::Value const& txNode, NodeSanity const& sane) { BEAST_EXPECT(txNode[jss::validated].asBool() == true); - BEAST_EXPECT( - txNode[jss::tx][sfTransactionType.jsonName].asString() == - sane.txType); + BEAST_EXPECT(txNode[jss::tx][sfTransactionType.jsonName].asString() == sane.txType); // Make sure all of the expected node types are present. boost::container::flat_set createdNodes; boost::container::flat_set deletedNodes; boost::container::flat_set modifiedNodes; - for (Json::Value const& metaNode : - txNode[jss::meta][sfAffectedNodes.jsonName]) + for (Json::Value const& metaNode : txNode[jss::meta][sfAffectedNodes.jsonName]) { if (metaNode.isMember(sfCreatedNode.jsonName)) - createdNodes.insert( - metaNode[sfCreatedNode.jsonName][sfLedgerEntryType.jsonName] - .asString()); + createdNodes.insert(metaNode[sfCreatedNode.jsonName][sfLedgerEntryType.jsonName].asString()); else if (metaNode.isMember(sfDeletedNode.jsonName)) - deletedNodes.insert( - metaNode[sfDeletedNode.jsonName][sfLedgerEntryType.jsonName] - .asString()); + deletedNodes.insert(metaNode[sfDeletedNode.jsonName][sfLedgerEntryType.jsonName].asString()); else if (metaNode.isMember(sfModifiedNode.jsonName)) - modifiedNodes.insert(metaNode[sfModifiedNode.jsonName] - [sfLedgerEntryType.jsonName] - .asString()); + modifiedNodes.insert(metaNode[sfModifiedNode.jsonName][sfLedgerEntryType.jsonName].asString()); else - fail( - "Unexpected or unlabeled node type in metadata.", - __FILE__, - __LINE__); + fail("Unexpected or unlabeled node type in metadata.", __FILE__, __LINE__); } BEAST_EXPECT(createdNodes == sane.created); @@ -112,47 +100,34 @@ class AccountTx_test : public beast::unit_test::suite switch (apiVersion) { case 1: - return j.isMember(jss::result) && - (j[jss::result][jss::status] == "success") && + return j.isMember(jss::result) && (j[jss::result][jss::status] == "success") && (j[jss::result][jss::transactions].size() == 2) && - (j[jss::result][jss::transactions][0u][jss::tx] - [jss::TransactionType] == jss::AccountSet) && - (j[jss::result][jss::transactions][1u][jss::tx] - [jss::TransactionType] == jss::Payment) && - (j[jss::result][jss::transactions][1u][jss::tx] - [jss::DeliverMax] == "10000000010") && - (j[jss::result][jss::transactions][1u][jss::tx] - [jss::Amount] == - j[jss::result][jss::transactions][1u][jss::tx] - [jss::DeliverMax]); + (j[jss::result][jss::transactions][0u][jss::tx][jss::TransactionType] == jss::AccountSet) && + (j[jss::result][jss::transactions][1u][jss::tx][jss::TransactionType] == jss::Payment) && + (j[jss::result][jss::transactions][1u][jss::tx][jss::DeliverMax] == "10000000010") && + (j[jss::result][jss::transactions][1u][jss::tx][jss::Amount] == + j[jss::result][jss::transactions][1u][jss::tx][jss::DeliverMax]); case 2: case 3: - if (j.isMember(jss::result) && - (j[jss::result][jss::status] == "success") && + if (j.isMember(jss::result) && (j[jss::result][jss::status] == "success") && (j[jss::result][jss::transactions].size() == 2) && - (j[jss::result][jss::transactions][0u][jss::tx_json] - [jss::TransactionType] == jss::AccountSet)) + (j[jss::result][jss::transactions][0u][jss::tx_json][jss::TransactionType] == jss::AccountSet)) { - auto const& payment = - j[jss::result][jss::transactions][1u]; + auto const& payment = j[jss::result][jss::transactions][1u]; return (payment.isMember(jss::tx_json)) && - (payment[jss::tx_json][jss::TransactionType] == - jss::Payment) && - (payment[jss::tx_json][jss::DeliverMax] == - "10000000010") && + (payment[jss::tx_json][jss::TransactionType] == jss::Payment) && + (payment[jss::tx_json][jss::DeliverMax] == "10000000010") && (!payment[jss::tx_json].isMember(jss::Amount)) && (!payment[jss::tx_json].isMember(jss::hash)) && (payment[jss::hash] == "9F3085D85F472D1CC29627F260DF68EDE59D42D1D0C33E345" "ECF0D4CE981D0A8") && - (payment[jss::validated] == true) && - (payment[jss::ledger_index] == 3) && + (payment[jss::validated] == true) && (payment[jss::ledger_index] == 3) && (payment[jss::ledger_hash] == "5476DCD816EA04CBBA57D47BBF1FC58A5217CC93A5ADD79CB" "580A5AFDD727E33") && - (payment[jss::close_time_iso] == - "2000-01-01T00:00:10Z"); + (payment[jss::close_time_iso] == "2000-01-01T00:00:10Z"); } else return false; @@ -163,115 +138,89 @@ class AccountTx_test : public beast::unit_test::suite }; auto noTxs = [](Json::Value const& j) { - return j.isMember(jss::result) && - (j[jss::result][jss::status] == "success") && + return j.isMember(jss::result) && (j[jss::result][jss::status] == "success") && (j[jss::result][jss::transactions].size() == 0); }; auto isErr = [](Json::Value const& j, error_code_i code) { - return j.isMember(jss::result) && - j[jss::result].isMember(jss::error) && + return j.isMember(jss::result) && j[jss::result].isMember(jss::error) && j[jss::result][jss::error] == RPC::get_error_info(code).token; }; Json::Value jParams; jParams[jss::api_version] = apiVersion; - BEAST_EXPECT(isErr( - env.rpc("json", "account_tx", to_string(jParams)), - rpcINVALID_PARAMS)); + BEAST_EXPECT(isErr(env.rpc("json", "account_tx", to_string(jParams)), rpcINVALID_PARAMS)); jParams[jss::account] = "0xDEADBEEF"; - BEAST_EXPECT(isErr( - env.rpc("json", "account_tx", to_string(jParams)), - rpcACT_MALFORMED)); + BEAST_EXPECT(isErr(env.rpc("json", "account_tx", to_string(jParams)), rpcACT_MALFORMED)); jParams[jss::account] = A1.human(); - BEAST_EXPECT(hasTxs( - env.rpc(apiVersion, "json", "account_tx", to_string(jParams)))); + BEAST_EXPECT(hasTxs(env.rpc(apiVersion, "json", "account_tx", to_string(jParams)))); // Ledger min/max index { Json::Value p{jParams}; p[jss::ledger_index_min] = -1; p[jss::ledger_index_max] = -1; - BEAST_EXPECT(hasTxs( - env.rpc(apiVersion, "json", "account_tx", to_string(p)))); + BEAST_EXPECT(hasTxs(env.rpc(apiVersion, "json", "account_tx", to_string(p)))); p[jss::ledger_index_min] = 0; p[jss::ledger_index_max] = 100; if (apiVersion < 2u) - BEAST_EXPECT(hasTxs( - env.rpc(apiVersion, "json", "account_tx", to_string(p)))); + BEAST_EXPECT(hasTxs(env.rpc(apiVersion, "json", "account_tx", to_string(p)))); else - BEAST_EXPECT(isErr( - env.rpc("json", "account_tx", to_string(p)), - rpcLGR_IDX_MALFORMED)); + BEAST_EXPECT(isErr(env.rpc("json", "account_tx", to_string(p)), rpcLGR_IDX_MALFORMED)); p[jss::ledger_index_min] = 1; p[jss::ledger_index_max] = 2; if (apiVersion < 2u) - BEAST_EXPECT( - noTxs(env.rpc("json", "account_tx", to_string(p)))); + BEAST_EXPECT(noTxs(env.rpc("json", "account_tx", to_string(p)))); else - BEAST_EXPECT(isErr( - env.rpc("json", "account_tx", to_string(p)), - rpcLGR_IDX_MALFORMED)); + BEAST_EXPECT(isErr(env.rpc("json", "account_tx", to_string(p)), rpcLGR_IDX_MALFORMED)); p[jss::ledger_index_min] = 2; p[jss::ledger_index_max] = 1; BEAST_EXPECT(isErr( env.rpc("json", "account_tx", to_string(p)), - (apiVersion == 1 ? rpcLGR_IDXS_INVALID - : rpcINVALID_LGR_RANGE))); + (apiVersion == 1 ? rpcLGR_IDXS_INVALID : rpcINVALID_LGR_RANGE))); } // Ledger index min only { Json::Value p{jParams}; p[jss::ledger_index_min] = -1; - BEAST_EXPECT(hasTxs( - env.rpc(apiVersion, "json", "account_tx", to_string(p)))); + BEAST_EXPECT(hasTxs(env.rpc(apiVersion, "json", "account_tx", to_string(p)))); p[jss::ledger_index_min] = 1; if (apiVersion < 2u) - BEAST_EXPECT(hasTxs( - env.rpc(apiVersion, "json", "account_tx", to_string(p)))); + BEAST_EXPECT(hasTxs(env.rpc(apiVersion, "json", "account_tx", to_string(p)))); else - BEAST_EXPECT(isErr( - env.rpc("json", "account_tx", to_string(p)), - rpcLGR_IDX_MALFORMED)); + BEAST_EXPECT(isErr(env.rpc("json", "account_tx", to_string(p)), rpcLGR_IDX_MALFORMED)); p[jss::ledger_index_min] = env.current()->header().seq; BEAST_EXPECT(isErr( env.rpc("json", "account_tx", to_string(p)), - (apiVersion == 1 ? rpcLGR_IDXS_INVALID - : rpcINVALID_LGR_RANGE))); + (apiVersion == 1 ? rpcLGR_IDXS_INVALID : rpcINVALID_LGR_RANGE))); } // Ledger index max only { Json::Value p{jParams}; p[jss::ledger_index_max] = -1; - BEAST_EXPECT(hasTxs( - env.rpc(apiVersion, "json", "account_tx", to_string(p)))); + BEAST_EXPECT(hasTxs(env.rpc(apiVersion, "json", "account_tx", to_string(p)))); p[jss::ledger_index_max] = env.current()->header().seq; if (apiVersion < 2u) - BEAST_EXPECT(hasTxs( - env.rpc(apiVersion, "json", "account_tx", to_string(p)))); + BEAST_EXPECT(hasTxs(env.rpc(apiVersion, "json", "account_tx", to_string(p)))); else - BEAST_EXPECT(isErr( - env.rpc("json", "account_tx", to_string(p)), - rpcLGR_IDX_MALFORMED)); + BEAST_EXPECT(isErr(env.rpc("json", "account_tx", to_string(p)), rpcLGR_IDX_MALFORMED)); p[jss::ledger_index_max] = 3; - BEAST_EXPECT(hasTxs( - env.rpc(apiVersion, "json", "account_tx", to_string(p)))); + BEAST_EXPECT(hasTxs(env.rpc(apiVersion, "json", "account_tx", to_string(p)))); p[jss::ledger_index_max] = env.closed()->header().seq; - BEAST_EXPECT(hasTxs( - env.rpc(apiVersion, "json", "account_tx", to_string(p)))); + BEAST_EXPECT(hasTxs(env.rpc(apiVersion, "json", "account_tx", to_string(p)))); p[jss::ledger_index_max] = env.closed()->header().seq - 1; BEAST_EXPECT(noTxs(env.rpc("json", "account_tx", to_string(p)))); @@ -282,20 +231,16 @@ class AccountTx_test : public beast::unit_test::suite Json::Value p{jParams}; p[jss::ledger_index] = env.closed()->header().seq; - BEAST_EXPECT(hasTxs( - env.rpc(apiVersion, "json", "account_tx", to_string(p)))); + BEAST_EXPECT(hasTxs(env.rpc(apiVersion, "json", "account_tx", to_string(p)))); p[jss::ledger_index] = env.closed()->header().seq - 1; BEAST_EXPECT(noTxs(env.rpc("json", "account_tx", to_string(p)))); p[jss::ledger_index] = env.current()->header().seq; - BEAST_EXPECT(isErr( - env.rpc("json", "account_tx", to_string(p)), - rpcLGR_NOT_VALIDATED)); + BEAST_EXPECT(isErr(env.rpc("json", "account_tx", to_string(p)), rpcLGR_NOT_VALIDATED)); p[jss::ledger_index] = env.current()->header().seq + 1; - BEAST_EXPECT(isErr( - env.rpc("json", "account_tx", to_string(p)), rpcLGR_NOT_FOUND)); + BEAST_EXPECT(isErr(env.rpc("json", "account_tx", to_string(p)), rpcLGR_NOT_FOUND)); } // Ledger Hash @@ -303,8 +248,7 @@ class AccountTx_test : public beast::unit_test::suite Json::Value p{jParams}; p[jss::ledger_hash] = to_string(env.closed()->header().hash); - BEAST_EXPECT(hasTxs( - env.rpc(apiVersion, "json", "account_tx", to_string(p)))); + BEAST_EXPECT(hasTxs(env.rpc(apiVersion, "json", "account_tx", to_string(p)))); p[jss::ledger_hash] = to_string(env.closed()->header().parentHash); BEAST_EXPECT(noTxs(env.rpc("json", "account_tx", to_string(p)))); @@ -322,12 +266,9 @@ class AccountTx_test : public beast::unit_test::suite p[jss::ledger_index] = -1; if (apiVersion < 2u) - BEAST_EXPECT(hasTxs( - env.rpc(apiVersion, "json", "account_tx", to_string(p)))); + BEAST_EXPECT(hasTxs(env.rpc(apiVersion, "json", "account_tx", to_string(p)))); else - BEAST_EXPECT(isErr( - env.rpc("json", "account_tx", to_string(p)), - rpcINVALID_PARAMS)); + BEAST_EXPECT(isErr(env.rpc("json", "account_tx", to_string(p)), rpcINVALID_PARAMS)); } // Ledger index max only @@ -335,23 +276,18 @@ class AccountTx_test : public beast::unit_test::suite Json::Value p{jParams}; p[jss::ledger_index_max] = env.current()->header().seq; if (apiVersion < 2u) - BEAST_EXPECT(hasTxs( - env.rpc(apiVersion, "json", "account_tx", to_string(p)))); + BEAST_EXPECT(hasTxs(env.rpc(apiVersion, "json", "account_tx", to_string(p)))); else - BEAST_EXPECT(isErr( - env.rpc("json", "account_tx", to_string(p)), - rpcLGR_IDX_MALFORMED)); + BEAST_EXPECT(isErr(env.rpc("json", "account_tx", to_string(p)), rpcLGR_IDX_MALFORMED)); } // test account non-string { auto testInvalidAccountParam = [&](auto const& param) { Json::Value params; params[jss::account] = param; - auto jrr = env.rpc( - "json", "account_tx", to_string(params))[jss::result]; + auto jrr = env.rpc("json", "account_tx", to_string(params))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); - BEAST_EXPECT( - jrr[jss::error_message] == "Invalid field 'account'."); + BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'account'."); }; testInvalidAccountParam(1); @@ -371,9 +307,7 @@ class AccountTx_test : public beast::unit_test::suite BEAST_EXPECT(result[jss::result][jss::status] == "success"); } else - BEAST_EXPECT(isErr( - env.rpc("json", "account_tx", to_string(p)), - rpcINVALID_PARAMS)); + BEAST_EXPECT(isErr(env.rpc("json", "account_tx", to_string(p)), rpcINVALID_PARAMS)); p[jss::binary] = true; Json::Value result{env.rpc("json", "account_tx", to_string(p))}; @@ -383,9 +317,7 @@ class AccountTx_test : public beast::unit_test::suite if (apiVersion < 2u) BEAST_EXPECT(result[jss::result][jss::status] == "success"); else - BEAST_EXPECT(isErr( - env.rpc("json", "account_tx", to_string(p)), - rpcINVALID_PARAMS)); + BEAST_EXPECT(isErr(env.rpc("json", "account_tx", to_string(p)), rpcINVALID_PARAMS)); p[jss::forward] = false; result = env.rpc("json", "account_tx", to_string(p)); @@ -397,90 +329,61 @@ class AccountTx_test : public beast::unit_test::suite // Test case: limit = 0 should fail (below minimum) p[jss::limit] = 0; - BEAST_EXPECT(isErr( - env.rpc("json", "account_tx", to_string(p)), - rpcINVALID_PARAMS)); + BEAST_EXPECT(isErr(env.rpc("json", "account_tx", to_string(p)), rpcINVALID_PARAMS)); // Test case: limit = 1.2 should fail (not an integer) p[jss::limit] = 1.2; BEAST_EXPECT( - env.rpc( - "json", - "account_tx", - to_string(p))[jss::result][jss::error_message] == + env.rpc("json", "account_tx", to_string(p))[jss::result][jss::error_message] == RPC::expected_field_message(jss::limit, "unsigned integer")); // Test case: limit = "10" should fail (string instead of integer) p[jss::limit] = "10"; BEAST_EXPECT( - env.rpc( - "json", - "account_tx", - to_string(p))[jss::result][jss::error_message] == + env.rpc("json", "account_tx", to_string(p))[jss::result][jss::error_message] == RPC::expected_field_message(jss::limit, "unsigned integer")); // Test case: limit = true should fail (boolean instead of integer) p[jss::limit] = true; BEAST_EXPECT( - env.rpc( - "json", - "account_tx", - to_string(p))[jss::result][jss::error_message] == + env.rpc("json", "account_tx", to_string(p))[jss::result][jss::error_message] == RPC::expected_field_message(jss::limit, "unsigned integer")); // Test case: limit = false should fail (boolean instead of integer) p[jss::limit] = false; BEAST_EXPECT( - env.rpc( - "json", - "account_tx", - to_string(p))[jss::result][jss::error_message] == + env.rpc("json", "account_tx", to_string(p))[jss::result][jss::error_message] == RPC::expected_field_message(jss::limit, "unsigned integer")); // Test case: limit = -1 should fail (negative number) p[jss::limit] = -1; BEAST_EXPECT( - env.rpc( - "json", - "account_tx", - to_string(p))[jss::result][jss::error_message] == + env.rpc("json", "account_tx", to_string(p))[jss::result][jss::error_message] == RPC::expected_field_message(jss::limit, "unsigned integer")); // Test case: limit = [] should fail (array instead of integer) p[jss::limit] = Json::Value(Json::arrayValue); BEAST_EXPECT( - env.rpc( - "json", - "account_tx", - to_string(p))[jss::result][jss::error_message] == + env.rpc("json", "account_tx", to_string(p))[jss::result][jss::error_message] == RPC::expected_field_message(jss::limit, "unsigned integer")); // Test case: limit = {} should fail (object instead of integer) p[jss::limit] = Json::Value(Json::objectValue); BEAST_EXPECT( - env.rpc( - "json", - "account_tx", - to_string(p))[jss::result][jss::error_message] == + env.rpc("json", "account_tx", to_string(p))[jss::result][jss::error_message] == RPC::expected_field_message(jss::limit, "unsigned integer")); // Test case: limit = "malformed" should fail (malformed string) p[jss::limit] = "malformed"; BEAST_EXPECT( - env.rpc( - "json", - "account_tx", - to_string(p))[jss::result][jss::error_message] == + env.rpc("json", "account_tx", to_string(p))[jss::result][jss::error_message] == RPC::expected_field_message(jss::limit, "unsigned integer")); // Test case: limit = ["limit"] should fail (array with string) p[jss::limit] = Json::Value(Json::arrayValue); p[jss::limit].append("limit"); BEAST_EXPECT( - env.rpc( - "json", - "account_tx", - to_string(p))[jss::result][jss::error_message] == + env.rpc("json", "account_tx", to_string(p))[jss::result][jss::error_message] == RPC::expected_field_message(jss::limit, "unsigned integer")); // Test case: limit = {"limit": 10} should fail (object with @@ -488,19 +391,12 @@ class AccountTx_test : public beast::unit_test::suite p[jss::limit] = Json::Value(Json::objectValue); p[jss::limit][jss::limit] = 10; BEAST_EXPECT( - env.rpc( - "json", - "account_tx", - to_string(p))[jss::result][jss::error_message] == + env.rpc("json", "account_tx", to_string(p))[jss::result][jss::error_message] == RPC::expected_field_message(jss::limit, "unsigned integer")); // Test case: limit = 10 should succeed (valid integer) p[jss::limit] = 10; - BEAST_EXPECT( - env.rpc( - "json", - "account_tx", - to_string(p))[jss::result][jss::status] == "success"); + BEAST_EXPECT(env.rpc("json", "account_tx", to_string(p))[jss::result][jss::status] == "success"); } } @@ -548,9 +444,7 @@ class AccountTx_test : public beast::unit_test::suite // Escrow { // Create an escrow. Requires either a CancelAfter or FinishAfter. - auto escrow = [](Account const& account, - Account const& to, - STAmount const& amount) { + auto escrow = [](Account const& account, Account const& to, STAmount const& amount) { Json::Value escrow; escrow[jss::TransactionType] = jss::EscrowCreate; escrow[jss::Account] = account.human(); @@ -562,17 +456,14 @@ class AccountTx_test : public beast::unit_test::suite NetClock::time_point const nextTime{env.now() + 2s}; Json::Value escrowWithFinish{escrow(alice, alice, XRP(500))}; - escrowWithFinish[sfFinishAfter.jsonName] = - nextTime.time_since_epoch().count(); + escrowWithFinish[sfFinishAfter.jsonName] = nextTime.time_since_epoch().count(); std::uint32_t const escrowFinishSeq{env.seq(alice)}; env(escrowWithFinish, sig(alie)); Json::Value escrowWithCancel{escrow(alice, alice, XRP(500))}; - escrowWithCancel[sfFinishAfter.jsonName] = - nextTime.time_since_epoch().count(); - escrowWithCancel[sfCancelAfter.jsonName] = - nextTime.time_since_epoch().count() + 1; + escrowWithCancel[sfFinishAfter.jsonName] = nextTime.time_since_epoch().count(); + escrowWithCancel[sfCancelAfter.jsonName] = nextTime.time_since_epoch().count() + 1; std::uint32_t const escrowCancelSeq{env.seq(alice)}; env(escrowWithCancel, sig(alie)); @@ -604,24 +495,20 @@ class AccountTx_test : public beast::unit_test::suite payChanCreate[jss::TransactionType] = jss::PaymentChannelCreate; payChanCreate[jss::Account] = alice.human(); payChanCreate[jss::Destination] = gw.human(); - payChanCreate[jss::Amount] = - XRP(500).value().getJson(JsonOptions::none); - payChanCreate[sfSettleDelay.jsonName] = - NetClock::duration{100s}.count(); + payChanCreate[jss::Amount] = XRP(500).value().getJson(JsonOptions::none); + payChanCreate[sfSettleDelay.jsonName] = NetClock::duration{100s}.count(); payChanCreate[sfPublicKey.jsonName] = strHex(alice.pk().slice()); env(payChanCreate, sig(alie)); env.close(); - std::string const payChanIndex{ - strHex(keylet::payChan(alice, gw, payChanSeq).key)}; + std::string const payChanIndex{strHex(keylet::payChan(alice, gw, payChanSeq).key)}; { Json::Value payChanFund; payChanFund[jss::TransactionType] = jss::PaymentChannelFund; payChanFund[jss::Account] = alice.human(); payChanFund[sfChannel.jsonName] = payChanIndex; - payChanFund[jss::Amount] = - XRP(200).value().getJson(JsonOptions::none); + payChanFund[jss::Amount] = XRP(200).value().getJson(JsonOptions::none); env(payChanFund, sig(alie)); env.close(); } @@ -666,8 +553,7 @@ class AccountTx_test : public beast::unit_test::suite params[jss::ledger_index_min] = -1; params[jss::ledger_index_max] = -1; - Json::Value const result{ - env.rpc("json", "account_tx", to_string(params))}; + Json::Value const result{env.rpc("json", "account_tx", to_string(params))}; BEAST_EXPECT(result[jss::result][jss::status] == "success"); BEAST_EXPECT(result[jss::result][jss::transactions].isArray()); @@ -704,8 +590,7 @@ class AccountTx_test : public beast::unit_test::suite }; // clang-format on - BEAST_EXPECT( - std::size(sanity) == result[jss::result][jss::transactions].size()); + BEAST_EXPECT(std::size(sanity) == result[jss::result][jss::transactions].size()); for (unsigned int index{0}; index < std::size(sanity); ++index) { @@ -739,8 +624,7 @@ class AccountTx_test : public beast::unit_test::suite env(noop(becky)); // Close enough ledgers to be able to delete becky's account. - std::uint32_t const ledgerCount{ - env.current()->seq() + 257 - env.seq(becky)}; + std::uint32_t const ledgerCount{env.current()->seq() + 257 - env.seq(becky)}; for (std::uint32_t i = 0; i < ledgerCount; ++i) env.close(); @@ -781,24 +665,18 @@ class AccountTx_test : public beast::unit_test::suite params[jss::ledger_index_min] = -1; params[jss::ledger_index_max] = -1; - Json::Value const result{ - env.rpc("json", "account_tx", to_string(params))}; + Json::Value const result{env.rpc("json", "account_tx", to_string(params))}; BEAST_EXPECT(result[jss::result][jss::status] == "success"); BEAST_EXPECT(result[jss::result][jss::transactions].isArray()); // The first two transactions listed in sanity haven't happened yet. constexpr unsigned int beckyDeletedOffset = 2; - BEAST_EXPECT( - std::size(sanity) == - result[jss::result][jss::transactions].size() + - beckyDeletedOffset); + BEAST_EXPECT(std::size(sanity) == result[jss::result][jss::transactions].size() + beckyDeletedOffset); Json::Value const& txs{result[jss::result][jss::transactions]}; - for (unsigned int index = beckyDeletedOffset; - index < std::size(sanity); - ++index) + for (unsigned int index = beckyDeletedOffset; index < std::size(sanity); ++index) { checkSanity(txs[index - beckyDeletedOffset], sanity[index]); } @@ -806,10 +684,7 @@ class AccountTx_test : public beast::unit_test::suite // All it takes is a large enough XRP payment to resurrect // becky's account. Try too small a payment. - env(pay(alice, - becky, - drops(env.current()->fees().accountReserve(0)) - XRP(1)), - ter(tecNO_DST_INSUF_XRP)); + env(pay(alice, becky, drops(env.current()->fees().accountReserve(0)) - XRP(1)), ter(tecNO_DST_INSUF_XRP)); env.close(); // Actually resurrect becky's account. @@ -831,14 +706,12 @@ class AccountTx_test : public beast::unit_test::suite params[jss::ledger_index_min] = -1; params[jss::ledger_index_max] = -1; - Json::Value const result{ - env.rpc("json", "account_tx", to_string(params))}; + Json::Value const result{env.rpc("json", "account_tx", to_string(params))}; BEAST_EXPECT(result[jss::result][jss::status] == "success"); BEAST_EXPECT(result[jss::result][jss::transactions].isArray()); - BEAST_EXPECT( - std::size(sanity) == result[jss::result][jss::transactions].size()); + BEAST_EXPECT(std::size(sanity) == result[jss::result][jss::transactions].size()); Json::Value const& txs{result[jss::result][jss::transactions]}; @@ -867,28 +740,23 @@ class AccountTx_test : public beast::unit_test::suite MPTTester mptAlice(env, alice, {.holders = {bob, carol}}); // check the latest mpt-related txn is in alice's account history - auto const checkAliceAcctTx = [&](size_t size, - Json::StaticString txType) { + auto const checkAliceAcctTx = [&](size_t size, Json::StaticString txType) { Json::Value params; params[jss::account] = alice.human(); params[jss::limit] = 100; - auto const jv = - env.rpc("json", "account_tx", to_string(params))[jss::result]; + auto const jv = env.rpc("json", "account_tx", to_string(params))[jss::result]; BEAST_EXPECT(jv[jss::transactions].size() == size); auto const& tx0(jv[jss::transactions][0u][jss::tx]); BEAST_EXPECT(tx0[jss::TransactionType] == txType); - std::string const txHash{ - env.tx()->getJson(JsonOptions::none)[jss::hash].asString()}; + std::string const txHash{env.tx()->getJson(JsonOptions::none)[jss::hash].asString()}; BEAST_EXPECT(tx0[jss::hash] == txHash); }; // alice creates issuance mptAlice.create( - {.ownerCount = 1, - .holderCount = 0, - .flags = tfMPTCanClawback | tfMPTRequireAuth | tfMPTCanTransfer}); + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanClawback | tfMPTRequireAuth | tfMPTCanTransfer}); checkAliceAcctTx(3, jss::MPTokenIssuanceCreate); @@ -931,8 +799,7 @@ public: void run() override { - forAllApiVersions( - std::bind_front(&AccountTx_test::testParameters, this)); + forAllApiVersions(std::bind_front(&AccountTx_test::testParameters, this)); testContents(); testAccountDelete(); testMPT(); diff --git a/src/test/rpc/AmendmentBlocked_test.cpp b/src/test/rpc/AmendmentBlocked_test.cpp index 2c3f631ac8..fc1e21a0b6 100644 --- a/src/test/rpc/AmendmentBlocked_test.cpp +++ b/src/test/rpc/AmendmentBlocked_test.cpp @@ -1,10 +1,10 @@ #include #include -#include #include #include +#include namespace xrpl { @@ -60,12 +60,10 @@ class AmendmentBlocked_test : public beast::unit_test::suite pf_req[jss::subcommand] = "create"; pf_req[jss::source_account] = alice.human(); pf_req[jss::destination_account] = bob.human(); - pf_req[jss::destination_amount] = - bob["USD"](20).value().getJson(JsonOptions::none); + pf_req[jss::destination_amount] = bob["USD"](20).value().getJson(JsonOptions::none); jr = wsc->invoke("path_find", pf_req)[jss::result]; BEAST_EXPECT( - jr.isMember(jss::alternatives) && jr[jss::alternatives].isArray() && - jr[jss::alternatives].size() == 1); + jr.isMember(jss::alternatives) && jr[jss::alternatives].isArray() && jr[jss::alternatives].size() == 1); BEAST_EXPECT(!jr.isMember(jss::warnings)); // submit @@ -73,9 +71,7 @@ class AmendmentBlocked_test : public beast::unit_test::suite Serializer s; jt.stx->add(s); jr = env.rpc("submit", strHex(s.slice()))[jss::result]; - BEAST_EXPECT( - jr.isMember(jss::engine_result) && - jr[jss::engine_result] == "tesSUCCESS"); + BEAST_EXPECT(jr.isMember(jss::engine_result) && jr[jss::engine_result] == "tesSUCCESS"); BEAST_EXPECT(!jr.isMember(jss::warnings)); // submit_multisigned @@ -100,11 +96,8 @@ class AmendmentBlocked_test : public beast::unit_test::suite Json::Value ms_req; ms_req[jss::tx_json] = jr[jss::tx_json]; - jr = env.rpc( - "json", "submit_multisigned", to_string(ms_req))[jss::result]; - BEAST_EXPECT( - jr.isMember(jss::engine_result) && - jr[jss::engine_result] == "tesSUCCESS"); + jr = env.rpc("json", "submit_multisigned", to_string(ms_req))[jss::result]; + BEAST_EXPECT(jr.isMember(jss::engine_result) && jr[jss::engine_result] == "tesSUCCESS"); BEAST_EXPECT(!jr.isMember(jss::warnings)); // set up an amendment warning. Nothing changes @@ -131,12 +124,10 @@ class AmendmentBlocked_test : public beast::unit_test::suite pf_req[jss::subcommand] = "create"; pf_req[jss::source_account] = alice.human(); pf_req[jss::destination_account] = bob.human(); - pf_req[jss::destination_amount] = - bob["USD"](20).value().getJson(JsonOptions::none); + pf_req[jss::destination_amount] = bob["USD"](20).value().getJson(JsonOptions::none); jr = wsc->invoke("path_find", pf_req)[jss::result]; BEAST_EXPECT( - jr.isMember(jss::alternatives) && jr[jss::alternatives].isArray() && - jr[jss::alternatives].size() == 1); + jr.isMember(jss::alternatives) && jr[jss::alternatives].isArray() && jr[jss::alternatives].size() == 1); BEAST_EXPECT(!jr.isMember(jss::warnings)); // submit @@ -144,9 +135,7 @@ class AmendmentBlocked_test : public beast::unit_test::suite s.erase(); jt.stx->add(s); jr = env.rpc("submit", strHex(s.slice()))[jss::result]; - BEAST_EXPECT( - jr.isMember(jss::engine_result) && - jr[jss::engine_result] == "tesSUCCESS"); + BEAST_EXPECT(jr.isMember(jss::engine_result) && jr[jss::engine_result] == "tesSUCCESS"); BEAST_EXPECT(!jr.isMember(jss::warnings)); // submit_multisigned @@ -168,11 +157,8 @@ class AmendmentBlocked_test : public beast::unit_test::suite BEAST_EXPECT(!jr.isMember(jss::warnings)); ms_req[jss::tx_json] = jr[jss::tx_json]; - jr = env.rpc( - "json", "submit_multisigned", to_string(ms_req))[jss::result]; - BEAST_EXPECT( - jr.isMember(jss::engine_result) && - jr[jss::engine_result] == "tesSUCCESS"); + jr = env.rpc("json", "submit_multisigned", to_string(ms_req))[jss::result]; + BEAST_EXPECT(jr.isMember(jss::engine_result) && jr[jss::engine_result] == "tesSUCCESS"); BEAST_EXPECT(!jr.isMember(jss::warnings)); // make the network amendment blocked...now all the same @@ -182,36 +168,31 @@ class AmendmentBlocked_test : public beast::unit_test::suite // ledger_accept jr = env.rpc("ledger_accept")[jss::result]; - BEAST_EXPECT( - jr.isMember(jss::error) && jr[jss::error] == "amendmentBlocked"); + BEAST_EXPECT(jr.isMember(jss::error) && jr[jss::error] == "amendmentBlocked"); BEAST_EXPECT(jr[jss::status] == "error"); BEAST_EXPECT(!jr.isMember(jss::warnings)); // ledger_current jr = env.rpc("ledger_current")[jss::result]; - BEAST_EXPECT( - jr.isMember(jss::error) && jr[jss::error] == "amendmentBlocked"); + BEAST_EXPECT(jr.isMember(jss::error) && jr[jss::error] == "amendmentBlocked"); BEAST_EXPECT(jr[jss::status] == "error"); BEAST_EXPECT(!jr.isMember(jss::warnings)); // owner_info jr = env.rpc("owner_info", alice.human())[jss::result]; - BEAST_EXPECT( - jr.isMember(jss::error) && jr[jss::error] == "amendmentBlocked"); + BEAST_EXPECT(jr.isMember(jss::error) && jr[jss::error] == "amendmentBlocked"); BEAST_EXPECT(jr[jss::status] == "error"); BEAST_EXPECT(!jr.isMember(jss::warnings)); // path_find jr = wsc->invoke("path_find", pf_req)[jss::result]; - BEAST_EXPECT( - jr.isMember(jss::error) && jr[jss::error] == "amendmentBlocked"); + BEAST_EXPECT(jr.isMember(jss::error) && jr[jss::error] == "amendmentBlocked"); BEAST_EXPECT(jr[jss::status] == "error"); BEAST_EXPECT(!jr.isMember(jss::warnings)); // submit jr = env.rpc("submit", strHex(s.slice()))[jss::result]; - BEAST_EXPECT( - jr.isMember(jss::error) && jr[jss::error] == "amendmentBlocked"); + BEAST_EXPECT(jr.isMember(jss::error) && jr[jss::error] == "amendmentBlocked"); BEAST_EXPECT(jr[jss::status] == "error"); BEAST_EXPECT(!jr.isMember(jss::warnings)); @@ -221,10 +202,8 @@ class AmendmentBlocked_test : public beast::unit_test::suite jr = env.rpc("json", "sign_for", to_string(sign_for))[jss::result]; BEAST_EXPECT(jr[jss::status] == "success"); ms_req[jss::tx_json] = jr[jss::tx_json]; - jr = env.rpc( - "json", "submit_multisigned", to_string(ms_req))[jss::result]; - BEAST_EXPECT( - jr.isMember(jss::error) && jr[jss::error] == "amendmentBlocked"); + jr = env.rpc("json", "submit_multisigned", to_string(ms_req))[jss::result]; + BEAST_EXPECT(jr.isMember(jss::error) && jr[jss::error] == "amendmentBlocked"); BEAST_EXPECT(!jr.isMember(jss::warnings)); } diff --git a/src/test/rpc/BookChanges_test.cpp b/src/test/rpc/BookChanges_test.cpp index 216f4bd895..4ea4b8233b 100644 --- a/src/test/rpc/BookChanges_test.cpp +++ b/src/test/rpc/BookChanges_test.cpp @@ -58,8 +58,7 @@ public: // As per convention in XRPL, ledgers can be specified with strings // "closed", "validated" or "current" - Json::Value const resp = - env.rpc("json", "book_changes", to_string(Json::Value{})); + Json::Value const resp = env.rpc("json", "book_changes", to_string(Json::Value{})); BEAST_EXPECT(!resp[jss::result].isMember(jss::error)); BEAST_EXPECT(resp[jss::result][jss::status] == "success"); @@ -75,27 +74,21 @@ public: using namespace jtx; FeatureBitset const all{ - jtx::testable_amendments() | featurePermissionedDomains | - featureCredentials | featurePermissionedDEX}; + jtx::testable_amendments() | featurePermissionedDomains | featureCredentials | featurePermissionedDEX}; Env env(*this, all); PermissionedDEX permDex(env); - auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = - permDex; + auto const& [gw, domainOwner, alice, bob, carol, USD, domainID, credType] = permDex; auto wsc = makeWSClient(env.app().config()); env(offer(alice, XRP(10), USD(10)), domain(domainID)); env.close(); - env(pay(bob, carol, USD(10)), - path(~USD), - sendmax(XRP(10)), - domain(domainID)); + env(pay(bob, carol, USD(10)), path(~USD), sendmax(XRP(10)), domain(domainID)); env.close(); - std::string const txHash{ - env.tx()->getJson(JsonOptions::none)[jss::hash].asString()}; + std::string const txHash{env.tx()->getJson(JsonOptions::none)[jss::hash].asString()}; Json::Value const txResult = env.rpc("tx", txHash)[jss::result]; auto const ledgerIndex = txResult[jss::ledger_index].asInt(); @@ -107,9 +100,7 @@ public: auto jrr = jv[jss::result]; BEAST_EXPECT(jrr[jss::changes].size() == 1); - BEAST_EXPECT( - jrr[jss::changes][0u][jss::domain].asString() == - to_string(domainID)); + BEAST_EXPECT(jrr[jss::changes][0u][jss::domain].asString() == to_string(domainID)); } void diff --git a/src/test/rpc/Book_test.cpp b/src/test/rpc/Book_test.cpp index ae2aff689d..543e163432 100644 --- a/src/test/rpc/Book_test.cpp +++ b/src/test/rpc/Book_test.cpp @@ -15,11 +15,7 @@ namespace test { class Book_test : public beast::unit_test::suite { std::string - getBookDir( - jtx::Env& env, - Issue const& in, - Issue const& out, - std::optional const& domain = std::nullopt) + getBookDir(jtx::Env& env, Issue const& in, Issue const& out, std::optional const& domain = std::nullopt) { std::string dir; auto uBookBase = getBookBase({in, out, domain}); @@ -31,8 +27,7 @@ class Book_test : public beast::unit_test::suite auto sleOfferDir = view->read(keylet::page(key.value())); uint256 offerIndex; unsigned int bookEntry; - cdirFirst( - *view, sleOfferDir->key(), sleOfferDir, bookEntry, offerIndex); + cdirFirst(*view, sleOfferDir->key(), sleOfferDir, bookEntry, offerIndex); auto sleOffer = view->read(keylet::offer(offerIndex)); dir = to_string(sleOffer->getFieldH256(sfBookDirectory)); } @@ -66,35 +61,28 @@ public: auto jv = wsc->invoke("subscribe", books); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } if (!BEAST_EXPECT(jv[jss::status] == "success")) return; - BEAST_EXPECT( - jv[jss::result].isMember(jss::offers) && - jv[jss::result][jss::offers].size() == 0); + BEAST_EXPECT(jv[jss::result].isMember(jss::offers) && jv[jss::result][jss::offers].size() == 0); BEAST_EXPECT(!jv[jss::result].isMember(jss::asks)); BEAST_EXPECT(!jv[jss::result].isMember(jss::bids)); } { // Create an ask: TakerPays 700, TakerGets 100/USD - env(offer("alice", XRP(700), USD(100)), - require(owners("alice", 1))); + env(offer("alice", XRP(700), USD(100)), require(owners("alice", 1))); env.close(); // Check stream update BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { auto const& t = jv[jss::transaction]; return t[jss::TransactionType] == jss::OfferCreate && - t[jss::TakerGets] == - USD(100).value().getJson(JsonOptions::none) && - t[jss::TakerPays] == - XRP(700).value().getJson(JsonOptions::none); + t[jss::TakerGets] == USD(100).value().getJson(JsonOptions::none) && + t[jss::TakerPays] == XRP(700).value().getJson(JsonOptions::none); })); } @@ -110,10 +98,8 @@ public: BEAST_EXPECT(jv[jss::status] == "success"); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } } @@ -151,41 +137,32 @@ public: auto jv = wsc->invoke("subscribe", books); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } if (!BEAST_EXPECT(jv[jss::status] == "success")) return; + BEAST_EXPECT(jv[jss::result].isMember(jss::offers) && jv[jss::result][jss::offers].size() == 1); BEAST_EXPECT( - jv[jss::result].isMember(jss::offers) && - jv[jss::result][jss::offers].size() == 1); + jv[jss::result][jss::offers][0u][jss::TakerGets] == XRP(200).value().getJson(JsonOptions::none)); BEAST_EXPECT( - jv[jss::result][jss::offers][0u][jss::TakerGets] == - XRP(200).value().getJson(JsonOptions::none)); - BEAST_EXPECT( - jv[jss::result][jss::offers][0u][jss::TakerPays] == - USD(100).value().getJson(JsonOptions::none)); + jv[jss::result][jss::offers][0u][jss::TakerPays] == USD(100).value().getJson(JsonOptions::none)); BEAST_EXPECT(!jv[jss::result].isMember(jss::asks)); BEAST_EXPECT(!jv[jss::result].isMember(jss::bids)); } { // Create an ask: TakerPays 700, TakerGets 100/USD - env(offer("alice", XRP(700), USD(100)), - require(owners("alice", 3))); + env(offer("alice", XRP(700), USD(100)), require(owners("alice", 3))); env.close(); // Check stream update BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { auto const& t = jv[jss::transaction]; return t[jss::TransactionType] == jss::OfferCreate && - t[jss::TakerGets] == - USD(100).value().getJson(JsonOptions::none) && - t[jss::TakerPays] == - XRP(700).value().getJson(JsonOptions::none); + t[jss::TakerGets] == USD(100).value().getJson(JsonOptions::none) && + t[jss::TakerPays] == XRP(700).value().getJson(JsonOptions::none); })); } @@ -201,10 +178,8 @@ public: BEAST_EXPECT(jv[jss::status] == "success"); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } } @@ -236,37 +211,28 @@ public: auto jv = wsc->invoke("subscribe", books); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } if (!BEAST_EXPECT(jv[jss::status] == "success")) return; - BEAST_EXPECT( - jv[jss::result].isMember(jss::asks) && - jv[jss::result][jss::asks].size() == 0); - BEAST_EXPECT( - jv[jss::result].isMember(jss::bids) && - jv[jss::result][jss::bids].size() == 0); + BEAST_EXPECT(jv[jss::result].isMember(jss::asks) && jv[jss::result][jss::asks].size() == 0); + BEAST_EXPECT(jv[jss::result].isMember(jss::bids) && jv[jss::result][jss::bids].size() == 0); BEAST_EXPECT(!jv[jss::result].isMember(jss::offers)); } { // Create an ask: TakerPays 700, TakerGets 100/USD - env(offer("alice", XRP(700), USD(100)), - require(owners("alice", 1))); + env(offer("alice", XRP(700), USD(100)), require(owners("alice", 1))); env.close(); // Check stream update BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { auto const& t = jv[jss::transaction]; return t[jss::TransactionType] == jss::OfferCreate && - t[jss::TakerGets] == - USD(100).value().getJson(JsonOptions::none) && - t[jss::TakerPays] == - XRP(700).value().getJson(JsonOptions::none); + t[jss::TakerGets] == USD(100).value().getJson(JsonOptions::none) && + t[jss::TakerPays] == XRP(700).value().getJson(JsonOptions::none); })); } @@ -279,10 +245,8 @@ public: BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { auto const& t = jv[jss::transaction]; return t[jss::TransactionType] == jss::OfferCreate && - t[jss::TakerGets] == - XRP(75).value().getJson(JsonOptions::none) && - t[jss::TakerPays] == - USD(100).value().getJson(JsonOptions::none); + t[jss::TakerGets] == XRP(75).value().getJson(JsonOptions::none) && + t[jss::TakerPays] == USD(100).value().getJson(JsonOptions::none); })); } @@ -291,10 +255,8 @@ public: BEAST_EXPECT(jv[jss::status] == "success"); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } } @@ -333,49 +295,32 @@ public: auto jv = wsc->invoke("subscribe", books); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } if (!BEAST_EXPECT(jv[jss::status] == "success")) return; - BEAST_EXPECT( - jv[jss::result].isMember(jss::asks) && - jv[jss::result][jss::asks].size() == 1); - BEAST_EXPECT( - jv[jss::result].isMember(jss::bids) && - jv[jss::result][jss::bids].size() == 1); - BEAST_EXPECT( - jv[jss::result][jss::asks][0u][jss::TakerGets] == - USD(100).value().getJson(JsonOptions::none)); - BEAST_EXPECT( - jv[jss::result][jss::asks][0u][jss::TakerPays] == - XRP(500).value().getJson(JsonOptions::none)); - BEAST_EXPECT( - jv[jss::result][jss::bids][0u][jss::TakerGets] == - XRP(200).value().getJson(JsonOptions::none)); - BEAST_EXPECT( - jv[jss::result][jss::bids][0u][jss::TakerPays] == - USD(100).value().getJson(JsonOptions::none)); + BEAST_EXPECT(jv[jss::result].isMember(jss::asks) && jv[jss::result][jss::asks].size() == 1); + BEAST_EXPECT(jv[jss::result].isMember(jss::bids) && jv[jss::result][jss::bids].size() == 1); + BEAST_EXPECT(jv[jss::result][jss::asks][0u][jss::TakerGets] == USD(100).value().getJson(JsonOptions::none)); + BEAST_EXPECT(jv[jss::result][jss::asks][0u][jss::TakerPays] == XRP(500).value().getJson(JsonOptions::none)); + BEAST_EXPECT(jv[jss::result][jss::bids][0u][jss::TakerGets] == XRP(200).value().getJson(JsonOptions::none)); + BEAST_EXPECT(jv[jss::result][jss::bids][0u][jss::TakerPays] == USD(100).value().getJson(JsonOptions::none)); BEAST_EXPECT(!jv[jss::result].isMember(jss::offers)); } { // Create an ask: TakerPays 700, TakerGets 100/USD - env(offer("alice", XRP(700), USD(100)), - require(owners("alice", 3))); + env(offer("alice", XRP(700), USD(100)), require(owners("alice", 3))); env.close(); // Check stream update BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { auto const& t = jv[jss::transaction]; return t[jss::TransactionType] == jss::OfferCreate && - t[jss::TakerGets] == - USD(100).value().getJson(JsonOptions::none) && - t[jss::TakerPays] == - XRP(700).value().getJson(JsonOptions::none); + t[jss::TakerGets] == USD(100).value().getJson(JsonOptions::none) && + t[jss::TakerPays] == XRP(700).value().getJson(JsonOptions::none); })); } @@ -388,10 +333,8 @@ public: BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { auto const& t = jv[jss::transaction]; return t[jss::TransactionType] == jss::OfferCreate && - t[jss::TakerGets] == - XRP(75).value().getJson(JsonOptions::none) && - t[jss::TakerPays] == - USD(100).value().getJson(JsonOptions::none); + t[jss::TakerGets] == XRP(75).value().getJson(JsonOptions::none) && + t[jss::TakerPays] == USD(100).value().getJson(JsonOptions::none); })); } @@ -400,10 +343,8 @@ public: BEAST_EXPECT(jv[jss::status] == "success"); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } } @@ -444,35 +385,28 @@ public: auto jv = wsc->invoke("subscribe", books); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } if (!BEAST_EXPECT(jv[jss::status] == "success")) return; - BEAST_EXPECT( - jv[jss::result].isMember(jss::offers) && - jv[jss::result][jss::offers].size() == 0); + BEAST_EXPECT(jv[jss::result].isMember(jss::offers) && jv[jss::result][jss::offers].size() == 0); BEAST_EXPECT(!jv[jss::result].isMember(jss::asks)); BEAST_EXPECT(!jv[jss::result].isMember(jss::bids)); } { // Create an ask: TakerPays 700, TakerGets 100/USD - env(offer("alice", XRP(700), USD(100)), - require(owners("alice", 1))); + env(offer("alice", XRP(700), USD(100)), require(owners("alice", 1))); env.close(); // Check stream update BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { auto const& t = jv[jss::transaction]; return t[jss::TransactionType] == jss::OfferCreate && - t[jss::TakerGets] == - USD(100).value().getJson(JsonOptions::none) && - t[jss::TakerPays] == - XRP(700).value().getJson(JsonOptions::none); + t[jss::TakerGets] == USD(100).value().getJson(JsonOptions::none) && + t[jss::TakerPays] == XRP(700).value().getJson(JsonOptions::none); })); } @@ -485,18 +419,15 @@ public: { // Create an ask: TakerPays 700/CNY, TakerGets 100/JPY - env(offer("alice", CNY(700), JPY(100)), - require(owners("alice", 3))); + env(offer("alice", CNY(700), JPY(100)), require(owners("alice", 3))); env.close(); // Check stream update BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { auto const& t = jv[jss::transaction]; return t[jss::TransactionType] == jss::OfferCreate && - t[jss::TakerGets] == - JPY(100).value().getJson(JsonOptions::none) && - t[jss::TakerPays] == - CNY(700).value().getJson(JsonOptions::none); + t[jss::TakerGets] == JPY(100).value().getJson(JsonOptions::none) && + t[jss::TakerPays] == CNY(700).value().getJson(JsonOptions::none); })); } @@ -512,10 +443,8 @@ public: BEAST_EXPECT(jv[jss::status] == "success"); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } } @@ -569,47 +498,36 @@ public: auto jv = wsc->invoke("subscribe", books); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } if (!BEAST_EXPECT(jv[jss::status] == "success")) return; + BEAST_EXPECT(jv[jss::result].isMember(jss::offers) && jv[jss::result][jss::offers].size() == 2); BEAST_EXPECT( - jv[jss::result].isMember(jss::offers) && - jv[jss::result][jss::offers].size() == 2); + jv[jss::result][jss::offers][0u][jss::TakerGets] == XRP(200).value().getJson(JsonOptions::none)); BEAST_EXPECT( - jv[jss::result][jss::offers][0u][jss::TakerGets] == - XRP(200).value().getJson(JsonOptions::none)); + jv[jss::result][jss::offers][0u][jss::TakerPays] == USD(100).value().getJson(JsonOptions::none)); BEAST_EXPECT( - jv[jss::result][jss::offers][0u][jss::TakerPays] == - USD(100).value().getJson(JsonOptions::none)); + jv[jss::result][jss::offers][1u][jss::TakerGets] == CNY(200).value().getJson(JsonOptions::none)); BEAST_EXPECT( - jv[jss::result][jss::offers][1u][jss::TakerGets] == - CNY(200).value().getJson(JsonOptions::none)); - BEAST_EXPECT( - jv[jss::result][jss::offers][1u][jss::TakerPays] == - JPY(100).value().getJson(JsonOptions::none)); + jv[jss::result][jss::offers][1u][jss::TakerPays] == JPY(100).value().getJson(JsonOptions::none)); BEAST_EXPECT(!jv[jss::result].isMember(jss::asks)); BEAST_EXPECT(!jv[jss::result].isMember(jss::bids)); } { // Create an ask: TakerPays 700, TakerGets 100/USD - env(offer("alice", XRP(700), USD(100)), - require(owners("alice", 5))); + env(offer("alice", XRP(700), USD(100)), require(owners("alice", 5))); env.close(); // Check stream update BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { auto const& t = jv[jss::transaction]; return t[jss::TransactionType] == jss::OfferCreate && - t[jss::TakerGets] == - USD(100).value().getJson(JsonOptions::none) && - t[jss::TakerPays] == - XRP(700).value().getJson(JsonOptions::none); + t[jss::TakerGets] == USD(100).value().getJson(JsonOptions::none) && + t[jss::TakerPays] == XRP(700).value().getJson(JsonOptions::none); })); } @@ -622,18 +540,15 @@ public: { // Create an ask: TakerPays 700/CNY, TakerGets 100/JPY - env(offer("alice", CNY(700), JPY(100)), - require(owners("alice", 7))); + env(offer("alice", CNY(700), JPY(100)), require(owners("alice", 7))); env.close(); // Check stream update BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { auto const& t = jv[jss::transaction]; return t[jss::TransactionType] == jss::OfferCreate && - t[jss::TakerGets] == - JPY(100).value().getJson(JsonOptions::none) && - t[jss::TakerPays] == - CNY(700).value().getJson(JsonOptions::none); + t[jss::TakerGets] == JPY(100).value().getJson(JsonOptions::none) && + t[jss::TakerPays] == CNY(700).value().getJson(JsonOptions::none); })); } @@ -649,10 +564,8 @@ public: BEAST_EXPECT(jv[jss::status] == "success"); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } } @@ -695,37 +608,28 @@ public: auto jv = wsc->invoke("subscribe", books); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } if (!BEAST_EXPECT(jv[jss::status] == "success")) return; - BEAST_EXPECT( - jv[jss::result].isMember(jss::asks) && - jv[jss::result][jss::asks].size() == 0); - BEAST_EXPECT( - jv[jss::result].isMember(jss::bids) && - jv[jss::result][jss::bids].size() == 0); + BEAST_EXPECT(jv[jss::result].isMember(jss::asks) && jv[jss::result][jss::asks].size() == 0); + BEAST_EXPECT(jv[jss::result].isMember(jss::bids) && jv[jss::result][jss::bids].size() == 0); BEAST_EXPECT(!jv[jss::result].isMember(jss::offers)); } { // Create an ask: TakerPays 700, TakerGets 100/USD - env(offer("alice", XRP(700), USD(100)), - require(owners("alice", 1))); + env(offer("alice", XRP(700), USD(100)), require(owners("alice", 1))); env.close(); // Check stream update BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { auto const& t = jv[jss::transaction]; return t[jss::TransactionType] == jss::OfferCreate && - t[jss::TakerGets] == - USD(100).value().getJson(JsonOptions::none) && - t[jss::TakerPays] == - XRP(700).value().getJson(JsonOptions::none); + t[jss::TakerGets] == USD(100).value().getJson(JsonOptions::none) && + t[jss::TakerPays] == XRP(700).value().getJson(JsonOptions::none); })); } @@ -738,27 +642,22 @@ public: BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { auto const& t = jv[jss::transaction]; return t[jss::TransactionType] == jss::OfferCreate && - t[jss::TakerGets] == - XRP(75).value().getJson(JsonOptions::none) && - t[jss::TakerPays] == - USD(100).value().getJson(JsonOptions::none); + t[jss::TakerGets] == XRP(75).value().getJson(JsonOptions::none) && + t[jss::TakerPays] == USD(100).value().getJson(JsonOptions::none); })); } { // Create an ask: TakerPays 700/CNY, TakerGets 100/JPY - env(offer("alice", CNY(700), JPY(100)), - require(owners("alice", 3))); + env(offer("alice", CNY(700), JPY(100)), require(owners("alice", 3))); env.close(); // Check stream update BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { auto const& t = jv[jss::transaction]; return t[jss::TransactionType] == jss::OfferCreate && - t[jss::TakerGets] == - JPY(100).value().getJson(JsonOptions::none) && - t[jss::TakerPays] == - CNY(700).value().getJson(JsonOptions::none); + t[jss::TakerGets] == JPY(100).value().getJson(JsonOptions::none) && + t[jss::TakerPays] == CNY(700).value().getJson(JsonOptions::none); })); } @@ -771,10 +670,8 @@ public: BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { auto const& t = jv[jss::transaction]; return t[jss::TransactionType] == jss::OfferCreate && - t[jss::TakerGets] == - CNY(75).value().getJson(JsonOptions::none) && - t[jss::TakerPays] == - JPY(100).value().getJson(JsonOptions::none); + t[jss::TakerGets] == CNY(75).value().getJson(JsonOptions::none) && + t[jss::TakerPays] == JPY(100).value().getJson(JsonOptions::none); })); } @@ -783,10 +680,8 @@ public: BEAST_EXPECT(jv[jss::status] == "success"); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } } @@ -843,61 +738,36 @@ public: auto jv = wsc->invoke("subscribe", books); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } if (!BEAST_EXPECT(jv[jss::status] == "success")) return; - BEAST_EXPECT( - jv[jss::result].isMember(jss::asks) && - jv[jss::result][jss::asks].size() == 2); - BEAST_EXPECT( - jv[jss::result].isMember(jss::bids) && - jv[jss::result][jss::bids].size() == 2); - BEAST_EXPECT( - jv[jss::result][jss::asks][0u][jss::TakerGets] == - USD(100).value().getJson(JsonOptions::none)); - BEAST_EXPECT( - jv[jss::result][jss::asks][0u][jss::TakerPays] == - XRP(500).value().getJson(JsonOptions::none)); - BEAST_EXPECT( - jv[jss::result][jss::asks][1u][jss::TakerGets] == - JPY(100).value().getJson(JsonOptions::none)); - BEAST_EXPECT( - jv[jss::result][jss::asks][1u][jss::TakerPays] == - CNY(500).value().getJson(JsonOptions::none)); - BEAST_EXPECT( - jv[jss::result][jss::bids][0u][jss::TakerGets] == - XRP(200).value().getJson(JsonOptions::none)); - BEAST_EXPECT( - jv[jss::result][jss::bids][0u][jss::TakerPays] == - USD(100).value().getJson(JsonOptions::none)); - BEAST_EXPECT( - jv[jss::result][jss::bids][1u][jss::TakerGets] == - CNY(200).value().getJson(JsonOptions::none)); - BEAST_EXPECT( - jv[jss::result][jss::bids][1u][jss::TakerPays] == - JPY(100).value().getJson(JsonOptions::none)); + BEAST_EXPECT(jv[jss::result].isMember(jss::asks) && jv[jss::result][jss::asks].size() == 2); + BEAST_EXPECT(jv[jss::result].isMember(jss::bids) && jv[jss::result][jss::bids].size() == 2); + BEAST_EXPECT(jv[jss::result][jss::asks][0u][jss::TakerGets] == USD(100).value().getJson(JsonOptions::none)); + BEAST_EXPECT(jv[jss::result][jss::asks][0u][jss::TakerPays] == XRP(500).value().getJson(JsonOptions::none)); + BEAST_EXPECT(jv[jss::result][jss::asks][1u][jss::TakerGets] == JPY(100).value().getJson(JsonOptions::none)); + BEAST_EXPECT(jv[jss::result][jss::asks][1u][jss::TakerPays] == CNY(500).value().getJson(JsonOptions::none)); + BEAST_EXPECT(jv[jss::result][jss::bids][0u][jss::TakerGets] == XRP(200).value().getJson(JsonOptions::none)); + BEAST_EXPECT(jv[jss::result][jss::bids][0u][jss::TakerPays] == USD(100).value().getJson(JsonOptions::none)); + BEAST_EXPECT(jv[jss::result][jss::bids][1u][jss::TakerGets] == CNY(200).value().getJson(JsonOptions::none)); + BEAST_EXPECT(jv[jss::result][jss::bids][1u][jss::TakerPays] == JPY(100).value().getJson(JsonOptions::none)); BEAST_EXPECT(!jv[jss::result].isMember(jss::offers)); } { // Create an ask: TakerPays 700, TakerGets 100/USD - env(offer("alice", XRP(700), USD(100)), - require(owners("alice", 5))); + env(offer("alice", XRP(700), USD(100)), require(owners("alice", 5))); env.close(); // Check stream update BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { auto const& t = jv[jss::transaction]; return t[jss::TransactionType] == jss::OfferCreate && - t[jss::TakerGets] == - USD(100).value().getJson(JsonOptions::none) && - t[jss::TakerPays] == - XRP(700).value().getJson(JsonOptions::none); + t[jss::TakerGets] == USD(100).value().getJson(JsonOptions::none) && + t[jss::TakerPays] == XRP(700).value().getJson(JsonOptions::none); })); } @@ -910,27 +780,22 @@ public: BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { auto const& t = jv[jss::transaction]; return t[jss::TransactionType] == jss::OfferCreate && - t[jss::TakerGets] == - XRP(75).value().getJson(JsonOptions::none) && - t[jss::TakerPays] == - USD(100).value().getJson(JsonOptions::none); + t[jss::TakerGets] == XRP(75).value().getJson(JsonOptions::none) && + t[jss::TakerPays] == USD(100).value().getJson(JsonOptions::none); })); } { // Create an ask: TakerPays 700/CNY, TakerGets 100/JPY - env(offer("alice", CNY(700), JPY(100)), - require(owners("alice", 7))); + env(offer("alice", CNY(700), JPY(100)), require(owners("alice", 7))); env.close(); // Check stream update BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { auto const& t = jv[jss::transaction]; return t[jss::TransactionType] == jss::OfferCreate && - t[jss::TakerGets] == - JPY(100).value().getJson(JsonOptions::none) && - t[jss::TakerPays] == - CNY(700).value().getJson(JsonOptions::none); + t[jss::TakerGets] == JPY(100).value().getJson(JsonOptions::none) && + t[jss::TakerPays] == CNY(700).value().getJson(JsonOptions::none); })); } @@ -943,10 +808,8 @@ public: BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { auto const& t = jv[jss::transaction]; return t[jss::TransactionType] == jss::OfferCreate && - t[jss::TakerGets] == - CNY(75).value().getJson(JsonOptions::none) && - t[jss::TakerPays] == - JPY(100).value().getJson(JsonOptions::none); + t[jss::TakerGets] == CNY(75).value().getJson(JsonOptions::none) && + t[jss::TakerPays] == JPY(100).value().getJson(JsonOptions::none); })); } @@ -955,10 +818,8 @@ public: BEAST_EXPECT(jv[jss::status] == "success"); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } } @@ -991,17 +852,13 @@ public: auto jv = wsc->invoke("subscribe", books); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } if (!BEAST_EXPECT(jv[jss::status] == "success")) return; - BEAST_EXPECT( - jv[jss::result].isMember(jss::offers) && - jv[jss::result][jss::offers].size() == 0); + BEAST_EXPECT(jv[jss::result].isMember(jss::offers) && jv[jss::result][jss::offers].size() == 0); BEAST_EXPECT(!jv[jss::result].isMember(jss::asks)); BEAST_EXPECT(!jv[jss::result].isMember(jss::bids)); } @@ -1025,10 +882,8 @@ public: auto jv = wsc->invoke("book_offers", jvParams); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } auto jrr = jv[jss::result]; @@ -1037,20 +892,14 @@ public: BEAST_EXPECT(jrr[jss::offers].size() == 1); auto const jrOffer = jrr[jss::offers][0u]; BEAST_EXPECT(jrOffer[sfAccount.fieldName] == alice.human()); - BEAST_EXPECT( - jrOffer[sfBookDirectory.fieldName] == - getBookDir(env, XRP, USD.issue())); + BEAST_EXPECT(jrOffer[sfBookDirectory.fieldName] == getBookDir(env, XRP, USD.issue())); BEAST_EXPECT(jrOffer[sfBookNode.fieldName] == "0"); BEAST_EXPECT(jrOffer[jss::Flags] == 0); BEAST_EXPECT(jrOffer[sfLedgerEntryType.fieldName] == jss::Offer); BEAST_EXPECT(jrOffer[sfOwnerNode.fieldName] == "0"); BEAST_EXPECT(jrOffer[sfSequence.fieldName] == 5); - BEAST_EXPECT( - jrOffer[jss::TakerGets] == - USD(10).value().getJson(JsonOptions::none)); - BEAST_EXPECT( - jrOffer[jss::TakerPays] == - XRP(4000).value().getJson(JsonOptions::none)); + BEAST_EXPECT(jrOffer[jss::TakerGets] == USD(10).value().getJson(JsonOptions::none)); + BEAST_EXPECT(jrOffer[jss::TakerPays] == XRP(4000).value().getJson(JsonOptions::none)); BEAST_EXPECT(jrOffer[jss::owner_funds] == "100"); BEAST_EXPECT(jrOffer[jss::quality] == "400000000"); @@ -1058,11 +907,8 @@ public: BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jval) { auto const& t = jval[jss::transaction]; return t[jss::TransactionType] == jss::OfferCreate && - t[jss::TakerGets] == - USD(10).value().getJson(JsonOptions::none) && - t[jss::owner_funds] == "100" && - t[jss::TakerPays] == - XRP(4000).value().getJson(JsonOptions::none); + t[jss::TakerGets] == USD(10).value().getJson(JsonOptions::none) && t[jss::owner_funds] == "100" && + t[jss::TakerPays] == XRP(4000).value().getJson(JsonOptions::none); })); env(offer(bob, XRP(2000), USD(5))); @@ -1071,20 +917,15 @@ public: BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jval) { auto const& t = jval[jss::transaction]; return t[jss::TransactionType] == jss::OfferCreate && - t[jss::TakerGets] == - USD(5).value().getJson(JsonOptions::none) && - t[jss::owner_funds] == "50" && - t[jss::TakerPays] == - XRP(2000).value().getJson(JsonOptions::none); + t[jss::TakerGets] == USD(5).value().getJson(JsonOptions::none) && t[jss::owner_funds] == "50" && + t[jss::TakerPays] == XRP(2000).value().getJson(JsonOptions::none); })); jv = wsc->invoke("book_offers", jvParams); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } jrr = jv[jss::result]; @@ -1093,30 +934,22 @@ public: BEAST_EXPECT(jrr[jss::offers].size() == 2); auto const jrNextOffer = jrr[jss::offers][1u]; BEAST_EXPECT(jrNextOffer[sfAccount.fieldName] == bob.human()); - BEAST_EXPECT( - jrNextOffer[sfBookDirectory.fieldName] == - getBookDir(env, XRP, USD.issue())); + BEAST_EXPECT(jrNextOffer[sfBookDirectory.fieldName] == getBookDir(env, XRP, USD.issue())); BEAST_EXPECT(jrNextOffer[sfBookNode.fieldName] == "0"); BEAST_EXPECT(jrNextOffer[jss::Flags] == 0); BEAST_EXPECT(jrNextOffer[sfLedgerEntryType.fieldName] == jss::Offer); BEAST_EXPECT(jrNextOffer[sfOwnerNode.fieldName] == "0"); BEAST_EXPECT(jrNextOffer[sfSequence.fieldName] == 5); - BEAST_EXPECT( - jrNextOffer[jss::TakerGets] == - USD(5).value().getJson(JsonOptions::none)); - BEAST_EXPECT( - jrNextOffer[jss::TakerPays] == - XRP(2000).value().getJson(JsonOptions::none)); + BEAST_EXPECT(jrNextOffer[jss::TakerGets] == USD(5).value().getJson(JsonOptions::none)); + BEAST_EXPECT(jrNextOffer[jss::TakerPays] == XRP(2000).value().getJson(JsonOptions::none)); BEAST_EXPECT(jrNextOffer[jss::owner_funds] == "50"); BEAST_EXPECT(jrNextOffer[jss::quality] == "400000000"); jv = wsc->invoke("unsubscribe", books); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } BEAST_EXPECT(jv[jss::status] == "success"); @@ -1312,8 +1145,7 @@ public: { Json::Value jvParams; jvParams[jss::ledger_index] = 10u; - auto const jrr = env.rpc( - "json", "book_offers", to_string(jvParams))[jss::result]; + auto const jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "lgrNotFound"); BEAST_EXPECT(jrr[jss::error_message] == "ledgerNotFound"); } @@ -1321,22 +1153,18 @@ public: { Json::Value jvParams; jvParams[jss::ledger_index] = "validated"; - auto const jrr = env.rpc( - "json", "book_offers", to_string(jvParams))[jss::result]; + auto const jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); - BEAST_EXPECT( - jrr[jss::error_message] == "Missing field 'taker_pays'."); + BEAST_EXPECT(jrr[jss::error_message] == "Missing field 'taker_pays'."); } { Json::Value jvParams; jvParams[jss::ledger_index] = "validated"; jvParams[jss::taker_pays] = Json::objectValue; - auto const jrr = env.rpc( - "json", "book_offers", to_string(jvParams))[jss::result]; + auto const jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); - BEAST_EXPECT( - jrr[jss::error_message] == "Missing field 'taker_gets'."); + BEAST_EXPECT(jrr[jss::error_message] == "Missing field 'taker_gets'."); } { @@ -1344,12 +1172,9 @@ public: jvParams[jss::ledger_index] = "validated"; jvParams[jss::taker_pays] = "not an object"; jvParams[jss::taker_gets] = Json::objectValue; - auto const jrr = env.rpc( - "json", "book_offers", to_string(jvParams))[jss::result]; + auto const jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); - BEAST_EXPECT( - jrr[jss::error_message] == - "Invalid field 'taker_pays', not object."); + BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'taker_pays', not object."); } { @@ -1357,12 +1182,9 @@ public: jvParams[jss::ledger_index] = "validated"; jvParams[jss::taker_pays] = Json::objectValue; jvParams[jss::taker_gets] = "not an object"; - auto const jrr = env.rpc( - "json", "book_offers", to_string(jvParams))[jss::result]; + auto const jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); - BEAST_EXPECT( - jrr[jss::error_message] == - "Invalid field 'taker_gets', not object."); + BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'taker_gets', not object."); } { @@ -1370,12 +1192,9 @@ public: jvParams[jss::ledger_index] = "validated"; jvParams[jss::taker_pays] = Json::objectValue; jvParams[jss::taker_gets] = Json::objectValue; - auto const jrr = env.rpc( - "json", "book_offers", to_string(jvParams))[jss::result]; + auto const jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); - BEAST_EXPECT( - jrr[jss::error_message] == - "Missing field 'taker_pays.currency'."); + BEAST_EXPECT(jrr[jss::error_message] == "Missing field 'taker_pays.currency'."); } { @@ -1383,12 +1202,9 @@ public: jvParams[jss::ledger_index] = "validated"; jvParams[jss::taker_pays][jss::currency] = 1; jvParams[jss::taker_gets] = Json::objectValue; - auto const jrr = env.rpc( - "json", "book_offers", to_string(jvParams))[jss::result]; + auto const jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); - BEAST_EXPECT( - jrr[jss::error_message] == - "Invalid field 'taker_pays.currency', not string."); + BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'taker_pays.currency', not string."); } { @@ -1396,12 +1212,9 @@ public: jvParams[jss::ledger_index] = "validated"; jvParams[jss::taker_pays][jss::currency] = "XRP"; jvParams[jss::taker_gets] = Json::objectValue; - auto const jrr = env.rpc( - "json", "book_offers", to_string(jvParams))[jss::result]; + auto const jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); - BEAST_EXPECT( - jrr[jss::error_message] == - "Missing field 'taker_gets.currency'."); + BEAST_EXPECT(jrr[jss::error_message] == "Missing field 'taker_gets.currency'."); } { @@ -1409,12 +1222,9 @@ public: jvParams[jss::ledger_index] = "validated"; jvParams[jss::taker_pays][jss::currency] = "XRP"; jvParams[jss::taker_gets][jss::currency] = 1; - auto const jrr = env.rpc( - "json", "book_offers", to_string(jvParams))[jss::result]; + auto const jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); - BEAST_EXPECT( - jrr[jss::error_message] == - "Invalid field 'taker_gets.currency', not string."); + BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'taker_gets.currency', not string."); } { @@ -1422,12 +1232,9 @@ public: jvParams[jss::ledger_index] = "validated"; jvParams[jss::taker_pays][jss::currency] = "NOT_VALID"; jvParams[jss::taker_gets][jss::currency] = "XRP"; - auto const jrr = env.rpc( - "json", "book_offers", to_string(jvParams))[jss::result]; + auto const jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "srcCurMalformed"); - BEAST_EXPECT( - jrr[jss::error_message] == - "Invalid field 'taker_pays.currency', bad currency."); + BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'taker_pays.currency', bad currency."); } { @@ -1435,12 +1242,9 @@ public: jvParams[jss::ledger_index] = "validated"; jvParams[jss::taker_pays][jss::currency] = "XRP"; jvParams[jss::taker_gets][jss::currency] = "NOT_VALID"; - auto const jrr = env.rpc( - "json", "book_offers", to_string(jvParams))[jss::result]; + auto const jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "dstAmtMalformed"); - BEAST_EXPECT( - jrr[jss::error_message] == - "Invalid field 'taker_gets.currency', bad currency."); + BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'taker_gets.currency', bad currency."); } { @@ -1449,12 +1253,9 @@ public: jvParams[jss::taker_pays][jss::currency] = "XRP"; jvParams[jss::taker_gets][jss::currency] = "USD"; jvParams[jss::taker_gets][jss::issuer] = 1; - auto const jrr = env.rpc( - "json", "book_offers", to_string(jvParams))[jss::result]; + auto const jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); - BEAST_EXPECT( - jrr[jss::error_message] == - "Invalid field 'taker_gets.issuer', not string."); + BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'taker_gets.issuer', not string."); } { @@ -1463,12 +1264,9 @@ public: jvParams[jss::taker_pays][jss::currency] = "XRP"; jvParams[jss::taker_pays][jss::issuer] = 1; jvParams[jss::taker_gets][jss::currency] = "USD"; - auto const jrr = env.rpc( - "json", "book_offers", to_string(jvParams))[jss::result]; + auto const jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); - BEAST_EXPECT( - jrr[jss::error_message] == - "Invalid field 'taker_pays.issuer', not string."); + BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'taker_pays.issuer', not string."); } { @@ -1477,12 +1275,9 @@ public: jvParams[jss::taker_pays][jss::currency] = "XRP"; jvParams[jss::taker_pays][jss::issuer] = gw.human() + "DEAD"; jvParams[jss::taker_gets][jss::currency] = "USD"; - auto const jrr = env.rpc( - "json", "book_offers", to_string(jvParams))[jss::result]; + auto const jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "srcIsrMalformed"); - BEAST_EXPECT( - jrr[jss::error_message] == - "Invalid field 'taker_pays.issuer', bad issuer."); + BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'taker_pays.issuer', bad issuer."); } { @@ -1491,12 +1286,9 @@ public: jvParams[jss::taker_pays][jss::currency] = "XRP"; jvParams[jss::taker_pays][jss::issuer] = toBase58(noAccount()); jvParams[jss::taker_gets][jss::currency] = "USD"; - auto const jrr = env.rpc( - "json", "book_offers", to_string(jvParams))[jss::result]; + auto const jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "srcIsrMalformed"); - BEAST_EXPECT( - jrr[jss::error_message] == - "Invalid field 'taker_pays.issuer', bad issuer account one."); + BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'taker_pays.issuer', bad issuer account one."); } { @@ -1505,12 +1297,9 @@ public: jvParams[jss::taker_pays][jss::currency] = "XRP"; jvParams[jss::taker_gets][jss::currency] = "USD"; jvParams[jss::taker_gets][jss::issuer] = gw.human() + "DEAD"; - auto const jrr = env.rpc( - "json", "book_offers", to_string(jvParams))[jss::result]; + auto const jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "dstIsrMalformed"); - BEAST_EXPECT( - jrr[jss::error_message] == - "Invalid field 'taker_gets.issuer', bad issuer."); + BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'taker_gets.issuer', bad issuer."); } { @@ -1519,12 +1308,9 @@ public: jvParams[jss::taker_pays][jss::currency] = "XRP"; jvParams[jss::taker_gets][jss::currency] = "USD"; jvParams[jss::taker_gets][jss::issuer] = toBase58(noAccount()); - auto const jrr = env.rpc( - "json", "book_offers", to_string(jvParams))[jss::result]; + auto const jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "dstIsrMalformed"); - BEAST_EXPECT( - jrr[jss::error_message] == - "Invalid field 'taker_gets.issuer', bad issuer account one."); + BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'taker_gets.issuer', bad issuer account one."); } { @@ -1534,8 +1320,7 @@ public: jvParams[jss::taker_pays][jss::issuer] = alice.human(); jvParams[jss::taker_gets][jss::currency] = "USD"; jvParams[jss::taker_gets][jss::issuer] = gw.human(); - auto const jrr = env.rpc( - "json", "book_offers", to_string(jvParams))[jss::result]; + auto const jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "srcIsrMalformed"); BEAST_EXPECT( jrr[jss::error_message] == @@ -1550,12 +1335,9 @@ public: jvParams[jss::taker_pays][jss::issuer] = toBase58(xrpAccount()); jvParams[jss::taker_gets][jss::currency] = "USD"; jvParams[jss::taker_gets][jss::issuer] = gw.human(); - auto const jrr = env.rpc( - "json", "book_offers", to_string(jvParams))[jss::result]; + auto const jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "srcIsrMalformed"); - BEAST_EXPECT( - jrr[jss::error_message] == - "Invalid field 'taker_pays.issuer', expected non-XRP issuer."); + BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'taker_pays.issuer', expected non-XRP issuer."); } { @@ -1565,12 +1347,9 @@ public: jvParams[jss::taker_pays][jss::currency] = "XRP"; jvParams[jss::taker_gets][jss::currency] = "USD"; jvParams[jss::taker_gets][jss::issuer] = gw.human(); - auto const jrr = env.rpc( - "json", "book_offers", to_string(jvParams))[jss::result]; + auto const jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); - BEAST_EXPECT( - jrr[jss::error_message] == - "Invalid field 'taker', not string."); + BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'taker', not string."); } { @@ -1580,8 +1359,7 @@ public: jvParams[jss::taker_pays][jss::currency] = "XRP"; jvParams[jss::taker_gets][jss::currency] = "USD"; jvParams[jss::taker_gets][jss::issuer] = gw.human(); - auto const jrr = env.rpc( - "json", "book_offers", to_string(jvParams))[jss::result]; + auto const jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'taker'."); } @@ -1594,8 +1372,7 @@ public: jvParams[jss::taker_pays][jss::issuer] = gw.human(); jvParams[jss::taker_gets][jss::currency] = "USD"; jvParams[jss::taker_gets][jss::issuer] = gw.human(); - auto const jrr = env.rpc( - "json", "book_offers", to_string(jvParams))[jss::result]; + auto const jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "badMarket"); BEAST_EXPECT(jrr[jss::error_message] == "No such market."); } @@ -1608,12 +1385,9 @@ public: jvParams[jss::taker_pays][jss::currency] = "XRP"; jvParams[jss::taker_gets][jss::currency] = "USD"; jvParams[jss::taker_gets][jss::issuer] = gw.human(); - auto const jrr = env.rpc( - "json", "book_offers", to_string(jvParams))[jss::result]; + auto const jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); - BEAST_EXPECT( - jrr[jss::error_message] == - "Invalid field 'limit', not unsigned integer."); + BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'limit', not unsigned integer."); } { @@ -1624,8 +1398,7 @@ public: jvParams[jss::taker_pays][jss::currency] = "XRP"; jvParams[jss::taker_gets][jss::currency] = "USD"; jvParams[jss::taker_gets][jss::issuer] = gw.human(); - auto const jrr = env.rpc( - "json", "book_offers", to_string(jvParams))[jss::result]; + auto const jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'limit'."); } @@ -1636,8 +1409,7 @@ public: jvParams[jss::taker_pays][jss::currency] = "USD"; jvParams[jss::taker_pays][jss::issuer] = gw.human(); jvParams[jss::taker_gets][jss::currency] = "USD"; - auto const jrr = env.rpc( - "json", "book_offers", to_string(jvParams))[jss::result]; + auto const jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "dstIsrMalformed"); BEAST_EXPECT( jrr[jss::error_message] == @@ -1652,8 +1424,7 @@ public: jvParams[jss::taker_pays][jss::issuer] = gw.human(); jvParams[jss::taker_gets][jss::currency] = "XRP"; jvParams[jss::taker_gets][jss::issuer] = gw.human(); - auto const jrr = env.rpc( - "json", "book_offers", to_string(jvParams))[jss::result]; + auto const jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "dstIsrMalformed"); BEAST_EXPECT( jrr[jss::error_message] == @@ -1668,8 +1439,7 @@ public: jvParams[jss::taker_gets][jss::currency] = "EUR"; jvParams[jss::taker_gets][jss::issuer] = gw.human(); jvParams[jss::domain] = "badString"; - auto const jrr = env.rpc( - "json", "book_offers", to_string(jvParams))[jss::result]; + auto const jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "domainMalformed"); BEAST_EXPECT(jrr[jss::error_message] == "Unable to parse domain."); } @@ -1701,8 +1471,7 @@ public: jvParams[jss::taker_pays][jss::currency] = "XRP"; jvParams[jss::taker_gets][jss::currency] = "USD"; jvParams[jss::taker_gets][jss::issuer] = gw.human(); - auto jrr = - env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; + auto jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::offers].isArray()); BEAST_EXPECT(jrr[jss::offers].size() == (asAdmin ? 1u : 0u)); // NOTE - a marker field is not returned for this method @@ -1710,16 +1479,12 @@ public: jvParams[jss::limit] = RPC::Tuning::bookOffers.rmax + 1; jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::offers].isArray()); - BEAST_EXPECT( - jrr[jss::offers].size() == - (asAdmin ? RPC::Tuning::bookOffers.rmax + 1 : 0u)); + BEAST_EXPECT(jrr[jss::offers].size() == (asAdmin ? RPC::Tuning::bookOffers.rmax + 1 : 0u)); jvParams[jss::limit] = Json::nullValue; jrr = env.rpc("json", "book_offers", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::offers].isArray()); - BEAST_EXPECT( - jrr[jss::offers].size() == - (asAdmin ? RPC::Tuning::bookOffers.rDefault : 0u)); + BEAST_EXPECT(jrr[jss::offers].size() == (asAdmin ? RPC::Tuning::bookOffers.rDefault : 0u)); } void @@ -1729,8 +1494,7 @@ public: using namespace jtx; FeatureBitset const all{ - jtx::testable_amendments() | featurePermissionedDomains | - featureCredentials | featurePermissionedDEX}; + jtx::testable_amendments() | featurePermissionedDomains | featureCredentials | featurePermissionedDEX}; Env env(*this, all); PermissionedDEX permDex(env); @@ -1751,21 +1515,14 @@ public: BEAST_EXPECT(jrr[jss::offers].size() == 1); auto const jrOffer = jrr[jss::offers][0u]; BEAST_EXPECT(jrOffer[sfAccount.fieldName] == alice.human()); - BEAST_EXPECT( - jrOffer[sfBookDirectory.fieldName] == - getBookDir(env, XRP, USD.issue(), domainID)); + BEAST_EXPECT(jrOffer[sfBookDirectory.fieldName] == getBookDir(env, XRP, USD.issue(), domainID)); BEAST_EXPECT(jrOffer[sfBookNode.fieldName] == "0"); BEAST_EXPECT(jrOffer[jss::Flags] == 0); BEAST_EXPECT(jrOffer[sfLedgerEntryType.fieldName] == jss::Offer); BEAST_EXPECT(jrOffer[sfOwnerNode.fieldName] == "0"); - BEAST_EXPECT( - jrOffer[jss::TakerGets] == - USD(10).value().getJson(JsonOptions::none)); - BEAST_EXPECT( - jrOffer[jss::TakerPays] == - XRP(10).value().getJson(JsonOptions::none)); - BEAST_EXPECT( - jrOffer[sfDomainID.jsonName].asString() == to_string(domainID)); + BEAST_EXPECT(jrOffer[jss::TakerGets] == USD(10).value().getJson(JsonOptions::none)); + BEAST_EXPECT(jrOffer[jss::TakerPays] == XRP(10).value().getJson(JsonOptions::none)); + BEAST_EXPECT(jrOffer[sfDomainID.jsonName].asString() == to_string(domainID)); }; // book_offers: open book doesn't return offer @@ -1784,18 +1541,12 @@ public: } auto checkSubBooks = [&](Json::Value const& jv) { + BEAST_EXPECT(jv[jss::result].isMember(jss::offers) && jv[jss::result][jss::offers].size() == 1); BEAST_EXPECT( - jv[jss::result].isMember(jss::offers) && - jv[jss::result][jss::offers].size() == 1); + jv[jss::result][jss::offers][0u][jss::TakerGets] == USD(10).value().getJson(JsonOptions::none)); BEAST_EXPECT( - jv[jss::result][jss::offers][0u][jss::TakerGets] == - USD(10).value().getJson(JsonOptions::none)); - BEAST_EXPECT( - jv[jss::result][jss::offers][0u][jss::TakerPays] == - XRP(10).value().getJson(JsonOptions::none)); - BEAST_EXPECT( - jv[jss::result][jss::offers][0u][sfDomainID.jsonName] - .asString() == to_string(domainID)); + jv[jss::result][jss::offers][0u][jss::TakerPays] == XRP(10).value().getJson(JsonOptions::none)); + BEAST_EXPECT(jv[jss::result][jss::offers][0u][sfDomainID.jsonName].asString() == to_string(domainID)); }; // book_offers: requesting domain book returns hybrid offer @@ -1847,9 +1598,7 @@ public: auto jv = wsc->invoke("subscribe", books); if (!BEAST_EXPECT(jv[jss::status] == "success")) return; - BEAST_EXPECT( - jv[jss::result].isMember(jss::offers) && - jv[jss::result][jss::offers].size() == 0); + BEAST_EXPECT(jv[jss::result].isMember(jss::offers) && jv[jss::result][jss::offers].size() == 0); } } @@ -1860,8 +1609,7 @@ public: using namespace jtx; FeatureBitset const all{ - jtx::testable_amendments() | featurePermissionedDomains | - featureCredentials | featurePermissionedDEX}; + jtx::testable_amendments() | featurePermissionedDomains | featureCredentials | featurePermissionedDEX}; Env env(*this, all); PermissionedDEX permDex(env); @@ -1874,9 +1622,7 @@ public: auto wsc = makeWSClient(env.app().config()); - env(offer(alice, XRP(10), USD(10)), - domain(domainID), - txflags(tfHybrid)); + env(offer(alice, XRP(10), USD(10)), domain(domainID), txflags(tfHybrid)); env.close(); auto checkBookOffers = [&](Json::Value const& jrr) { @@ -1884,21 +1630,14 @@ public: BEAST_EXPECT(jrr[jss::offers].size() == 1); auto const jrOffer = jrr[jss::offers][0u]; BEAST_EXPECT(jrOffer[sfAccount.fieldName] == alice.human()); - BEAST_EXPECT( - jrOffer[sfBookDirectory.fieldName] == - getBookDir(env, XRP, USD.issue(), domainID)); + BEAST_EXPECT(jrOffer[sfBookDirectory.fieldName] == getBookDir(env, XRP, USD.issue(), domainID)); BEAST_EXPECT(jrOffer[sfBookNode.fieldName] == "0"); BEAST_EXPECT(jrOffer[jss::Flags] == lsfHybrid); BEAST_EXPECT(jrOffer[sfLedgerEntryType.fieldName] == jss::Offer); BEAST_EXPECT(jrOffer[sfOwnerNode.fieldName] == "0"); - BEAST_EXPECT( - jrOffer[jss::TakerGets] == - USD(10).value().getJson(JsonOptions::none)); - BEAST_EXPECT( - jrOffer[jss::TakerPays] == - XRP(10).value().getJson(JsonOptions::none)); - BEAST_EXPECT( - jrOffer[sfDomainID.jsonName].asString() == to_string(domainID)); + BEAST_EXPECT(jrOffer[jss::TakerGets] == USD(10).value().getJson(JsonOptions::none)); + BEAST_EXPECT(jrOffer[jss::TakerPays] == XRP(10).value().getJson(JsonOptions::none)); + BEAST_EXPECT(jrOffer[sfDomainID.jsonName].asString() == to_string(domainID)); BEAST_EXPECT(jrOffer[sfAdditionalBooks.jsonName].size() == 1); }; @@ -1917,18 +1656,12 @@ public: } auto checkSubBooks = [&](Json::Value const& jv) { + BEAST_EXPECT(jv[jss::result].isMember(jss::offers) && jv[jss::result][jss::offers].size() == 1); BEAST_EXPECT( - jv[jss::result].isMember(jss::offers) && - jv[jss::result][jss::offers].size() == 1); + jv[jss::result][jss::offers][0u][jss::TakerGets] == USD(10).value().getJson(JsonOptions::none)); BEAST_EXPECT( - jv[jss::result][jss::offers][0u][jss::TakerGets] == - USD(10).value().getJson(JsonOptions::none)); - BEAST_EXPECT( - jv[jss::result][jss::offers][0u][jss::TakerPays] == - XRP(10).value().getJson(JsonOptions::none)); - BEAST_EXPECT( - jv[jss::result][jss::offers][0u][sfDomainID.jsonName] - .asString() == to_string(domainID)); + jv[jss::result][jss::offers][0u][jss::TakerPays] == XRP(10).value().getJson(JsonOptions::none)); + BEAST_EXPECT(jv[jss::result][jss::offers][0u][sfDomainID.jsonName].asString() == to_string(domainID)); }; // book_offers: requesting domain book returns hybrid offer diff --git a/src/test/rpc/Connect_test.cpp b/src/test/rpc/Connect_test.cpp index 8d5a2ca33f..c029356bf6 100644 --- a/src/test/rpc/Connect_test.cpp +++ b/src/test/rpc/Connect_test.cpp @@ -22,9 +22,7 @@ class Connect_test : public beast::unit_test::suite BEAST_EXPECT(result[jss::result][jss::status] == "error"); BEAST_EXPECT(result[jss::result].isMember(jss::error)); BEAST_EXPECT(result[jss::result][jss::error] == "notSynced"); - BEAST_EXPECT( - result[jss::result][jss::error_message] == - "Not synced to the network."); + BEAST_EXPECT(result[jss::result][jss::error_message] == "Not synced to the network."); } } diff --git a/src/test/rpc/DeliveredAmount_test.cpp b/src/test/rpc/DeliveredAmount_test.cpp index 3e256aa03b..8d376893ec 100644 --- a/src/test/rpc/DeliveredAmount_test.cpp +++ b/src/test/rpc/DeliveredAmount_test.cpp @@ -46,8 +46,7 @@ class CheckDeliveredAmount } public: - explicit CheckDeliveredAmount(bool afterSwitchTime) - : afterSwitchTime_(afterSwitchTime) + explicit CheckDeliveredAmount(bool afterSwitchTime) : afterSwitchTime_(afterSwitchTime) { } @@ -73,8 +72,7 @@ public: bool checkExpectedCounters() const { - return !numExpectedAvailable_ && !numExpectedNotSet_ && - !numExpectedSetUnavailable_; + return !numExpectedAvailable_ && !numExpectedNotSet_ && !numExpectedSetUnavailable_; } // Check if the transaction has `delivered_amount` in the metaData as @@ -108,8 +106,7 @@ public: { if (metaData.isMember(sfDeliveredAmount.jsonName)) { - if (metaData[jss::delivered_amount] != - metaData[sfDeliveredAmount.jsonName]) + if (metaData[jss::delivered_amount] != metaData[sfDeliveredAmount.jsonName]) return false; } else @@ -220,11 +217,8 @@ class DeliveredAmount_test : public beast::unit_test::suite auto jv = wsc->invoke("subscribe", stream); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && - jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } BEAST_EXPECT(jv[jss::result][jss::ledger_index] == 3); @@ -234,17 +228,14 @@ class DeliveredAmount_test : public beast::unit_test::suite // Check stream update while (true) { - auto const r = wsc->findMsg(1s, [&](auto const& jv) { - return jv[jss::ledger_index] == 4; - }); + auto const r = wsc->findMsg(1s, [&](auto const& jv) { return jv[jss::ledger_index] == 4; }); if (!r) break; if (!r->isMember(jss::transaction)) continue; - BEAST_EXPECT(checkDeliveredAmount.checkTxn( - (*r)[jss::transaction], (*r)[jss::meta])); + BEAST_EXPECT(checkDeliveredAmount.checkTxn((*r)[jss::transaction], (*r)[jss::meta])); } } BEAST_EXPECT(checkDeliveredAmount.checkExpectedCounters()); @@ -299,14 +290,10 @@ class DeliveredAmount_test : public beast::unit_test::suite jvParams[jss::ledger_index] = 4u; jvParams[jss::transactions] = true; jvParams[jss::expand] = true; - auto const jtxn = env.rpc( - "json", - "ledger", - to_string( - jvParams))[jss::result][jss::ledger][jss::transactions]; + auto const jtxn = + env.rpc("json", "ledger", to_string(jvParams))[jss::result][jss::ledger][jss::transactions]; for (auto const& t : jtxn) - BEAST_EXPECT( - checkDeliveredAmount.checkTxn(t, t[jss::metaData])); + BEAST_EXPECT(checkDeliveredAmount.checkTxn(t, t[jss::metaData])); BEAST_EXPECT(checkDeliveredAmount.checkExpectedCounters()); } } @@ -322,14 +309,9 @@ class DeliveredAmount_test : public beast::unit_test::suite Account const bob("bob"); Env env{*this, features}; - MPTTester mptAlice( - env, alice, {.holders = {bob, carol}, .close = false}); + MPTTester mptAlice(env, alice, {.holders = {bob, carol}, .close = false}); - mptAlice.create( - {.transferFee = 25000, - .ownerCount = 1, - .holderCount = 0, - .flags = tfMPTCanTransfer}); + mptAlice.create({.transferFee = 25000, .ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer}); auto const MPT = mptAlice["MPT"]; mptAlice.authorize({.account = bob}); @@ -343,29 +325,21 @@ class DeliveredAmount_test : public beast::unit_test::suite env.close(); // Get the hash for the most recent transaction. - std::string txHash{ - env.tx()->getJson(JsonOptions::none)[jss::hash].asString()}; + std::string txHash{env.tx()->getJson(JsonOptions::none)[jss::hash].asString()}; Json::Value meta = env.rpc("tx", txHash)[jss::result][jss::meta]; if (features[fixMPTDeliveredAmount]) { - BEAST_EXPECT( - meta[sfDeliveredAmount.jsonName] == - STAmount{MPT(800)}.getJson(JsonOptions::none)); - BEAST_EXPECT( - meta[jss::delivered_amount] == - STAmount{MPT(800)}.getJson(JsonOptions::none)); + BEAST_EXPECT(meta[sfDeliveredAmount.jsonName] == STAmount{MPT(800)}.getJson(JsonOptions::none)); + BEAST_EXPECT(meta[jss::delivered_amount] == STAmount{MPT(800)}.getJson(JsonOptions::none)); } else { BEAST_EXPECT(!meta.isMember(sfDeliveredAmount.jsonName)); - BEAST_EXPECT( - meta[jss::delivered_amount] = Json::Value("unavailable")); + BEAST_EXPECT(meta[jss::delivered_amount] = Json::Value("unavailable")); } - env(pay(bob, carol, MPT(1000)), - sendmax(MPT(1200)), - txflags(tfPartialPayment)); + env(pay(bob, carol, MPT(1000)), sendmax(MPT(1200)), txflags(tfPartialPayment)); env.close(); txHash = env.tx()->getJson(JsonOptions::none)[jss::hash].asString(); @@ -373,18 +347,13 @@ class DeliveredAmount_test : public beast::unit_test::suite if (features[fixMPTDeliveredAmount]) { - BEAST_EXPECT( - meta[sfDeliveredAmount.jsonName] == - STAmount{MPT(960)}.getJson(JsonOptions::none)); - BEAST_EXPECT( - meta[jss::delivered_amount] == - STAmount{MPT(960)}.getJson(JsonOptions::none)); + BEAST_EXPECT(meta[sfDeliveredAmount.jsonName] == STAmount{MPT(960)}.getJson(JsonOptions::none)); + BEAST_EXPECT(meta[jss::delivered_amount] == STAmount{MPT(960)}.getJson(JsonOptions::none)); } else { BEAST_EXPECT(!meta.isMember(sfDeliveredAmount.jsonName)); - BEAST_EXPECT( - meta[jss::delivered_amount] = Json::Value("unavailable")); + BEAST_EXPECT(meta[jss::delivered_amount] = Json::Value("unavailable")); } } diff --git a/src/test/rpc/DepositAuthorized_test.cpp b/src/test/rpc/DepositAuthorized_test.cpp index 3e082a70a1..e8abfd58b8 100644 --- a/src/test/rpc/DepositAuthorized_test.cpp +++ b/src/test/rpc/DepositAuthorized_test.cpp @@ -58,47 +58,27 @@ public: // becky is authorized to deposit to herself. validateDepositAuthResult( - env.rpc( - "json", - "deposit_authorized", - depositAuthArgs(becky, becky, "validated").toStyledString()), - true); + env.rpc("json", "deposit_authorized", depositAuthArgs(becky, becky, "validated").toStyledString()), true); // alice should currently be authorized to deposit to becky. validateDepositAuthResult( - env.rpc( - "json", - "deposit_authorized", - depositAuthArgs(alice, becky, "validated").toStyledString()), - true); + env.rpc("json", "deposit_authorized", depositAuthArgs(alice, becky, "validated").toStyledString()), true); // becky sets the DepositAuth flag in the current ledger. env(fset(becky, asfDepositAuth)); // alice is no longer authorized to deposit to becky in current ledger. validateDepositAuthResult( - env.rpc( - "json", - "deposit_authorized", - depositAuthArgs(alice, becky).toStyledString()), - false); + env.rpc("json", "deposit_authorized", depositAuthArgs(alice, becky).toStyledString()), false); env.close(); // becky is still authorized to deposit to herself. validateDepositAuthResult( - env.rpc( - "json", - "deposit_authorized", - depositAuthArgs(becky, becky, "validated").toStyledString()), - true); + env.rpc("json", "deposit_authorized", depositAuthArgs(becky, becky, "validated").toStyledString()), true); // It's not a reciprocal arrangement. becky can deposit to alice. validateDepositAuthResult( - env.rpc( - "json", - "deposit_authorized", - depositAuthArgs(becky, alice, "current").toStyledString()), - true); + env.rpc("json", "deposit_authorized", depositAuthArgs(becky, alice, "current").toStyledString()), true); // becky creates a deposit authorization for alice. env(deposit::auth(becky, alice)); @@ -106,38 +86,22 @@ public: // alice is now authorized to deposit to becky. validateDepositAuthResult( - env.rpc( - "json", - "deposit_authorized", - depositAuthArgs(alice, becky, "closed").toStyledString()), - true); + env.rpc("json", "deposit_authorized", depositAuthArgs(alice, becky, "closed").toStyledString()), true); // carol is still not authorized to deposit to becky. validateDepositAuthResult( - env.rpc( - "json", - "deposit_authorized", - depositAuthArgs(carol, becky).toStyledString()), - false); + env.rpc("json", "deposit_authorized", depositAuthArgs(carol, becky).toStyledString()), false); // becky clears the DepositAuth flag so carol becomes authorized. env(fclear(becky, asfDepositAuth)); env.close(); validateDepositAuthResult( - env.rpc( - "json", - "deposit_authorized", - depositAuthArgs(carol, becky).toStyledString()), - true); + env.rpc("json", "deposit_authorized", depositAuthArgs(carol, becky).toStyledString()), true); // alice is still authorized to deposit to becky. validateDepositAuthResult( - env.rpc( - "json", - "deposit_authorized", - depositAuthArgs(alice, becky).toStyledString()), - true); + env.rpc("json", "deposit_authorized", depositAuthArgs(alice, becky).toStyledString()), true); } // Test malformed cases. @@ -150,10 +114,7 @@ public: Account const becky{"becky"}; // Lambda that checks the (error) result of deposit_authorized. - auto verifyErr = [this]( - Json::Value const& result, - char const* error, - char const* errorMsg) { + auto verifyErr = [this](Json::Value const& result, char const* error, char const* errorMsg) { BEAST_EXPECT(result[jss::result][jss::status] == jss::error); BEAST_EXPECT(result[jss::result][jss::error] == error); BEAST_EXPECT(result[jss::result][jss::error_message] == errorMsg); @@ -164,91 +125,67 @@ public: // Missing source_account field. Json::Value args{depositAuthArgs(alice, becky)}; args.removeMember(jss::source_account); - Json::Value const result{ - env.rpc("json", "deposit_authorized", args.toStyledString())}; - verifyErr( - result, "invalidParams", "Missing field 'source_account'."); + Json::Value const result{env.rpc("json", "deposit_authorized", args.toStyledString())}; + verifyErr(result, "invalidParams", "Missing field 'source_account'."); } { // Non-string source_account field. Json::Value args{depositAuthArgs(alice, becky)}; args[jss::source_account] = 7.3; - Json::Value const result{ - env.rpc("json", "deposit_authorized", args.toStyledString())}; - verifyErr( - result, - "invalidParams", - "Invalid field 'source_account', not a string."); + Json::Value const result{env.rpc("json", "deposit_authorized", args.toStyledString())}; + verifyErr(result, "invalidParams", "Invalid field 'source_account', not a string."); } { // Corrupt source_account field. Json::Value args{depositAuthArgs(alice, becky)}; args[jss::source_account] = "rG1QQv2nh2gr7RCZ!P8YYcBUKCCN633jCn"; - Json::Value const result{ - env.rpc("json", "deposit_authorized", args.toStyledString())}; + Json::Value const result{env.rpc("json", "deposit_authorized", args.toStyledString())}; verifyErr(result, "actMalformed", "Account malformed."); } { // Missing destination_account field. Json::Value args{depositAuthArgs(alice, becky)}; args.removeMember(jss::destination_account); - Json::Value const result{ - env.rpc("json", "deposit_authorized", args.toStyledString())}; - verifyErr( - result, - "invalidParams", - "Missing field 'destination_account'."); + Json::Value const result{env.rpc("json", "deposit_authorized", args.toStyledString())}; + verifyErr(result, "invalidParams", "Missing field 'destination_account'."); } { // Non-string destination_account field. Json::Value args{depositAuthArgs(alice, becky)}; args[jss::destination_account] = 7.3; - Json::Value const result{ - env.rpc("json", "deposit_authorized", args.toStyledString())}; - verifyErr( - result, - "invalidParams", - "Invalid field 'destination_account', not a string."); + Json::Value const result{env.rpc("json", "deposit_authorized", args.toStyledString())}; + verifyErr(result, "invalidParams", "Invalid field 'destination_account', not a string."); } { // Corrupt destination_account field. Json::Value args{depositAuthArgs(alice, becky)}; - args[jss::destination_account] = - "rP6P9ypfAmc!pw8SZHNwM4nvZHFXDraQas"; - Json::Value const result{ - env.rpc("json", "deposit_authorized", args.toStyledString())}; + args[jss::destination_account] = "rP6P9ypfAmc!pw8SZHNwM4nvZHFXDraQas"; + Json::Value const result{env.rpc("json", "deposit_authorized", args.toStyledString())}; verifyErr(result, "actMalformed", "Account malformed."); } { // Request an invalid ledger. Json::Value args{depositAuthArgs(alice, becky, "-1")}; - Json::Value const result{ - env.rpc("json", "deposit_authorized", args.toStyledString())}; - verifyErr( - result, - "invalidParams", - "Invalid field 'ledger_index', not string or number."); + Json::Value const result{env.rpc("json", "deposit_authorized", args.toStyledString())}; + verifyErr(result, "invalidParams", "Invalid field 'ledger_index', not string or number."); } { // Request a ledger that doesn't exist yet as a string. Json::Value args{depositAuthArgs(alice, becky, "17")}; - Json::Value const result{ - env.rpc("json", "deposit_authorized", args.toStyledString())}; + Json::Value const result{env.rpc("json", "deposit_authorized", args.toStyledString())}; verifyErr(result, "lgrNotFound", "ledgerNotFound"); } { // Request a ledger that doesn't exist yet. Json::Value args{depositAuthArgs(alice, becky)}; args[jss::ledger_index] = 17; - Json::Value const result{ - env.rpc("json", "deposit_authorized", args.toStyledString())}; + Json::Value const result{env.rpc("json", "deposit_authorized", args.toStyledString())}; verifyErr(result, "lgrNotFound", "ledgerNotFound"); } { // alice is not yet funded. Json::Value args{depositAuthArgs(alice, becky)}; - Json::Value const result{ - env.rpc("json", "deposit_authorized", args.toStyledString())}; + Json::Value const result{env.rpc("json", "deposit_authorized", args.toStyledString())}; verifyErr(result, "srcActNotFound", "Source account not found."); } env.fund(XRP(1000), alice); @@ -256,18 +193,15 @@ public: { // becky is not yet funded. Json::Value args{depositAuthArgs(alice, becky)}; - Json::Value const result{ - env.rpc("json", "deposit_authorized", args.toStyledString())}; - verifyErr( - result, "dstActNotFound", "Destination account not found."); + Json::Value const result{env.rpc("json", "deposit_authorized", args.toStyledString())}; + verifyErr(result, "dstActNotFound", "Destination account not found."); } env.fund(XRP(1000), becky); env.close(); { // Once becky is funded try it again and see it succeed. Json::Value args{depositAuthArgs(alice, becky)}; - Json::Value const result{ - env.rpc("json", "deposit_authorized", args.toStyledString())}; + Json::Value const result{env.rpc("json", "deposit_authorized", args.toStyledString())}; validateDepositAuthResult(result, true); } } @@ -281,14 +215,11 @@ public: std::vector credentialIDs = {}, std::string_view error = "") { - BEAST_EXPECT( - result[jss::status] == authorized ? jss::success : jss::error); + BEAST_EXPECT(result[jss::status] == authorized ? jss::success : jss::error); if (result.isMember(jss::deposit_authorized)) BEAST_EXPECT(result[jss::deposit_authorized] == authorized); if (authorized) - BEAST_EXPECT( - result.isMember(jss::deposit_authorized) && - (result[jss::deposit_authorized] == true)); + BEAST_EXPECT(result.isMember(jss::deposit_authorized) && (result[jss::deposit_authorized] == true)); BEAST_EXPECT(result.isMember(jss::error) == !error.empty()); if (!error.empty()) @@ -350,16 +281,13 @@ public: env.close(); { - testcase( - "deposit_authorized with credentials failure: empty array."); + testcase("deposit_authorized with credentials failure: empty array."); auto args = depositAuthArgs(alice, becky, "validated"); args[jss::credentials] = Json::arrayValue; - auto const jv = - env.rpc("json", "deposit_authorized", args.toStyledString()); - checkCredentialsResponse( - jv[jss::result], alice, becky, false, {}, "invalidParams"); + auto const jv = env.rpc("json", "deposit_authorized", args.toStyledString()); + checkCredentialsResponse(jv[jss::result], alice, becky, false, {}, "invalidParams"); } { @@ -372,10 +300,8 @@ public: args[jss::credentials].append(1); args[jss::credentials].append(3); - auto const jv = - env.rpc("json", "deposit_authorized", args.toStyledString()); - checkCredentialsResponse( - jv[jss::result], alice, becky, false, {}, "invalidParams"); + auto const jv = env.rpc("json", "deposit_authorized", args.toStyledString()); + checkCredentialsResponse(jv[jss::result], alice, becky, false, {}, "invalidParams"); } { @@ -387,15 +313,8 @@ public: args[jss::credentials] = Json::arrayValue; args[jss::credentials].append("hello world"); - auto const jv = - env.rpc("json", "deposit_authorized", args.toStyledString()); - checkCredentialsResponse( - jv[jss::result], - alice, - becky, - false, - {"hello world"}, - "invalidParams"); + auto const jv = env.rpc("json", "deposit_authorized", args.toStyledString()); + checkCredentialsResponse(jv[jss::result], alice, becky, false, {"hello world"}, "invalidParams"); } { @@ -410,8 +329,7 @@ public: {"0127AB8B4B29CCDBB61AA51C0799A8A6BB80B86A9899807C11ED576AF8516" "473"}); - auto const jv = - env.rpc("json", "deposit_authorized", args.toStyledString()); + auto const jv = env.rpc("json", "deposit_authorized", args.toStyledString()); checkCredentialsResponse( jv[jss::result], alice, @@ -427,17 +345,8 @@ public: "deposit_authorized with credentials not authorized: " "credential not accepted"); auto const jv = env.rpc( - "json", - "deposit_authorized", - depositAuthArgs(alice, becky, "validated", {credIdx}) - .toStyledString()); - checkCredentialsResponse( - jv[jss::result], - alice, - becky, - false, - {credIdx}, - "badCredentials"); + "json", "deposit_authorized", depositAuthArgs(alice, becky, "validated", {credIdx}).toStyledString()); + checkCredentialsResponse(jv[jss::result], alice, becky, false, {credIdx}, "badCredentials"); } // alice accept credentials @@ -449,15 +358,8 @@ public: auto const jv = env.rpc( "json", "deposit_authorized", - depositAuthArgs(alice, becky, "validated", {credIdx, credIdx}) - .toStyledString()); - checkCredentialsResponse( - jv[jss::result], - alice, - becky, - false, - {credIdx, credIdx}, - "badCredentials"); + depositAuthArgs(alice, becky, "validated", {credIdx, credIdx}).toStyledString()); + checkCredentialsResponse(jv[jss::result], alice, becky, false, {credIdx, credIdx}, "badCredentials"); } { @@ -484,23 +386,15 @@ public: testcase("deposit_authorized too long credentials"); auto const jv = env.rpc( - "json", - "deposit_authorized", - depositAuthArgs(alice, becky, "validated", credIds) - .toStyledString()); - checkCredentialsResponse( - jv[jss::result], alice, becky, false, credIds, "invalidParams"); + "json", "deposit_authorized", depositAuthArgs(alice, becky, "validated", credIds).toStyledString()); + checkCredentialsResponse(jv[jss::result], alice, becky, false, credIds, "invalidParams"); } { testcase("deposit_authorized with credentials"); auto const jv = env.rpc( - "json", - "deposit_authorized", - depositAuthArgs(alice, becky, "validated", {credIdx}) - .toStyledString()); - checkCredentialsResponse( - jv[jss::result], alice, becky, true, {credIdx}); + "json", "deposit_authorized", depositAuthArgs(alice, becky, "validated", {credIdx}).toStyledString()); + checkCredentialsResponse(jv[jss::result], alice, becky, true, {credIdx}); } { @@ -512,17 +406,12 @@ public: // retrieve the index of the credentials auto jv = credentials::ledgerEntry(env, becky, diana, credType); - std::string const credBecky = - jv[jss::result][jss::index].asString(); + std::string const credBecky = jv[jss::result][jss::index].asString(); testcase("deposit_authorized account without preauth"); jv = env.rpc( - "json", - "deposit_authorized", - depositAuthArgs(becky, alice, "validated", {credBecky}) - .toStyledString()); - checkCredentialsResponse( - jv[jss::result], becky, alice, true, {credBecky}); + "json", "deposit_authorized", depositAuthArgs(becky, alice, "validated", {credBecky}).toStyledString()); + checkCredentialsResponse(jv[jss::result], becky, alice, true, {credBecky}); } { @@ -533,22 +422,12 @@ public: env.close(); // retrieve the index of the credentials auto jv = credentials::ledgerEntry(env, alice, carol, credType); - std::string const credDiana = - jv[jss::result][jss::index].asString(); + std::string const credDiana = jv[jss::result][jss::index].asString(); // alice try to use credential for different account jv = env.rpc( - "json", - "deposit_authorized", - depositAuthArgs(becky, alice, "validated", {credDiana}) - .toStyledString()); - checkCredentialsResponse( - jv[jss::result], - becky, - alice, - false, - {credDiana}, - "badCredentials"); + "json", "deposit_authorized", depositAuthArgs(becky, alice, "validated", {credDiana}).toStyledString()); + checkCredentialsResponse(jv[jss::result], becky, alice, false, {credDiana}, "badCredentials"); } { @@ -556,11 +435,7 @@ public: // check expired credentials char const credType2[] = "random"; - std::uint32_t const x = env.current() - ->header() - .parentCloseTime.time_since_epoch() - .count() + - 40; + std::uint32_t const x = env.current()->header().parentCloseTime.time_since_epoch().count() + 40; // create credentials with expire time 40s auto jv = credentials::create(alice, carol, credType2); @@ -585,10 +460,8 @@ public: jv = env.rpc( "json", "deposit_authorized", - depositAuthArgs(alice, becky, "validated", {credIdx2}) - .toStyledString()); - checkCredentialsResponse( - jv[jss::result], alice, becky, true, {credIdx2}); + depositAuthArgs(alice, becky, "validated", {credIdx2}).toStyledString()); + checkCredentialsResponse(jv[jss::result], alice, becky, true, {credIdx2}); } // increase timer by 20s @@ -599,16 +472,9 @@ public: jv = env.rpc( "json", "deposit_authorized", - depositAuthArgs(alice, becky, "validated", {credIdx2}) - .toStyledString()); + depositAuthArgs(alice, becky, "validated", {credIdx2}).toStyledString()); - checkCredentialsResponse( - jv[jss::result], - alice, - becky, - false, - {credIdx2}, - "badCredentials"); + checkCredentialsResponse(jv[jss::result], alice, becky, false, {credIdx2}, "badCredentials"); } } } diff --git a/src/test/rpc/Feature_test.cpp b/src/test/rpc/Feature_test.cpp index 6b66da072e..21596634e3 100644 --- a/src/test/rpc/Feature_test.cpp +++ b/src/test/rpc/Feature_test.cpp @@ -19,8 +19,7 @@ class Feature_test : public beast::unit_test::suite BEAST_EXPECT( supportedAmendments.size() == - xrpl::detail::numDownVotedAmendments() + - xrpl::detail::numUpVotedAmendments()); + xrpl::detail::numDownVotedAmendments() + xrpl::detail::numUpVotedAmendments()); { std::size_t up = 0, down = 0, obsolete = 0; for (auto const& [name, vote] : supportedAmendments) @@ -42,19 +41,14 @@ class Feature_test : public beast::unit_test::suite if (vote == VoteBehavior::Obsolete) { - BEAST_EXPECT( - allAmendments.contains(name) && - allAmendments.at(name) == AmendmentSupport::Retired); + BEAST_EXPECT(allAmendments.contains(name) && allAmendments.at(name) == AmendmentSupport::Retired); } else { - BEAST_EXPECT( - allAmendments.contains(name) && - allAmendments.at(name) == AmendmentSupport::Supported); + BEAST_EXPECT(allAmendments.contains(name) && allAmendments.at(name) == AmendmentSupport::Supported); } } - BEAST_EXPECT( - down + obsolete == xrpl::detail::numDownVotedAmendments()); + BEAST_EXPECT(down + obsolete == xrpl::detail::numDownVotedAmendments()); BEAST_EXPECT(up == xrpl::detail::numUpVotedAmendments()); } { @@ -79,9 +73,7 @@ class Feature_test : public beast::unit_test::suite } BEAST_EXPECT(supported + retired == supportedAmendments.size()); - BEAST_EXPECT( - allAmendments.size() - unsupported == - supportedAmendments.size()); + BEAST_EXPECT(allAmendments.size() - unsupported == supportedAmendments.size()); } } @@ -102,31 +94,24 @@ class Feature_test : public beast::unit_test::suite if (BEAST_EXPECT(registered)) { BEAST_EXPECT(featureToName(*registered) == feature); - BEAST_EXPECT( - bitsetIndexToFeature(featureToBitsetIndex(*registered)) == - *registered); + BEAST_EXPECT(bitsetIndexToFeature(featureToBitsetIndex(*registered)) == *registered); } } // Test an arbitrary unknown feature uint256 zero{0}; BEAST_EXPECT(featureToName(zero) == to_string(zero)); - BEAST_EXPECT( - featureToName(zero) == - "0000000000000000000000000000000000000000000000000000000000000000"); + BEAST_EXPECT(featureToName(zero) == "0000000000000000000000000000000000000000000000000000000000000000"); // Test looking up an unknown feature BEAST_EXPECT(!getRegisteredFeature("unknown")); // Test a random sampling of the variables. If any of these get retired // or removed, swap out for any other feature. - BEAST_EXPECT( - featureToName(fixRemoveNFTokenAutoTrustLine) == - "fixRemoveNFTokenAutoTrustLine"); + BEAST_EXPECT(featureToName(fixRemoveNFTokenAutoTrustLine) == "fixRemoveNFTokenAutoTrustLine"); BEAST_EXPECT(featureToName(featureBatch) == "Batch"); BEAST_EXPECT(featureToName(featureDID) == "DID"); - BEAST_EXPECT( - featureToName(fixIncludeKeyletFields) == "fixIncludeKeyletFields"); + BEAST_EXPECT(featureToName(fixIncludeKeyletFields) == "fixIncludeKeyletFields"); BEAST_EXPECT(featureToName(featureTokenEscrow) == "TokenEscrow"); } @@ -138,8 +123,7 @@ class Feature_test : public beast::unit_test::suite using namespace test::jtx; Env env{*this}; - std::map const& votes = - xrpl::detail::supportedAmendments(); + std::map const& votes = xrpl::detail::supportedAmendments(); auto jrr = env.rpc("feature")[jss::result]; if (!BEAST_EXPECT(jrr.isMember(jss::features))) @@ -150,27 +134,18 @@ class Feature_test : public beast::unit_test::suite return; // default config - so all should be disabled, and // supported. Some may be vetoed. - bool expectVeto = - (votes.at(feature[jss::name].asString()) == - VoteBehavior::DefaultNo); - bool expectObsolete = - (votes.at(feature[jss::name].asString()) == - VoteBehavior::Obsolete); + bool expectVeto = (votes.at(feature[jss::name].asString()) == VoteBehavior::DefaultNo); + bool expectObsolete = (votes.at(feature[jss::name].asString()) == VoteBehavior::Obsolete); BEAST_EXPECTS( - feature.isMember(jss::enabled) && - !feature[jss::enabled].asBool(), + feature.isMember(jss::enabled) && !feature[jss::enabled].asBool(), feature[jss::name].asString() + " enabled"); BEAST_EXPECTS( - feature.isMember(jss::vetoed) && - feature[jss::vetoed].isBool() == !expectObsolete && - (!feature[jss::vetoed].isBool() || - feature[jss::vetoed].asBool() == expectVeto) && - (feature[jss::vetoed].isBool() || - feature[jss::vetoed].asString() == "Obsolete"), + feature.isMember(jss::vetoed) && feature[jss::vetoed].isBool() == !expectObsolete && + (!feature[jss::vetoed].isBool() || feature[jss::vetoed].asBool() == expectVeto) && + (feature[jss::vetoed].isBool() || feature[jss::vetoed].asString() == "Obsolete"), feature[jss::name].asString() + " vetoed"); BEAST_EXPECTS( - feature.isMember(jss::supported) && - feature[jss::supported].asBool(), + feature.isMember(jss::supported) && feature[jss::supported].asBool(), feature[jss::name].asString() + " supported"); } } @@ -194,9 +169,7 @@ class Feature_test : public beast::unit_test::suite BEAST_EXPECTS(feature[jss::name] == "fixAMMOverflowOffer", "name"); BEAST_EXPECTS(!feature[jss::enabled].asBool(), "enabled"); - BEAST_EXPECTS( - feature[jss::vetoed].isBool() && !feature[jss::vetoed].asBool(), - "vetoed"); + BEAST_EXPECTS(feature[jss::vetoed].isBool() && !feature[jss::vetoed].asBool(), "vetoed"); BEAST_EXPECTS(feature[jss::supported].asBool(), "supported"); // feature names are case-sensitive - expect error here @@ -216,8 +189,7 @@ class Feature_test : public beast::unit_test::suite auto testInvalidParam = [&](auto const& param) { Json::Value params; params[jss::feature] = param; - auto jrr = - env.rpc("json", "feature", to_string(params))[jss::result]; + auto jrr = env.rpc("json", "feature", to_string(params))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); BEAST_EXPECT(jrr[jss::error_message] == "Invalid parameters."); }; @@ -232,8 +204,7 @@ class Feature_test : public beast::unit_test::suite { auto jrr = env.rpc("feature", "AllTheThings")[jss::result]; BEAST_EXPECT(jrr[jss::error] == "badFeature"); - BEAST_EXPECT( - jrr[jss::error_message] == "Feature unknown or invalid."); + BEAST_EXPECT(jrr[jss::error_message] == "Feature unknown or invalid."); } } @@ -256,25 +227,19 @@ class Feature_test : public beast::unit_test::suite // comparison to avoid maintenance as more amendments are added in // the future. BEAST_EXPECT(result[jss::features].size() >= 50); - for (auto it = result[jss::features].begin(); - it != result[jss::features].end(); - ++it) + for (auto it = result[jss::features].begin(); it != result[jss::features].end(); ++it) { uint256 id; (void)id.parseHex(it.key().asString().c_str()); if (!BEAST_EXPECT((*it).isMember(jss::name))) return; - bool expectEnabled = - env.app().getAmendmentTable().isEnabled(id); - bool expectSupported = - env.app().getAmendmentTable().isSupported(id); + bool expectEnabled = env.app().getAmendmentTable().isEnabled(id); + bool expectSupported = env.app().getAmendmentTable().isSupported(id); BEAST_EXPECTS( - (*it).isMember(jss::enabled) && - (*it)[jss::enabled].asBool() == expectEnabled, + (*it).isMember(jss::enabled) && (*it)[jss::enabled].asBool() == expectEnabled, (*it)[jss::name].asString() + " enabled"); BEAST_EXPECTS( - (*it).isMember(jss::supported) && - (*it)[jss::supported].asBool() == expectSupported, + (*it).isMember(jss::supported) && (*it)[jss::supported].asBool() == expectSupported, (*it)[jss::name].asString() + " supported"); BEAST_EXPECT(!(*it).isMember(jss::vetoed)); BEAST_EXPECT(!(*it).isMember(jss::majority)); @@ -290,12 +255,9 @@ class Feature_test : public beast::unit_test::suite params[jss::feature] = "1234567890ABCDEF1234567890ABCDEF1234567890ABCDEF1234567890ABCD" "EF"; - auto const result = - env.rpc("json", "feature", to_string(params))[jss::result]; - BEAST_EXPECTS( - result[jss::error] == "badFeature", result.toStyledString()); - BEAST_EXPECT( - result[jss::error_message] == "Feature unknown or invalid."); + auto const result = env.rpc("json", "feature", to_string(params))[jss::result]; + BEAST_EXPECTS(result[jss::error] == "badFeature", result.toStyledString()); + BEAST_EXPECT(result[jss::error_message] == "Feature unknown or invalid."); } { @@ -305,14 +267,9 @@ class Feature_test : public beast::unit_test::suite "A7"; // invalid param params[jss::vetoed] = true; - auto const result = - env.rpc("json", "feature", to_string(params))[jss::result]; - BEAST_EXPECTS( - result[jss::error] == "noPermission", - result[jss::error].asString()); - BEAST_EXPECT( - result[jss::error_message] == - "You don't have permission for this command."); + auto const result = env.rpc("json", "feature", to_string(params))[jss::result]; + BEAST_EXPECTS(result[jss::error] == "noPermission", result[jss::error].asString()); + BEAST_EXPECT(result[jss::error_message] == "You don't have permission for this command."); } } @@ -324,49 +281,34 @@ class Feature_test : public beast::unit_test::suite using namespace test::jtx; Env env{*this, FeatureBitset{}}; - std::map const& votes = - xrpl::detail::supportedAmendments(); + std::map const& votes = xrpl::detail::supportedAmendments(); auto jrr = env.rpc("feature")[jss::result]; if (!BEAST_EXPECT(jrr.isMember(jss::features))) return; - for (auto it = jrr[jss::features].begin(); - it != jrr[jss::features].end(); - ++it) + for (auto it = jrr[jss::features].begin(); it != jrr[jss::features].end(); ++it) { uint256 id; (void)id.parseHex(it.key().asString().c_str()); if (!BEAST_EXPECT((*it).isMember(jss::name))) return; bool expectEnabled = env.app().getAmendmentTable().isEnabled(id); - bool expectSupported = - env.app().getAmendmentTable().isSupported(id); - bool expectVeto = - (votes.at((*it)[jss::name].asString()) == - VoteBehavior::DefaultNo); - bool expectObsolete = - (votes.at((*it)[jss::name].asString()) == - VoteBehavior::Obsolete); + bool expectSupported = env.app().getAmendmentTable().isSupported(id); + bool expectVeto = (votes.at((*it)[jss::name].asString()) == VoteBehavior::DefaultNo); + bool expectObsolete = (votes.at((*it)[jss::name].asString()) == VoteBehavior::Obsolete); BEAST_EXPECTS( - (*it).isMember(jss::enabled) && - (*it)[jss::enabled].asBool() == expectEnabled, + (*it).isMember(jss::enabled) && (*it)[jss::enabled].asBool() == expectEnabled, (*it)[jss::name].asString() + " enabled"); if (expectEnabled) - BEAST_EXPECTS( - !(*it).isMember(jss::vetoed), - (*it)[jss::name].asString() + " vetoed"); + BEAST_EXPECTS(!(*it).isMember(jss::vetoed), (*it)[jss::name].asString() + " vetoed"); else BEAST_EXPECTS( - (*it).isMember(jss::vetoed) && - (*it)[jss::vetoed].isBool() == !expectObsolete && - (!(*it)[jss::vetoed].isBool() || - (*it)[jss::vetoed].asBool() == expectVeto) && - ((*it)[jss::vetoed].isBool() || - (*it)[jss::vetoed].asString() == "Obsolete"), + (*it).isMember(jss::vetoed) && (*it)[jss::vetoed].isBool() == !expectObsolete && + (!(*it)[jss::vetoed].isBool() || (*it)[jss::vetoed].asBool() == expectVeto) && + ((*it)[jss::vetoed].isBool() || (*it)[jss::vetoed].asString() == "Obsolete"), (*it)[jss::name].asString() + " vetoed"); BEAST_EXPECTS( - (*it).isMember(jss::supported) && - (*it)[jss::supported].asBool() == expectSupported, + (*it).isMember(jss::supported) && (*it)[jss::supported].asBool() == expectSupported, (*it)[jss::name].asString() + " supported"); } } @@ -389,21 +331,11 @@ class Feature_test : public beast::unit_test::suite { if (!BEAST_EXPECT(feature.isMember(jss::name))) return; - BEAST_EXPECTS( - !feature.isMember(jss::majority), - feature[jss::name].asString() + " majority"); - BEAST_EXPECTS( - !feature.isMember(jss::count), - feature[jss::name].asString() + " count"); - BEAST_EXPECTS( - !feature.isMember(jss::threshold), - feature[jss::name].asString() + " threshold"); - BEAST_EXPECTS( - !feature.isMember(jss::validations), - feature[jss::name].asString() + " validations"); - BEAST_EXPECTS( - !feature.isMember(jss::vote), - feature[jss::name].asString() + " vote"); + BEAST_EXPECTS(!feature.isMember(jss::majority), feature[jss::name].asString() + " majority"); + BEAST_EXPECTS(!feature.isMember(jss::count), feature[jss::name].asString() + " count"); + BEAST_EXPECTS(!feature.isMember(jss::threshold), feature[jss::name].asString() + " threshold"); + BEAST_EXPECTS(!feature.isMember(jss::validations), feature[jss::name].asString() + " validations"); + BEAST_EXPECTS(!feature.isMember(jss::vote), feature[jss::name].asString() + " vote"); } auto majorities = getMajorityAmendments(*env.closed()); @@ -422,8 +354,7 @@ class Feature_test : public beast::unit_test::suite // There should be at least 2 amendments. Don't do exact comparison // to avoid maintenance as more amendments are added in the future. BEAST_EXPECT(majorities.size() >= 2); - std::map const& votes = - xrpl::detail::supportedAmendments(); + std::map const& votes = xrpl::detail::supportedAmendments(); jrr = env.rpc("feature")[jss::result]; if (!BEAST_EXPECT(jrr.isMember(jss::features))) @@ -432,36 +363,20 @@ class Feature_test : public beast::unit_test::suite { if (!BEAST_EXPECT(feature.isMember(jss::name))) return; - bool expectVeto = - (votes.at(feature[jss::name].asString()) == - VoteBehavior::DefaultNo); - bool expectObsolete = - (votes.at(feature[jss::name].asString()) == - VoteBehavior::Obsolete); + bool expectVeto = (votes.at(feature[jss::name].asString()) == VoteBehavior::DefaultNo); + bool expectObsolete = (votes.at(feature[jss::name].asString()) == VoteBehavior::Obsolete); BEAST_EXPECTS( - (expectVeto || expectObsolete) ^ - feature.isMember(jss::majority), + (expectVeto || expectObsolete) ^ feature.isMember(jss::majority), feature[jss::name].asString() + " majority"); BEAST_EXPECTS( - feature.isMember(jss::vetoed) && - feature[jss::vetoed].isBool() == !expectObsolete && - (!feature[jss::vetoed].isBool() || - feature[jss::vetoed].asBool() == expectVeto) && - (feature[jss::vetoed].isBool() || - feature[jss::vetoed].asString() == "Obsolete"), + feature.isMember(jss::vetoed) && feature[jss::vetoed].isBool() == !expectObsolete && + (!feature[jss::vetoed].isBool() || feature[jss::vetoed].asBool() == expectVeto) && + (feature[jss::vetoed].isBool() || feature[jss::vetoed].asString() == "Obsolete"), feature[jss::name].asString() + " vetoed"); - BEAST_EXPECTS( - feature.isMember(jss::count), - feature[jss::name].asString() + " count"); - BEAST_EXPECTS( - feature.isMember(jss::threshold), - feature[jss::name].asString() + " threshold"); - BEAST_EXPECTS( - feature.isMember(jss::validations), - feature[jss::name].asString() + " validations"); - BEAST_EXPECT( - feature[jss::count] == - ((expectVeto || expectObsolete) ? 0 : 1)); + BEAST_EXPECTS(feature.isMember(jss::count), feature[jss::name].asString() + " count"); + BEAST_EXPECTS(feature.isMember(jss::threshold), feature[jss::name].asString() + " threshold"); + BEAST_EXPECTS(feature.isMember(jss::validations), feature[jss::name].asString() + " validations"); + BEAST_EXPECT(feature[jss::count] == ((expectVeto || expectObsolete) ? 0 : 1)); BEAST_EXPECT(feature[jss::threshold] == 1); BEAST_EXPECT(feature[jss::validations] == 1); BEAST_EXPECTS( @@ -487,9 +402,7 @@ class Feature_test : public beast::unit_test::suite return; auto feature = *(jrr.begin()); BEAST_EXPECTS(feature[jss::name] == featureName, "name"); - BEAST_EXPECTS( - feature[jss::vetoed].isBool() && !feature[jss::vetoed].asBool(), - "vetoed"); + BEAST_EXPECTS(feature[jss::vetoed].isBool() && !feature[jss::vetoed].asBool(), "vetoed"); jrr = env.rpc("feature", featureName, "reject")[jss::result]; if (!BEAST_EXPECTS(jrr[jss::status] == jss::success, "status")) @@ -499,9 +412,7 @@ class Feature_test : public beast::unit_test::suite return; feature = *(jrr.begin()); BEAST_EXPECTS(feature[jss::name] == featureName, "name"); - BEAST_EXPECTS( - feature[jss::vetoed].isBool() && feature[jss::vetoed].asBool(), - "vetoed"); + BEAST_EXPECTS(feature[jss::vetoed].isBool() && feature[jss::vetoed].asBool(), "vetoed"); jrr = env.rpc("feature", featureName, "accept")[jss::result]; if (!BEAST_EXPECTS(jrr[jss::status] == jss::success, "status")) @@ -511,9 +422,7 @@ class Feature_test : public beast::unit_test::suite return; feature = *(jrr.begin()); BEAST_EXPECTS(feature[jss::name] == featureName, "name"); - BEAST_EXPECTS( - feature[jss::vetoed].isBool() && !feature[jss::vetoed].asBool(), - "vetoed"); + BEAST_EXPECTS(feature[jss::vetoed].isBool() && !feature[jss::vetoed].asBool(), "vetoed"); // anything other than accept or reject is an error jrr = env.rpc("feature", featureName, "maybe"); @@ -530,10 +439,8 @@ class Feature_test : public beast::unit_test::suite Env env{*this}; auto const& supportedAmendments = detail::supportedAmendments(); - auto obsoleteFeature = std::find_if( - std::begin(supportedAmendments), - std::end(supportedAmendments), - [](auto const& pair) { + auto obsoleteFeature = + std::find_if(std::begin(supportedAmendments), std::end(supportedAmendments), [](auto const& pair) { return pair.second == VoteBehavior::Obsolete; }); @@ -553,10 +460,7 @@ class Feature_test : public beast::unit_test::suite return; auto feature = *(jrr.begin()); BEAST_EXPECTS(feature[jss::name] == featureName, "name"); - BEAST_EXPECTS( - feature[jss::vetoed].isString() && - feature[jss::vetoed].asString() == "Obsolete", - "vetoed"); + BEAST_EXPECTS(feature[jss::vetoed].isString() && feature[jss::vetoed].asString() == "Obsolete", "vetoed"); jrr = env.rpc("feature", featureName, "reject")[jss::result]; if (!BEAST_EXPECTS(jrr[jss::status] == jss::success, "status")) @@ -566,10 +470,7 @@ class Feature_test : public beast::unit_test::suite return; feature = *(jrr.begin()); BEAST_EXPECTS(feature[jss::name] == featureName, "name"); - BEAST_EXPECTS( - feature[jss::vetoed].isString() && - feature[jss::vetoed].asString() == "Obsolete", - "vetoed"); + BEAST_EXPECTS(feature[jss::vetoed].isString() && feature[jss::vetoed].asString() == "Obsolete", "vetoed"); jrr = env.rpc("feature", featureName, "accept")[jss::result]; if (!BEAST_EXPECTS(jrr[jss::status] == jss::success, "status")) @@ -579,10 +480,7 @@ class Feature_test : public beast::unit_test::suite return; feature = *(jrr.begin()); BEAST_EXPECTS(feature[jss::name] == featureName, "name"); - BEAST_EXPECTS( - feature[jss::vetoed].isString() && - feature[jss::vetoed].asString() == "Obsolete", - "vetoed"); + BEAST_EXPECTS(feature[jss::vetoed].isString() && feature[jss::vetoed].asString() == "Obsolete", "vetoed"); // anything other than accept or reject is an error jrr = env.rpc("feature", featureName, "maybe"); diff --git a/src/test/rpc/GRPCTestClientBase.h b/src/test/rpc/GRPCTestClientBase.h index 6cb806a562..3c39cd1747 100644 --- a/src/test/rpc/GRPCTestClientBase.h +++ b/src/test/rpc/GRPCTestClientBase.h @@ -1,5 +1,4 @@ -#ifndef XRPL_GRPCTESTCLIENTBASE_H -#define XRPL_GRPCTESTCLIENTBASE_H +#pragma once #include @@ -13,13 +12,9 @@ namespace test { struct GRPCTestClientBase { explicit GRPCTestClientBase(std::string const& port) - : stub_(org::xrpl::rpc::v1::XRPLedgerAPIService::NewStub( - grpc::CreateChannel( - beast::IP::Endpoint( - boost::asio::ip::make_address(getEnvLocalhostAddr()), - std::stoi(port)) - .to_string(), - grpc::InsecureChannelCredentials()))) + : stub_(org::xrpl::rpc::v1::XRPLedgerAPIService::NewStub(grpc::CreateChannel( + beast::IP::Endpoint(boost::asio::ip::make_address(getEnvLocalhostAddr()), std::stoi(port)).to_string(), + grpc::InsecureChannelCredentials()))) { } @@ -30,4 +25,3 @@ struct GRPCTestClientBase } // namespace test } // namespace xrpl -#endif // XRPL_GRPCTESTCLIENTBASE_H diff --git a/src/test/rpc/GatewayBalances_test.cpp b/src/test/rpc/GatewayBalances_test.cpp index 40f56dfc81..6415f6a51f 100644 --- a/src/test/rpc/GatewayBalances_test.cpp +++ b/src/test/rpc/GatewayBalances_test.cpp @@ -77,8 +77,7 @@ public: if (wsc->version() == 2) { expect(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - expect( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + expect(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); expect(jv.isMember(jss::id) && jv[jss::id] == 5); } @@ -98,9 +97,7 @@ public: auto c2 = hwBalance[1u][jss::currency]; expect(c1 == "USD" || c2 == "USD"); expect(c1 == "JPY" || c2 == "JPY"); - expect( - hwBalance[0u][jss::value] == "5000" && - hwBalance[1u][jss::value] == "5000"); + expect(hwBalance[0u][jss::value] == "5000" && hwBalance[1u][jss::value] == "5000"); } { @@ -165,8 +162,7 @@ public: expect(jv[jss::status] == "error"); auto response = jv[jss::result]; - auto const error = - apiVersion < 2u ? "invalidHotWallet" : "invalidParams"; + auto const error = apiVersion < 2u ? "invalidHotWallet" : "invalidParams"; BEAST_EXPECT(response[jss::error] == error); }); } @@ -185,8 +181,7 @@ public: auto USD = alice["USD"]; // The largest valid STAmount of USD: - STAmount const maxUSD( - USD.issue(), STAmount::cMaxValue, STAmount::cMaxOffset); + STAmount const maxUSD(USD.issue(), STAmount::cMaxValue, STAmount::cMaxOffset); // Create a hotwallet Account const hw{"hw"}; diff --git a/src/test/rpc/GetAggregatePrice_test.cpp b/src/test/rpc/GetAggregatePrice_test.cpp index 0ffefc6cb6..e6cfb3a229 100644 --- a/src/test/rpc/GetAggregatePrice_test.cpp +++ b/src/test/rpc/GetAggregatePrice_test.cpp @@ -26,17 +26,12 @@ public: Env env(*this); auto const baseFee = env.current()->fees().base; // missing base_asset - auto ret = - Oracle::aggregatePrice(env, std::nullopt, "USD", oracles); - BEAST_EXPECT( - ret[jss::error_message].asString() == - "Missing field 'base_asset'."); + auto ret = Oracle::aggregatePrice(env, std::nullopt, "USD", oracles); + BEAST_EXPECT(ret[jss::error_message].asString() == "Missing field 'base_asset'."); // missing quote_asset ret = Oracle::aggregatePrice(env, "XRP", std::nullopt, oracles); - BEAST_EXPECT( - ret[jss::error_message].asString() == - "Missing field 'quote_asset'."); + BEAST_EXPECT(ret[jss::error_message].asString() == "Missing field 'quote_asset'."); // invalid base_asset, quote_asset std::vector invalidAsset = { @@ -66,9 +61,7 @@ public: // missing oracles array ret = Oracle::aggregatePrice(env, "XRP", "USD"); - BEAST_EXPECT( - ret[jss::error_message].asString() == - "Missing field 'oracles'."); + BEAST_EXPECT(ret[jss::error_message].asString() == "Missing field 'oracles'."); // empty oracles array ret = Oracle::aggregatePrice(env, "XRP", "USD", OraclesData{}); @@ -83,8 +76,7 @@ public: ret = Oracle::aggregatePrice(env, "XRP", "USD", {{{owner, 2}}}); BEAST_EXPECT(ret[jss::error].asString() == "objectNotFound"); // invalid values - std::vector invalidDocument = { - NoneTag, 1.2, -1, "", "none", "1.2"}; + std::vector invalidDocument = {NoneTag, 1.2, -1, "", "none", "1.2"}; for (auto const& v : invalidDocument) { ret = Oracle::aggregatePrice(env, "XRP", "USD", {{{owner, v}}}); @@ -93,51 +85,36 @@ public: BEAST_EXPECT(ret[jss::error].asString() == "invalidParams"); } // missing document id - ret = Oracle::aggregatePrice( - env, "XRP", "USD", {{{owner, std::nullopt}}}); + ret = Oracle::aggregatePrice(env, "XRP", "USD", {{{owner, std::nullopt}}}); BEAST_EXPECT(ret[jss::error].asString() == "oracleMalformed"); // invalid owner ret = Oracle::aggregatePrice(env, "XRP", "USD", {{{some, 1}}}); BEAST_EXPECT(ret[jss::error].asString() == "objectNotFound"); // missing account - ret = Oracle::aggregatePrice( - env, "XRP", "USD", {{{std::nullopt, 1}}}); + ret = Oracle::aggregatePrice(env, "XRP", "USD", {{{std::nullopt, 1}}}); BEAST_EXPECT(ret[jss::error].asString() == "oracleMalformed"); // oracles have wrong asset pair env.fund(XRP(1'000), owner); Oracle oracle( - env, - {.owner = owner, - .series = {{"XRP", "EUR", 740, 1}}, - .fee = static_cast(baseFee.drops())}); - ret = Oracle::aggregatePrice( - env, "XRP", "USD", {{{owner, oracle.documentID()}}}); + env, {.owner = owner, .series = {{"XRP", "EUR", 740, 1}}, .fee = static_cast(baseFee.drops())}); + ret = Oracle::aggregatePrice(env, "XRP", "USD", {{{owner, oracle.documentID()}}}); BEAST_EXPECT(ret[jss::error].asString() == "objectNotFound"); // invalid trim value - std::vector invalidTrim = { - NoneTag, 0, 26, -1, 1.2, "", "none", "1.2"}; + std::vector invalidTrim = {NoneTag, 0, 26, -1, 1.2, "", "none", "1.2"}; for (auto const& v : invalidTrim) { - ret = Oracle::aggregatePrice( - env, "XRP", "USD", {{{owner, oracle.documentID()}}}, v); + ret = Oracle::aggregatePrice(env, "XRP", "USD", {{{owner, oracle.documentID()}}}, v); BEAST_EXPECT(ret[jss::error].asString() == "invalidParams"); } // invalid time threshold value - std::vector invalidTime = { - NoneTag, -1, 1.2, "", "none", "1.2"}; + std::vector invalidTime = {NoneTag, -1, 1.2, "", "none", "1.2"}; for (auto const& v : invalidTime) { - ret = Oracle::aggregatePrice( - env, - "XRP", - "USD", - {{{owner, oracle.documentID()}}}, - std::nullopt, - v); + ret = Oracle::aggregatePrice(env, "XRP", "USD", {{{owner, oracle.documentID()}}}, std::nullopt, v); BEAST_EXPECT(ret[jss::error].asString() == "invalidParams"); } } @@ -145,16 +122,14 @@ public: // too many oracles { Env env(*this); - auto const baseFee = - static_cast(env.current()->fees().base.drops()); + auto const baseFee = static_cast(env.current()->fees().base.drops()); OraclesData oracles; for (int i = 0; i < 201; ++i) { Account const owner(std::to_string(i)); env.fund(XRP(1'000), owner); - Oracle oracle( - env, {.owner = owner, .documentID = i, .fee = baseFee}); + Oracle oracle(env, {.owner = owner, .documentID = i, .fee = baseFee}); oracles.emplace_back(owner, oracle.documentID()); } auto const ret = Oracle::aggregatePrice(env, "XRP", "USD", oracles); @@ -172,8 +147,7 @@ public: oracles.reserve(10); for (int i = 0; i < 10; ++i) { - auto const baseFee = - static_cast(env.current()->fees().base.drops()); + auto const baseFee = static_cast(env.current()->fees().base.drops()); Account const owner{std::to_string(i)}; env.fund(XRP(1'000), owner); @@ -181,8 +155,7 @@ public: env, {.owner = owner, .documentID = rand(), - .series = - {{"XRP", "USD", 740 + i, 1}, {"XRP", "EUR", 740, 1}}, + .series = {{"XRP", "USD", 740 + i, 1}, {"XRP", "EUR", 740, 1}}, .fee = baseFee}); oracles.emplace_back(owner, oracle.documentID()); } @@ -192,11 +165,9 @@ public: // or time threshold { auto const all = testable_amendments(); - for (auto const& feats : - {all - featureSingleAssetVault - featureLendingProtocol, all}) + for (auto const& feats : {all - featureSingleAssetVault - featureLendingProtocol, all}) { - for (auto const mantissaSize : - {MantissaRange::small, MantissaRange::large}) + for (auto const mantissaSize : {MantissaRange::small, MantissaRange::large}) { // Regardless of the features enabled, RPC is controlled by // the global mantissa size. And since it's a thread-local, @@ -208,17 +179,13 @@ public: OraclesData oracles; prep(env, oracles); // entire and trimmed stats - auto ret = - Oracle::aggregatePrice(env, "XRP", "USD", oracles); + auto ret = Oracle::aggregatePrice(env, "XRP", "USD", oracles); BEAST_EXPECT(ret[jss::entire_set][jss::mean] == "74.45"); - BEAST_EXPECT( - ret[jss::entire_set][jss::size].asUInt() == 10); + BEAST_EXPECT(ret[jss::entire_set][jss::size].asUInt() == 10); // Short: 0.3027650354097492 BEAST_EXPECTS( - ret[jss::entire_set][jss::standard_deviation] == - "0.3027650354097491666", - ret[jss::entire_set][jss::standard_deviation] - .asString()); + ret[jss::entire_set][jss::standard_deviation] == "0.3027650354097491666", + ret[jss::entire_set][jss::standard_deviation].asString()); BEAST_EXPECT(ret[jss::median] == "74.45"); BEAST_EXPECT(ret[jss::time] == 946694900); } @@ -231,22 +198,19 @@ public: OraclesData oracles; prep(env, oracles); // entire and trimmed stats - auto ret = - Oracle::aggregatePrice(env, "XRP", "USD", oracles, 20, 100); + auto ret = Oracle::aggregatePrice(env, "XRP", "USD", oracles, 20, 100); BEAST_EXPECT(ret[jss::entire_set][jss::mean] == "74.45"); BEAST_EXPECT(ret[jss::entire_set][jss::size].asUInt() == 10); // Short: "0.3027650354097492", BEAST_EXPECTS( - ret[jss::entire_set][jss::standard_deviation] == - "0.3027650354097491666", + ret[jss::entire_set][jss::standard_deviation] == "0.3027650354097491666", ret[jss::entire_set][jss::standard_deviation].asString()); BEAST_EXPECT(ret[jss::median] == "74.45"); BEAST_EXPECT(ret[jss::trimmed_set][jss::mean] == "74.45"); BEAST_EXPECT(ret[jss::trimmed_set][jss::size].asUInt() == 6); // Short: "0.187082869338697", BEAST_EXPECTS( - ret[jss::trimmed_set][jss::standard_deviation] == - "0.1870828693386970693", + ret[jss::trimmed_set][jss::standard_deviation] == "0.1870828693386970693", ret[jss::trimmed_set][jss::standard_deviation].asString()); BEAST_EXPECT(ret[jss::time] == 946694900); } @@ -255,61 +219,44 @@ public: // updated ledgers { Env env(*this); - auto const baseFee = - static_cast(env.current()->fees().base.drops()); + auto const baseFee = static_cast(env.current()->fees().base.drops()); OraclesData oracles; prep(env, oracles); for (int i = 0; i < 3; ++i) { Oracle oracle( - env, - {.owner = oracles[i].first, - .documentID = asUInt(*oracles[i].second), - .fee = baseFee}, - false); + env, {.owner = oracles[i].first, .documentID = asUInt(*oracles[i].second), .fee = baseFee}, false); // push XRP/USD by more than three ledgers, so this price // oracle is not included in the dataset - oracle.set(UpdateArg{ - .series = {{"XRP", "EUR", 740, 1}}, .fee = baseFee}); - oracle.set(UpdateArg{ - .series = {{"XRP", "EUR", 740, 1}}, .fee = baseFee}); - oracle.set(UpdateArg{ - .series = {{"XRP", "EUR", 740, 1}}, .fee = baseFee}); + oracle.set(UpdateArg{.series = {{"XRP", "EUR", 740, 1}}, .fee = baseFee}); + oracle.set(UpdateArg{.series = {{"XRP", "EUR", 740, 1}}, .fee = baseFee}); + oracle.set(UpdateArg{.series = {{"XRP", "EUR", 740, 1}}, .fee = baseFee}); } for (int i = 3; i < 6; ++i) { Oracle oracle( - env, - {.owner = oracles[i].first, - .documentID = asUInt(*oracles[i].second), - .fee = baseFee}, - false); + env, {.owner = oracles[i].first, .documentID = asUInt(*oracles[i].second), .fee = baseFee}, false); // push XRP/USD by two ledgers, so this price // is included in the dataset - oracle.set(UpdateArg{ - .series = {{"XRP", "EUR", 740, 1}}, .fee = baseFee}); - oracle.set(UpdateArg{ - .series = {{"XRP", "EUR", 740, 1}}, .fee = baseFee}); + oracle.set(UpdateArg{.series = {{"XRP", "EUR", 740, 1}}, .fee = baseFee}); + oracle.set(UpdateArg{.series = {{"XRP", "EUR", 740, 1}}, .fee = baseFee}); } // entire and trimmed stats - auto ret = - Oracle::aggregatePrice(env, "XRP", "USD", oracles, 20, "200"); + auto ret = Oracle::aggregatePrice(env, "XRP", "USD", oracles, 20, "200"); BEAST_EXPECT(ret[jss::entire_set][jss::mean] == "74.6"); BEAST_EXPECT(ret[jss::entire_set][jss::size].asUInt() == 7); // Short: 0.2160246899469287 BEAST_EXPECTS( - ret[jss::entire_set][jss::standard_deviation] == - "0.2160246899469286744", + ret[jss::entire_set][jss::standard_deviation] == "0.2160246899469286744", ret[jss::entire_set][jss::standard_deviation].asString()); BEAST_EXPECT(ret[jss::median] == "74.6"); BEAST_EXPECT(ret[jss::trimmed_set][jss::mean] == "74.6"); BEAST_EXPECT(ret[jss::trimmed_set][jss::size].asUInt() == 5); // Short: 0.158113883008419 BEAST_EXPECTS( - ret[jss::trimmed_set][jss::standard_deviation] == - "0.1581138830084189666", + ret[jss::trimmed_set][jss::standard_deviation] == "0.1581138830084189666", ret[jss::trimmed_set][jss::standard_deviation].asString()); BEAST_EXPECT(ret[jss::time] == 946694900); } @@ -317,28 +264,21 @@ public: // Reduced data set because of the time threshold { Env env(*this); - auto const baseFee = - static_cast(env.current()->fees().base.drops()); + auto const baseFee = static_cast(env.current()->fees().base.drops()); OraclesData oracles; prep(env, oracles); for (int i = 0; i < oracles.size(); ++i) { Oracle oracle( - env, - {.owner = oracles[i].first, - .documentID = asUInt(*oracles[i].second), - .fee = baseFee}, - false); + env, {.owner = oracles[i].first, .documentID = asUInt(*oracles[i].second), .fee = baseFee}, false); // push XRP/USD by two ledgers, so this price // is included in the dataset - oracle.set(UpdateArg{ - .series = {{"XRP", "USD", 740, 1}}, .fee = baseFee}); + oracle.set(UpdateArg{.series = {{"XRP", "USD", 740, 1}}, .fee = baseFee}); } // entire stats only, limit lastUpdateTime to {200, 125} - auto ret = Oracle::aggregatePrice( - env, "XRP", "USD", oracles, std::nullopt, 75); + auto ret = Oracle::aggregatePrice(env, "XRP", "USD", oracles, std::nullopt, 75); BEAST_EXPECT(ret[jss::entire_set][jss::mean] == "74"); BEAST_EXPECT(ret[jss::entire_set][jss::size].asUInt() == 8); BEAST_EXPECT(ret[jss::entire_set][jss::standard_deviation] == "0"); diff --git a/src/test/rpc/GetCounts_test.cpp b/src/test/rpc/GetCounts_test.cpp index b9ad5ec254..07c29e3648 100644 --- a/src/test/rpc/GetCounts_test.cpp +++ b/src/test/rpc/GetCounts_test.cpp @@ -26,12 +26,8 @@ class GetCounts_test : public beast::unit_test::suite BEAST_EXPECT(!result.isMember("Transaction")); BEAST_EXPECT(!result.isMember("STObject")); BEAST_EXPECT(!result.isMember("HashRouterEntry")); - BEAST_EXPECT( - result.isMember(jss::uptime) && - !result[jss::uptime].asString().empty()); - BEAST_EXPECT( - result.isMember(jss::dbKBTotal) && - result[jss::dbKBTotal].asInt() > 0); + BEAST_EXPECT(result.isMember(jss::uptime) && !result[jss::uptime].asString().empty()); + BEAST_EXPECT(result.isMember(jss::dbKBTotal) && result[jss::dbKBTotal].asInt() > 0); } // create some transactions @@ -51,8 +47,7 @@ class GetCounts_test : public beast::unit_test::suite result = env.rpc("get_counts")[jss::result]; BEAST_EXPECT(result[jss::status] == "success"); // compare with values reported by CountedObjects - auto const& objectCounts = - CountedObjects::getInstance().getCounts(10); + auto const& objectCounts = CountedObjects::getInstance().getCounts(10); for (auto const& it : objectCounts) { BEAST_EXPECTS(result.isMember(it.first), it.first); @@ -68,8 +63,7 @@ class GetCounts_test : public beast::unit_test::suite BEAST_EXPECT(result[jss::status] == "success"); // compare with values reported by CountedObjects - auto const& objectCounts = - CountedObjects::getInstance().getCounts(100); + auto const& objectCounts = CountedObjects::getInstance().getCounts(100); for (auto const& it : objectCounts) { BEAST_EXPECTS(result.isMember(it.first), it.first); @@ -87,9 +81,7 @@ class GetCounts_test : public beast::unit_test::suite env(pay(alice, bob, alice["USD"](5))); result = env.rpc("get_counts")[jss::result]; // deliberately don't call close so we have open Tx - BEAST_EXPECT( - result.isMember(jss::local_txs) && - result[jss::local_txs].asInt() > 0); + BEAST_EXPECT(result.isMember(jss::local_txs) && result[jss::local_txs].asInt() > 0); } } diff --git a/src/test/rpc/Handler_test.cpp b/src/test/rpc/Handler_test.cpp index 9a6f1b3aa1..7aeb059f56 100644 --- a/src/test/rpc/Handler_test.cpp +++ b/src/test/rpc/Handler_test.cpp @@ -8,6 +8,7 @@ #include #include #include +// cspell: words stdev namespace xrpl::test { @@ -68,8 +69,7 @@ class Handler_test : public beast::unit_test::suite double const mean_squared = (sum * sum) / (j * j); return std::make_tuple( clock::duration{static_cast(sum / j)}, - clock::duration{ - static_cast(std::sqrt((sum_squared / j) - mean_squared))}, + clock::duration{static_cast(std::sqrt((sum_squared / j) - mean_squared))}, j); } @@ -81,8 +81,7 @@ class Handler_test : public beast::unit_test::suite std::random_device dev; std::ranlux48 prng(dev()); - std::vector names = - test::jtx::make_vector(xrpl::RPC::getHandlerNames()); + std::vector names = test::jtx::make_vector(xrpl::RPC::getHandlerNames()); std::uniform_int_distribution distr{0, names.size() - 1}; @@ -95,8 +94,7 @@ class Handler_test : public beast::unit_test::suite }, [&]() -> std::size_t { return distr(prng); }); - std::cout << "mean=" << mean << " stdev=" << stdev << " N=" << n - << '\n'; + std::cout << "mean=" << mean << " stdev=" << stdev << " N=" << n << '\n'; BEAST_EXPECT(dummy != 0); } diff --git a/src/test/rpc/JSONRPC_test.cpp b/src/test/rpc/JSONRPC_test.cpp index 6a9fae74a5..f0329748e1 100644 --- a/src/test/rpc/JSONRPC_test.cpp +++ b/src/test/rpc/JSONRPC_test.cpp @@ -63,10 +63,7 @@ static constexpr TxnTestData txnTestArray[] = { "TransactionType": "Payment" } })", - {{"", - "", - "Missing field 'account'.", - "Missing field 'tx_json.Sequence'."}}}, + {{"", "", "Missing field 'account'.", "Missing field 'tx_json.Sequence'."}}}, {"Pass in Fee with minimal payment, both Amount and DeliverMax.", __LINE__, @@ -83,10 +80,7 @@ static constexpr TxnTestData txnTestArray[] = { "TransactionType": "Payment" } })", - {{"", - "", - "Missing field 'tx_json.Sequence'.", - "Missing field 'tx_json.Sequence'."}}}, + {{"", "", "Missing field 'tx_json.Sequence'.", "Missing field 'tx_json.Sequence'."}}}, {"Pass in Sequence, no Amount only DeliverMax", __LINE__, @@ -102,10 +96,7 @@ static constexpr TxnTestData txnTestArray[] = { "TransactionType": "Payment" } })", - {{"", - "", - "Missing field 'tx_json.Fee'.", - "Missing field 'tx_json.SigningPubKey'."}}}, + {{"", "", "Missing field 'tx_json.Fee'.", "Missing field 'tx_json.SigningPubKey'."}}}, {"Pass in Sequence and Fee with minimal payment, both Amount and " "DeliverMax.", @@ -145,10 +136,7 @@ static constexpr TxnTestData txnTestArray[] = { "TransactionType": "Payment" } })", - {{"", - "", - "Missing field 'tx_json.Fee'.", - "Missing field 'tx_json.SigningPubKey'."}}}, + {{"", "", "Missing field 'tx_json.Fee'.", "Missing field 'tx_json.SigningPubKey'."}}}, {"Add 'fee_mult_max' and 'fee_div_max' field.", __LINE__, @@ -166,10 +154,7 @@ static constexpr TxnTestData txnTestArray[] = { "TransactionType": "Payment" } })", - {{"", - "", - "Missing field 'tx_json.Fee'.", - "Missing field 'tx_json.SigningPubKey'."}}}, + {{"", "", "Missing field 'tx_json.Fee'.", "Missing field 'tx_json.SigningPubKey'."}}}, {"fee_mult_max is ignored if 'Fee' is present.", __LINE__, @@ -426,10 +411,7 @@ static constexpr TxnTestData txnTestArray[] = { "TransactionType": "Payment" } })", - {{"", - "", - "Missing field 'tx_json.Sequence'.", - "Missing field 'tx_json.Sequence'."}}}, + {{"", "", "Missing field 'tx_json.Sequence'.", "Missing field 'tx_json.Sequence'."}}}, {"Not valid to include both 'Paths' and 'build_path'.", __LINE__, @@ -478,10 +460,7 @@ static constexpr TxnTestData txnTestArray[] = { "TransactionType": "Payment" } })", - {{"", - "", - "Missing field 'tx_json.Sequence'.", - "Missing field 'tx_json.Sequence'."}}}, + {{"", "", "Missing field 'tx_json.Sequence'.", "Missing field 'tx_json.Sequence'."}}}, {"'Amount' may not be XRP for pathfinding, but 'SendMax' may be XRP.", __LINE__, @@ -502,10 +481,7 @@ static constexpr TxnTestData txnTestArray[] = { "TransactionType": "Payment" } })", - {{"", - "", - "Missing field 'tx_json.Sequence'.", - "Missing field 'tx_json.Sequence'."}}}, + {{"", "", "Missing field 'tx_json.Sequence'.", "Missing field 'tx_json.Sequence'."}}}, {"'secret' must be present.", __LINE__, @@ -556,10 +532,7 @@ static constexpr TxnTestData txnTestArray[] = { "TransactionType": "Payment" } })", - {{"", - "", - "Missing field 'tx_json.Sequence'.", - "Missing field 'tx_json.Sequence'."}}}, + {{"", "", "Missing field 'tx_json.Sequence'.", "Missing field 'tx_json.Sequence'."}}}, {"Malformed 'seed'.", __LINE__, @@ -646,10 +619,7 @@ static constexpr TxnTestData txnTestArray[] = { "TransactionType": 0 } })", - {{"", - "", - "Missing field 'tx_json.Sequence'.", - "Missing field 'tx_json.Sequence'."}}}, + {{"", "", "Missing field 'tx_json.Sequence'.", "Missing field 'tx_json.Sequence'."}}}, {"'Account' must be present.", __LINE__, @@ -700,10 +670,7 @@ static constexpr TxnTestData txnTestArray[] = { "TransactionType": "Payment" } })", - {{"", - "", - "Missing field 'tx_json.Sequence'.", - "Missing field 'tx_json.Sequence'."}}}, + {{"", "", "Missing field 'tx_json.Sequence'.", "Missing field 'tx_json.Sequence'."}}}, {"If 'offline' is true then a 'Sequence' field must be supplied.", __LINE__, @@ -803,10 +770,7 @@ static constexpr TxnTestData txnTestArray[] = { "TransactionType": "Payment" } })", - {{"", - "", - "Missing field 'tx_json.Sequence'.", - "Missing field 'tx_json.Sequence'."}}}, + {{"", "", "Missing field 'tx_json.Sequence'.", "Missing field 'tx_json.Sequence'."}}}, {"The 'Flags' field must be numeric.", __LINE__, @@ -841,10 +805,7 @@ static constexpr TxnTestData txnTestArray[] = { "TransactionType": "Payment" } })", - {{"", - "", - "Missing field 'tx_json.Sequence'.", - "Missing field 'tx_json.Sequence'."}}}, + {{"", "", "Missing field 'tx_json.Sequence'.", "Missing field 'tx_json.Sequence'."}}}, {"Single-sign a multisigned transaction.", __LINE__, @@ -871,10 +832,7 @@ static constexpr TxnTestData txnTestArray[] = { "TransactionType" : "Payment" } })", - {{"Already multisigned.", - "Already multisigned.", - "Secret does not match account.", - ""}}}, + {{"Already multisigned.", "Already multisigned.", "Secret does not match account.", ""}}}, {"Minimal sign_for.", __LINE__, @@ -892,10 +850,7 @@ static constexpr TxnTestData txnTestArray[] = { "TransactionType": "Payment" } })", - {{"Secret does not match account.", - "Secret does not match account.", - "", - "Missing field 'tx_json.Signers'."}}}, + {{"Secret does not match account.", "Secret does not match account.", "", "Missing field 'tx_json.Signers'."}}}, {"Minimal offline sign_for.", __LINE__, @@ -954,10 +909,7 @@ static constexpr TxnTestData txnTestArray[] = { "TransactionType": "Payment" } })", - {{"Disallowed seed.", - "Disallowed seed.", - "Disallowed seed.", - "Missing field 'tx_json.Signers'."}}}, + {{"Disallowed seed.", "Disallowed seed.", "Disallowed seed.", "Missing field 'tx_json.Signers'."}}}, {"Missing 'Account' in sign_for.", __LINE__, @@ -1203,10 +1155,7 @@ static constexpr TxnTestData txnTestArray[] = { "TransactionType" : "Payment" } })", - {{"Already multisigned.", - "Already multisigned.", - "Invalid signature.", - "Invalid signature."}}}, + {{"Already multisigned.", "Already multisigned.", "Invalid signature.", "Invalid signature."}}}, {"Non-empty 'SigningPubKey' in sign_for.", __LINE__, @@ -1362,10 +1311,7 @@ static constexpr TxnTestData txnTestArray[] = { "TransactionType": "Payment" } })", - {{"Missing field 'secret'.", - "Missing field 'secret'.", - "Missing field 'account'.", - ""}}}, + {{"Missing field 'secret'.", "Missing field 'secret'.", "Missing field 'account'.", ""}}}, {"Minimal submit_multisigned with bad signature.", __LINE__, @@ -1390,10 +1336,7 @@ static constexpr TxnTestData txnTestArray[] = { "TransactionType": "Payment" } })", - {{"Missing field 'secret'.", - "Missing field 'secret'.", - "Missing field 'account'.", - "Invalid signature."}}}, + {{"Missing field 'secret'.", "Missing field 'secret'.", "Missing field 'account'.", "Invalid signature."}}}, {"Missing tx_json in submit_multisigned.", __LINE__, @@ -1409,10 +1352,7 @@ static constexpr TxnTestData txnTestArray[] = { } ] })", - {{"Missing field 'secret'.", - "Missing field 'secret'.", - "Missing field 'account'.", - "Missing field 'tx_json'."}}}, + {{"Missing field 'secret'.", "Missing field 'secret'.", "Missing field 'account'.", "Missing field 'tx_json'."}}}, {"Missing sequence in submit_multisigned.", __LINE__, @@ -1601,10 +1541,7 @@ static constexpr TxnTestData txnTestArray[] = { "TransactionType": "Payment" } })", - {{"Missing field 'secret'.", - "Missing field 'secret'.", - "Missing field 'account'.", - "Source account not found."}}}, + {{"Missing field 'secret'.", "Missing field 'secret'.", "Missing field 'account'.", "Source account not found."}}}, {"Missing Fee in submit_multisigned.", __LINE__, @@ -2058,10 +1995,7 @@ static constexpr TxnTestData txnTestArray[] = { "Delegate": "rnUy2SHTrB9DubsPmkJZUXTf5FcNDGrYEA" } })", - {{"", - "", - "Missing field 'account'.", - "Missing field 'tx_json.Sequence'."}}}, + {{"", "", "Missing field 'account'.", "Missing field 'tx_json.Sequence'."}}}, {"Delegate not well formed.", __LINE__, @@ -2127,12 +2061,10 @@ public: { testcase("bad RPC command"); test::jtx::Env env(*this); - Json::Value const result{ - env.rpc("bad_command", R"({"MakingThisUp": 0})")}; + Json::Value const result{env.rpc("bad_command", R"({"MakingThisUp": 0})")}; BEAST_EXPECT(result[jss::result][jss::error] == "unknownCmd"); - BEAST_EXPECT( - result[jss::result][jss::request][jss::command] == "bad_command"); + BEAST_EXPECT(result[jss::result][jss::request][jss::command] == "bad_command"); } void @@ -2169,19 +2101,12 @@ public: jt.jv.removeMember(jss::Fee); jt.jv.removeMember(jss::TxnSignature); req[jss::tx_json] = jt.jv; - Json::Value result = checkFee( - req, - Role::ADMIN, - true, - env.app().config(), - feeTrack, - env.app().getTxQ(), - env.app()); + Json::Value result = + checkFee(req, Role::ADMIN, true, env.app().config(), feeTrack, env.app().getTxQ(), env.app()); BEAST_EXPECT(result.size() == 0); BEAST_EXPECT( req[jss::tx_json].isMember(jss::Fee) && - req[jss::tx_json][jss::Fee] == - env.current()->fees().base.jsonClipped()); + req[jss::tx_json][jss::Fee] == env.current()->fees().base.jsonClipped()); } // test signers max size @@ -2240,19 +2165,12 @@ public: alice)); req[jss::tx_json] = jt.jv; - Json::Value result = checkFee( - req, - Role::ADMIN, - true, - env.app().config(), - feeTrack, - env.app().getTxQ(), - env.app()); + Json::Value result = + checkFee(req, Role::ADMIN, true, env.app().config(), feeTrack, env.app().getTxQ(), env.app()); BEAST_EXPECT(result.size() == 0); BEAST_EXPECT( req[jss::tx_json].isMember(jss::Fee) && - req[jss::tx_json][jss::Fee] == - env.current()->fees().base.jsonClipped()); + req[jss::tx_json][jss::Fee] == env.current()->fees().base.jsonClipped()); } } @@ -2261,28 +2179,18 @@ public: { testcase("autofill fees"); test::jtx::Env env(*this); - auto const baseFee = - static_cast(env.current()->fees().base.drops()); + auto const baseFee = static_cast(env.current()->fees().base.drops()); auto ledger = env.current(); auto const& feeTrack = env.app().getFeeTrack(); { Json::Value req; - Json::Reader().parse( - "{ \"fee_mult_max\" : 1, \"tx_json\" : { } } ", req); - Json::Value result = checkFee( - req, - Role::ADMIN, - true, - env.app().config(), - feeTrack, - env.app().getTxQ(), - env.app()); + Json::Reader().parse("{ \"fee_mult_max\" : 1, \"tx_json\" : { } } ", req); + Json::Value result = + checkFee(req, Role::ADMIN, true, env.app().config(), feeTrack, env.app().getTxQ(), env.app()); BEAST_EXPECT(!RPC::contains_error(result)); - BEAST_EXPECT( - req[jss::tx_json].isMember(jss::Fee) && - req[jss::tx_json][jss::Fee] == baseFee); + BEAST_EXPECT(req[jss::tx_json].isMember(jss::Fee) && req[jss::tx_json][jss::Fee] == baseFee); } { @@ -2291,33 +2199,18 @@ public: "{ \"fee_mult_max\" : 3, \"fee_div_max\" : 2, " "\"tx_json\" : { } } ", req); - Json::Value result = checkFee( - req, - Role::ADMIN, - true, - env.app().config(), - feeTrack, - env.app().getTxQ(), - env.app()); + Json::Value result = + checkFee(req, Role::ADMIN, true, env.app().config(), feeTrack, env.app().getTxQ(), env.app()); BEAST_EXPECT(!RPC::contains_error(result)); - BEAST_EXPECT( - req[jss::tx_json].isMember(jss::Fee) && - req[jss::tx_json][jss::Fee] == baseFee); + BEAST_EXPECT(req[jss::tx_json].isMember(jss::Fee) && req[jss::tx_json][jss::Fee] == baseFee); } { Json::Value req; - Json::Reader().parse( - "{ \"fee_mult_max\" : 0, \"tx_json\" : { } } ", req); - Json::Value result = checkFee( - req, - Role::ADMIN, - true, - env.app().config(), - feeTrack, - env.app().getTxQ(), - env.app()); + Json::Reader().parse("{ \"fee_mult_max\" : 0, \"tx_json\" : { } } ", req); + Json::Value result = + checkFee(req, Role::ADMIN, true, env.app().config(), feeTrack, env.app().getTxQ(), env.app()); BEAST_EXPECT(RPC::contains_error(result)); BEAST_EXPECT(!req[jss::tx_json].isMember(jss::Fee)); @@ -2331,14 +2224,8 @@ public: "{ \"fee_mult_max\" : 3, \"fee_div_max\" : 6, " "\"tx_json\" : { } } ", req); - Json::Value result = checkFee( - req, - Role::ADMIN, - true, - env.app().config(), - feeTrack, - env.app().getTxQ(), - env.app()); + Json::Value result = + checkFee(req, Role::ADMIN, true, env.app().config(), feeTrack, env.app().getTxQ(), env.app()); BEAST_EXPECT(RPC::contains_error(result)); BEAST_EXPECT(!req[jss::tx_json].isMember(jss::Fee)); @@ -2350,14 +2237,8 @@ public: "{ \"fee_mult_max\" : 0, \"fee_div_max\" : 2, " "\"tx_json\" : { } } ", req); - Json::Value result = checkFee( - req, - Role::ADMIN, - true, - env.app().config(), - feeTrack, - env.app().getTxQ(), - env.app()); + Json::Value result = + checkFee(req, Role::ADMIN, true, env.app().config(), feeTrack, env.app().getTxQ(), env.app()); BEAST_EXPECT(RPC::contains_error(result)); BEAST_EXPECT(!req[jss::tx_json].isMember(jss::Fee)); @@ -2369,14 +2250,8 @@ public: "{ \"fee_mult_max\" : 10, \"fee_div_max\" : 0, " "\"tx_json\" : { } } ", req); - Json::Value result = checkFee( - req, - Role::ADMIN, - true, - env.app().config(), - feeTrack, - env.app().getTxQ(), - env.app()); + Json::Value result = + checkFee(req, Role::ADMIN, true, env.app().config(), feeTrack, env.app().getTxQ(), env.app()); BEAST_EXPECT(RPC::contains_error(result)); BEAST_EXPECT(!req[jss::tx_json].isMember(jss::Fee)); @@ -2386,22 +2261,14 @@ public: // transaction with a higher base fee Json::Value req; test::jtx::Account const alice("alice"); - req[jss::tx_json] = - test::jtx::acctdelete(env.master.human(), alice.human()); - Json::Value result = checkFee( - req, - Role::ADMIN, - true, - env.app().config(), - feeTrack, - env.app().getTxQ(), - env.app()); + req[jss::tx_json] = test::jtx::acctdelete(env.master.human(), alice.human()); + Json::Value result = + checkFee(req, Role::ADMIN, true, env.app().config(), feeTrack, env.app().getTxQ(), env.app()); BEAST_EXPECT(result.size() == 0); BEAST_EXPECT( req[jss::tx_json].isMember(jss::Fee) && - req[jss::tx_json][jss::Fee] == - env.current()->fees().increment.jsonClipped()); + req[jss::tx_json][jss::Fee] == env.current()->fees().increment.jsonClipped()); } } @@ -2412,8 +2279,7 @@ public: using namespace test::jtx; Env env{*this, envconfig([](std::unique_ptr cfg) { cfg->loadFromString("[" SECTION_SIGNING_SUPPORT "]\ntrue"); - cfg->section("transaction_queue") - .set("minimum_txn_in_ledger_standalone", "3"); + cfg->section("transaction_queue").set("minimum_txn_in_ledger_standalone", "3"); return cfg; })}; LoadFeeTrack const& feeTrackOuter = env.app().getFeeTrack(); @@ -2427,19 +2293,11 @@ public: "tx_json" : { } })", req); - Json::Value result = checkFee( - req, - Role::ADMIN, - true, - env.app().config(), - feeTrackOuter, - env.app().getTxQ(), - env.app()); + Json::Value result = + checkFee(req, Role::ADMIN, true, env.app().config(), feeTrackOuter, env.app().getTxQ(), env.app()); BEAST_EXPECT(!RPC::contains_error(result)); - BEAST_EXPECT( - req[jss::tx_json].isMember(jss::Fee) && - req[jss::tx_json][jss::Fee] == 10); + BEAST_EXPECT(req[jss::tx_json].isMember(jss::Fee) && req[jss::tx_json][jss::Fee] == 10); } { @@ -2451,19 +2309,11 @@ public: "tx_json" : { } })", req); - Json::Value result = checkFee( - req, - Role::ADMIN, - true, - env.app().config(), - feeTrackOuter, - env.app().getTxQ(), - env.app()); + Json::Value result = + checkFee(req, Role::ADMIN, true, env.app().config(), feeTrackOuter, env.app().getTxQ(), env.app()); BEAST_EXPECT(!RPC::contains_error(result)); - BEAST_EXPECT( - req[jss::tx_json].isMember(jss::Fee) && - req[jss::tx_json][jss::Fee] == 10); + BEAST_EXPECT(req[jss::tx_json].isMember(jss::Fee) && req[jss::tx_json][jss::Fee] == 10); } // put 4 transactions into the open ledger @@ -2481,19 +2331,11 @@ public: "tx_json" : { } })", req); - Json::Value result = checkFee( - req, - Role::ADMIN, - true, - env.app().config(), - feeTrackOuter, - env.app().getTxQ(), - env.app()); + Json::Value result = + checkFee(req, Role::ADMIN, true, env.app().config(), feeTrackOuter, env.app().getTxQ(), env.app()); BEAST_EXPECT(!RPC::contains_error(result)); - BEAST_EXPECT( - req[jss::tx_json].isMember(jss::Fee) && - req[jss::tx_json][jss::Fee] == 8889); + BEAST_EXPECT(req[jss::tx_json].isMember(jss::Fee) && req[jss::tx_json][jss::Fee] == 8889); } { @@ -2505,14 +2347,8 @@ public: "tx_json" : { } })", req); - Json::Value result = checkFee( - req, - Role::ADMIN, - true, - env.app().config(), - feeTrackOuter, - env.app().getTxQ(), - env.app()); + Json::Value result = + checkFee(req, Role::ADMIN, true, env.app().config(), feeTrackOuter, env.app().getTxQ(), env.app()); BEAST_EXPECT(RPC::contains_error(result)); BEAST_EXPECT(!req[jss::tx_json].isMember(jss::Fee)); @@ -2528,14 +2364,8 @@ public: "tx_json" : { } })", req); - Json::Value result = checkFee( - req, - Role::ADMIN, - true, - env.app().config(), - feeTrackOuter, - env.app().getTxQ(), - env.app()); + Json::Value result = + checkFee(req, Role::ADMIN, true, env.app().config(), feeTrackOuter, env.app().getTxQ(), env.app()); BEAST_EXPECT(RPC::contains_error(result)); BEAST_EXPECT(!req[jss::tx_json].isMember(jss::Fee)); @@ -2551,19 +2381,11 @@ public: "tx_json" : { } })", req); - Json::Value result = checkFee( - req, - Role::ADMIN, - true, - env.app().config(), - feeTrackOuter, - env.app().getTxQ(), - env.app()); + Json::Value result = + checkFee(req, Role::ADMIN, true, env.app().config(), feeTrackOuter, env.app().getTxQ(), env.app()); BEAST_EXPECT(!RPC::contains_error(result)); - BEAST_EXPECT( - req[jss::tx_json].isMember(jss::Fee) && - req[jss::tx_json][jss::Fee] == 8889); + BEAST_EXPECT(req[jss::tx_json].isMember(jss::Fee) && req[jss::tx_json][jss::Fee] == 8889); } { @@ -2575,14 +2397,8 @@ public: "tx_json" : { } })", req); - Json::Value result = checkFee( - req, - Role::ADMIN, - true, - env.app().config(), - feeTrackOuter, - env.app().getTxQ(), - env.app()); + Json::Value result = + checkFee(req, Role::ADMIN, true, env.app().config(), feeTrackOuter, env.app().getTxQ(), env.app()); BEAST_EXPECT(RPC::contains_error(result)); } @@ -2596,14 +2412,8 @@ public: "tx_json" : { } })", req); - Json::Value result = checkFee( - req, - Role::ADMIN, - true, - env.app().config(), - feeTrackOuter, - env.app().getTxQ(), - env.app()); + Json::Value result = + checkFee(req, Role::ADMIN, true, env.app().config(), feeTrackOuter, env.app().getTxQ(), env.app()); BEAST_EXPECT(RPC::contains_error(result)); } @@ -2618,14 +2428,8 @@ public: "tx_json" : { } })", req); - Json::Value result = checkFee( - req, - Role::ADMIN, - true, - env.app().config(), - feeTrackOuter, - env.app().getTxQ(), - env.app()); + Json::Value result = + checkFee(req, Role::ADMIN, true, env.app().config(), feeTrackOuter, env.app().getTxQ(), env.app()); BEAST_EXPECT(RPC::contains_error(result)); } @@ -2641,13 +2445,10 @@ public: auto result = rpcResult[jss::result]; BEAST_EXPECT(!RPC::contains_error(result)); - BEAST_EXPECT( - result[jss::tx_json].isMember(jss::Fee) && - result[jss::tx_json][jss::Fee] == "10"); + BEAST_EXPECT(result[jss::tx_json].isMember(jss::Fee) && result[jss::tx_json][jss::Fee] == "10"); BEAST_EXPECT( result[jss::tx_json].isMember(jss::Sequence) && - result[jss::tx_json][jss::Sequence].isConvertibleTo( - Json::ValueType::uintValue)); + result[jss::tx_json][jss::Sequence].isConvertibleTo(Json::ValueType::uintValue)); } { @@ -2669,13 +2470,10 @@ public: auto result = rpcResult[jss::result]; BEAST_EXPECT(!RPC::contains_error(result)); - BEAST_EXPECT( - result[jss::tx_json].isMember(jss::Fee) && - result[jss::tx_json][jss::Fee] == "7813"); + BEAST_EXPECT(result[jss::tx_json].isMember(jss::Fee) && result[jss::tx_json][jss::Fee] == "7813"); BEAST_EXPECT( result[jss::tx_json].isMember(jss::Sequence) && - result[jss::tx_json][jss::Sequence].isConvertibleTo( - Json::ValueType::uintValue)); + result[jss::tx_json][jss::Sequence].isConvertibleTo(Json::ValueType::uintValue)); env.close(); } @@ -2697,13 +2495,10 @@ public: auto result = rpcResult[jss::result]; BEAST_EXPECT(!RPC::contains_error(result)); - BEAST_EXPECT( - result[jss::tx_json].isMember(jss::Fee) && - result[jss::tx_json][jss::Fee] == "47"); + BEAST_EXPECT(result[jss::tx_json].isMember(jss::Fee) && result[jss::tx_json][jss::Fee] == "47"); BEAST_EXPECT( result[jss::tx_json].isMember(jss::Sequence) && - result[jss::tx_json][jss::Sequence].isConvertibleTo( - Json::ValueType::uintValue)); + result[jss::tx_json][jss::Sequence].isConvertibleTo(Json::ValueType::uintValue)); } { @@ -2730,13 +2525,10 @@ public: auto result = rpcResult[jss::result]; BEAST_EXPECT(!RPC::contains_error(result)); - BEAST_EXPECT( - result[jss::tx_json].isMember(jss::Fee) && - result[jss::tx_json][jss::Fee] == "6806"); + BEAST_EXPECT(result[jss::tx_json].isMember(jss::Fee) && result[jss::tx_json][jss::Fee] == "6806"); BEAST_EXPECT( result[jss::tx_json].isMember(jss::Sequence) && - result[jss::tx_json][jss::Sequence].isConvertibleTo( - Json::ValueType::uintValue)); + result[jss::tx_json][jss::Sequence].isConvertibleTo(Json::ValueType::uintValue)); } } @@ -2760,19 +2552,13 @@ public: auto result = rpcResult[jss::result]; BEAST_EXPECT(!RPC::contains_error(result)); - BEAST_EXPECT( - result[jss::tx_json].isMember(jss::NetworkID) && - result[jss::tx_json][jss::NetworkID] == 1025); + BEAST_EXPECT(result[jss::tx_json].isMember(jss::NetworkID) && result[jss::tx_json][jss::NetworkID] == 1025); } } // A function that can be called as though it would process a transaction. static void - fakeProcessTransaction( - std::shared_ptr&, - bool, - bool, - NetworkOPs::FailHard) + fakeProcessTransaction(std::shared_ptr&, bool, bool, NetworkOPs::FailHard) { ; } @@ -2828,18 +2614,13 @@ public: Application& app, ProcessTransactionFn const& processTransaction); - using TestStuff = - std::tuple; + using TestStuff = std::tuple; static TestStuff const testFuncs[] = { TestStuff{transactionSign, nullptr, "sign", 0}, TestStuff{nullptr, transactionSubmit, "submit", 1}, TestStuff{transactionSignFor, nullptr, "sign_for", 2}, - TestStuff{ - nullptr, - transactionSubmitMultiSigned, - "submit_multisigned", - 3}}; + TestStuff{nullptr, transactionSubmitMultiSigned, "submit_multisigned", 3}}; for (auto testFunc : testFuncs) { @@ -2849,11 +2630,9 @@ public: Json::Value req; Json::Reader().parse(txnTest.json, req); if (RPC::contains_error(req)) - Throw( - "Internal JSONRPC_test error. Bad test JSON."); + Throw("Internal JSONRPC_test error. Bad test JSON."); - static Role const testedRoles[] = { - Role::GUEST, Role::USER, Role::ADMIN, Role::FORBID}; + static Role const testedRoles[] = {Role::GUEST, Role::USER, Role::ADMIN, Role::FORBID}; for (Role testRole : testedRoles) { @@ -2862,26 +2641,13 @@ public: if (signFn != nullptr) { assert(get<1>(testFunc) == nullptr); - result = signFn( - req, - 1, - NetworkOPs::FailHard::yes, - testRole, - 1s, - env.app()); + result = signFn(req, 1, NetworkOPs::FailHard::yes, testRole, 1s, env.app()); } else { auto const submitFn = get<1>(testFunc); assert(submitFn != nullptr); - result = submitFn( - req, - 1, - NetworkOPs::FailHard::yes, - testRole, - 1s, - env.app(), - processTxn); + result = submitFn(req, 1, NetworkOPs::FailHard::yes, testRole, 1s, env.app(), processTxn); } std::string errStr; @@ -2895,9 +2661,8 @@ public: else { std::ostringstream description; - description << txnTest.description << " Called " - << get<2>(testFunc) << "(). Got \'" - << errStr << "\'"; + description << txnTest.description << " Called " << get<2>(testFunc) << "(). Got \'" << errStr + << "\'"; fail(description.str(), __FILE__, txnTest.line); } } diff --git a/src/test/rpc/KeyGeneration_test.cpp b/src/test/rpc/KeyGeneration_test.cpp index 23f2723d6a..987985070d 100644 --- a/src/test/rpc/KeyGeneration_test.cpp +++ b/src/test/rpc/KeyGeneration_test.cpp @@ -27,8 +27,7 @@ struct key_strings namespace common { static char const* passphrase = "REINDEER FLOTILLA"; -static char const* master_key = - "SCAT BERN ISLE FOR ROIL BUS SOAK AQUA FREE FOR DRAM BRIG"; +static char const* master_key = "SCAT BERN ISLE FOR ROIL BUS SOAK AQUA FREE FOR DRAM BRIG"; static char const* master_seed = "snMwVWs2hZzfDUF3p2tHZ3EgmyhFs"; static char const* master_seed_hex = "BE6A670A19B209E112146D0A7ED2AAD7"; } // namespace common @@ -94,10 +93,7 @@ public: BEAST_EXPECT(result.isMember(jss::public_key_hex)); BEAST_EXPECT(result.isMember(jss::key_type)); - expectEquals( - result[jss::key_type], - params.isMember(jss::key_type) ? params[jss::key_type] - : "secp256k1"); + expectEquals(result[jss::key_type], params.isMember(jss::key_type) ? params[jss::key_type] : "secp256k1"); BEAST_EXPECT(!result.isMember(jss::warning)); std::string seed = result[jss::master_seed].asString(); @@ -119,17 +115,12 @@ public: expectEquals(result[jss::master_seed_hex], s.master_seed_hex); expectEquals(result[jss::public_key], s.public_key); expectEquals(result[jss::public_key_hex], s.public_key_hex); - expectEquals( - result[jss::key_type], - params.isMember(jss::key_type) ? params[jss::key_type] - : "secp256k1"); + expectEquals(result[jss::key_type], params.isMember(jss::key_type) ? params[jss::key_type] : "secp256k1"); return result; } void - testSeed( - std::optional const& keyType, - key_strings const& strings) + testSeed(std::optional const& keyType, key_strings const& strings) { testcase("seed"); @@ -143,9 +134,7 @@ public: } void - testSeedHex( - std::optional const& keyType, - key_strings const& strings) + testSeedHex(std::optional const& keyType, key_strings const& strings) { testcase("seed_hex"); @@ -159,10 +148,7 @@ public: } void - testLegacyPassphrase( - char const* value, - std::optional const& keyType, - key_strings const& strings) + testLegacyPassphrase(char const* value, std::optional const& keyType, key_strings const& strings) { Json::Value params; if (keyType) @@ -177,9 +163,7 @@ public: } void - testLegacyPassphrase( - std::optional const& keyType, - key_strings const& strings) + testLegacyPassphrase(std::optional const& keyType, key_strings const& strings) { testcase("passphrase"); @@ -190,9 +174,7 @@ public: } void - testKeyType( - std::optional const& keyType, - key_strings const& strings) + testKeyType(std::optional const& keyType, key_strings const& strings) { testcase(keyType ? *keyType : "no key_type"); @@ -223,9 +205,7 @@ public: params[jss::passphrase] = 20160506; auto result = walletPropose(params); BEAST_EXPECT(contains_error(result)); - BEAST_EXPECT( - result[jss::error_message] == - "Invalid field 'passphrase', not string."); + BEAST_EXPECT(result[jss::error_message] == "Invalid field 'passphrase', not string."); } { @@ -234,9 +214,7 @@ public: params[jss::seed] = Json::objectValue; auto result = walletPropose(params); BEAST_EXPECT(contains_error(result)); - BEAST_EXPECT( - result[jss::error_message] == - "Invalid field 'seed', not string."); + BEAST_EXPECT(result[jss::error_message] == "Invalid field 'seed', not string."); } { @@ -245,9 +223,7 @@ public: params[jss::seed_hex] = Json::arrayValue; auto result = walletPropose(params); BEAST_EXPECT(contains_error(result)); - BEAST_EXPECT( - result[jss::error_message] == - "Invalid field 'seed_hex', not string."); + BEAST_EXPECT(result[jss::error_message] == "Invalid field 'seed_hex', not string."); } // Specifying multiple items at once @@ -281,9 +257,7 @@ public: params[jss::seed_hex] = common::master_seed_hex; auto result = walletPropose(params); BEAST_EXPECT(contains_error(result)); - BEAST_EXPECT( - result[jss::error_message] == - "Invalid field 'key_type', not string."); + BEAST_EXPECT(result[jss::error_message] == "Invalid field 'key_type', not string."); } { @@ -292,22 +266,16 @@ public: params[jss::seed] = common::master_seed; auto result = walletPropose(params); BEAST_EXPECT(contains_error(result)); - BEAST_EXPECT( - result[jss::error_message] == - "Invalid field 'key_type', not string."); + BEAST_EXPECT(result[jss::error_message] == "Invalid field 'key_type', not string."); } } void - testKeypairForSignature( - std::optional keyType, - key_strings const& strings) + testKeypairForSignature(std::optional keyType, key_strings const& strings) { - testcase( - "keypairForSignature - " + (keyType ? *keyType : "no key_type")); + testcase("keypairForSignature - " + (keyType ? *keyType : "no key_type")); - auto const publicKey = parseBase58( - TokenType::AccountPublic, strings.public_key); + auto const publicKey = parseBase58(TokenType::AccountPublic, strings.public_key); BEAST_EXPECT(publicKey); if (!keyType) @@ -417,9 +385,7 @@ public: auto ret = keypairForSignature(params, error); BEAST_EXPECT(contains_error(error)); BEAST_EXPECT(!ret); - BEAST_EXPECT( - error[jss::error_message] == - "Invalid field 'secret', not string."); + BEAST_EXPECT(error[jss::error_message] == "Invalid field 'secret', not string."); } { @@ -431,9 +397,7 @@ public: auto ret = keypairForSignature(params, error); BEAST_EXPECT(contains_error(error)); BEAST_EXPECT(!ret); - BEAST_EXPECT( - error[jss::error_message] == - "Invalid field 'secret', not string."); + BEAST_EXPECT(error[jss::error_message] == "Invalid field 'secret', not string."); } { @@ -446,9 +410,7 @@ public: auto ret = keypairForSignature(params, error); BEAST_EXPECT(contains_error(error)); BEAST_EXPECT(!ret); - BEAST_EXPECT( - error[jss::error_message] == - "Invalid field 'secret', not string."); + BEAST_EXPECT(error[jss::error_message] == "Invalid field 'secret', not string."); } // Specify "secret" and "key_type" @@ -461,9 +423,7 @@ public: auto ret = keypairForSignature(params, error); BEAST_EXPECT(contains_error(error)); BEAST_EXPECT(!ret); - BEAST_EXPECT( - error[jss::error_message] == - "The secret field is not allowed if key_type is used."); + BEAST_EXPECT(error[jss::error_message] == "The secret field is not allowed if key_type is used."); } // Specify unknown or bad "key_type" @@ -476,8 +436,7 @@ public: auto ret = keypairForSignature(params, error); BEAST_EXPECT(contains_error(error)); BEAST_EXPECT(!ret); - BEAST_EXPECT( - error[jss::error_message] == "Invalid field 'key_type'."); + BEAST_EXPECT(error[jss::error_message] == "Invalid field 'key_type'."); } { @@ -489,9 +448,7 @@ public: auto ret = keypairForSignature(params, error); BEAST_EXPECT(contains_error(error)); BEAST_EXPECT(!ret); - BEAST_EXPECT( - error[jss::error_message] == - "Invalid field 'key_type', not string."); + BEAST_EXPECT(error[jss::error_message] == "Invalid field 'key_type', not string."); } { @@ -503,9 +460,7 @@ public: auto ret = keypairForSignature(params, error); BEAST_EXPECT(contains_error(error)); BEAST_EXPECT(!ret); - BEAST_EXPECT( - error[jss::error_message] == - "Invalid field 'key_type', not string."); + BEAST_EXPECT(error[jss::error_message] == "Invalid field 'key_type', not string."); } // Specify non-string passphrase @@ -518,9 +473,7 @@ public: auto ret = keypairForSignature(params, error); BEAST_EXPECT(contains_error(error)); BEAST_EXPECT(!ret); - BEAST_EXPECT( - error[jss::error_message] == - "Invalid field 'passphrase', not string."); + BEAST_EXPECT(error[jss::error_message] == "Invalid field 'passphrase', not string."); } { // not a passphrase: object @@ -532,9 +485,7 @@ public: auto ret = keypairForSignature(params, error); BEAST_EXPECT(contains_error(error)); BEAST_EXPECT(!ret); - BEAST_EXPECT( - error[jss::error_message] == - "Invalid field 'passphrase', not string."); + BEAST_EXPECT(error[jss::error_message] == "Invalid field 'passphrase', not string."); } { // not a passphrase: array @@ -546,9 +497,7 @@ public: auto ret = keypairForSignature(params, error); BEAST_EXPECT(contains_error(error)); BEAST_EXPECT(!ret); - BEAST_EXPECT( - error[jss::error_message] == - "Invalid field 'passphrase', not string."); + BEAST_EXPECT(error[jss::error_message] == "Invalid field 'passphrase', not string."); } { // not a passphrase: empty string @@ -573,9 +522,7 @@ public: auto ret = keypairForSignature(params, error); BEAST_EXPECT(contains_error(error)); BEAST_EXPECT(!ret); - BEAST_EXPECT( - error[jss::error_message] == - "Invalid field 'seed', not string."); + BEAST_EXPECT(error[jss::error_message] == "Invalid field 'seed', not string."); } { // not a string: object @@ -587,9 +534,7 @@ public: auto ret = keypairForSignature(params, error); BEAST_EXPECT(contains_error(error)); BEAST_EXPECT(!ret); - BEAST_EXPECT( - error[jss::error_message] == - "Invalid field 'seed', not string."); + BEAST_EXPECT(error[jss::error_message] == "Invalid field 'seed', not string."); } { // not a string: array @@ -601,9 +546,7 @@ public: auto ret = keypairForSignature(params, error); BEAST_EXPECT(contains_error(error)); BEAST_EXPECT(!ret); - BEAST_EXPECT( - error[jss::error_message] == - "Invalid field 'seed', not string."); + BEAST_EXPECT(error[jss::error_message] == "Invalid field 'seed', not string."); } { // not a seed: empty @@ -652,9 +595,7 @@ public: auto ret = keypairForSignature(params, error); BEAST_EXPECT(contains_error(error)); BEAST_EXPECT(!ret); - BEAST_EXPECT( - error[jss::error_message] == - "Invalid field 'seed_hex', not string."); + BEAST_EXPECT(error[jss::error_message] == "Invalid field 'seed_hex', not string."); } { // not a string: object @@ -666,9 +607,7 @@ public: auto ret = keypairForSignature(params, error); BEAST_EXPECT(contains_error(error)); BEAST_EXPECT(!ret); - BEAST_EXPECT( - error[jss::error_message] == - "Invalid field 'seed_hex', not string."); + BEAST_EXPECT(error[jss::error_message] == "Invalid field 'seed_hex', not string."); } { // not a string: array @@ -680,9 +619,7 @@ public: auto ret = keypairForSignature(params, error); BEAST_EXPECT(contains_error(error)); BEAST_EXPECT(!ret); - BEAST_EXPECT( - error[jss::error_message] == - "Invalid field 'seed_hex', not string."); + BEAST_EXPECT(error[jss::error_message] == "Invalid field 'seed_hex', not string."); } { // empty @@ -725,8 +662,7 @@ public: Json::Value params; Json::Value error; params[jss::key_type] = "secp256k1"; - params[jss::seed_hex] = - "BE6A670A19B209E112146D0A7ED2AAD72567D0FC913"; + params[jss::seed_hex] = "BE6A670A19B209E112146D0A7ED2AAD72567D0FC913"; auto ret = keypairForSignature(params, error); BEAST_EXPECT(contains_error(error)); @@ -767,9 +703,7 @@ public: auto ret = keypairForSignature(params, error); BEAST_EXPECT(contains_error(error)); - BEAST_EXPECT( - error[jss::error_message] == - "Specified seed is for an Ed25519 wallet."); + BEAST_EXPECT(error[jss::error_message] == "Specified seed is for an Ed25519 wallet."); } { @@ -799,60 +733,26 @@ public: auto ret = keypairForSignature(params, error); BEAST_EXPECT(contains_error(error)); - BEAST_EXPECT( - error[jss::error_message] == - "Specified seed is for an Ed25519 wallet."); + BEAST_EXPECT(error[jss::error_message] == "Specified seed is for an Ed25519 wallet."); } }; - test( - "sEdVWZmeUDgQdMEFKTK9kYVX71FKB7o", - "r34XnDB2zS11NZ1wKJzpU1mjWExGVugTaQ"); - test( - "sEd7zJoVnqg1FxB9EuaHC1AB5UPfHWz", - "rDw51qRrBEeMw7Na1Nh79LN7HYZDo7nZFE"); - test( - "sEdSxVntbihdLyabbfttMCqsaaucVR9", - "rwiyBDfAYegXZyaQcN2L1vAbKRYn2wNFMq"); - test( - "sEdSVwJjEXTYCztqDK4JD9WByH3otDX", - "rQJ4hZzNGkLQhLtKPCmu1ywEw1ai2vgUJN"); - test( - "sEdV3jXjKuUoQTSr1Rb4yw8Kyn9r46U", - "rERRw2Pxbau4tevE61V5vZUwD7Rus5Y6vW"); - test( - "sEdVeUZjuYT47Uy51FQCnzivsuWyiwB", - "rszewT5gRjUgWNEmnfMjvVYzJCkhvWY32i"); - test( - "sEd7MHTewdw4tFYeS7rk7XT4qHiA9jH", - "rBB2rvnf4ztwjgNhinFXQJ91nAZjkFgR3p"); - test( - "sEd7A5jFBSdWbNeKGriQvLr1thBScJh", - "rLAXz8Nz7aDivz7PwThsLFqaKrizepNCdA"); - test( - "sEdVPU9M2uyzVNT4Yb5Dn4tUtYjbFAw", - "rHbHRFPCxD5fnn98TBzsQHJ7SsRq7eHkRj"); - test( - "sEdVfF2zhAmS8gfMYzJ4yWBMeR4BZKc", - "r9PsneKHcAE7kUfiTixomM5Mnwi28tCc7h"); - test( - "sEdTjRtcsQkwthDXUSLi9DHNyJcR8GW", - "rM4soF4XS3wZrmLurvE6ZmudG16Lk5Dur5"); - test( - "sEdVNKeu1Lhpfh7Nf6tRDbxnmMyZ4Dv", - "r4ZwJxq6FDtWjapDtCGhjG6mtNm1nWdJcD"); - test( - "sEd7bK4gf5BHJ1WbaEWx8pKMA9MLHpC", - "rD6tnn51m4o1uXeEK9CFrZ3HR7DcFhiYnp"); - test( - "sEd7jCh3ppnQMsLdGcZ6TZayZaHhBLg", - "rTcBkiRQ1EfFQ4FCCwqXNHpn1yUTAACkj"); - test( - "sEdTFJezurQwSJAbkLygj2gQXBut2wh", - "rnXaMacNbRwcJddbbPbqdcpSUQcfzFmrR8"); - test( - "sEdSWajfQAAWFuDvVZF3AiGucReByLt", - "rBJtow6V3GTdsWMamrxetRDwWs6wwTxcKa"); + test("sEdVWZmeUDgQdMEFKTK9kYVX71FKB7o", "r34XnDB2zS11NZ1wKJzpU1mjWExGVugTaQ"); + test("sEd7zJoVnqg1FxB9EuaHC1AB5UPfHWz", "rDw51qRrBEeMw7Na1Nh79LN7HYZDo7nZFE"); + test("sEdSxVntbihdLyabbfttMCqsaaucVR9", "rwiyBDfAYegXZyaQcN2L1vAbKRYn2wNFMq"); + test("sEdSVwJjEXTYCztqDK4JD9WByH3otDX", "rQJ4hZzNGkLQhLtKPCmu1ywEw1ai2vgUJN"); + test("sEdV3jXjKuUoQTSr1Rb4yw8Kyn9r46U", "rERRw2Pxbau4tevE61V5vZUwD7Rus5Y6vW"); + test("sEdVeUZjuYT47Uy51FQCnzivsuWyiwB", "rszewT5gRjUgWNEmnfMjvVYzJCkhvWY32i"); + test("sEd7MHTewdw4tFYeS7rk7XT4qHiA9jH", "rBB2rvnf4ztwjgNhinFXQJ91nAZjkFgR3p"); + test("sEd7A5jFBSdWbNeKGriQvLr1thBScJh", "rLAXz8Nz7aDivz7PwThsLFqaKrizepNCdA"); + test("sEdVPU9M2uyzVNT4Yb5Dn4tUtYjbFAw", "rHbHRFPCxD5fnn98TBzsQHJ7SsRq7eHkRj"); + test("sEdVfF2zhAmS8gfMYzJ4yWBMeR4BZKc", "r9PsneKHcAE7kUfiTixomM5Mnwi28tCc7h"); + test("sEdTjRtcsQkwthDXUSLi9DHNyJcR8GW", "rM4soF4XS3wZrmLurvE6ZmudG16Lk5Dur5"); + test("sEdVNKeu1Lhpfh7Nf6tRDbxnmMyZ4Dv", "r4ZwJxq6FDtWjapDtCGhjG6mtNm1nWdJcD"); + test("sEd7bK4gf5BHJ1WbaEWx8pKMA9MLHpC", "rD6tnn51m4o1uXeEK9CFrZ3HR7DcFhiYnp"); + test("sEd7jCh3ppnQMsLdGcZ6TZayZaHhBLg", "rTcBkiRQ1EfFQ4FCCwqXNHpn1yUTAACkj"); + test("sEdTFJezurQwSJAbkLygj2gQXBut2wh", "rnXaMacNbRwcJddbbPbqdcpSUQcfzFmrR8"); + test("sEdSWajfQAAWFuDvVZF3AiGucReByLt", "rBJtow6V3GTdsWMamrxetRDwWs6wwTxcKa"); } void diff --git a/src/test/rpc/LedgerClosed_test.cpp b/src/test/rpc/LedgerClosed_test.cpp index 2bc5c2b0c9..d6b67ce406 100644 --- a/src/test/rpc/LedgerClosed_test.cpp +++ b/src/test/rpc/LedgerClosed_test.cpp @@ -21,9 +21,7 @@ public: env.fund(XRP(10000), alice); auto lc_result = env.rpc("ledger_closed")[jss::result]; - BEAST_EXPECT( - lc_result[jss::ledger_hash] == - "CCC3B3E88CCAC17F1BE6B4A648A55999411F19E3FE55EB721960EB0DF28EDDA5"); + BEAST_EXPECT(lc_result[jss::ledger_hash] == "CCC3B3E88CCAC17F1BE6B4A648A55999411F19E3FE55EB721960EB0DF28EDDA5"); BEAST_EXPECT(lc_result[jss::ledger_index] == 2); env.close(); @@ -36,9 +34,7 @@ public: BEAST_EXPECT((*ar_alice)[sfBalance] == XRP(10000)); lc_result = env.rpc("ledger_closed")[jss::result]; - BEAST_EXPECT( - lc_result[jss::ledger_hash] == - "0F1A9E0C109ADEF6DA2BDE19217C12BBEC57174CBDBD212B0EBDC1CEDB853185"); + BEAST_EXPECT(lc_result[jss::ledger_hash] == "0F1A9E0C109ADEF6DA2BDE19217C12BBEC57174CBDBD212B0EBDC1CEDB853185"); BEAST_EXPECT(lc_result[jss::ledger_index] == 3); } diff --git a/src/test/rpc/LedgerData_test.cpp b/src/test/rpc/LedgerData_test.cpp index 66be8486b4..0148185276 100644 --- a/src/test/rpc/LedgerData_test.cpp +++ b/src/test/rpc/LedgerData_test.cpp @@ -12,8 +12,7 @@ public: static bool checkMarker(Json::Value const& val) { - return val.isMember(jss::marker) && val[jss::marker].isString() && - val[jss::marker].asString().size() > 0; + return val.isMember(jss::marker) && val[jss::marker].isString() && val[jss::marker].asString().size() > 0; } void @@ -43,11 +42,8 @@ public: jvParams[jss::ledger_index] = "current"; jvParams[jss::binary] = false; { - auto const jrr = env.rpc( - "json", "ledger_data", to_string(jvParams))[jss::result]; - BEAST_EXPECT( - jrr[jss::ledger_current_index].isIntegral() && - jrr[jss::ledger_current_index].asInt() > 0); + auto const jrr = env.rpc("json", "ledger_data", to_string(jvParams))[jss::result]; + BEAST_EXPECT(jrr[jss::ledger_current_index].isIntegral() && jrr[jss::ledger_current_index].asInt() > 0); BEAST_EXPECT(checkMarker(jrr)); BEAST_EXPECT(checkArraySize(jrr[jss::state], max_limit)); } @@ -56,11 +52,8 @@ public: for (auto delta = -1; delta <= 1; delta++) { jvParams[jss::limit] = max_limit + delta; - auto const jrr = env.rpc( - "json", "ledger_data", to_string(jvParams))[jss::result]; - BEAST_EXPECT(checkArraySize( - jrr[jss::state], - (delta > 0 && !asAdmin) ? max_limit : max_limit + delta)); + auto const jrr = env.rpc("json", "ledger_data", to_string(jvParams))[jss::result]; + BEAST_EXPECT(checkArraySize(jrr[jss::state], (delta > 0 && !asAdmin) ? max_limit : max_limit + delta)); } } @@ -86,11 +79,8 @@ public: Json::Value jvParams; jvParams[jss::ledger_index] = "current"; jvParams[jss::binary] = true; - auto const jrr = - env.rpc("json", "ledger_data", to_string(jvParams))[jss::result]; - BEAST_EXPECT( - jrr[jss::ledger_current_index].isIntegral() && - jrr[jss::ledger_current_index].asInt() > 0); + auto const jrr = env.rpc("json", "ledger_data", to_string(jvParams))[jss::result]; + BEAST_EXPECT(jrr[jss::ledger_current_index].isIntegral() && jrr[jss::ledger_current_index].asInt() > 0); BEAST_EXPECT(!jrr.isMember(jss::marker)); BEAST_EXPECT(checkArraySize(jrr[jss::state], num_accounts + 4)); } @@ -111,47 +101,37 @@ public: // bad limit Json::Value jvParams; jvParams[jss::limit] = "0"; // NOT an integer - auto const jrr = env.rpc( - "json", "ledger_data", to_string(jvParams))[jss::result]; + auto const jrr = env.rpc("json", "ledger_data", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); BEAST_EXPECT(jrr[jss::status] == "error"); - BEAST_EXPECT( - jrr[jss::error_message] == - "Invalid field 'limit', not integer."); + BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'limit', not integer."); } { // invalid marker Json::Value jvParams; jvParams[jss::marker] = "NOT_A_MARKER"; - auto const jrr = env.rpc( - "json", "ledger_data", to_string(jvParams))[jss::result]; + auto const jrr = env.rpc("json", "ledger_data", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); BEAST_EXPECT(jrr[jss::status] == "error"); - BEAST_EXPECT( - jrr[jss::error_message] == - "Invalid field 'marker', not valid."); + BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'marker', not valid."); } { // invalid marker - not a string Json::Value jvParams; jvParams[jss::marker] = 1; - auto const jrr = env.rpc( - "json", "ledger_data", to_string(jvParams))[jss::result]; + auto const jrr = env.rpc("json", "ledger_data", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); BEAST_EXPECT(jrr[jss::status] == "error"); - BEAST_EXPECT( - jrr[jss::error_message] == - "Invalid field 'marker', not valid."); + BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'marker', not valid."); } { // ask for a bad ledger index Json::Value jvParams; jvParams[jss::ledger_index] = 10u; - auto const jrr = env.rpc( - "json", "ledger_data", to_string(jvParams))[jss::result]; + auto const jrr = env.rpc("json", "ledger_data", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "lgrNotFound"); BEAST_EXPECT(jrr[jss::status] == "error"); BEAST_EXPECT(jrr[jss::error_message] == "ledgerNotFound"); @@ -180,8 +160,7 @@ public: Json::Value jvParams; jvParams[jss::ledger_index] = "current"; jvParams[jss::binary] = false; - auto jrr = - env.rpc("json", "ledger_data", to_string(jvParams))[jss::result]; + auto jrr = env.rpc("json", "ledger_data", to_string(jvParams))[jss::result]; auto const total_count = jrr[jss::state].size(); // now make request with a limit and loop until we get all @@ -192,8 +171,7 @@ public: while (jrr.isMember(jss::marker)) { jvParams[jss::marker] = jrr[jss::marker]; - jrr = env.rpc( - "json", "ledger_data", to_string(jvParams))[jss::result]; + jrr = env.rpc("json", "ledger_data", to_string(jvParams))[jss::result]; running_total += jrr[jss::state].size(); } BEAST_EXPECT(running_total == total_count); @@ -212,24 +190,19 @@ public: // Closed ledger with non binary form Json::Value jvParams; jvParams[jss::ledger_index] = "closed"; - auto jrr = env.rpc( - "json", "ledger_data", to_string(jvParams))[jss::result]; + auto jrr = env.rpc("json", "ledger_data", to_string(jvParams))[jss::result]; if (BEAST_EXPECT(jrr.isMember(jss::ledger))) - BEAST_EXPECT( - jrr[jss::ledger][jss::ledger_hash] == - to_string(env.closed()->header().hash)); + BEAST_EXPECT(jrr[jss::ledger][jss::ledger_hash] == to_string(env.closed()->header().hash)); } { // Closed ledger with binary form Json::Value jvParams; jvParams[jss::ledger_index] = "closed"; jvParams[jss::binary] = true; - auto jrr = env.rpc( - "json", "ledger_data", to_string(jvParams))[jss::result]; + auto jrr = env.rpc("json", "ledger_data", to_string(jvParams))[jss::result]; if (BEAST_EXPECT(jrr.isMember(jss::ledger))) { - auto data = - strUnHex(jrr[jss::ledger][jss::ledger_data].asString()); + auto data = strUnHex(jrr[jss::ledger][jss::ledger_data].asString()); if (BEAST_EXPECT(data)) { Serializer s(data->data(), data->size()); @@ -243,8 +216,7 @@ public: // Current ledger with binary form Json::Value jvParams; jvParams[jss::binary] = true; - auto jrr = env.rpc( - "json", "ledger_data", to_string(jvParams))[jss::result]; + auto jrr = env.rpc("json", "ledger_data", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr.isMember(jss::ledger)); BEAST_EXPECT(!jrr[jss::ledger].isMember(jss::ledger_data)); } @@ -258,8 +230,7 @@ public: // Make sure fixInnerObjTemplate2 doesn't break amendments. for (FeatureBitset const& features : - {testable_amendments() - fixInnerObjTemplate2, - testable_amendments() | fixInnerObjTemplate2}) + {testable_amendments() - fixInnerObjTemplate2, testable_amendments() | fixInnerObjTemplate2}) { using namespace std::chrono; Env env{*this, envconfig(validator, ""), features}; @@ -272,8 +243,7 @@ public: Json::Value jvParams; jvParams[jss::ledger_index] = "current"; jvParams[jss::type] = type; - return env.rpc( - "json", "ledger_data", to_string(jvParams))[jss::result]; + return env.rpc("json", "ledger_data", to_string(jvParams))[jss::result]; }; // Assert that state is an empty array. @@ -312,10 +282,7 @@ public: break; } - env(signers( - Account{"bob0"}, - 1, - {{Account{"bob1"}, 1}, {Account{"bob2"}, 1}})); + env(signers(Account{"bob0"}, 1, {{Account{"bob1"}, 1}, {Account{"bob2"}, 1}})); env(ticket::create(env.master, 1)); { @@ -324,10 +291,7 @@ public: jv[jss::Account] = Account{"bob5"}.human(); jv[jss::Destination] = Account{"bob6"}.human(); jv[jss::Amount] = XRP(50).value().getJson(JsonOptions::none); - jv[sfFinishAfter.fieldName] = - NetClock::time_point{env.now() + 10s} - .time_since_epoch() - .count(); + jv[sfFinishAfter.fieldName] = NetClock::time_point{env.now() + 10s}.time_since_epoch().count(); env(jv); } @@ -338,12 +302,8 @@ public: jv[jss::Destination] = Account{"bob7"}.human(); jv[jss::Amount] = XRP(100).value().getJson(JsonOptions::none); jv[jss::SettleDelay] = NetClock::duration{10s}.count(); - jv[sfPublicKey.fieldName] = - strHex(Account{"bob6"}.pk().slice()); - jv[sfCancelAfter.fieldName] = - NetClock::time_point{env.now() + 300s} - .time_since_epoch() - .count(); + jv[sfPublicKey.fieldName] = strHex(Account{"bob6"}.pk().slice()); + jv[sfCancelAfter.fieldName] = NetClock::time_point{env.now() + 300s}.time_since_epoch().count(); env(jv); } @@ -451,8 +411,7 @@ public: Json::Value jvParams; jvParams[jss::ledger_index] = "current"; jvParams[jss::type] = "misspelling"; - auto const jrr = env.rpc( - "json", "ledger_data", to_string(jvParams))[jss::result]; + auto const jrr = env.rpc("json", "ledger_data", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr.isMember("error")); BEAST_EXPECT(jrr["error"] == "invalidParams"); BEAST_EXPECT(jrr["error_message"] == "Invalid field 'type'."); diff --git a/src/test/rpc/LedgerEntry_test.cpp b/src/test/rpc/LedgerEntry_test.cpp index 551e67dc5e..5d12e7bb83 100644 --- a/src/test/rpc/LedgerEntry_test.cpp +++ b/src/test/rpc/LedgerEntry_test.cpp @@ -5,6 +5,8 @@ #include #include +#include + #include #include #include @@ -12,13 +14,7 @@ #include #include -#if (defined(__clang_major__) && __clang_major__ < 15) -#include -using source_location = std::experimental::source_location; -#else #include -using std::source_location; -#endif namespace xrpl { namespace test { @@ -30,6 +26,7 @@ enum class FieldType { CurrencyField, HashField, HashOrObjectField, + FixedHashField, IssueField, ObjectField, StringField, @@ -58,17 +55,14 @@ std::vector> mappings{ FieldType getFieldType(Json::StaticString fieldName) { - auto it = std::ranges::find_if(mappings, [&fieldName](auto const& pair) { - return pair.first == fieldName; - }); + auto it = std::ranges::find_if(mappings, [&fieldName](auto const& pair) { return pair.first == fieldName; }); if (it != mappings.end()) { return it->second; } else { - Throw( - "`mappings` is missing field " + std::string(fieldName.c_str())); + Throw("`mappings` is missing field " + std::string(fieldName.c_str())); } } @@ -86,6 +80,7 @@ getTypeName(FieldType typeID) case FieldType::CurrencyField: return "Currency"; case FieldType::HashField: + case FieldType::FixedHashField: return "hex string"; case FieldType::HashOrObjectField: return "hex string or object"; @@ -98,8 +93,7 @@ getTypeName(FieldType typeID) case FieldType::UInt64Field: return "number"; default: - Throw( - "unknown type " + std::to_string(static_cast(typeID))); + Throw("unknown type " + std::to_string(static_cast(typeID))); } } @@ -110,35 +104,27 @@ class LedgerEntry_test : public beast::unit_test::suite Json::Value const& jv, std::string const& err, std::string const& msg, - source_location const location = source_location::current()) + std::source_location const location = std::source_location::current()) { if (BEAST_EXPECT(jv.isMember(jss::status))) - BEAST_EXPECTS( - jv[jss::status] == "error", std::to_string(location.line())); + BEAST_EXPECTS(jv[jss::status] == "error", std::to_string(location.line())); if (BEAST_EXPECT(jv.isMember(jss::error))) BEAST_EXPECTS( jv[jss::error] == err, - "Expected error " + err + ", received " + - jv[jss::error].asString() + ", at line " + - std::to_string(location.line()) + ", " + - jv.toStyledString()); + "Expected error " + err + ", received " + jv[jss::error].asString() + ", at line " + + std::to_string(location.line()) + ", " + jv.toStyledString()); if (msg.empty()) { BEAST_EXPECTS( - jv[jss::error_message] == Json::nullValue || - jv[jss::error_message] == "", - "Expected no error message, received \"" + - jv[jss::error_message].asString() + "\", at line " + - std::to_string(location.line()) + ", " + - jv.toStyledString()); + jv[jss::error_message] == Json::nullValue || jv[jss::error_message] == "", + "Expected no error message, received \"" + jv[jss::error_message].asString() + "\", at line " + + std::to_string(location.line()) + ", " + jv.toStyledString()); } else if (BEAST_EXPECT(jv.isMember(jss::error_message))) BEAST_EXPECTS( jv[jss::error_message] == msg, - "Expected error message \"" + msg + "\", received \"" + - jv[jss::error_message].asString() + "\", at line " + - std::to_string(location.line()) + ", " + - jv.toStyledString()); + "Expected error message \"" + msg + "\", received \"" + jv[jss::error_message].asString() + + "\", at line " + std::to_string(location.line()) + ", " + jv.toStyledString()); } std::vector @@ -181,10 +167,8 @@ class LedgerEntry_test : public beast::unit_test::suite injectArray // 20 }; - auto remove = - [&](std::vector indices) -> std::vector { - std::unordered_set indexSet( - indices.begin(), indices.end()); + auto remove = [&](std::vector indices) -> std::vector { + std::unordered_set indexSet(indices.begin(), indices.end()); std::vector values; values.reserve(allBadValues.size() - indexSet.size()); for (std::size_t i = 0; i < allBadValues.size(); ++i) @@ -202,6 +186,7 @@ class LedgerEntry_test : public beast::unit_test::suite static auto const& badBlobValues = remove({3, 7, 8, 16}); static auto const& badCurrencyValues = remove({14}); static auto const& badHashValues = remove({2, 3, 7, 8, 16}); + static auto const& badFixedHashValues = remove({1, 2, 3, 4, 7, 8, 16}); static auto const& badIndexValues = remove({12, 16, 18, 19}); static auto const& badUInt32Values = remove({2, 3}); static auto const& badUInt64Values = remove({2, 3}); @@ -222,6 +207,8 @@ class LedgerEntry_test : public beast::unit_test::suite return badHashValues; case FieldType::HashOrObjectField: return badIndexValues; + case FieldType::FixedHashField: + return badFixedHashValues; case FieldType::IssueField: return badIssueValues; case FieldType::UInt32Field: @@ -229,9 +216,7 @@ class LedgerEntry_test : public beast::unit_test::suite case FieldType::UInt64Field: return badUInt64Values; default: - Throw( - "unknown type " + - std::to_string(static_cast(fieldType))); + Throw("unknown type " + std::to_string(static_cast(fieldType))); } } @@ -276,9 +261,7 @@ class LedgerEntry_test : public beast::unit_test::suite case FieldType::UInt64Field: return 1; default: - Throw( - "unknown type " + - std::to_string(static_cast(typeID))); + Throw("unknown type " + std::to_string(static_cast(typeID))); } } @@ -290,35 +273,24 @@ class LedgerEntry_test : public beast::unit_test::suite FieldType const typeID, std::string const& expectedError, bool required = true, - source_location const location = source_location::current()) + std::source_location const location = std::source_location::current()) { forAllApiVersions([&, this](unsigned apiVersion) { if (required) { correctRequest.removeMember(fieldName); - Json::Value const jrr = env.rpc( - apiVersion, - "json", - "ledger_entry", - to_string(correctRequest))[jss::result]; + Json::Value const jrr = + env.rpc(apiVersion, "json", "ledger_entry", to_string(correctRequest))[jss::result]; if (apiVersion < 2u) checkErrorValue(jrr, "unknownOption", "", location); else - checkErrorValue( - jrr, - "invalidParams", - "No ledger_entry params provided.", - location); + checkErrorValue(jrr, "invalidParams", "No ledger_entry params provided.", location); } auto tryField = [&](Json::Value fieldValue) -> void { correctRequest[fieldName] = fieldValue; - Json::Value const jrr = env.rpc( - apiVersion, - "json", - "ledger_entry", - to_string(correctRequest))[jss::result]; - auto const expectedErrMsg = - RPC::expected_field_message(fieldName, getTypeName(typeID)); + Json::Value const jrr = + env.rpc(apiVersion, "json", "ledger_entry", to_string(correctRequest))[jss::result]; + auto const expectedErrMsg = RPC::expected_field_message(fieldName, getTypeName(typeID)); checkErrorValue(jrr, expectedError, expectedErrMsg, location); }; @@ -343,48 +315,28 @@ class LedgerEntry_test : public beast::unit_test::suite FieldType typeID, std::string const& expectedError, bool required = true, - source_location const location = source_location::current()) + std::source_location const location = std::source_location::current()) { forAllApiVersions([&, this](unsigned apiVersion) { if (required) { correctRequest[parentFieldName].removeMember(fieldName); - Json::Value const jrr = env.rpc( - apiVersion, - "json", - "ledger_entry", - to_string(correctRequest))[jss::result]; - checkErrorValue( - jrr, - "malformedRequest", - RPC::missing_field_message(fieldName.c_str()), - location); + Json::Value const jrr = + env.rpc(apiVersion, "json", "ledger_entry", to_string(correctRequest))[jss::result]; + checkErrorValue(jrr, "malformedRequest", RPC::missing_field_message(fieldName.c_str()), location); correctRequest[parentFieldName][fieldName] = Json::nullValue; - Json::Value const jrr2 = env.rpc( - apiVersion, - "json", - "ledger_entry", - to_string(correctRequest))[jss::result]; - checkErrorValue( - jrr2, - "malformedRequest", - RPC::missing_field_message(fieldName.c_str()), - location); + Json::Value const jrr2 = + env.rpc(apiVersion, "json", "ledger_entry", to_string(correctRequest))[jss::result]; + checkErrorValue(jrr2, "malformedRequest", RPC::missing_field_message(fieldName.c_str()), location); } auto tryField = [&](Json::Value fieldValue) -> void { correctRequest[parentFieldName][fieldName] = fieldValue; - Json::Value const jrr = env.rpc( - apiVersion, - "json", - "ledger_entry", - to_string(correctRequest))[jss::result]; + Json::Value const jrr = + env.rpc(apiVersion, "json", "ledger_entry", to_string(correctRequest))[jss::result]; checkErrorValue( - jrr, - expectedError, - RPC::expected_field_message(fieldName, getTypeName(typeID)), - location); + jrr, expectedError, RPC::expected_field_message(fieldName, getTypeName(typeID)), location); }; auto const& badValues = getBadValues(typeID); @@ -400,16 +352,9 @@ class LedgerEntry_test : public beast::unit_test::suite runLedgerEntryTest( test::jtx::Env& env, Json::StaticString const& parentField, - source_location const location = source_location::current()) + std::source_location const location = std::source_location::current()) { - testMalformedField( - env, - Json::Value{}, - parentField, - FieldType::HashField, - "malformedRequest", - true, - location); + testMalformedField(env, Json::Value{}, parentField, FieldType::HashField, "malformedRequest", true, location); } struct Subfield @@ -424,23 +369,16 @@ class LedgerEntry_test : public beast::unit_test::suite test::jtx::Env& env, Json::StaticString const& parentField, std::vector const& subfields, - source_location const location = source_location::current()) + std::source_location const location = std::source_location::current()) { testMalformedField( - env, - Json::Value{}, - parentField, - FieldType::HashOrObjectField, - "malformedRequest", - true, - location); + env, Json::Value{}, parentField, FieldType::HashOrObjectField, "malformedRequest", true, location); Json::Value correctOutput; correctOutput[parentField] = Json::objectValue; for (auto const& subfield : subfields) { - correctOutput[parentField][subfield.fieldName] = - getCorrectValue(subfield.fieldName); + correctOutput[parentField][subfield.fieldName] = getCorrectValue(subfield.fieldName); } for (auto const& subfield : subfields) @@ -474,8 +412,7 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[jss::ledger_hash] = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" "AA"; - auto const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; + auto const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; checkErrorValue(jrr, "lgrNotFound", "ledgerNotFound"); } { @@ -487,15 +424,9 @@ class LedgerEntry_test : public beast::unit_test::suite forAllApiVersions([&, this](unsigned apiVersion) { auto tryField = [&](Json::Value fieldValue) -> void { jvParams[jss::ledger_hash] = fieldValue; - Json::Value const jrr = env.rpc( - apiVersion, - "json", - "ledger_entry", - to_string(jvParams))[jss::result]; - checkErrorValue( - jrr, - "invalidParams", - "Invalid field 'ledger_hash', not hex string."); + Json::Value const jrr = + env.rpc(apiVersion, "json", "ledger_entry", to_string(jvParams))[jss::result]; + checkErrorValue(jrr, "invalidParams", "Invalid field 'ledger_hash', not hex string."); }; auto const& badValues = getBadValues(typeId); @@ -513,8 +444,7 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[jss::index] = "00000000000000000000000000000000000000000000000000000000000000" "00"; - auto const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; + auto const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; checkErrorValue(jrr, "entryNotFound", "Entry not found."); } @@ -526,16 +456,12 @@ class LedgerEntry_test : public beast::unit_test::suite "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" "AAAAAAAAAA"; jvParams[jss::api_version] = apiVersion; - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; if (apiVersion < 2u) checkErrorValue(jrr, "unknownOption", ""); else - checkErrorValue( - jrr, - "invalidParams", - "No ledger_entry params provided."); + checkErrorValue(jrr, "invalidParams", "No ledger_entry params provided."); } }); } @@ -568,15 +494,14 @@ class LedgerEntry_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::account_root] = alice.human(); jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr.isMember(jss::node)); BEAST_EXPECT(jrr[jss::node][jss::Account] == alice.human()); BEAST_EXPECT(jrr[jss::node][sfBalance.jsonName] == "10000000000"); accountRootIndex = jrr[jss::index].asString(); } { - constexpr char alicesAcctRootBinary[]{ + constexpr char aliceAcctRootBinary[]{ "1100612200800000240000000425000000032D00000000559CE54C3B934E4" "73A995B477E92EC229F99CED5B62BF4D2ACE4DC42719103AE2F6240000002" "540BE4008114AE123A8556F3CF91154711376AFB0F894F832B3D"}; @@ -586,17 +511,15 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[jss::account_root] = alice.human(); jvParams[jss::binary] = 1; jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr.isMember(jss::node_binary)); - BEAST_EXPECT(jrr[jss::node_binary] == alicesAcctRootBinary); + BEAST_EXPECT(jrr[jss::node_binary] == aliceAcctRootBinary); } { // Request alice's account root using the index. Json::Value jvParams; jvParams[jss::index] = accountRootIndex; - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(!jrr.isMember(jss::node_binary)); BEAST_EXPECT(jrr.isMember(jss::node)); BEAST_EXPECT(jrr[jss::node][jss::Account] == alice.human()); @@ -607,8 +530,7 @@ class LedgerEntry_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::index] = accountRootIndex; jvParams[jss::binary] = 0; - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr.isMember(jss::node)); BEAST_EXPECT(jrr[jss::node][jss::Account] == alice.human()); BEAST_EXPECT(jrr[jss::node][sfBalance.jsonName] == "10000000000"); @@ -618,8 +540,7 @@ class LedgerEntry_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::account] = alice.human(); jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr.isMember(jss::node)); BEAST_EXPECT(jrr[jss::node][jss::Account] == alice.human()); BEAST_EXPECT(jrr[jss::node][sfBalance.jsonName] == "10000000000"); @@ -628,20 +549,14 @@ class LedgerEntry_test : public beast::unit_test::suite { // Check malformed cases Json::Value jvParams; - testMalformedField( - env, - jvParams, - jss::account_root, - FieldType::AccountField, - "malformedAddress"); + testMalformedField(env, jvParams, jss::account_root, FieldType::AccountField, "malformedAddress"); } { // Request an account that is not in the ledger. Json::Value jvParams; jvParams[jss::account_root] = Account("bob").human(); jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; checkErrorValue(jrr, "entryNotFound", "Entry not found."); } } @@ -660,8 +575,7 @@ class LedgerEntry_test : public beast::unit_test::suite // easier to hack an object into the ledger than generate it // legitimately { - auto const amendments = [&](OpenView& view, - beast::Journal) -> bool { + auto const amendments = [&](OpenView& view, beast::Journal) -> bool { auto const sle = std::make_shared(keylet); // Create Amendments vector (enabled amendments) @@ -678,8 +592,7 @@ class LedgerEntry_test : public beast::unit_test::suite enabledAmendments.push_back( uint256::fromVoid("35291ADD2D79EB6991343BDA0912269C817D" "0F094B02226C1C14AD2858962ED4")); - sle->setFieldV256( - sfAmendments, STVector256(enabledAmendments)); + sle->setFieldV256(sfAmendments, STVector256(enabledAmendments)); // Create Majorities array STArray majorities; @@ -710,14 +623,12 @@ class LedgerEntry_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::amendments] = to_string(keylet.key); - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; - BEAST_EXPECT( - jrr[jss::node][sfLedgerEntryType.jsonName] == jss::Amendments); + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + BEAST_EXPECT(jrr[jss::node][sfLedgerEntryType.jsonName] == jss::Amendments); } // negative tests - runLedgerEntryTest(env, jss::amendments); + testMalformedField(env, Json::Value{}, jss::amendments, FieldType::FixedHashField, "malformedRequest"); } void @@ -737,16 +648,12 @@ class LedgerEntry_test : public beast::unit_test::suite { Json::Value jvParams; jvParams[jss::amm] = to_string(amm.ammID()); - auto const result = - env.rpc("json", "ledger_entry", to_string(jvParams)); + auto const result = env.rpc("json", "ledger_entry", to_string(jvParams)); BEAST_EXPECT( - result.isObject() && result.isMember(jss::result) && - !result[jss::result].isMember(jss::error) && + result.isObject() && result.isMember(jss::result) && !result[jss::result].isMember(jss::error) && result[jss::result].isMember(jss::node) && - result[jss::result][jss::node].isMember( - sfLedgerEntryType.jsonName) && - result[jss::result][jss::node][sfLedgerEntryType.jsonName] == - jss::AMM); + result[jss::result][jss::node].isMember(sfLedgerEntryType.jsonName) && + result[jss::result][jss::node][sfLedgerEntryType.jsonName] == jss::AMM); } { @@ -764,16 +671,12 @@ class LedgerEntry_test : public beast::unit_test::suite ammParams[jss::asset2] = obj; } jvParams[jss::amm] = ammParams; - auto const result = - env.rpc("json", "ledger_entry", to_string(jvParams)); + auto const result = env.rpc("json", "ledger_entry", to_string(jvParams)); BEAST_EXPECT( - result.isObject() && result.isMember(jss::result) && - !result[jss::result].isMember(jss::error) && + result.isObject() && result.isMember(jss::result) && !result[jss::result].isMember(jss::error) && result[jss::result].isMember(jss::node) && - result[jss::result][jss::node].isMember( - sfLedgerEntryType.jsonName) && - result[jss::result][jss::node][sfLedgerEntryType.jsonName] == - jss::AMM); + result[jss::result][jss::node].isMember(sfLedgerEntryType.jsonName) && + result[jss::result][jss::node][sfLedgerEntryType.jsonName] == jss::AMM); } // negative tests @@ -807,10 +710,8 @@ class LedgerEntry_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::check] = to_string(checkId.key); jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; - BEAST_EXPECT( - jrr[jss::node][sfLedgerEntryType.jsonName] == jss::Check); + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + BEAST_EXPECT(jrr[jss::node][sfLedgerEntryType.jsonName] == jss::Check); BEAST_EXPECT(jrr[jss::node][sfSendMax.jsonName] == "100000000"); } { @@ -820,17 +721,14 @@ class LedgerEntry_test : public beast::unit_test::suite { Json::Value jvParams; jvParams[jss::account_root] = alice.human(); - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; accountRootIndex = jrr[jss::index].asString(); } Json::Value jvParams; jvParams[jss::check] = accountRootIndex; jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; - checkErrorValue( - jrr, "unexpectedLedgerType", "Unexpected ledger type."); + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + checkErrorValue(jrr, "unexpectedLedgerType", "Unexpected ledger type."); } { // Check malformed cases @@ -862,25 +760,19 @@ class LedgerEntry_test : public beast::unit_test::suite // Succeed auto jv = credentials::ledgerEntry(env, alice, issuer, credType); BEAST_EXPECT( - jv.isObject() && jv.isMember(jss::result) && - !jv[jss::result].isMember(jss::error) && + jv.isObject() && jv.isMember(jss::result) && !jv[jss::result].isMember(jss::error) && jv[jss::result].isMember(jss::node) && - jv[jss::result][jss::node].isMember( - sfLedgerEntryType.jsonName) && - jv[jss::result][jss::node][sfLedgerEntryType.jsonName] == - jss::Credential); + jv[jss::result][jss::node].isMember(sfLedgerEntryType.jsonName) && + jv[jss::result][jss::node][sfLedgerEntryType.jsonName] == jss::Credential); std::string const credIdx = jv[jss::result][jss::index].asString(); jv = credentials::ledgerEntry(env, credIdx); BEAST_EXPECT( - jv.isObject() && jv.isMember(jss::result) && - !jv[jss::result].isMember(jss::error) && + jv.isObject() && jv.isMember(jss::result) && !jv[jss::result].isMember(jss::error) && jv[jss::result].isMember(jss::node) && - jv[jss::result][jss::node].isMember( - sfLedgerEntryType.jsonName) && - jv[jss::result][jss::node][sfLedgerEntryType.jsonName] == - jss::Credential); + jv[jss::result][jss::node].isMember(sfLedgerEntryType.jsonName) && + jv[jss::result][jss::node][sfLedgerEntryType.jsonName] == jss::Credential); } { @@ -889,8 +781,7 @@ class LedgerEntry_test : public beast::unit_test::suite env, "48004829F915654A81B11C4AB8218D96FED67F209B58328A72314FB6EA288B" "E4"); - checkErrorValue( - jv[jss::result], "entryNotFound", "Entry not found."); + checkErrorValue(jv[jss::result], "entryNotFound", "Entry not found."); } { @@ -928,10 +819,8 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[jss::delegate][jss::account] = alice.human(); jvParams[jss::delegate][jss::authorize] = bob.human(); jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; - BEAST_EXPECT( - jrr[jss::node][sfLedgerEntryType.jsonName] == jss::Delegate); + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + BEAST_EXPECT(jrr[jss::node][sfLedgerEntryType.jsonName] == jss::Delegate); BEAST_EXPECT(jrr[jss::node][sfAccount.jsonName] == alice.human()); BEAST_EXPECT(jrr[jss::node][sfAuthorize.jsonName] == bob.human()); delegateIndex = jrr[jss::node][jss::index].asString(); @@ -941,10 +830,8 @@ class LedgerEntry_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::delegate] = delegateIndex; jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; - BEAST_EXPECT( - jrr[jss::node][sfLedgerEntryType.jsonName] == jss::Delegate); + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + BEAST_EXPECT(jrr[jss::node][sfLedgerEntryType.jsonName] == jss::Delegate); BEAST_EXPECT(jrr[jss::node][sfAccount.jsonName] == alice.human()); BEAST_EXPECT(jrr[jss::node][sfAuthorize.jsonName] == bob.human()); } @@ -986,12 +873,9 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[jss::deposit_preauth][jss::owner] = alice.human(); jvParams[jss::deposit_preauth][jss::authorized] = becky.human(); jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; - BEAST_EXPECT( - jrr[jss::node][sfLedgerEntryType.jsonName] == - jss::DepositPreauth); + BEAST_EXPECT(jrr[jss::node][sfLedgerEntryType.jsonName] == jss::DepositPreauth); BEAST_EXPECT(jrr[jss::node][sfAccount.jsonName] == alice.human()); BEAST_EXPECT(jrr[jss::node][sfAuthorize.jsonName] == becky.human()); depositPreauthIndex = jrr[jss::node][jss::index].asString(); @@ -1001,12 +885,9 @@ class LedgerEntry_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::deposit_preauth] = depositPreauthIndex; jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; - BEAST_EXPECT( - jrr[jss::node][sfLedgerEntryType.jsonName] == - jss::DepositPreauth); + BEAST_EXPECT(jrr[jss::node][sfLedgerEntryType.jsonName] == jss::DepositPreauth); BEAST_EXPECT(jrr[jss::node][sfAccount.jsonName] == alice.human()); BEAST_EXPECT(jrr[jss::node][sfAuthorize.jsonName] == becky.human()); } @@ -1052,26 +933,20 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[jss::ledger_index] = jss::validated; jvParams[jss::deposit_preauth][jss::owner] = bob.human(); - jvParams[jss::deposit_preauth][jss::authorized_credentials] = - Json::arrayValue; - auto& arr( - jvParams[jss::deposit_preauth][jss::authorized_credentials]); + jvParams[jss::deposit_preauth][jss::authorized_credentials] = Json::arrayValue; + auto& arr(jvParams[jss::deposit_preauth][jss::authorized_credentials]); Json::Value jo; jo[jss::issuer] = issuer.human(); jo[jss::credential_type] = strHex(std::string_view(credType)); arr.append(std::move(jo)); - auto const jrr = - env.rpc("json", "ledger_entry", to_string(jvParams)); + auto const jrr = env.rpc("json", "ledger_entry", to_string(jvParams)); BEAST_EXPECT( - jrr.isObject() && jrr.isMember(jss::result) && - !jrr[jss::result].isMember(jss::error) && + jrr.isObject() && jrr.isMember(jss::result) && !jrr[jss::result].isMember(jss::error) && jrr[jss::result].isMember(jss::node) && - jrr[jss::result][jss::node].isMember( - sfLedgerEntryType.jsonName) && - jrr[jss::result][jss::node][sfLedgerEntryType.jsonName] == - jss::DepositPreauth); + jrr[jss::result][jss::node].isMember(sfLedgerEntryType.jsonName) && + jrr[jss::result][jss::node][sfLedgerEntryType.jsonName] == jss::DepositPreauth); } { @@ -1086,16 +961,12 @@ class LedgerEntry_test : public beast::unit_test::suite jo[jss::issuer] = fieldValue; jo[jss::credential_type] = strHex(std::string_view(credType)); arr.append(jo); - jvParams[jss::deposit_preauth][jss::authorized_credentials] = - arr; + jvParams[jss::deposit_preauth][jss::authorized_credentials] = arr; - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; - auto const expectedErrMsg = fieldValue.isNull() - ? RPC::missing_field_message(jss::issuer.c_str()) - : RPC::expected_field_message(jss::issuer, "AccountID"); - checkErrorValue( - jrr, "malformedAuthorizedCredentials", expectedErrMsg); + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + auto const expectedErrMsg = fieldValue.isNull() ? RPC::missing_field_message(jss::issuer.c_str()) + : RPC::expected_field_message(jss::issuer, "AccountID"); + checkErrorValue(jrr, "malformedAuthorizedCredentials", expectedErrMsg); }; auto const& badValues = getBadValues(FieldType::AccountField); @@ -1112,23 +983,19 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[jss::ledger_index] = jss::validated; jvParams[jss::deposit_preauth][jss::owner] = bob.human(); - jvParams[jss::deposit_preauth][jss::authorized_credentials] = - Json::arrayValue; - auto& arr( - jvParams[jss::deposit_preauth][jss::authorized_credentials]); + jvParams[jss::deposit_preauth][jss::authorized_credentials] = Json::arrayValue; + auto& arr(jvParams[jss::deposit_preauth][jss::authorized_credentials]); Json::Value jo; jo[jss::issuer] = issuer.human(); jo[jss::credential_type] = strHex(std::string_view(credType)); arr.append(jo); arr.append(std::move(jo)); - auto const jrr = - env.rpc("json", "ledger_entry", to_string(jvParams)); + auto const jrr = env.rpc("json", "ledger_entry", to_string(jvParams)); checkErrorValue( jrr[jss::result], "malformedAuthorizedCredentials", - RPC::expected_field_message( - jss::authorized_credentials, "array")); + RPC::expected_field_message(jss::authorized_credentials, "array")); } { @@ -1143,17 +1010,13 @@ class LedgerEntry_test : public beast::unit_test::suite jo[jss::issuer] = issuer.human(); jo[jss::credential_type] = fieldValue; arr.append(jo); - jvParams[jss::deposit_preauth][jss::authorized_credentials] = - arr; + jvParams[jss::deposit_preauth][jss::authorized_credentials] = arr; - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; auto const expectedErrMsg = fieldValue.isNull() ? RPC::missing_field_message(jss::credential_type.c_str()) - : RPC::expected_field_message( - jss::credential_type, "hex string"); - checkErrorValue( - jrr, "malformedAuthorizedCredentials", expectedErrMsg); + : RPC::expected_field_message(jss::credential_type, "hex string"); + checkErrorValue(jrr, "malformedAuthorizedCredentials", expectedErrMsg); }; auto const& badValues = getBadValues(FieldType::BlobField); @@ -1171,18 +1034,15 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[jss::deposit_preauth][jss::owner] = bob.human(); jvParams[jss::deposit_preauth][jss::authorized] = alice.human(); - jvParams[jss::deposit_preauth][jss::authorized_credentials] = - Json::arrayValue; - auto& arr( - jvParams[jss::deposit_preauth][jss::authorized_credentials]); + jvParams[jss::deposit_preauth][jss::authorized_credentials] = Json::arrayValue; + auto& arr(jvParams[jss::deposit_preauth][jss::authorized_credentials]); Json::Value jo; jo[jss::issuer] = issuer.human(); jo[jss::credential_type] = strHex(std::string_view(credType)); arr.append(std::move(jo)); - auto const jrr = - env.rpc("json", "ledger_entry", to_string(jvParams)); + auto const jrr = env.rpc("json", "ledger_entry", to_string(jvParams)); checkErrorValue( jrr[jss::result], "malformedRequest", @@ -1210,14 +1070,11 @@ class LedgerEntry_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::ledger_index] = jss::validated; jvParams[jss::deposit_preauth][jss::owner] = bob.human(); - jvParams[jss::deposit_preauth][jss::authorized_credentials] = - Json::arrayValue; - auto& arr( - jvParams[jss::deposit_preauth][jss::authorized_credentials]); + jvParams[jss::deposit_preauth][jss::authorized_credentials] = Json::arrayValue; + auto& arr(jvParams[jss::deposit_preauth][jss::authorized_credentials]); arr.append("foobar"); - auto const jrr = - env.rpc("json", "ledger_entry", to_string(jvParams)); + auto const jrr = env.rpc("json", "ledger_entry", to_string(jvParams)); checkErrorValue( jrr[jss::result], "malformedAuthorizedCredentials", @@ -1229,16 +1086,13 @@ class LedgerEntry_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::ledger_index] = jss::validated; jvParams[jss::deposit_preauth][jss::owner] = bob.human(); - jvParams[jss::deposit_preauth][jss::authorized_credentials] = - Json::arrayValue; - auto& arr( - jvParams[jss::deposit_preauth][jss::authorized_credentials]); + jvParams[jss::deposit_preauth][jss::authorized_credentials] = Json::arrayValue; + auto& arr(jvParams[jss::deposit_preauth][jss::authorized_credentials]); Json::Value payload = Json::arrayValue; payload.append(42); arr.append(std::move(payload)); - auto const jrr = - env.rpc("json", "ledger_entry", to_string(jvParams)); + auto const jrr = env.rpc("json", "ledger_entry", to_string(jvParams)); checkErrorValue( jrr[jss::result], "malformedAuthorizedCredentials", @@ -1250,11 +1104,9 @@ class LedgerEntry_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::ledger_index] = jss::validated; jvParams[jss::deposit_preauth][jss::owner] = bob.human(); - jvParams[jss::deposit_preauth][jss::authorized_credentials] = - Json::arrayValue; + jvParams[jss::deposit_preauth][jss::authorized_credentials] = Json::arrayValue; - auto const jrr = - env.rpc("json", "ledger_entry", to_string(jvParams)); + auto const jrr = env.rpc("json", "ledger_entry", to_string(jvParams)); checkErrorValue( jrr[jss::result], "malformedAuthorizedCredentials", @@ -1264,27 +1116,15 @@ class LedgerEntry_test : public beast::unit_test::suite { // Failed, authorized_credentials is too long static std::array const credTypes = { - "cred1", - "cred2", - "cred3", - "cred4", - "cred5", - "cred6", - "cred7", - "cred8", - "cred9"}; - static_assert( - sizeof(credTypes) / sizeof(credTypes[0]) > - maxCredentialsArraySize); + "cred1", "cred2", "cred3", "cred4", "cred5", "cred6", "cred7", "cred8", "cred9"}; + static_assert(sizeof(credTypes) / sizeof(credTypes[0]) > maxCredentialsArraySize); Json::Value jvParams; jvParams[jss::ledger_index] = jss::validated; jvParams[jss::deposit_preauth][jss::owner] = bob.human(); - jvParams[jss::deposit_preauth][jss::authorized_credentials] = - Json::arrayValue; + jvParams[jss::deposit_preauth][jss::authorized_credentials] = Json::arrayValue; - auto& arr( - jvParams[jss::deposit_preauth][jss::authorized_credentials]); + auto& arr(jvParams[jss::deposit_preauth][jss::authorized_credentials]); for (auto cred : credTypes) { @@ -1294,8 +1134,7 @@ class LedgerEntry_test : public beast::unit_test::suite arr.append(std::move(jo)); } - auto const jrr = - env.rpc("json", "ledger_entry", to_string(jvParams)); + auto const jrr = env.rpc("json", "ledger_entry", to_string(jvParams)); checkErrorValue( jrr[jss::result], "malformedAuthorizedCredentials", @@ -1334,15 +1173,13 @@ class LedgerEntry_test : public beast::unit_test::suite BEAST_EXPECT(jrr[jss::ledger_index] == 5); } - std::string const dirRootIndex = - "A33EC6BB85FB5674074C4A3A43373BB17645308F3EAE1933E3E35252162B217D"; + std::string const dirRootIndex = "A33EC6BB85FB5674074C4A3A43373BB17645308F3EAE1933E3E35252162B217D"; { // Locate directory by index. Json::Value jvParams; jvParams[jss::directory] = dirRootIndex; jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::node][sfIndexes.jsonName].size() == 32); } { @@ -1350,8 +1187,7 @@ class LedgerEntry_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::directory] = Json::objectValue; jvParams[jss::directory][jss::dir_root] = dirRootIndex; - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::index] == dirRootIndex); } { @@ -1360,8 +1196,7 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[jss::directory] = Json::objectValue; jvParams[jss::directory][jss::owner] = alice.human(); jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::index] == dirRootIndex); } { @@ -1370,8 +1205,7 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[jss::directory] = Json::objectValue; jvParams[jss::directory][jss::dir_root] = dirRootIndex; jvParams[jss::directory][jss::sub_index] = 1; - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::index] != dirRootIndex); BEAST_EXPECT(jrr[jss::node][sfIndexes.jsonName].size() == 2); } @@ -1382,8 +1216,7 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[jss::directory][jss::owner] = alice.human(); jvParams[jss::directory][jss::sub_index] = 1; jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::index] != dirRootIndex); BEAST_EXPECT(jrr[jss::node][sfIndexes.jsonName].size() == 2); } @@ -1391,12 +1224,7 @@ class LedgerEntry_test : public beast::unit_test::suite // Bad directory argument. Json::Value jvParams; jvParams[jss::ledger_hash] = ledgerHash; - testMalformedField( - env, - jvParams, - jss::directory, - FieldType::HashOrObjectField, - "malformedRequest"); + testMalformedField(env, jvParams, jss::directory, FieldType::HashOrObjectField, "malformedRequest"); } { // Non-integer sub_index. @@ -1405,13 +1233,7 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[jss::directory][jss::dir_root] = dirRootIndex; jvParams[jss::ledger_hash] = ledgerHash; testMalformedSubfield( - env, - jvParams, - jss::directory, - jss::sub_index, - FieldType::UInt64Field, - "malformedRequest", - false); + env, jvParams, jss::directory, jss::sub_index, FieldType::UInt64Field, "malformedRequest", false); } { // Malformed owner entry. @@ -1420,13 +1242,7 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[jss::ledger_hash] = ledgerHash; testMalformedSubfield( - env, - jvParams, - jss::directory, - jss::owner, - FieldType::AccountField, - "malformedAddress", - false); + env, jvParams, jss::directory, jss::owner, FieldType::AccountField, "malformedAddress", false); } { // Malformed directory object. Specifies both dir_root and owner. @@ -1435,12 +1251,8 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[jss::directory][jss::owner] = alice.human(); jvParams[jss::directory][jss::dir_root] = dirRootIndex; jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; - checkErrorValue( - jrr, - "malformedRequest", - "Must have exactly one of `owner` and `dir_root` fields."); + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + checkErrorValue(jrr, "malformedRequest", "Must have exactly one of `owner` and `dir_root` fields."); } { // Incomplete directory object. Missing both dir_root and owner. @@ -1448,12 +1260,8 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[jss::directory] = Json::objectValue; jvParams[jss::directory][jss::sub_index] = 1; jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; - checkErrorValue( - jrr, - "malformedRequest", - "Must have exactly one of `owner` and `dir_root` fields."); + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + checkErrorValue(jrr, "malformedRequest", "Must have exactly one of `owner` and `dir_root` fields."); } } @@ -1477,8 +1285,7 @@ class LedgerEntry_test : public beast::unit_test::suite jv[jss::Account] = account.human(); jv[jss::Destination] = to.human(); jv[jss::Amount] = amount.getJson(JsonOptions::none); - jv[sfFinishAfter.jsonName] = - cancelAfter.time_since_epoch().count() + 2; + jv[sfFinishAfter.jsonName] = cancelAfter.time_since_epoch().count() + 2; return jv; }; @@ -1494,10 +1301,8 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[jss::escrow] = Json::objectValue; jvParams[jss::escrow][jss::owner] = alice.human(); jvParams[jss::escrow][jss::seq] = env.seq(alice) - 1; - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; - BEAST_EXPECT( - jrr[jss::node][jss::Amount] == XRP(333).value().getText()); + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + BEAST_EXPECT(jrr[jss::node][jss::Amount] == XRP(333).value().getText()); escrowIndex = jrr[jss::index].asString(); } { @@ -1505,17 +1310,12 @@ class LedgerEntry_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::escrow] = escrowIndex; jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; - BEAST_EXPECT( - jrr[jss::node][jss::Amount] == XRP(333).value().getText()); + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + BEAST_EXPECT(jrr[jss::node][jss::Amount] == XRP(333).value().getText()); } { // Malformed escrow fields - runLedgerEntryTest( - env, - jss::escrow, - {{jss::owner, "malformedOwner"}, {jss::seq, "malformedSeq"}}); + runLedgerEntryTest(env, jss::escrow, {{jss::owner, "malformedOwner"}, {jss::seq, "malformedSeq"}}); } } @@ -1531,14 +1331,12 @@ class LedgerEntry_test : public beast::unit_test::suite Keylet const keylet = keylet::fees(); Json::Value jvParams; jvParams[jss::fee] = to_string(keylet.key); - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; - BEAST_EXPECT( - jrr[jss::node][sfLedgerEntryType.jsonName] == jss::FeeSettings); + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + BEAST_EXPECT(jrr[jss::node][sfLedgerEntryType.jsonName] == jss::FeeSettings); } // negative tests - runLedgerEntryTest(env, jss::fee); + testMalformedField(env, Json::Value{}, jss::fee, FieldType::FixedHashField, "malformedRequest"); } void @@ -1553,15 +1351,12 @@ class LedgerEntry_test : public beast::unit_test::suite Keylet const keylet = keylet::skip(); Json::Value jvParams; jvParams[jss::hashes] = to_string(keylet.key); - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; - BEAST_EXPECT( - jrr[jss::node][sfLedgerEntryType.jsonName] == - jss::LedgerHashes); + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + BEAST_EXPECT(jrr[jss::node][sfLedgerEntryType.jsonName] == jss::LedgerHashes); } // negative tests - runLedgerEntryTest(env, jss::hashes); + testMalformedField(env, Json::Value{}, jss::hashes, FieldType::FixedHashField, "malformedRequest"); } void @@ -1576,26 +1371,19 @@ class LedgerEntry_test : public beast::unit_test::suite Account const buyer{"buyer"}; env.fund(XRP(1000), issuer, buyer); - uint256 const nftokenID0 = - token::getNextID(env, issuer, 0, tfTransferable); + uint256 const nftokenID0 = token::getNextID(env, issuer, 0, tfTransferable); env(token::mint(issuer, 0), txflags(tfTransferable)); env.close(); uint256 const offerID = keylet::nftoffer(issuer, env.seq(issuer)).key; - env(token::createOffer(issuer, nftokenID0, drops(1)), - token::destination(buyer), - txflags(tfSellNFToken)); + env(token::createOffer(issuer, nftokenID0, drops(1)), token::destination(buyer), txflags(tfSellNFToken)); { Json::Value jvParams; jvParams[jss::nft_offer] = to_string(offerID); - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; - BEAST_EXPECT( - jrr[jss::node][sfLedgerEntryType.jsonName] == - jss::NFTokenOffer); + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + BEAST_EXPECT(jrr[jss::node][sfLedgerEntryType.jsonName] == jss::NFTokenOffer); BEAST_EXPECT(jrr[jss::node][sfOwner.jsonName] == issuer.human()); - BEAST_EXPECT( - jrr[jss::node][sfNFTokenID.jsonName] == to_string(nftokenID0)); + BEAST_EXPECT(jrr[jss::node][sfNFTokenID.jsonName] == to_string(nftokenID0)); BEAST_EXPECT(jrr[jss::node][sfAmount.jsonName] == "1"); } @@ -1623,10 +1411,8 @@ class LedgerEntry_test : public beast::unit_test::suite { Json::Value jvParams; jvParams[jss::nft_page] = to_string(nftpage.key); - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; - BEAST_EXPECT( - jrr[jss::node][sfLedgerEntryType.jsonName] == jss::NFTokenPage); + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + BEAST_EXPECT(jrr[jss::node][sfLedgerEntryType.jsonName] == jss::NFTokenPage); } // negative tests @@ -1652,18 +1438,15 @@ class LedgerEntry_test : public beast::unit_test::suite // Create DisabledValidators array STArray disabledValidators; - auto disabledValidator = - STObject::makeInnerObject(sfDisabledValidator); + auto disabledValidator = STObject::makeInnerObject(sfDisabledValidator); auto pubKeyBlob = strUnHex( "ED58F6770DB5DD77E59D28CB650EC3816E2FC95021BB56E720C9A1" "2DA79C58A3AB"); disabledValidator.setFieldVL(sfPublicKey, *pubKeyBlob); - disabledValidator.setFieldU32( - sfFirstLedgerSequence, 91371264); + disabledValidator.setFieldU32(sfFirstLedgerSequence, 91371264); disabledValidators.push_back(std::move(disabledValidator)); - sle->setFieldArray( - sfDisabledValidators, disabledValidators); + sle->setFieldArray(sfDisabledValidators, disabledValidators); sle->setFieldH256( sfPreviousTxnID, uint256::fromVoid("8D47FFE664BE6C335108DF689537625855A6" @@ -1679,14 +1462,12 @@ class LedgerEntry_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::nunl] = to_string(keylet.key); - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; - BEAST_EXPECT( - jrr[jss::node][sfLedgerEntryType.jsonName] == jss::NegativeUNL); + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + BEAST_EXPECT(jrr[jss::node][sfLedgerEntryType.jsonName] == jss::NegativeUNL); } // negative tests - runLedgerEntryTest(env, jss::nunl); + testMalformedField(env, Json::Value{}, jss::nunl, FieldType::FixedHashField, "malformedRequest"); } void @@ -1713,8 +1494,7 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[jss::offer][jss::account] = alice.human(); jvParams[jss::offer][jss::seq] = env.seq(alice) - 1; jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::node][jss::TakerGets] == "322000000"); offerIndex = jrr[jss::index].asString(); } @@ -1722,18 +1502,13 @@ class LedgerEntry_test : public beast::unit_test::suite // Request the offer using its index. Json::Value jvParams; jvParams[jss::offer] = offerIndex; - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::node][jss::TakerGets] == "322000000"); } { // Malformed offer fields - runLedgerEntryTest( - env, - jss::offer, - {{jss::account, "malformedAddress"}, - {jss::seq, "malformedRequest"}}); + runLedgerEntryTest(env, jss::offer, {{jss::account, "malformedAddress"}, {jss::seq, "malformedRequest"}}); } } @@ -1770,15 +1545,13 @@ class LedgerEntry_test : public beast::unit_test::suite std::string const ledgerHash{to_string(env.closed()->header().hash)}; - uint256 const payChanIndex{ - keylet::payChan(alice, env.master, env.seq(alice) - 1).key}; + uint256 const payChanIndex{keylet::payChan(alice, env.master, env.seq(alice) - 1).key}; { // Request the payment channel using its index. Json::Value jvParams; jvParams[jss::payment_channel] = to_string(payChanIndex); jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::node][sfAmount.jsonName] == "57000000"); BEAST_EXPECT(jrr[jss::node][sfBalance.jsonName] == "0"); BEAST_EXPECT(jrr[jss::node][sfSettleDelay.jsonName] == 18); @@ -1788,8 +1561,7 @@ class LedgerEntry_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::payment_channel] = ledgerHash; jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; checkErrorValue(jrr, "entryNotFound", "Entry not found."); } @@ -1820,8 +1592,7 @@ class LedgerEntry_test : public beast::unit_test::suite // check both aliases for (auto const& fieldName : {jss::ripple_state, jss::state}) { - std::string const ledgerHash{ - to_string(env.closed()->header().hash)}; + std::string const ledgerHash{to_string(env.closed()->header().hash)}; { // Request the trust line using the accounts and currency. Json::Value jvParams; @@ -1831,12 +1602,9 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[fieldName][jss::accounts][1u] = gw.human(); jvParams[fieldName][jss::currency] = "USD"; jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; - BEAST_EXPECT( - jrr[jss::node][sfBalance.jsonName][jss::value] == "-97"); - BEAST_EXPECT( - jrr[jss::node][sfHighLimit.jsonName][jss::value] == "999"); + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + BEAST_EXPECT(jrr[jss::node][sfBalance.jsonName][jss::value] == "-97"); + BEAST_EXPECT(jrr[jss::node][sfHighLimit.jsonName][jss::value] == "999"); } { // test basic malformed scenarios @@ -1856,8 +1624,7 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[fieldName][jss::accounts][0u] = alice.human(); jvParams[fieldName][jss::currency] = "USD"; jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; checkErrorValue( jrr, "malformedRequest", @@ -1874,8 +1641,7 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[fieldName][jss::accounts][2u] = alice.human(); jvParams[fieldName][jss::currency] = "USD"; jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; checkErrorValue( jrr, "malformedRequest", @@ -1894,15 +1660,9 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[fieldName][jss::accounts][1u] = gw.human(); jvParams[fieldName][jss::currency] = "USD"; - Json::Value const jrr = env.rpc( - "json", - "ledger_entry", - to_string(jvParams))[jss::result]; + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; checkErrorValue( - jrr, - "malformedAddress", - RPC::expected_field_message( - jss::accounts, "array of Accounts")); + jrr, "malformedAddress", RPC::expected_field_message(jss::accounts, "array of Accounts")); } { @@ -1912,15 +1672,9 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[fieldName][jss::accounts][1u] = badAccount; jvParams[fieldName][jss::currency] = "USD"; - Json::Value const jrr = env.rpc( - "json", - "ledger_entry", - to_string(jvParams))[jss::result]; + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; checkErrorValue( - jrr, - "malformedAddress", - RPC::expected_field_message( - jss::accounts, "array of Accounts")); + jrr, "malformedAddress", RPC::expected_field_message(jss::accounts, "array of Accounts")); } }; @@ -1940,12 +1694,8 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[fieldName][jss::accounts][1u] = alice.human(); jvParams[fieldName][jss::currency] = "USD"; jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; - checkErrorValue( - jrr, - "malformedRequest", - "Cannot have a trustline to self."); + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + checkErrorValue(jrr, "malformedRequest", "Cannot have a trustline to self."); } } } @@ -1979,11 +1729,9 @@ class LedgerEntry_test : public beast::unit_test::suite { // Not a valid ticket requested by index. Json::Value jvParams; - jvParams[jss::ticket] = - to_string(getTicketIndex(env.master, tkt1 - 1)); + jvParams[jss::ticket] = to_string(getTicketIndex(env.master, tkt1 - 1)); jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; checkErrorValue(jrr, "entryNotFound", "Entry not found."); } { @@ -1991,10 +1739,8 @@ class LedgerEntry_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::ticket] = to_string(getTicketIndex(env.master, tkt1)); jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; - BEAST_EXPECT( - jrr[jss::node][sfLedgerEntryType.jsonName] == jss::Ticket); + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + BEAST_EXPECT(jrr[jss::node][sfLedgerEntryType.jsonName] == jss::Ticket); BEAST_EXPECT(jrr[jss::node][sfTicketSequence.jsonName] == tkt1); } { @@ -2004,11 +1750,8 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[jss::ticket][jss::account] = env.master.human(); jvParams[jss::ticket][jss::ticket_seq] = tkt1 + 1; jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; - BEAST_EXPECT( - jrr[jss::node][jss::index] == - to_string(getTicketIndex(env.master, tkt1 + 1))); + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + BEAST_EXPECT(jrr[jss::node][jss::index] == to_string(getTicketIndex(env.master, tkt1 + 1))); } { // Not a valid ticket requested by account and sequence. @@ -2017,8 +1760,7 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[jss::ticket][jss::account] = env.master.human(); jvParams[jss::ticket][jss::ticket_seq] = tkt1 + 2; jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; checkErrorValue(jrr, "entryNotFound", "Entry not found."); } { @@ -2026,10 +1768,8 @@ class LedgerEntry_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::ticket] = to_string(keylet::account(env.master).key); jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; - checkErrorValue( - jrr, "unexpectedLedgerType", "Unexpected ledger type."); + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + checkErrorValue(jrr, "unexpectedLedgerType", "Unexpected ledger type."); } { @@ -2076,32 +1816,22 @@ class LedgerEntry_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::did] = alice.human(); jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; - BEAST_EXPECT( - jrr[jss::node][sfDIDDocument.jsonName] == - strHex(std::string{"data"})); - BEAST_EXPECT( - jrr[jss::node][sfURI.jsonName] == strHex(std::string{"uri"})); + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + BEAST_EXPECT(jrr[jss::node][sfDIDDocument.jsonName] == strHex(std::string{"data"})); + BEAST_EXPECT(jrr[jss::node][sfURI.jsonName] == strHex(std::string{"uri"})); } { // Request an index that is not a DID. Json::Value jvParams; jvParams[jss::did] = env.master.human(); jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; checkErrorValue(jrr, "entryNotFound", "Entry not found."); } { // Malformed DID index Json::Value jvParams; - testMalformedField( - env, - jvParams, - jss::did, - FieldType::AccountField, - "malformedAddress"); + testMalformedField(env, jvParams, jss::did, FieldType::AccountField, "malformedAddress"); } } @@ -2115,10 +1845,7 @@ class LedgerEntry_test : public beast::unit_test::suite Env env(*this); Account const owner("owner"); env.fund(XRP(1'000), owner); - Oracle oracle( - env, - {.owner = owner, - .fee = static_cast(env.current()->fees().base.drops())}); + Oracle oracle(env, {.owner = owner, .fee = static_cast(env.current()->fees().base.drops())}); { // test basic malformed scenarios @@ -2140,8 +1867,7 @@ class LedgerEntry_test : public beast::unit_test::suite using namespace xrpl::test::jtx::oracle; Env env(*this); - auto const baseFee = - static_cast(env.current()->fees().base.drops()); + auto const baseFee = static_cast(env.current()->fees().base.drops()); std::vector accounts; std::vector oracles; for (int i = 0; i < 10; ++i) @@ -2149,13 +1875,11 @@ class LedgerEntry_test : public beast::unit_test::suite Account const owner(std::string("owner") + std::to_string(i)); env.fund(XRP(1'000), owner); // different accounts can have the same asset pair - Oracle oracle( - env, {.owner = owner, .documentID = i, .fee = baseFee}); + Oracle oracle(env, {.owner = owner, .documentID = i, .fee = baseFee}); accounts.push_back(owner.id()); oracles.push_back(oracle.documentID()); // same account can have different asset pair - Oracle oracle1( - env, {.owner = owner, .documentID = i + 10, .fee = baseFee}); + Oracle oracle1(env, {.owner = owner, .documentID = i + 10, .fee = baseFee}); accounts.push_back(owner.id()); oracles.push_back(oracle1.documentID()); } @@ -2166,13 +1890,11 @@ class LedgerEntry_test : public beast::unit_test::suite if (i % 2) return Oracle::ledgerEntry(env, accounts[i], oracles[i]); // document id is string - return Oracle::ledgerEntry( - env, accounts[i], std::to_string(oracles[i])); + return Oracle::ledgerEntry(env, accounts[i], std::to_string(oracles[i])); }(); try { - BEAST_EXPECT( - jv[jss::node][jss::Owner] == to_string(accounts[i])); + BEAST_EXPECT(jv[jss::node][jss::Owner] == to_string(accounts[i])); } catch (...) { @@ -2196,35 +1918,28 @@ class LedgerEntry_test : public beast::unit_test::suite {.transferFee = 10, .metadata = "123", .ownerCount = 1, - .flags = tfMPTCanLock | tfMPTRequireAuth | tfMPTCanEscrow | - tfMPTCanTrade | tfMPTCanTransfer | tfMPTCanClawback}); + .flags = tfMPTCanLock | tfMPTRequireAuth | tfMPTCanEscrow | tfMPTCanTrade | tfMPTCanTransfer | + tfMPTCanClawback}); mptAlice.authorize({.account = bob, .holderCount = 1}); std::string const ledgerHash{to_string(env.closed()->header().hash)}; - std::string const badMptID = - "00000193B9DDCAF401B5B3B26875986043F82CD0D13B4315"; + std::string const badMptID = "00000193B9DDCAF401B5B3B26875986043F82CD0D13B4315"; { // Request the MPTIssuance using its MPTIssuanceID. Json::Value jvParams; jvParams[jss::mpt_issuance] = strHex(mptAlice.issuanceID()); jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; - BEAST_EXPECT( - jrr[jss::node][sfMPTokenMetadata.jsonName] == - strHex(std::string{"123"})); - BEAST_EXPECT( - jrr[jss::node][jss::mpt_issuance_id] == - strHex(mptAlice.issuanceID())); + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + BEAST_EXPECT(jrr[jss::node][sfMPTokenMetadata.jsonName] == strHex(std::string{"123"})); + BEAST_EXPECT(jrr[jss::node][jss::mpt_issuance_id] == strHex(mptAlice.issuanceID())); } { // Request an index that is not a MPTIssuance. Json::Value jvParams; jvParams[jss::mpt_issuance] = badMptID; jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; checkErrorValue(jrr, "entryNotFound", "Entry not found."); } { @@ -2232,14 +1947,10 @@ class LedgerEntry_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::mptoken] = Json::objectValue; jvParams[jss::mptoken][jss::account] = bob.human(); - jvParams[jss::mptoken][jss::mpt_issuance_id] = - strHex(mptAlice.issuanceID()); + jvParams[jss::mptoken][jss::mpt_issuance_id] = strHex(mptAlice.issuanceID()); jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; - BEAST_EXPECT( - jrr[jss::node][sfMPTokenIssuanceID.jsonName] == - strHex(mptAlice.issuanceID())); + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; + BEAST_EXPECT(jrr[jss::node][sfMPTokenIssuanceID.jsonName] == strHex(mptAlice.issuanceID())); } { // Request the MPToken using a bad mptIssuanceID. @@ -2248,19 +1959,13 @@ class LedgerEntry_test : public beast::unit_test::suite jvParams[jss::mptoken][jss::account] = bob.human(); jvParams[jss::mptoken][jss::mpt_issuance_id] = badMptID; jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = env.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; checkErrorValue(jrr, "entryNotFound", "Entry not found."); } { // Malformed MPTIssuance index Json::Value jvParams; - testMalformedField( - env, - jvParams, - jss::mptoken, - FieldType::HashOrObjectField, - "malformedRequest"); + testMalformedField(env, jvParams, jss::mptoken, FieldType::HashOrObjectField, "malformedRequest"); } } @@ -2294,30 +1999,23 @@ class LedgerEntry_test : public beast::unit_test::suite params[jss::permissioned_domain][jss::seq] = seq; auto jv = env.rpc("json", "ledger_entry", to_string(params)); BEAST_EXPECT( - jv.isObject() && jv.isMember(jss::result) && - !jv[jss::result].isMember(jss::error) && + jv.isObject() && jv.isMember(jss::result) && !jv[jss::result].isMember(jss::error) && jv[jss::result].isMember(jss::node) && - jv[jss::result][jss::node].isMember( - sfLedgerEntryType.jsonName) && - jv[jss::result][jss::node][sfLedgerEntryType.jsonName] == - jss::PermissionedDomain); + jv[jss::result][jss::node].isMember(sfLedgerEntryType.jsonName) && + jv[jss::result][jss::node][sfLedgerEntryType.jsonName] == jss::PermissionedDomain); std::string const pdIdx = jv[jss::result][jss::index].asString(); - BEAST_EXPECT( - strHex(keylet::permissionedDomain(alice, seq).key) == pdIdx); + BEAST_EXPECT(strHex(keylet::permissionedDomain(alice, seq).key) == pdIdx); params.clear(); params[jss::ledger_index] = jss::validated; params[jss::permissioned_domain] = pdIdx; jv = env.rpc("json", "ledger_entry", to_string(params)); BEAST_EXPECT( - jv.isObject() && jv.isMember(jss::result) && - !jv[jss::result].isMember(jss::error) && + jv.isObject() && jv.isMember(jss::result) && !jv[jss::result].isMember(jss::error) && jv[jss::result].isMember(jss::node) && - jv[jss::result][jss::node].isMember( - sfLedgerEntryType.jsonName) && - jv[jss::result][jss::node][sfLedgerEntryType.jsonName] == - jss::PermissionedDomain); + jv[jss::result][jss::node].isMember(sfLedgerEntryType.jsonName) && + jv[jss::result][jss::node][sfLedgerEntryType.jsonName] == jss::PermissionedDomain); } { @@ -2328,8 +2026,7 @@ class LedgerEntry_test : public beast::unit_test::suite "12F1F1F1F180D67377B2FAB292A31C922470326268D2B9B74CD1E582645B9A" "DE"; auto const jrr = env.rpc("json", "ledger_entry", to_string(params)); - checkErrorValue( - jrr[jss::result], "entryNotFound", "Entry not found."); + checkErrorValue(jrr[jss::result], "entryNotFound", "Entry not found."); } { // test basic malformed scenarios @@ -2343,6 +2040,396 @@ class LedgerEntry_test : public beast::unit_test::suite } } + /// Test the ledger entry types that don't take parameters + void + testFixed() + { + using namespace test::jtx; + + Account const alice{"alice"}; + Account const bob{"bob"}; + + Env env{*this, envconfig([](auto cfg) { + cfg->START_UP = StartUpType::FRESH; + return cfg; + })}; + + env.close(); + + /** Verifies that the RPC result has the expected data + * + * @param good: Indicates that the request should have succeeded + * and returned a ledger object of `expectedType` type. + * @param jv: The RPC result Json value + * @param expectedType: The type that the ledger object should + * have if "good". + * @param expectedError: Optional. The expected error if not + * good. Defaults to "entryNotFound". + */ + auto checkResult = [&](bool good, + Json::Value const& jv, + Json::StaticString const& expectedType, + std::optional const& expectedError = {}) { + if (good) + { + BEAST_EXPECTS( + jv.isObject() && jv.isMember(jss::result) && !jv[jss::result].isMember(jss::error) && + jv[jss::result].isMember(jss::node) && + jv[jss::result][jss::node].isMember(sfLedgerEntryType.jsonName) && + jv[jss::result][jss::node][sfLedgerEntryType.jsonName] == expectedType, + to_string(jv)); + } + else + { + BEAST_EXPECTS( + jv.isObject() && jv.isMember(jss::result) && jv[jss::result].isMember(jss::error) && + !jv[jss::result].isMember(jss::node) && + jv[jss::result][jss::error] == expectedError.value_or("entryNotFound"), + to_string(jv)); + } + }; + + /** Runs a series of tests for a given fixed-position ledger + * entry. + * + * @param field: The Json request field to use. + * @param expectedType: The type that the ledger object should + * have if "good". + * @param expectedKey: The keylet of the fixed object. + * @param good: Indicates whether the object is expected to + * exist. + */ + auto test = [&](Json::StaticString const& field, + Json::StaticString const& expectedType, + Keylet const& expectedKey, + bool good) { + testcase << expectedType.c_str() << (good ? "" : " not") << " found"; + + auto const hexKey = strHex(expectedKey.key); + + { + // Test bad values + // "field":null + Json::Value params; + params[jss::ledger_index] = jss::validated; + params[field] = Json::nullValue; + auto const jv = env.rpc("json", "ledger_entry", to_string(params)); + checkResult(false, jv, expectedType, "malformedRequest"); + BEAST_EXPECT(!jv[jss::result].isMember(jss::index)); + } + + { + Json::Value params; + // "field":"string" + params[jss::ledger_index] = jss::validated; + params[field] = "arbitrary string"; + auto const jv = env.rpc("json", "ledger_entry", to_string(params)); + checkResult(false, jv, expectedType, "malformedRequest"); + BEAST_EXPECT(!jv[jss::result].isMember(jss::index)); + } + + { + Json::Value params; + // "field":false + params[jss::ledger_index] = jss::validated; + params[field] = false; + auto const jv = env.rpc("json", "ledger_entry", to_string(params)); + checkResult(false, jv, expectedType, "invalidParams"); + BEAST_EXPECT(!jv[jss::result].isMember(jss::index)); + } + + { + Json::Value params; + + // "field":[incorrect index hash] + auto const badKey = strHex(expectedKey.key + uint256{1}); + params[jss::ledger_index] = jss::validated; + params[field] = badKey; + auto const jv = env.rpc("json", "ledger_entry", to_string(params)); + checkResult(false, jv, expectedType, "entryNotFound"); + BEAST_EXPECTS(jv[jss::result][jss::index] == badKey, to_string(jv)); + } + + { + Json::Value params; + // "index":"field" using API 2 + params[jss::ledger_index] = jss::validated; + params[jss::index] = field; + params[jss::api_version] = 2; + auto const jv = env.rpc("json", "ledger_entry", to_string(params)); + checkResult(false, jv, expectedType, "malformedRequest"); + BEAST_EXPECT(!jv[jss::result].isMember(jss::index)); + } + + std::string const pdIdx = [&]() { + { + Json::Value params; + // Test good values + // Use the "field":true notation + params[jss::ledger_index] = jss::validated; + params[field] = true; + auto const jv = env.rpc("json", "ledger_entry", to_string(params)); + // Index will always be returned for valid parameters. + std::string const pdIdx = jv[jss::result][jss::index].asString(); + BEAST_EXPECTS(hexKey == pdIdx, to_string(jv)); + checkResult(good, jv, expectedType); + + return pdIdx; + } + }(); + + { + Json::Value params; + // "field":"[index hash]" + params[jss::ledger_index] = jss::validated; + params[field] = hexKey; + auto const jv = env.rpc("json", "ledger_entry", to_string(params)); + checkResult(good, jv, expectedType); + BEAST_EXPECT(jv[jss::result][jss::index].asString() == hexKey); + } + + { + // Bad value + // Use the "index":"field" notation with API 2 + Json::Value params; + params[jss::ledger_index] = jss::validated; + params[jss::index] = field; + params[jss::api_version] = 2; + auto const jv = env.rpc("json", "ledger_entry", to_string(params)); + checkResult(false, jv, expectedType, "malformedRequest"); + BEAST_EXPECT(!jv[jss::result].isMember(jss::index)); + } + + { + Json::Value params; + // Use the "index":"field" notation with API 3 + params[jss::ledger_index] = jss::validated; + params[jss::index] = field; + params[jss::api_version] = 3; + auto const jv = env.rpc("json", "ledger_entry", to_string(params)); + // Index is correct either way + BEAST_EXPECT(jv[jss::result][jss::index].asString() == hexKey); + checkResult(good, jv, expectedType); + } + + { + Json::Value params; + // Use the "index":"[index hash]" notation + params[jss::ledger_index] = jss::validated; + params[jss::index] = pdIdx; + auto const jv = env.rpc("json", "ledger_entry", to_string(params)); + // Index is correct either way + BEAST_EXPECT(jv[jss::result][jss::index].asString() == hexKey); + checkResult(good, jv, expectedType); + } + }; + + test(jss::amendments, jss::Amendments, keylet::amendments(), true); + test(jss::fee, jss::FeeSettings, keylet::fees(), true); + // There won't be an nunl + test(jss::nunl, jss::NegativeUNL, keylet::negativeUNL(), false); + // Can only get the short skip list this way + test(jss::hashes, jss::LedgerHashes, keylet::skip(), true); + } + + void + testHashes() + { + using namespace test::jtx; + + Account const alice{"alice"}; + Account const bob{"bob"}; + + Env env{*this, envconfig([](auto cfg) { + cfg->START_UP = StartUpType::FRESH; + return cfg; + })}; + + env.close(); + + /** Verifies that the RPC result has the expected data + * + * @param good: Indicates that the request should have succeeded + * and returned a ledger object of `expectedType` type. + * @param jv: The RPC result Json value + * @param expectedCount: The number of Hashes expected in the + * object if "good". + * @param expectedError: Optional. The expected error if not + * good. Defaults to "entryNotFound". + */ + auto checkResult = [&](bool good, + Json::Value const& jv, + int expectedCount, + std::optional const& expectedError = {}) { + if (good) + { + BEAST_EXPECTS( + jv.isObject() && jv.isMember(jss::result) && !jv[jss::result].isMember(jss::error) && + jv[jss::result].isMember(jss::node) && + jv[jss::result][jss::node].isMember(sfLedgerEntryType.jsonName) && + jv[jss::result][jss::node][sfLedgerEntryType.jsonName] == jss::LedgerHashes, + to_string(jv)); + BEAST_EXPECTS( + jv[jss::result].isMember(jss::node) && jv[jss::result][jss::node].isMember("Hashes") && + jv[jss::result][jss::node]["Hashes"].size() == expectedCount, + to_string(jv[jss::result][jss::node]["Hashes"].size())); + } + else + { + BEAST_EXPECTS( + jv.isObject() && jv.isMember(jss::result) && jv[jss::result].isMember(jss::error) && + !jv[jss::result].isMember(jss::node) && + jv[jss::result][jss::error] == expectedError.value_or("entryNotFound"), + to_string(jv)); + } + }; + + /** Runs a series of tests for a given ledger index. + * + * @param ledger: The ledger index value of the "hashes" request + * parameter. May not necessarily be a number. + * @param expectedKey: The expected keylet of the object. + * @param good: Indicates whether the object is expected to + * exist. + * @param expectedCount: The number of Hashes expected in the + * object if "good". + */ + auto test = [&](Json::Value ledger, Keylet const& expectedKey, bool good, int expectedCount = 0) { + testcase << "LedgerHashes: seq: " << env.current()->header().seq << " \"hashes\":" << to_string(ledger) + << (good ? "" : " not") << " found"; + + auto const hexKey = strHex(expectedKey.key); + + { + // Test bad values + // "hashes":null + Json::Value params; + params[jss::ledger_index] = jss::validated; + params[jss::hashes] = Json::nullValue; + auto jv = env.rpc("json", "ledger_entry", to_string(params)); + checkResult(false, jv, 0, "malformedRequest"); + BEAST_EXPECT(!jv[jss::result].isMember(jss::index)); + } + + { + Json::Value params; + // "hashes":"non-uint string" + params[jss::ledger_index] = jss::validated; + params[jss::hashes] = "arbitrary string"; + auto const jv = env.rpc("json", "ledger_entry", to_string(params)); + checkResult(false, jv, 0, "malformedRequest"); + BEAST_EXPECT(!jv[jss::result].isMember(jss::index)); + } + + { + Json::Value params; + // "hashes":"uint string" is invalid, too + params[jss::ledger_index] = jss::validated; + params[jss::hashes] = "10"; + auto const jv = env.rpc("json", "ledger_entry", to_string(params)); + checkResult(false, jv, 0, "malformedRequest"); + BEAST_EXPECT(!jv[jss::result].isMember(jss::index)); + } + + { + Json::Value params; + // "hashes":false + params[jss::ledger_index] = jss::validated; + params[jss::hashes] = false; + auto const jv = env.rpc("json", "ledger_entry", to_string(params)); + checkResult(false, jv, 0, "invalidParams"); + BEAST_EXPECT(!jv[jss::result].isMember(jss::index)); + } + + { + Json::Value params; + // "hashes":-1 + params[jss::ledger_index] = jss::validated; + params[jss::hashes] = -1; + auto const jv = env.rpc("json", "ledger_entry", to_string(params)); + checkResult(false, jv, 0, "internal"); + BEAST_EXPECT(!jv[jss::result].isMember(jss::index)); + } + + // "hashes":[incorrect index hash] + { + Json::Value params; + auto const badKey = strHex(expectedKey.key + uint256{1}); + params[jss::ledger_index] = jss::validated; + params[jss::hashes] = badKey; + auto const jv = env.rpc("json", "ledger_entry", to_string(params)); + checkResult(false, jv, 0, "entryNotFound"); + BEAST_EXPECT(jv[jss::result][jss::index] == badKey); + } + + { + Json::Value params; + // Test good values + // Use the "hashes":ledger notation + params[jss::ledger_index] = jss::validated; + params[jss::hashes] = ledger; + auto const jv = env.rpc("json", "ledger_entry", to_string(params)); + checkResult(good, jv, expectedCount); + // Index will always be returned for valid parameters. + std::string const pdIdx = jv[jss::result][jss::index].asString(); + BEAST_EXPECTS(hexKey == pdIdx, strHex(pdIdx)); + } + + { + Json::Value params; + // "hashes":"[index hash]" + params[jss::ledger_index] = jss::validated; + params[jss::hashes] = hexKey; + auto const jv = env.rpc("json", "ledger_entry", to_string(params)); + checkResult(good, jv, expectedCount); + // Index is correct either way + BEAST_EXPECTS( + hexKey == jv[jss::result][jss::index].asString(), strHex(jv[jss::result][jss::index].asString())); + } + + { + Json::Value params; + // Use the "index":"[index hash]" notation + params[jss::ledger_index] = jss::validated; + params[jss::index] = hexKey; + auto const jv = env.rpc("json", "ledger_entry", to_string(params)); + checkResult(good, jv, expectedCount); + // Index is correct either way + BEAST_EXPECTS( + hexKey == jv[jss::result][jss::index].asString(), strHex(jv[jss::result][jss::index].asString())); + } + }; + + // short skip list + test(true, keylet::skip(), true, 2); + // long skip list at index 0 + test(1, keylet::skip(1), false); + // long skip list at index 1 + test(1 << 17, keylet::skip(1 << 17), false); + + // Close more ledgers, but stop short of the flag ledger + for (auto i = env.current()->seq(); i <= 250; ++i) + env.close(); + + // short skip list + test(true, keylet::skip(), true, 249); + // long skip list at index 0 + test(1, keylet::skip(1), false); + // long skip list at index 1 + test(1 << 17, keylet::skip(1 << 17), false); + + // Close a flag ledger so the first "long" skip list is created + for (auto i = env.current()->seq(); i <= 260; ++i) + env.close(); + + // short skip list + test(true, keylet::skip(), true, 256); + // long skip list at index 0 + test(1, keylet::skip(1), true, 1); + // long skip list at index 1 + test(1 << 17, keylet::skip(1 << 17), false); + } + void testCLI() { @@ -2362,10 +2449,8 @@ class LedgerEntry_test : public beast::unit_test::suite std::string const ledgerHash{to_string(env.closed()->header().hash)}; { // Request a check. - Json::Value const jrr = - env.rpc("ledger_entry", to_string(checkId.key))[jss::result]; - BEAST_EXPECT( - jrr[jss::node][sfLedgerEntryType.jsonName] == jss::Check); + Json::Value const jrr = env.rpc("ledger_entry", to_string(checkId.key))[jss::result]; + BEAST_EXPECT(jrr[jss::node][sfLedgerEntryType.jsonName] == jss::Check); BEAST_EXPECT(jrr[jss::node][sfSendMax.jsonName] == "100000000"); } } @@ -2400,18 +2485,16 @@ public: testOracleLedgerEntry(); testMPT(); testPermissionedDomain(); + testFixed(); + testHashes(); testCLI(); } }; -class LedgerEntry_XChain_test : public beast::unit_test::suite, - public test::jtx::XChainBridgeObjects +class LedgerEntry_XChain_test : public beast::unit_test::suite, public test::jtx::XChainBridgeObjects { void - checkErrorValue( - Json::Value const& jv, - std::string const& err, - std::string const& msg) + checkErrorValue(Json::Value const& jv, std::string const& err, std::string const& msg) { if (BEAST_EXPECT(jv.isMember(jss::status))) BEAST_EXPECT(jv[jss::status] == "error"); @@ -2419,9 +2502,7 @@ class LedgerEntry_XChain_test : public beast::unit_test::suite, BEAST_EXPECT(jv[jss::error] == err); if (msg.empty()) { - BEAST_EXPECT( - jv[jss::error_message] == Json::nullValue || - jv[jss::error_message] == ""); + BEAST_EXPECT(jv[jss::error_message] == Json::nullValue || jv[jss::error_message] == ""); } else if (BEAST_EXPECT(jv.isMember(jss::error_message))) BEAST_EXPECT(jv[jss::error_message] == msg); @@ -2446,8 +2527,7 @@ class LedgerEntry_XChain_test : public beast::unit_test::suite, Json::Value jvParams; jvParams[jss::bridge_account] = mcDoor.human(); jvParams[jss::bridge] = jvb; - Json::Value const jrr = mcEnv.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = mcEnv.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr.isMember(jss::node)); auto r = jrr[jss::node]; @@ -2476,8 +2556,7 @@ class LedgerEntry_XChain_test : public beast::unit_test::suite, // request the bridge via RPC by index Json::Value jvParams; jvParams[jss::index] = bridge_index; - Json::Value const jrr = mcEnv.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = mcEnv.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr.isMember(jss::node)); BEAST_EXPECT(jrr[jss::node] == mcBridge); @@ -2489,8 +2568,7 @@ class LedgerEntry_XChain_test : public beast::unit_test::suite, jvParams[jss::bridge_account] = Account::master.human(); jvParams[jss::bridge] = jvb; jvParams[jss::ledger_hash] = ledgerHash; - Json::Value const jrr = mcEnv.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = mcEnv.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; checkErrorValue(jrr, "entryNotFound", "Entry not found."); } @@ -2506,8 +2584,7 @@ class LedgerEntry_XChain_test : public beast::unit_test::suite, Json::Value jvParams; jvParams[jss::bridge_account] = mcDoor.human(); jvParams[jss::bridge] = jvb; - Json::Value const jrr = mcEnv.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; + Json::Value const jrr = mcEnv.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr.isMember(jss::node)); auto r = jrr[jss::node]; @@ -2539,18 +2616,15 @@ class LedgerEntry_XChain_test : public beast::unit_test::suite, // request the xchain_claim_id via RPC Json::Value jvParams; jvParams[jss::xchain_owned_claim_id] = jvXRPBridgeRPC; - jvParams[jss::xchain_owned_claim_id][jss::xchain_owned_claim_id] = - 1; - Json::Value const jrr = scEnv.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; + jvParams[jss::xchain_owned_claim_id][jss::xchain_owned_claim_id] = 1; + Json::Value const jrr = scEnv.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr.isMember(jss::node)); auto r = jrr[jss::node]; BEAST_EXPECT(r.isMember(jss::Account)); BEAST_EXPECT(r[jss::Account] == scAlice.human()); - BEAST_EXPECT( - r[sfLedgerEntryType.jsonName] == jss::XChainOwnedClaimID); + BEAST_EXPECT(r[sfLedgerEntryType.jsonName] == jss::XChainOwnedClaimID); BEAST_EXPECT(r[sfXChainClaimID.jsonName].asInt() == 1); BEAST_EXPECT(r[sfOwnerNode.jsonName].asInt() == 0); } @@ -2559,18 +2633,15 @@ class LedgerEntry_XChain_test : public beast::unit_test::suite, // request the xchain_claim_id via RPC Json::Value jvParams; jvParams[jss::xchain_owned_claim_id] = jvXRPBridgeRPC; - jvParams[jss::xchain_owned_claim_id][jss::xchain_owned_claim_id] = - 2; - Json::Value const jrr = scEnv.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; + jvParams[jss::xchain_owned_claim_id][jss::xchain_owned_claim_id] = 2; + Json::Value const jrr = scEnv.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr.isMember(jss::node)); auto r = jrr[jss::node]; BEAST_EXPECT(r.isMember(jss::Account)); BEAST_EXPECT(r[jss::Account] == scBob.human()); - BEAST_EXPECT( - r[sfLedgerEntryType.jsonName] == jss::XChainOwnedClaimID); + BEAST_EXPECT(r[sfLedgerEntryType.jsonName] == jss::XChainOwnedClaimID); BEAST_EXPECT(r[sfXChainClaimID.jsonName].asInt() == 2); BEAST_EXPECT(r[sfOwnerNode.jsonName].asInt() == 0); } @@ -2588,12 +2659,10 @@ class LedgerEntry_XChain_test : public beast::unit_test::suite, // note: signers.size() and quorum are both 5 in createBridgeObjects createBridgeObjects(mcEnv, scEnv); - auto scCarol = - Account("scCarol"); // Don't fund it - it will be created with the - // xchain transaction + auto scCarol = Account("scCarol"); // Don't fund it - it will be created with the + // xchain transaction auto const amt = XRP(1000); - mcEnv(sidechain_xchain_account_create( - mcAlice, jvb, scCarol, amt, reward)); + mcEnv(sidechain_xchain_account_create(mcAlice, jvb, scCarol, amt, reward)); mcEnv.close(); // send less than quorum of attestations (otherwise funds are @@ -2620,12 +2689,9 @@ class LedgerEntry_XChain_test : public beast::unit_test::suite, { // request the create account claim_id via RPC Json::Value jvParams; - jvParams[jss::xchain_owned_create_account_claim_id] = - jvXRPBridgeRPC; - jvParams[jss::xchain_owned_create_account_claim_id] - [jss::xchain_owned_create_account_claim_id] = 1; - Json::Value const jrr = scEnv.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; + jvParams[jss::xchain_owned_create_account_claim_id] = jvXRPBridgeRPC; + jvParams[jss::xchain_owned_create_account_claim_id][jss::xchain_owned_create_account_claim_id] = 1; + Json::Value const jrr = scEnv.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr.isMember(jss::node)); auto r = jrr[jss::node]; @@ -2636,47 +2702,32 @@ class LedgerEntry_XChain_test : public beast::unit_test::suite, BEAST_EXPECT(r.isMember(sfXChainAccountCreateCount.jsonName)); BEAST_EXPECT(r[sfXChainAccountCreateCount.jsonName].asInt() == 1); - BEAST_EXPECT( - r.isMember(sfXChainCreateAccountAttestations.jsonName)); + BEAST_EXPECT(r.isMember(sfXChainCreateAccountAttestations.jsonName)); auto attest = r[sfXChainCreateAccountAttestations.jsonName]; BEAST_EXPECT(attest.isArray()); BEAST_EXPECT(attest.size() == 3); - BEAST_EXPECT(attest[Json::Value::UInt(0)].isMember( - sfXChainCreateAccountProofSig.jsonName)); + BEAST_EXPECT(attest[Json::Value::UInt(0)].isMember(sfXChainCreateAccountProofSig.jsonName)); Json::Value a[num_attest]; for (size_t i = 0; i < num_attest; ++i) { - a[i] = attest[Json::Value::UInt(0)] - [sfXChainCreateAccountProofSig.jsonName]; - BEAST_EXPECT( - a[i].isMember(jss::Amount) && - a[i][jss::Amount].asInt() == 1000 * drop_per_xrp); - BEAST_EXPECT( - a[i].isMember(jss::Destination) && - a[i][jss::Destination] == scCarol.human()); + a[i] = attest[Json::Value::UInt(0)][sfXChainCreateAccountProofSig.jsonName]; + BEAST_EXPECT(a[i].isMember(jss::Amount) && a[i][jss::Amount].asInt() == 1000 * drop_per_xrp); + BEAST_EXPECT(a[i].isMember(jss::Destination) && a[i][jss::Destination] == scCarol.human()); BEAST_EXPECT( a[i].isMember(sfAttestationSignerAccount.jsonName) && - std::any_of( - signers.begin(), signers.end(), [&](signer const& s) { - return a[i][sfAttestationSignerAccount.jsonName] == - s.account.human(); - })); + std::any_of(signers.begin(), signers.end(), [&](signer const& s) { + return a[i][sfAttestationSignerAccount.jsonName] == s.account.human(); + })); BEAST_EXPECT( a[i].isMember(sfAttestationRewardAccount.jsonName) && - std::any_of( - payee.begin(), - payee.end(), - [&](Account const& account) { - return a[i][sfAttestationRewardAccount.jsonName] == - account.human(); - })); + std::any_of(payee.begin(), payee.end(), [&](Account const& account) { + return a[i][sfAttestationRewardAccount.jsonName] == account.human(); + })); BEAST_EXPECT( - a[i].isMember(sfWasLockingChainSend.jsonName) && - a[i][sfWasLockingChainSend.jsonName] == 1); + a[i].isMember(sfWasLockingChainSend.jsonName) && a[i][sfWasLockingChainSend.jsonName] == 1); BEAST_EXPECT( a[i].isMember(sfSignatureReward.jsonName) && - a[i][sfSignatureReward.jsonName].asInt() == - 1 * drop_per_xrp); + a[i][sfSignatureReward.jsonName].asInt() == 1 * drop_per_xrp); } } @@ -2690,12 +2741,9 @@ class LedgerEntry_XChain_test : public beast::unit_test::suite, { // request the create account claim_id via RPC Json::Value jvParams; - jvParams[jss::xchain_owned_create_account_claim_id] = - jvXRPBridgeRPC; - jvParams[jss::xchain_owned_create_account_claim_id] - [jss::xchain_owned_create_account_claim_id] = 1; - Json::Value const jrr = scEnv.rpc( - "json", "ledger_entry", to_string(jvParams))[jss::result]; + jvParams[jss::xchain_owned_create_account_claim_id] = jvXRPBridgeRPC; + jvParams[jss::xchain_owned_create_account_claim_id][jss::xchain_owned_create_account_claim_id] = 1; + Json::Value const jrr = scEnv.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; checkErrorValue(jrr, "entryNotFound", "Entry not found."); } } diff --git a/src/test/rpc/LedgerHeader_test.cpp b/src/test/rpc/LedgerHeader_test.cpp index 3af82d683e..8b460fe6a4 100644 --- a/src/test/rpc/LedgerHeader_test.cpp +++ b/src/test/rpc/LedgerHeader_test.cpp @@ -17,8 +17,7 @@ class LedgerHeader_test : public beast::unit_test::suite Json::Value params{Json::objectValue}; params[jss::api_version] = 1; params[jss::ledger_index] = "current"; - auto const result = - env.client().invoke("ledger_header", params)[jss::result]; + auto const result = env.client().invoke("ledger_header", params)[jss::result]; BEAST_EXPECT(result[jss::status] == "success"); BEAST_EXPECT(result.isMember("ledger")); BEAST_EXPECT(result[jss::ledger][jss::closed] == false); @@ -35,8 +34,7 @@ class LedgerHeader_test : public beast::unit_test::suite Json::Value params{Json::objectValue}; params[jss::api_version] = 1; params[jss::ledger_index] = "validated"; - auto const result = - env.client().invoke("ledger_header", params)[jss::result]; + auto const result = env.client().invoke("ledger_header", params)[jss::result]; BEAST_EXPECT(result[jss::status] == "success"); BEAST_EXPECT(result.isMember("ledger")); BEAST_EXPECT(result[jss::ledger][jss::closed] == true); @@ -52,8 +50,7 @@ class LedgerHeader_test : public beast::unit_test::suite Json::Value params{Json::objectValue}; params[jss::api_version] = 2; - auto const result = - env.client().invoke("ledger_header", params)[jss::result]; + auto const result = env.client().invoke("ledger_header", params)[jss::result]; BEAST_EXPECT(result[jss::error] == "unknownCmd"); BEAST_EXPECT(result[jss::status] == "error"); } diff --git a/src/test/rpc/LedgerRPC_test.cpp b/src/test/rpc/LedgerRPC_test.cpp index 583ff0a531..a656db558c 100644 --- a/src/test/rpc/LedgerRPC_test.cpp +++ b/src/test/rpc/LedgerRPC_test.cpp @@ -19,10 +19,7 @@ namespace test { class LedgerRPC_test : public beast::unit_test::suite { void - checkErrorValue( - Json::Value const& jv, - std::string const& err, - std::string const& msg) + checkErrorValue(Json::Value const& jv, std::string const& err, std::string const& msg) { if (BEAST_EXPECT(jv.isMember(jss::status))) BEAST_EXPECT(jv[jss::status] == "error"); @@ -30,15 +27,12 @@ class LedgerRPC_test : public beast::unit_test::suite BEAST_EXPECT(jv[jss::error] == err); if (msg.empty()) { - BEAST_EXPECT( - jv[jss::error_message] == Json::nullValue || - jv[jss::error_message] == ""); + BEAST_EXPECT(jv[jss::error_message] == Json::nullValue || jv[jss::error_message] == ""); } else if (BEAST_EXPECT(jv.isMember(jss::error_message))) BEAST_EXPECTS( jv[jss::error_message] == msg, - "Expected error message \"" + msg + "\", received \"" + - jv[jss::error_message].asString() + "\""); + "Expected error message \"" + msg + "\", received \"" + jv[jss::error_message].asString() + "\""); } // Corrupt a valid address by replacing the 10th character with '!'. @@ -66,8 +60,7 @@ class LedgerRPC_test : public beast::unit_test::suite Json::Value jvParams; // can be either numeric or quoted numeric jvParams[jss::ledger_index] = 1; - auto const jrr = - env.rpc("json", "ledger", to_string(jvParams))[jss::result]; + auto const jrr = env.rpc("json", "ledger", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::ledger][jss::closed] == true); BEAST_EXPECT(jrr[jss::ledger][jss::ledger_index] == "1"); } @@ -75,8 +68,7 @@ class LedgerRPC_test : public beast::unit_test::suite { Json::Value jvParams; jvParams[jss::ledger_index] = "1"; - auto const jrr = - env.rpc("json", "ledger", to_string(jvParams))[jss::result]; + auto const jrr = env.rpc("json", "ledger", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::ledger][jss::closed] == true); BEAST_EXPECT(jrr[jss::ledger][jss::ledger_index] == "1"); } @@ -85,11 +77,8 @@ class LedgerRPC_test : public beast::unit_test::suite // using current identifier auto const jrr = env.rpc("ledger", "current")[jss::result]; BEAST_EXPECT(jrr[jss::ledger][jss::closed] == false); - BEAST_EXPECT( - jrr[jss::ledger][jss::ledger_index] == - std::to_string(env.current()->header().seq)); - BEAST_EXPECT( - jrr[jss::ledger_current_index] == env.current()->header().seq); + BEAST_EXPECT(jrr[jss::ledger][jss::ledger_index] == std::to_string(env.current()->header().seq)); + BEAST_EXPECT(jrr[jss::ledger_current_index] == env.current()->header().seq); } } @@ -112,32 +101,23 @@ class LedgerRPC_test : public beast::unit_test::suite // ask for an arbitrary string - index Json::Value jvParams; jvParams[jss::ledger_index] = "potato"; - auto const jrr = - env.rpc("json", "ledger", to_string(jvParams))[jss::result]; - checkErrorValue( - jrr, - "invalidParams", - "Invalid field 'ledger_index', not string or number."); + auto const jrr = env.rpc("json", "ledger", to_string(jvParams))[jss::result]; + checkErrorValue(jrr, "invalidParams", "Invalid field 'ledger_index', not string or number."); } { // ask for a negative index Json::Value jvParams; jvParams[jss::ledger_index] = -1; - auto const jrr = - env.rpc("json", "ledger", to_string(jvParams))[jss::result]; - checkErrorValue( - jrr, - "invalidParams", - "Invalid field 'ledger_index', not string or number."); + auto const jrr = env.rpc("json", "ledger", to_string(jvParams))[jss::result]; + checkErrorValue(jrr, "invalidParams", "Invalid field 'ledger_index', not string or number."); } { // ask for a bad ledger index Json::Value jvParams; jvParams[jss::ledger_index] = 10u; - auto const jrr = - env.rpc("json", "ledger", to_string(jvParams))[jss::result]; + auto const jrr = env.rpc("json", "ledger", to_string(jvParams))[jss::result]; checkErrorValue(jrr, "lgrNotFound", "ledgerNotFound"); } @@ -152,23 +132,20 @@ class LedgerRPC_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::ledger_index] = "validated"; jvParams[jss::queue] = true; - auto const jrr = - env.rpc("json", "ledger", to_string(jvParams))[jss::result]; + auto const jrr = env.rpc("json", "ledger", to_string(jvParams))[jss::result]; checkErrorValue(jrr, "invalidParams", "Invalid parameters."); } { // Request a ledger with a very large (double) sequence. - auto const ret = - env.rpc("json", "ledger", "{ \"ledger_index\" : 2e15 }"); + auto const ret = env.rpc("json", "ledger", "{ \"ledger_index\" : 2e15 }"); BEAST_EXPECT(RPC::contains_error(ret)); BEAST_EXPECT(ret[jss::error_message] == "Invalid parameters."); } { // Request a ledger with very large (integer) sequence. - auto const ret = env.rpc( - "json", "ledger", "{ \"ledger_index\" : 1000000000000000 }"); + auto const ret = env.rpc("json", "ledger", "{ \"ledger_index\" : 1000000000000000 }"); checkErrorValue(ret, "invalidParams", "Invalid parameters."); } } @@ -186,8 +163,7 @@ class LedgerRPC_test : public beast::unit_test::suite { auto const jrr = env.rpc("ledger_current")[jss::result]; - BEAST_EXPECT( - jrr[jss::ledger_current_index] == env.current()->header().seq); + BEAST_EXPECT(jrr[jss::ledger_current_index] == env.current()->header().seq); } } @@ -204,8 +180,7 @@ class LedgerRPC_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::ledger_index] = 3u; jvParams[jss::full] = true; - auto const jrr = - env.rpc("json", "ledger", to_string(jvParams))[jss::result]; + auto const jrr = env.rpc("json", "ledger", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::ledger].isMember(jss::accountState)); BEAST_EXPECT(jrr[jss::ledger][jss::accountState].isArray()); BEAST_EXPECT(jrr[jss::ledger][jss::accountState].size() == 3u); @@ -224,10 +199,8 @@ class LedgerRPC_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::ledger_index] = 1u; jvParams[jss::full] = true; - auto const jrr = - env.rpc("json", "ledger", to_string(jvParams))[jss::result]; - checkErrorValue( - jrr, "noPermission", "You don't have permission for this command."); + auto const jrr = env.rpc("json", "ledger", to_string(jvParams))[jss::result]; + checkErrorValue(jrr, "noPermission", "You don't have permission for this command."); } void @@ -243,8 +216,7 @@ class LedgerRPC_test : public beast::unit_test::suite Json::Value jvParams; jvParams[jss::ledger_index] = 3u; jvParams[jss::accounts] = true; - auto const jrr = - env.rpc("json", "ledger", to_string(jvParams))[jss::result]; + auto const jrr = env.rpc("json", "ledger", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::ledger].isMember(jss::accountState)); BEAST_EXPECT(jrr[jss::ledger][jss::accountState].isArray()); BEAST_EXPECT(jrr[jss::ledger][jss::accountState].size() == 3u); @@ -262,9 +234,8 @@ class LedgerRPC_test : public beast::unit_test::suite auto cfg = envconfig(); cfg->FEES.reference_fee = 10; - Env env{ - *this, std::move(cfg), FeatureBitset{}}; // hashes requested below - // assume no amendments + Env env{*this, std::move(cfg), FeatureBitset{}}; // hashes requested below + // assume no amendments env.fund(XRP(10000), "alice"); env.close(); env.fund(XRP(10000), "bob"); @@ -277,8 +248,7 @@ class LedgerRPC_test : public beast::unit_test::suite // access via the legacy ledger field, keyword index values Json::Value jvParams; jvParams[jss::ledger] = "closed"; - auto jrr = - env.rpc("json", "ledger", to_string(jvParams))[jss::result]; + auto jrr = env.rpc("json", "ledger", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr.isMember(jss::ledger)); BEAST_EXPECT(jrr.isMember(jss::ledger_hash)); BEAST_EXPECT(jrr[jss::ledger][jss::ledger_index] == "5"); @@ -298,9 +268,7 @@ class LedgerRPC_test : public beast::unit_test::suite jvParams[jss::ledger] = "invalid"; jrr = env.rpc("json", "ledger", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); - BEAST_EXPECT( - jrr[jss::error_message] == - "Invalid field 'ledger', not string or number."); + BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'ledger', not string or number."); // numeric index jvParams[jss::ledger] = 4; @@ -323,8 +291,7 @@ class LedgerRPC_test : public beast::unit_test::suite // access via the ledger_hash field Json::Value jvParams; jvParams[jss::ledger_hash] = hash3; - auto jrr = - env.rpc("json", "ledger", to_string(jvParams))[jss::result]; + auto jrr = env.rpc("json", "ledger", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr.isMember(jss::ledger)); BEAST_EXPECT(jrr.isMember(jss::ledger_hash)); BEAST_EXPECT(jrr[jss::ledger][jss::ledger_index] == "3"); @@ -333,17 +300,13 @@ class LedgerRPC_test : public beast::unit_test::suite jvParams[jss::ledger_hash] = "DEADBEEF" + hash3; jrr = env.rpc("json", "ledger", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); - BEAST_EXPECT( - jrr[jss::error_message] == - "Invalid field 'ledger_hash', not hex string."); + BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'ledger_hash', not hex string."); // request with non-string ledger_hash jvParams[jss::ledger_hash] = 2; jrr = env.rpc("json", "ledger", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); - BEAST_EXPECT( - jrr[jss::error_message] == - "Invalid field 'ledger_hash', not hex string."); + BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'ledger_hash', not hex string."); // malformed (non hex) hash jvParams[jss::ledger_hash] = @@ -351,9 +314,7 @@ class LedgerRPC_test : public beast::unit_test::suite "7F2775F2F7485BB37307984C3C0F2340"; jrr = env.rpc("json", "ledger", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); - BEAST_EXPECT( - jrr[jss::error_message] == - "Invalid field 'ledger_hash', not hex string."); + BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'ledger_hash', not hex string."); // properly formed, but just doesn't exist jvParams[jss::ledger_hash] = @@ -368,8 +329,7 @@ class LedgerRPC_test : public beast::unit_test::suite // access via the ledger_index field, keyword index values Json::Value jvParams; jvParams[jss::ledger_index] = "closed"; - auto jrr = - env.rpc("json", "ledger", to_string(jvParams))[jss::result]; + auto jrr = env.rpc("json", "ledger", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr.isMember(jss::ledger)); BEAST_EXPECT(jrr.isMember(jss::ledger_hash)); BEAST_EXPECT(jrr[jss::ledger][jss::ledger_index] == "5"); @@ -391,21 +351,17 @@ class LedgerRPC_test : public beast::unit_test::suite jvParams[jss::ledger_index] = "invalid"; jrr = env.rpc("json", "ledger", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); - BEAST_EXPECT( - jrr[jss::error_message] == - "Invalid field 'ledger_index', not string or number."); + BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'ledger_index', not string or number."); // numeric index for (auto i : {1, 2, 3, 4, 5, 6}) { jvParams[jss::ledger_index] = i; - jrr = - env.rpc("json", "ledger", to_string(jvParams))[jss::result]; + jrr = env.rpc("json", "ledger", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr.isMember(jss::ledger)); if (i < 6) BEAST_EXPECT(jrr.isMember(jss::ledger_hash)); - BEAST_EXPECT( - jrr[jss::ledger][jss::ledger_index] == std::to_string(i)); + BEAST_EXPECT(jrr[jss::ledger][jss::ledger_index] == std::to_string(i)); } // numeric index - out of range @@ -479,12 +435,8 @@ class LedgerRPC_test : public beast::unit_test::suite // Put some txs in the queue // Alice auto aliceSeq = env.seq(alice); - env(pay(alice, "george", XRP(1000)), - last_ledger_seq(7), - ter(terQUEUED)); - env(offer(alice, XRP(50000), alice["USD"](5000)), - seq(aliceSeq + 1), - ter(terQUEUED)); + env(pay(alice, "george", XRP(1000)), last_ledger_seq(7), ter(terQUEUED)); + env(offer(alice, XRP(50000), alice["USD"](5000)), seq(aliceSeq + 1), ter(terQUEUED)); env(noop(alice), seq(aliceSeq + 2), ter(terQUEUED)); // Bob auto batch = [&env](Account a) { @@ -671,18 +623,14 @@ class LedgerRPC_test : public beast::unit_test::suite jvParams[jss::accounts] = true; jvParams[jss::expand] = true; jvParams[jss::type] = "hashes"; - auto const jrr = - env.rpc("json", "ledger", to_string(jvParams))[jss::result]; + auto const jrr = env.rpc("json", "ledger", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::ledger].isMember(jss::accountState)); BEAST_EXPECT(jrr[jss::ledger][jss::accountState].isArray()); - for (auto i = 0; i < jrr[jss::ledger][jss::accountState].size(); - i++) - if (jrr[jss::ledger][jss::accountState][i]["LedgerEntryType"] == - jss::LedgerHashes) + for (auto i = 0; i < jrr[jss::ledger][jss::accountState].size(); i++) + if (jrr[jss::ledger][jss::accountState][i]["LedgerEntryType"] == jss::LedgerHashes) { - index = jrr[jss::ledger][jss::accountState][i]["index"] - .asString(); + index = jrr[jss::ledger][jss::accountState][i]["index"].asString(); hashesLedgerEntryIndex = i; } @@ -692,10 +640,8 @@ class LedgerRPC_test : public beast::unit_test::suite // jss::type is a deprecated field BEAST_EXPECT( - jrr.isMember(jss::warnings) && jrr[jss::warnings].isArray() && - jrr[jss::warnings].size() == 1 && - jrr[jss::warnings][0u][jss::id].asInt() == - warnRPC_FIELDS_DEPRECATED); + jrr.isMember(jss::warnings) && jrr[jss::warnings].isArray() && jrr[jss::warnings].size() == 1 && + jrr[jss::warnings][0u][jss::id].asInt() == warnRPC_FIELDS_DEPRECATED); } { Json::Value jvParams; @@ -703,21 +649,16 @@ class LedgerRPC_test : public beast::unit_test::suite jvParams[jss::accounts] = true; jvParams[jss::expand] = false; jvParams[jss::type] = "hashes"; - auto const jrr = - env.rpc("json", "ledger", to_string(jvParams))[jss::result]; + auto const jrr = env.rpc("json", "ledger", to_string(jvParams))[jss::result]; BEAST_EXPECT(jrr[jss::ledger].isMember(jss::accountState)); BEAST_EXPECT(jrr[jss::ledger][jss::accountState].isArray()); BEAST_EXPECT( - hashesLedgerEntryIndex > 0 && - jrr[jss::ledger][jss::accountState][hashesLedgerEntryIndex] == - index); + hashesLedgerEntryIndex > 0 && jrr[jss::ledger][jss::accountState][hashesLedgerEntryIndex] == index); // jss::type is a deprecated field BEAST_EXPECT( - jrr.isMember(jss::warnings) && jrr[jss::warnings].isArray() && - jrr[jss::warnings].size() == 1 && - jrr[jss::warnings][0u][jss::id].asInt() == - warnRPC_FIELDS_DEPRECATED); + jrr.isMember(jss::warnings) && jrr[jss::warnings].isArray() && jrr[jss::warnings].size() == 1 && + jrr[jss::warnings][0u][jss::id].asInt() == warnRPC_FIELDS_DEPRECATED); } } diff --git a/src/test/rpc/LedgerRequest_test.cpp b/src/test/rpc/LedgerRequest_test.cpp index 153c6ad508..6a1bb2fb89 100644 --- a/src/test/rpc/LedgerRequest_test.cpp +++ b/src/test/rpc/LedgerRequest_test.cpp @@ -14,13 +14,10 @@ namespace RPC { class LedgerRequest_test : public beast::unit_test::suite { - static constexpr char const* hash1 = - "3020EB9E7BE24EF7D7A060CB051583EC117384636D1781AFB5B87F3E348DA489"; - static constexpr char const* accounthash1 = - "BD8A3D72CA73DDE887AD63666EC2BAD07875CBA997A102579B5B95ECDFFEAED8"; + static constexpr char const* hash1 = "3020EB9E7BE24EF7D7A060CB051583EC117384636D1781AFB5B87F3E348DA489"; + static constexpr char const* accounthash1 = "BD8A3D72CA73DDE887AD63666EC2BAD07875CBA997A102579B5B95ECDFFEAED8"; - static constexpr char const* zerohash = - "0000000000000000000000000000000000000000000000000000000000000000"; + static constexpr char const* zerohash = "0000000000000000000000000000000000000000000000000000000000000000"; public: void @@ -39,31 +36,27 @@ public: auto const result = env.rpc("ledger_request", "arbitrary_text"); BEAST_EXPECT( RPC::contains_error(result[jss::result]) && - result[jss::result][jss::error_message] == - "Ledger index too small"); + result[jss::result][jss::error_message] == "Ledger index too small"); } { auto const result = env.rpc("ledger_request", "-1"); BEAST_EXPECT( RPC::contains_error(result[jss::result]) && - result[jss::result][jss::error_message] == - "Ledger index too small"); + result[jss::result][jss::error_message] == "Ledger index too small"); } { auto const result = env.rpc("ledger_request", "0"); BEAST_EXPECT( RPC::contains_error(result[jss::result]) && - result[jss::result][jss::error_message] == - "Ledger index too small"); + result[jss::result][jss::error_message] == "Ledger index too small"); } { auto const result = env.rpc("ledger_request", "1"); BEAST_EXPECT( - !RPC::contains_error(result[jss::result]) && - result[jss::result][jss::ledger_index] == 1 && + !RPC::contains_error(result[jss::result]) && result[jss::result][jss::ledger_index] == 1 && result[jss::result].isMember(jss::ledger)); BEAST_EXPECT( result[jss::result][jss::ledger].isMember(jss::ledger_hash) && @@ -73,8 +66,7 @@ public: { auto const result = env.rpc("ledger_request", "2"); BEAST_EXPECT( - !RPC::contains_error(result[jss::result]) && - result[jss::result][jss::ledger_index] == 2 && + !RPC::contains_error(result[jss::result]) && result[jss::result][jss::ledger_index] == 2 && result[jss::result].isMember(jss::ledger)); BEAST_EXPECT( result[jss::result][jss::ledger].isMember(jss::ledger_hash) && @@ -84,26 +76,22 @@ public: { auto const result = env.rpc("ledger_request", "3"); BEAST_EXPECT( - !RPC::contains_error(result[jss::result]) && - result[jss::result][jss::ledger_index] == 3 && + !RPC::contains_error(result[jss::result]) && result[jss::result][jss::ledger_index] == 3 && result[jss::result].isMember(jss::ledger)); BEAST_EXPECT( result[jss::result][jss::ledger].isMember(jss::ledger_hash) && result[jss::result][jss::ledger][jss::ledger_hash].isString()); - auto const ledgerHash = - result[jss::result][jss::ledger][jss::ledger_hash].asString(); + auto const ledgerHash = result[jss::result][jss::ledger][jss::ledger_hash].asString(); { auto const r = env.rpc("ledger_request", ledgerHash); BEAST_EXPECT( - !RPC::contains_error(r[jss::result]) && - r[jss::result][jss::ledger_index] == 3 && + !RPC::contains_error(r[jss::result]) && r[jss::result][jss::ledger_index] == 3 && r[jss::result].isMember(jss::ledger)); BEAST_EXPECT( r[jss::result][jss::ledger].isMember(jss::ledger_hash) && - r[jss::result][jss::ledger][jss::ledger_hash] == - ledgerHash); + r[jss::result][jss::ledger][jss::ledger_hash] == ledgerHash); } } @@ -114,8 +102,7 @@ public: BEAST_EXPECT( RPC::contains_error(result[jss::result]) && - result[jss::result][jss::error_message] == - "Invalid field 'ledger_hash', not hex string."); + result[jss::result][jss::error_message] == "Invalid field 'ledger_hash', not hex string."); } { @@ -123,25 +110,21 @@ public: auto const result = env.rpc("ledger_request", ledgerHash); - BEAST_EXPECT( - !RPC::contains_error(result[jss::result]) && - result[jss::result][jss::have_header] == false); + BEAST_EXPECT(!RPC::contains_error(result[jss::result]) && result[jss::result][jss::have_header] == false); } { auto const result = env.rpc("ledger_request", "4"); BEAST_EXPECT( RPC::contains_error(result[jss::result]) && - result[jss::result][jss::error_message] == - "Ledger index too large"); + result[jss::result][jss::error_message] == "Ledger index too large"); } { auto const result = env.rpc("ledger_request", "5"); BEAST_EXPECT( RPC::contains_error(result[jss::result]) && - result[jss::result][jss::error_message] == - "Ledger index too large"); + result[jss::result][jss::error_message] == "Ledger index too large"); } } @@ -152,11 +135,8 @@ public: auto cfg = envconfig(); cfg->FEES.reference_fee = 10; - Env env{ - *this, - std::move(cfg), - FeatureBitset{}}; // the hashes being checked below - // assume no amendments + Env env{*this, std::move(cfg), FeatureBitset{}}; // the hashes being checked below + // assume no amendments Account const gw{"gateway"}; auto const USD = gw["USD"]; env.fund(XRP(100000), gw); @@ -176,8 +156,7 @@ public: auto result = env.rpc("ledger_request", "1")[jss::result]; BEAST_EXPECT(result[jss::ledger][jss::ledger_index] == "1"); - BEAST_EXPECT( - result[jss::ledger][jss::total_coins] == "100000000000000000"); + BEAST_EXPECT(result[jss::ledger][jss::total_coins] == "100000000000000000"); BEAST_EXPECT(result[jss::ledger][jss::closed] == true); BEAST_EXPECT(result[jss::ledger][jss::ledger_hash] == hash1); BEAST_EXPECT(result[jss::ledger][jss::parent_hash] == zerohash); @@ -185,11 +164,9 @@ public: BEAST_EXPECT(result[jss::ledger][jss::transaction_hash] == zerohash); result = env.rpc("ledger_request", "2")[jss::result]; - constexpr char const* hash2 = - "CCC3B3E88CCAC17F1BE6B4A648A55999411F19E3FE55EB721960EB0DF28EDDA5"; + constexpr char const* hash2 = "CCC3B3E88CCAC17F1BE6B4A648A55999411F19E3FE55EB721960EB0DF28EDDA5"; BEAST_EXPECT(result[jss::ledger][jss::ledger_index] == "2"); - BEAST_EXPECT( - result[jss::ledger][jss::total_coins] == "100000000000000000"); + BEAST_EXPECT(result[jss::ledger][jss::total_coins] == "100000000000000000"); BEAST_EXPECT(result[jss::ledger][jss::closed] == true); BEAST_EXPECT(result[jss::ledger][jss::ledger_hash] == hash2); BEAST_EXPECT(result[jss::ledger][jss::parent_hash] == hash1); @@ -199,11 +176,9 @@ public: BEAST_EXPECT(result[jss::ledger][jss::transaction_hash] == zerohash); result = env.rpc("ledger_request", "3")[jss::result]; - constexpr char const* hash3 = - "9FFD8AE09190D5002FE4252A1B29EABCF40DABBCE3B42619C6BD0BE381D51103"; + constexpr char const* hash3 = "9FFD8AE09190D5002FE4252A1B29EABCF40DABBCE3B42619C6BD0BE381D51103"; BEAST_EXPECT(result[jss::ledger][jss::ledger_index] == "3"); - BEAST_EXPECT( - result[jss::ledger][jss::total_coins] == "99999999999999980"); + BEAST_EXPECT(result[jss::ledger][jss::total_coins] == "99999999999999980"); BEAST_EXPECT(result[jss::ledger][jss::closed] == true); BEAST_EXPECT(result[jss::ledger][jss::ledger_hash] == hash3); BEAST_EXPECT(result[jss::ledger][jss::parent_hash] == hash2); @@ -215,11 +190,9 @@ public: "CBD7F0948EBFA2241DE4EA627939A0FFEE6B80A90FE09C42C825DA546E9B73FF"); result = env.rpc("ledger_request", "4")[jss::result]; - constexpr char const* hash4 = - "7C9B614445517B8C6477E0AB10A35FFC1A23A34FEA41A91ECBDE884CC097C6E1"; + constexpr char const* hash4 = "7C9B614445517B8C6477E0AB10A35FFC1A23A34FEA41A91ECBDE884CC097C6E1"; BEAST_EXPECT(result[jss::ledger][jss::ledger_index] == "4"); - BEAST_EXPECT( - result[jss::ledger][jss::total_coins] == "99999999999999960"); + BEAST_EXPECT(result[jss::ledger][jss::total_coins] == "99999999999999960"); BEAST_EXPECT(result[jss::ledger][jss::closed] == true); BEAST_EXPECT(result[jss::ledger][jss::ledger_hash] == hash4); BEAST_EXPECT(result[jss::ledger][jss::parent_hash] == hash3); @@ -231,11 +204,9 @@ public: "9BBDDBF926100DFFF364E16268F544B19F5B9BC6ECCBBC104F98D13FA9F3BC35"); result = env.rpc("ledger_request", "5")[jss::result]; - constexpr char const* hash5 = - "98885D02145CCE4AD2605F1809F17188DB2053B14ED399CAC985DD8E03DCA8C0"; + constexpr char const* hash5 = "98885D02145CCE4AD2605F1809F17188DB2053B14ED399CAC985DD8E03DCA8C0"; BEAST_EXPECT(result[jss::ledger][jss::ledger_index] == "5"); - BEAST_EXPECT( - result[jss::ledger][jss::total_coins] == "99999999999999940"); + BEAST_EXPECT(result[jss::ledger][jss::total_coins] == "99999999999999940"); BEAST_EXPECT(result[jss::ledger][jss::closed] == true); BEAST_EXPECT(result[jss::ledger][jss::ledger_hash] == hash5); BEAST_EXPECT(result[jss::ledger][jss::parent_hash] == hash4); @@ -268,10 +239,7 @@ public: "AB868A6CFEEC779C2FF845C0AF00A642259986AF40C01976A7F842B6918936" "C7"; jvParams[jss::ledger_index] = "1"; - auto const result = env.rpc( - "json", - "ledger_request", - jvParams.toStyledString())[jss::result]; + auto const result = env.rpc("json", "ledger_request", jvParams.toStyledString())[jss::result]; BEAST_EXPECT(result[jss::error] == "invalidParams"); BEAST_EXPECT(result[jss::status] == "error"); BEAST_EXPECT( @@ -283,34 +251,26 @@ public: { Json::Value jvParams; jvParams[jss::ledger_index] = "index"; - auto const result = env.rpc( - "json", - "ledger_request", - jvParams.toStyledString())[jss::result]; + auto const result = env.rpc("json", "ledger_request", jvParams.toStyledString())[jss::result]; BEAST_EXPECT(result[jss::error] == "invalidParams"); BEAST_EXPECT(result[jss::status] == "error"); - BEAST_EXPECT( - result[jss::error_message] == - "Invalid field 'ledger_index', not number."); + BEAST_EXPECT(result[jss::error_message] == "Invalid field 'ledger_index', not number."); } // the purpose in this test is to force the ledger expiration/out of // date check to trigger env.timeKeeper().adjustCloseTime(weeks{3}); - auto const result = - env.rpc(apiVersion, "ledger_request", "1")[jss::result]; + auto const result = env.rpc(apiVersion, "ledger_request", "1")[jss::result]; BEAST_EXPECT(result[jss::status] == "error"); if (apiVersion == 1) { BEAST_EXPECT(result[jss::error] == "noCurrent"); - BEAST_EXPECT( - result[jss::error_message] == "Current ledger is unavailable."); + BEAST_EXPECT(result[jss::error_message] == "Current ledger is unavailable."); } else { BEAST_EXPECT(result[jss::error] == "notSynced"); - BEAST_EXPECT( - result[jss::error_message] == "Not synced to the network."); + BEAST_EXPECT(result[jss::error_message] == "Not synced to the network."); } } @@ -339,8 +299,7 @@ public: auto result = env.rpc("ledger_request", "1")[jss::result]; BEAST_EXPECT(result[jss::ledger][jss::ledger_index] == "1"); - BEAST_EXPECT( - result[jss::ledger][jss::total_coins] == "100000000000000000"); + BEAST_EXPECT(result[jss::ledger][jss::total_coins] == "100000000000000000"); BEAST_EXPECT(result[jss::ledger][jss::closed] == true); BEAST_EXPECT(result[jss::ledger][jss::ledger_hash] == hash1); BEAST_EXPECT(result[jss::ledger][jss::parent_hash] == zerohash); @@ -370,8 +329,7 @@ public: { testLedgerRequest(); testEvolution(); - forAllApiVersions( - std::bind_front(&LedgerRequest_test::testBadInput, this)); + forAllApiVersions(std::bind_front(&LedgerRequest_test::testBadInput, this)); testMoreThan256Closed(); testNonAdmin(); } diff --git a/src/test/rpc/ManifestRPC_test.cpp b/src/test/rpc/ManifestRPC_test.cpp index 96326e010f..f42fdd7164 100644 --- a/src/test/rpc/ManifestRPC_test.cpp +++ b/src/test/rpc/ManifestRPC_test.cpp @@ -25,9 +25,7 @@ public: { // manifest with no public key auto const info = env.rpc("json", "manifest", "{ }"); - BEAST_EXPECT( - info[jss::result][jss::error_message] == - "Missing field 'public_key'."); + BEAST_EXPECT(info[jss::result][jss::error_message] == "Missing field 'public_key'."); } { // manifest with malformed public key @@ -36,8 +34,7 @@ public: "manifest", "{ \"public_key\": " "\"abcdef12345\"}"); - BEAST_EXPECT( - info[jss::result][jss::error_message] == "Invalid parameters."); + BEAST_EXPECT(info[jss::result][jss::error_message] == "Invalid parameters."); } } @@ -47,8 +44,7 @@ public: testcase("Lookup"); using namespace jtx; - std::string const key = - "n949f75evCHwgyP4fPVgaHqNHxUVN15PsJEZ3B3HnXPcPjcZAoy7"; + std::string const key = "n949f75evCHwgyP4fPVgaHqNHxUVN15PsJEZ3B3HnXPcPjcZAoy7"; Env env{*this, envconfig([&key](std::unique_ptr cfg) { cfg->section(SECTION_VALIDATORS).append(key); return cfg; diff --git a/src/test/rpc/NoRippleCheck_test.cpp b/src/test/rpc/NoRippleCheck_test.cpp index 7ed2cd8fd1..0857561fda 100644 --- a/src/test/rpc/NoRippleCheck_test.cpp +++ b/src/test/rpc/NoRippleCheck_test.cpp @@ -29,18 +29,15 @@ class NoRippleCheck_test : public beast::unit_test::suite env.close(); { // missing account field - auto const result = - env.rpc("json", "noripple_check", "{}")[jss::result]; + auto const result = env.rpc("json", "noripple_check", "{}")[jss::result]; BEAST_EXPECT(result[jss::error] == "invalidParams"); - BEAST_EXPECT( - result[jss::error_message] == "Missing field 'account'."); + BEAST_EXPECT(result[jss::error_message] == "Missing field 'account'."); } { // missing role field Json::Value params; params[jss::account] = alice.human(); - auto const result = env.rpc( - "json", "noripple_check", to_string(params))[jss::result]; + auto const result = env.rpc("json", "noripple_check", to_string(params))[jss::result]; BEAST_EXPECT(result[jss::error] == "invalidParams"); BEAST_EXPECT(result[jss::error_message] == "Missing field 'role'."); } @@ -51,11 +48,9 @@ class NoRippleCheck_test : public beast::unit_test::suite Json::Value params; params[jss::account] = param; params[jss::role] = "user"; - auto jrr = env.rpc( - "json", "noripple_check", to_string(params))[jss::result]; + auto jrr = env.rpc("json", "noripple_check", to_string(params))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "invalidParams"); - BEAST_EXPECT( - jrr[jss::error_message] == "Invalid field 'account'."); + BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'account'."); }; testInvalidAccountParam(1); @@ -70,8 +65,7 @@ class NoRippleCheck_test : public beast::unit_test::suite Json::Value params; params[jss::account] = alice.human(); params[jss::role] = "not_a_role"; - auto const result = env.rpc( - "json", "noripple_check", to_string(params))[jss::result]; + auto const result = env.rpc("json", "noripple_check", to_string(params))[jss::result]; BEAST_EXPECT(result[jss::error] == "invalidParams"); BEAST_EXPECT(result[jss::error_message] == "Invalid field 'role'."); } @@ -81,12 +75,9 @@ class NoRippleCheck_test : public beast::unit_test::suite params[jss::account] = alice.human(); params[jss::role] = "user"; params[jss::limit] = -1; - auto const result = env.rpc( - "json", "noripple_check", to_string(params))[jss::result]; + auto const result = env.rpc("json", "noripple_check", to_string(params))[jss::result]; BEAST_EXPECT(result[jss::error] == "invalidParams"); - BEAST_EXPECT( - result[jss::error_message] == - "Invalid field 'limit', not unsigned integer."); + BEAST_EXPECT(result[jss::error_message] == "Invalid field 'limit', not unsigned integer."); } { // invalid ledger (hash) @@ -94,12 +85,9 @@ class NoRippleCheck_test : public beast::unit_test::suite params[jss::account] = alice.human(); params[jss::role] = "user"; params[jss::ledger_hash] = 1; - auto const result = env.rpc( - "json", "noripple_check", to_string(params))[jss::result]; + auto const result = env.rpc("json", "noripple_check", to_string(params))[jss::result]; BEAST_EXPECT(result[jss::error] == "invalidParams"); - BEAST_EXPECT( - result[jss::error_message] == - "Invalid field 'ledger_hash', not hex string."); + BEAST_EXPECT(result[jss::error_message] == "Invalid field 'ledger_hash', not hex string."); } { // account not found @@ -107,8 +95,7 @@ class NoRippleCheck_test : public beast::unit_test::suite params[jss::account] = Account{"nobody"}.human(); params[jss::role] = "user"; params[jss::ledger] = "current"; - auto const result = env.rpc( - "json", "noripple_check", to_string(params))[jss::result]; + auto const result = env.rpc("json", "noripple_check", to_string(params))[jss::result]; BEAST_EXPECT(result[jss::error] == "actNotFound"); BEAST_EXPECT(result[jss::error_message] == "Account not found."); } @@ -119,8 +106,7 @@ class NoRippleCheck_test : public beast::unit_test::suite params[jss::account] = toBase58(TokenType::NodePrivate, alice.sk()); params[jss::role] = "user"; params[jss::ledger] = "current"; - auto const result = env.rpc( - "json", "noripple_check", to_string(params))[jss::result]; + auto const result = env.rpc("json", "noripple_check", to_string(params))[jss::result]; BEAST_EXPECT(result[jss::error] == "actMalformed"); BEAST_EXPECT(result[jss::error_message] == "Account malformed."); } @@ -132,8 +118,7 @@ class NoRippleCheck_test : public beast::unit_test::suite params[jss::role] = "user"; params[jss::ledger] = "current"; params[jss::ledger_hash] = "ABCDEF"; - auto const result = env.rpc( - "json", "noripple_check", to_string(params))[jss::result]; + auto const result = env.rpc("json", "noripple_check", to_string(params))[jss::result]; BEAST_EXPECT(result[jss::error] == "invalidParams"); BEAST_EXPECT( result[jss::error_message] == @@ -147,20 +132,17 @@ class NoRippleCheck_test : public beast::unit_test::suite params[jss::account] = Account{"nobody"}.human(); params[jss::role] = "user"; params[jss::ledger] = Json::objectValue; - auto const result = env.rpc( - "json", "noripple_check", to_string(params))[jss::result]; + auto const result = env.rpc("json", "noripple_check", to_string(params))[jss::result]; BEAST_EXPECT(result[jss::error] == "invalidParams"); - BEAST_EXPECT( - result[jss::error_message] == - "Invalid field 'ledger', not string or number."); + BEAST_EXPECT(result[jss::error_message] == "Invalid field 'ledger', not string or number."); } } void testBasic(bool user, bool problems) { - testcase << "Request noripple_check for " << (user ? "user" : "gateway") - << " role, expect" << (problems ? "" : " no") << " problems"; + testcase << "Request noripple_check for " << (user ? "user" : "gateway") << " role, expect" + << (problems ? "" : " no") << " problems"; using namespace test::jtx; Env env{*this}; @@ -185,8 +167,7 @@ class NoRippleCheck_test : public beast::unit_test::suite params[jss::account] = alice.human(); params[jss::role] = (user ? "user" : "gateway"); params[jss::ledger] = "current"; - auto result = - env.rpc("json", "noripple_check", to_string(params))[jss::result]; + auto result = env.rpc("json", "noripple_check", to_string(params))[jss::result]; auto const pa = result["problems"]; if (!BEAST_EXPECT(pa.isArray())) @@ -199,17 +180,13 @@ class NoRippleCheck_test : public beast::unit_test::suite if (user) { - BEAST_EXPECT(boost::starts_with( - pa[0u].asString(), "You appear to have set")); - BEAST_EXPECT(boost::starts_with( - pa[1u].asString(), "You should probably set")); + BEAST_EXPECT(boost::starts_with(pa[0u].asString(), "You appear to have set")); + BEAST_EXPECT(boost::starts_with(pa[1u].asString(), "You should probably set")); } else { - BEAST_EXPECT(boost::starts_with( - pa[0u].asString(), "You should immediately set")); - BEAST_EXPECT( - boost::starts_with(pa[1u].asString(), "You should clear")); + BEAST_EXPECT(boost::starts_with(pa[0u].asString(), "You should immediately set")); + BEAST_EXPECT(boost::starts_with(pa[1u].asString(), "You should clear")); } } else @@ -220,8 +197,7 @@ class NoRippleCheck_test : public beast::unit_test::suite // now make a second request asking for the relevant transactions this // time. params[jss::transactions] = true; - result = - env.rpc("json", "noripple_check", to_string(params))[jss::result]; + result = env.rpc("json", "noripple_check", to_string(params))[jss::result]; if (!BEAST_EXPECT(result[jss::transactions].isArray())) return; @@ -237,12 +213,8 @@ class NoRippleCheck_test : public beast::unit_test::suite BEAST_EXPECT(txs[0u][jss::TransactionType] == jss::AccountSet); } - BEAST_EXPECT( - result[jss::transactions][txs.size() - 1][jss::Account] == - alice.human()); - BEAST_EXPECT( - result[jss::transactions][txs.size() - 1] - [jss::TransactionType] == jss::TrustSet); + BEAST_EXPECT(result[jss::transactions][txs.size() - 1][jss::Account] == alice.human()); + BEAST_EXPECT(result[jss::transactions][txs.size() - 1][jss::TransactionType] == jss::TrustSet); BEAST_EXPECT( result[jss::transactions][txs.size() - 1][jss::LimitAmount] == gw["USD"](100).value().getJson(JsonOptions::none)); @@ -269,8 +241,7 @@ class NoRippleCheckLimits_test : public beast::unit_test::suite void testLimits(bool admin) { - testcase << "Check limits in returned data, " - << (admin ? "admin" : "non-admin"); + testcase << "Check limits in returned data, " << (admin ? "admin" : "non-admin"); using namespace test::jtx; @@ -292,15 +263,14 @@ class NoRippleCheckLimits_test : public beast::unit_test::suite using namespace xrpl::Resource; using namespace std::chrono; using namespace beast::IP; - auto c = env.app().getResourceManager().newInboundEndpoint( - Endpoint::from_string(test::getEnvLocalhostAddr())); + auto c = + env.app().getResourceManager().newInboundEndpoint(Endpoint::from_string(test::getEnvLocalhostAddr())); // if we go above the warning threshold, reset if (c.balance() > warningThreshold) { using ct = beast::abstract_clock; - c.entry().local_balance = - DecayingSample{steady_clock::now()}; + c.entry().local_balance = DecayingSample{steady_clock::now()}; } }; @@ -315,23 +285,14 @@ class NoRippleCheckLimits_test : public beast::unit_test::suite auto const baseFee = env.current()->fees().base; env(pay(env.master, gw, XRP(1000)), seq(autofill), - fee(toDrops( - txq.getMetrics(*env.current()).openLedgerFeeLevel, - baseFee) + - 1), + fee(toDrops(txq.getMetrics(*env.current()).openLedgerFeeLevel, baseFee) + 1), sig(autofill)); env(fset(gw, asfDefaultRipple), seq(autofill), - fee(toDrops( - txq.getMetrics(*env.current()).openLedgerFeeLevel, - baseFee) + - 1), + fee(toDrops(txq.getMetrics(*env.current()).openLedgerFeeLevel, baseFee) + 1), sig(autofill)); env(trust(alice, gw["USD"](10)), - fee(toDrops( - txq.getMetrics(*env.current()).openLedgerFeeLevel, - baseFee) + - 1)); + fee(toDrops(txq.getMetrics(*env.current()).openLedgerFeeLevel, baseFee) + 1)); env.close(); } @@ -340,33 +301,28 @@ class NoRippleCheckLimits_test : public beast::unit_test::suite params[jss::account] = alice.human(); params[jss::role] = "user"; params[jss::ledger] = "current"; - auto result = - env.rpc("json", "noripple_check", to_string(params))[jss::result]; + auto result = env.rpc("json", "noripple_check", to_string(params))[jss::result]; BEAST_EXPECT(result["problems"].size() == 301); // one below minimum params[jss::limit] = 9; - result = - env.rpc("json", "noripple_check", to_string(params))[jss::result]; + result = env.rpc("json", "noripple_check", to_string(params))[jss::result]; BEAST_EXPECT(result["problems"].size() == (admin ? 10 : 11)); // at minimum params[jss::limit] = 10; - result = - env.rpc("json", "noripple_check", to_string(params))[jss::result]; + result = env.rpc("json", "noripple_check", to_string(params))[jss::result]; BEAST_EXPECT(result["problems"].size() == 11); // at max params[jss::limit] = 400; - result = - env.rpc("json", "noripple_check", to_string(params))[jss::result]; + result = env.rpc("json", "noripple_check", to_string(params))[jss::result]; BEAST_EXPECT(result["problems"].size() == 401); // at max+1 params[jss::limit] = 401; - result = - env.rpc("json", "noripple_check", to_string(params))[jss::result]; + result = env.rpc("json", "noripple_check", to_string(params))[jss::result]; BEAST_EXPECT(result["problems"].size() == (admin ? 402 : 401)); } diff --git a/src/test/rpc/NoRipple_test.cpp b/src/test/rpc/NoRipple_test.cpp index 040ceaaa29..9cfc69ccd5 100644 --- a/src/test/rpc/NoRipple_test.cpp +++ b/src/test/rpc/NoRipple_test.cpp @@ -33,18 +33,13 @@ public: for (auto SetOrClear : {true, false}) { // Create a trust line with no-ripple flag setting - env(trust( - gw, - USD(100), - alice, - SetOrClear ? tfSetNoRipple : tfClearNoRipple)); + env(trust(gw, USD(100), alice, SetOrClear ? tfSetNoRipple : tfClearNoRipple)); env.close(); // Check no-ripple flag on sender 'gateway' - Json::Value lines{ - env.rpc("json", "account_lines", to_string(account_gw))}; - auto const& gline0 = lines[jss::result][jss::lines][0u]; - BEAST_EXPECT(gline0[jss::no_ripple].asBool() == SetOrClear); + Json::Value lines{env.rpc("json", "account_lines", to_string(account_gw))}; + auto const& gwLine0 = lines[jss::result][jss::lines][0u]; + BEAST_EXPECT(gwLine0[jss::no_ripple].asBool() == SetOrClear); // Check no-ripple peer flag on destination 'alice' lines = env.rpc("json", "account_lines", to_string(account_alice)); @@ -96,8 +91,7 @@ public: return dest_amt; }(); - auto const resp = - env.rpc("json", "ripple_path_find", to_string(params)); + auto const resp = env.rpc("json", "ripple_path_find", to_string(params)); BEAST_EXPECT(resp[jss::result][jss::alternatives].size() == 1); auto getAccountLines = [&env](Account const& acct) { @@ -167,8 +161,7 @@ public: return dest_amt; }(); - Json::Value const resp{ - env.rpc("json", "ripple_path_find", to_string(params))}; + Json::Value const resp{env.rpc("json", "ripple_path_find", to_string(params))}; BEAST_EXPECT(resp[jss::result][jss::alternatives].size() == 0); env(pay(alice, carol, bob["USD"](50)), ter(tecPATH_DRY)); @@ -239,13 +232,11 @@ public: params[jss::role] = "gateway"; params[jss::transactions] = "asdf"; - auto lines = - env.rpc("json", "noripple_check", to_string(params)); + auto lines = env.rpc("json", "noripple_check", to_string(params)); if (apiVersion < 2u) BEAST_EXPECT(lines[jss::result][jss::status] == "success"); else - BEAST_EXPECT( - lines[jss::result][jss::error] == "invalidParams"); + BEAST_EXPECT(lines[jss::result][jss::error] == "invalidParams"); } } } @@ -256,9 +247,7 @@ public: testSetAndClear(); auto withFeatsTests = [this](FeatureBitset features) { - forAllApiVersions([&, this](unsigned testVersion) { - testDefaultRipple(features, testVersion); - }); + forAllApiVersions([&, this](unsigned testVersion) { testDefaultRipple(features, testVersion); }); testNegativeBalance(features); testPairwise(features); }; diff --git a/src/test/rpc/OwnerInfo_test.cpp b/src/test/rpc/OwnerInfo_test.cpp index b47b529680..9e3fee04c2 100644 --- a/src/test/rpc/OwnerInfo_test.cpp +++ b/src/test/rpc/OwnerInfo_test.cpp @@ -22,32 +22,21 @@ class OwnerInfo_test : public beast::unit_test::suite env.close(); { // missing account field - auto const result = - env.rpc("json", "owner_info", "{}")[jss::result]; + auto const result = env.rpc("json", "owner_info", "{}")[jss::result]; BEAST_EXPECT(result[jss::error] == "invalidParams"); - BEAST_EXPECT( - result[jss::error_message] == "Missing field 'account'."); + BEAST_EXPECT(result[jss::error_message] == "Missing field 'account'."); } { // ask for empty account Json::Value params; params[jss::account] = ""; - auto const result = - env.rpc("json", "owner_info", to_string(params))[jss::result]; - if (BEAST_EXPECT( - result.isMember(jss::accepted) && - result.isMember(jss::current))) + auto const result = env.rpc("json", "owner_info", to_string(params))[jss::result]; + if (BEAST_EXPECT(result.isMember(jss::accepted) && result.isMember(jss::current))) { - BEAST_EXPECT( - result[jss::accepted][jss::error] == "actMalformed"); - BEAST_EXPECT( - result[jss::accepted][jss::error_message] == - "Account malformed."); - BEAST_EXPECT( - result[jss::current][jss::error] == "actMalformed"); - BEAST_EXPECT( - result[jss::current][jss::error_message] == - "Account malformed."); + BEAST_EXPECT(result[jss::accepted][jss::error] == "actMalformed"); + BEAST_EXPECT(result[jss::accepted][jss::error_message] == "Account malformed."); + BEAST_EXPECT(result[jss::current][jss::error] == "actMalformed"); + BEAST_EXPECT(result[jss::current][jss::error_message] == "Account malformed."); } } @@ -56,8 +45,7 @@ class OwnerInfo_test : public beast::unit_test::suite // (deprecated) does not return an error, just empty fields. Json::Value params; params[jss::account] = Account{"bob"}.human(); - auto const result = - env.rpc("json", "owner_info", to_string(params))[jss::result]; + auto const result = env.rpc("json", "owner_info", to_string(params))[jss::result]; BEAST_EXPECT(result[jss::accepted] == Json::objectValue); BEAST_EXPECT(result[jss::current] == Json::objectValue); BEAST_EXPECT(result[jss::status] == "success"); @@ -89,11 +77,8 @@ class OwnerInfo_test : public beast::unit_test::suite Json::Value params; params[jss::account] = alice.human(); - auto const result = - env.rpc("json", "owner_info", to_string(params))[jss::result]; - if (!BEAST_EXPECT( - result.isMember(jss::accepted) && - result.isMember(jss::current))) + auto const result = env.rpc("json", "owner_info", to_string(params))[jss::result]; + if (!BEAST_EXPECT(result.isMember(jss::accepted) && result.isMember(jss::current))) { return; } @@ -107,27 +92,15 @@ class OwnerInfo_test : public beast::unit_test::suite BEAST_EXPECT( lines[0u][sfBalance.fieldName] == - (STAmount{Issue{to_currency("CNY"), noAccount()}, 0} - .value() - .getJson(JsonOptions::none))); - BEAST_EXPECT( - lines[0u][sfHighLimit.fieldName] == - alice["CNY"](1000).value().getJson(JsonOptions::none)); - BEAST_EXPECT( - lines[0u][sfLowLimit.fieldName] == - gw["CNY"](0).value().getJson(JsonOptions::none)); + (STAmount{Issue{to_currency("CNY"), noAccount()}, 0}.value().getJson(JsonOptions::none))); + BEAST_EXPECT(lines[0u][sfHighLimit.fieldName] == alice["CNY"](1000).value().getJson(JsonOptions::none)); + BEAST_EXPECT(lines[0u][sfLowLimit.fieldName] == gw["CNY"](0).value().getJson(JsonOptions::none)); BEAST_EXPECT( lines[1u][sfBalance.fieldName] == - (STAmount{Issue{to_currency("USD"), noAccount()}, 0} - .value() - .getJson(JsonOptions::none))); - BEAST_EXPECT( - lines[1u][sfHighLimit.fieldName] == - alice["USD"](1000).value().getJson(JsonOptions::none)); - BEAST_EXPECT( - lines[1u][sfLowLimit.fieldName] == - USD(0).value().getJson(JsonOptions::none)); + (STAmount{Issue{to_currency("USD"), noAccount()}, 0}.value().getJson(JsonOptions::none))); + BEAST_EXPECT(lines[1u][sfHighLimit.fieldName] == alice["USD"](1000).value().getJson(JsonOptions::none)); + BEAST_EXPECT(lines[1u][sfLowLimit.fieldName] == USD(0).value().getJson(JsonOptions::none)); if (!BEAST_EXPECT(result[jss::accepted].isMember(jss::offers))) return; @@ -136,12 +109,8 @@ class OwnerInfo_test : public beast::unit_test::suite return; BEAST_EXPECT(offers[0u][jss::Account] == alice.human()); - BEAST_EXPECT( - offers[0u][sfTakerGets.fieldName] == - XRP(1000).value().getJson(JsonOptions::none)); - BEAST_EXPECT( - offers[0u][sfTakerPays.fieldName] == - USD(1).value().getJson(JsonOptions::none)); + BEAST_EXPECT(offers[0u][sfTakerGets.fieldName] == XRP(1000).value().getJson(JsonOptions::none)); + BEAST_EXPECT(offers[0u][sfTakerPays.fieldName] == USD(1).value().getJson(JsonOptions::none)); // current ledger entry if (!BEAST_EXPECT(result[jss::current].isMember(jss::ripple_lines))) @@ -152,27 +121,15 @@ class OwnerInfo_test : public beast::unit_test::suite BEAST_EXPECT( lines[0u][sfBalance.fieldName] == - (STAmount{Issue{to_currency("CNY"), noAccount()}, -50} - .value() - .getJson(JsonOptions::none))); - BEAST_EXPECT( - lines[0u][sfHighLimit.fieldName] == - alice["CNY"](1000).value().getJson(JsonOptions::none)); - BEAST_EXPECT( - lines[0u][sfLowLimit.fieldName] == - gw["CNY"](0).value().getJson(JsonOptions::none)); + (STAmount{Issue{to_currency("CNY"), noAccount()}, -50}.value().getJson(JsonOptions::none))); + BEAST_EXPECT(lines[0u][sfHighLimit.fieldName] == alice["CNY"](1000).value().getJson(JsonOptions::none)); + BEAST_EXPECT(lines[0u][sfLowLimit.fieldName] == gw["CNY"](0).value().getJson(JsonOptions::none)); BEAST_EXPECT( lines[1u][sfBalance.fieldName] == - (STAmount{Issue{to_currency("USD"), noAccount()}, -50} - .value() - .getJson(JsonOptions::none))); - BEAST_EXPECT( - lines[1u][sfHighLimit.fieldName] == - alice["USD"](1000).value().getJson(JsonOptions::none)); - BEAST_EXPECT( - lines[1u][sfLowLimit.fieldName] == - gw["USD"](0).value().getJson(JsonOptions::none)); + (STAmount{Issue{to_currency("USD"), noAccount()}, -50}.value().getJson(JsonOptions::none))); + BEAST_EXPECT(lines[1u][sfHighLimit.fieldName] == alice["USD"](1000).value().getJson(JsonOptions::none)); + BEAST_EXPECT(lines[1u][sfLowLimit.fieldName] == gw["USD"](0).value().getJson(JsonOptions::none)); if (!BEAST_EXPECT(result[jss::current].isMember(jss::offers))) return; @@ -183,12 +140,8 @@ class OwnerInfo_test : public beast::unit_test::suite BEAST_EXPECT(offers[1u] == result[jss::accepted][jss::offers][0u]); BEAST_EXPECT(offers[0u][jss::Account] == alice.human()); - BEAST_EXPECT( - offers[0u][sfTakerGets.fieldName] == - XRP(1000).value().getJson(JsonOptions::none)); - BEAST_EXPECT( - offers[0u][sfTakerPays.fieldName] == - CNY(2).value().getJson(JsonOptions::none)); + BEAST_EXPECT(offers[0u][sfTakerGets.fieldName] == XRP(1000).value().getJson(JsonOptions::none)); + BEAST_EXPECT(offers[0u][sfTakerPays.fieldName] == CNY(2).value().getJson(JsonOptions::none)); } public: diff --git a/src/test/rpc/Peers_test.cpp b/src/test/rpc/Peers_test.cpp index 639f5e98cb..8e4e560f3e 100644 --- a/src/test/rpc/Peers_test.cpp +++ b/src/test/rpc/Peers_test.cpp @@ -22,24 +22,20 @@ class Peers_test : public beast::unit_test::suite // without modification of the cluster, expect an empty set // from this request auto peers = env.rpc("peers")[jss::result]; - BEAST_EXPECT( - peers.isMember(jss::cluster) && peers[jss::cluster].size() == 0); + BEAST_EXPECT(peers.isMember(jss::cluster) && peers[jss::cluster].size() == 0); BEAST_EXPECT(peers.isMember(jss::peers) && peers[jss::peers].isNull()); // insert some nodes in to the cluster std::unordered_map nodes; for (auto i = 0; i < 3; ++i) { - auto kp = generateKeyPair( - KeyType::secp256k1, generateSeed("seed" + std::to_string(i))); + auto kp = generateKeyPair(KeyType::secp256k1, generateSeed("seed" + std::to_string(i))); std::string name = "Node " + std::to_string(i); using namespace std::chrono_literals; - env.app().cluster().update( - kp.first, name, 200, env.timeKeeper().now() - 10s); - nodes.insert(std::make_pair( - toBase58(TokenType::NodePublic, kp.first), name)); + env.app().cluster().update(kp.first, name, 200, env.timeKeeper().now() - 10s); + nodes.insert(std::make_pair(toBase58(TokenType::NodePublic, kp.first), name)); } // make request, verify nodes we created match @@ -49,9 +45,7 @@ class Peers_test : public beast::unit_test::suite return; if (!BEAST_EXPECT(peers[jss::cluster].size() == nodes.size())) return; - for (auto it = peers[jss::cluster].begin(); - it != peers[jss::cluster].end(); - ++it) + for (auto it = peers[jss::cluster].begin(); it != peers[jss::cluster].end(); ++it) { auto key = it.key().asString(); auto search = nodes.find(key); diff --git a/src/test/rpc/RPCCall_test.cpp b/src/test/rpc/RPCCall_test.cpp index 85402ff024..26f7ed0f18 100644 --- a/src/test/rpc/RPCCall_test.cpp +++ b/src/test/rpc/RPCCall_test.cpp @@ -37,11 +37,7 @@ struct RPCCallTestData std::initializer_list const& args_, Exception throwsWhat_, char const* exp_) - : description(description_) - , line(line_) - , args(args_) - , throwsWhat(throwsWhat_) - , exp(1, exp_) + : description(description_), line(line_), args(args_), throwsWhat(throwsWhat_), exp(1, exp_) { } @@ -51,11 +47,7 @@ struct RPCCallTestData std::initializer_list const& args_, Exception throwsWhat_, std::initializer_list exp_) - : description(description_) - , line(line_) - , args(args_) - , throwsWhat(throwsWhat_) - , exp(exp_) + : description(description_), line(line_), args(args_), throwsWhat(throwsWhat_), exp(exp_) { } @@ -86,9 +78,7 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"account_channels: account and ledger hash.", __LINE__, - {"account_channels", - "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", - "rD5MbavGfiSC5m7mkxy1FANuT7s3HxqpoF"}, + {"account_channels", "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", "rD5MbavGfiSC5m7mkxy1FANuT7s3HxqpoF"}, RPCCallTestData::no_exception, R"({ "method" : "account_channels", @@ -102,9 +92,7 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"account_channels: account and ledger index.", __LINE__, - {"account_channels", - "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", - "r9emE59aTWb85t64dAebKrxYMBTpzK5yR7"}, + {"account_channels", "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", "r9emE59aTWb85t64dAebKrxYMBTpzK5yR7"}, RPCCallTestData::no_exception, R"({ "method" : "account_channels", @@ -118,9 +106,7 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"account_channels: two accounts.", __LINE__, - {"account_channels", - "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", - "rnUy2SHTrB9DubsPmkJZUXTf5FcNDGrYEA"}, + {"account_channels", "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", "rnUy2SHTrB9DubsPmkJZUXTf5FcNDGrYEA"}, RPCCallTestData::no_exception, R"({ "method" : "account_channels", @@ -152,10 +138,7 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"account_channels: two accounts and ledger index.", __LINE__, - {"account_channels", - "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", - "rnUy2SHTrB9DubsPmkJZUXTf5FcNDGrYEA", - "90210"}, + {"account_channels", "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", "rnUy2SHTrB9DubsPmkJZUXTf5FcNDGrYEA", "90210"}, RPCCallTestData::no_exception, R"({ "method" : "account_channels", @@ -308,11 +291,7 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"account_currencies: too many arguments.", __LINE__, - {"account_currencies", - "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", - "current", - "spare1", - "spare2"}, + {"account_currencies", "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", "current", "spare1", "spare2"}, RPCCallTestData::no_exception, R"({ "method" : "account_currencies", @@ -449,11 +428,7 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"account_info: too many arguments.", __LINE__, - {"account_info", - "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", - "current", - "extra1", - "extra2"}, + {"account_info", "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", "current", "extra1", "extra2"}, RPCCallTestData::no_exception, R"({ "method" : "account_info", @@ -502,9 +477,7 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"account_lines: peer.", __LINE__, - {"account_lines", - "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", - "rnUy2SHTrB9DubsPmkJZUXTf5FcNDGrYEA"}, + {"account_lines", "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", "rnUy2SHTrB9DubsPmkJZUXTf5FcNDGrYEA"}, RPCCallTestData::no_exception, R"({ "method" : "account_lines", @@ -518,10 +491,7 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"account_lines: peer and numeric ledger index.", __LINE__, - {"account_lines", - "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", - "rnUy2SHTrB9DubsPmkJZUXTf5FcNDGrYEA", - "888888888"}, + {"account_lines", "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", "rnUy2SHTrB9DubsPmkJZUXTf5FcNDGrYEA", "888888888"}, RPCCallTestData::no_exception, R"({ "method" : "account_lines", @@ -536,10 +506,7 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"account_lines: peer and text ledger index.", __LINE__, - {"account_lines", - "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", - "rnUy2SHTrB9DubsPmkJZUXTf5FcNDGrYEA", - "closed"}, + {"account_lines", "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", "rnUy2SHTrB9DubsPmkJZUXTf5FcNDGrYEA", "closed"}, RPCCallTestData::no_exception, R"({ "method" : "account_lines", @@ -688,10 +655,7 @@ static RPCCallTestData const rpcCallTestArray[] = { { "account_lines: invalid ledger selector.", __LINE__, - {"account_lines", - "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", - "rnUy2SHTrB9DubsPmkJZUXTf5FcNDGrYEA", - "not_a_ledger"}, + {"account_lines", "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", "rnUy2SHTrB9DubsPmkJZUXTf5FcNDGrYEA", "not_a_ledger"}, RPCCallTestData::no_exception, R"({ "method" : "account_lines", @@ -1006,10 +970,7 @@ static RPCCallTestData const rpcCallTestArray[] = { {// Note: I believe this _ought_ to be detected as too many arguments. "account_offers: four arguments.", __LINE__, - {"account_offers", - "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", - "current", - "extra"}, + {"account_offers", "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", "current", "extra"}, RPCCallTestData::no_exception, R"({ "method" : "account_offers", @@ -1128,12 +1089,7 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"account_tx: ledger_index plus trailing params.", __LINE__, - {"account_tx", - "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", - "707", - "descending", - "binary", - "count"}, + {"account_tx", "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", "707", "descending", "binary", "count"}, RPCCallTestData::no_exception, R"({ "method" : "account_tx", @@ -1165,13 +1121,7 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"account_tx: ledger_index_min and _max plus trailing params.", __LINE__, - {"account_tx", - "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", - "-1", - "413", - "binary", - "count", - "descending"}, + {"account_tx", "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", "-1", "413", "binary", "count", "descending"}, RPCCallTestData::no_exception, R"({ "method" : "account_tx", @@ -1205,14 +1155,7 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"account_tx: ledger_index_min and _max, limit, trailing args.", __LINE__, - {"account_tx", - "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", - "247", - "-1", - "300", - "count", - "descending", - "binary"}, + {"account_tx", "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", "247", "-1", "300", "count", "descending", "binary"}, RPCCallTestData::no_exception, R"({ "method" : "account_tx", @@ -1231,12 +1174,7 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"account_tx: ledger_index_min and _max plus limit and offset.", __LINE__, - {"account_tx", - "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", - "589", - "590", - "67", - "45"}, + {"account_tx", "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", "589", "590", "67", "45"}, RPCCallTestData::no_exception, R"({ "method" : "account_tx", @@ -1253,14 +1191,7 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"account_tx: ledger_index_min and _max, limit, offset, trailing.", __LINE__, - {"account_tx", - "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", - "589", - "590", - "67", - "45", - "descending", - "count"}, + {"account_tx", "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", "589", "590", "67", "45", "descending", "count"}, RPCCallTestData::no_exception, R"({ "method" : "account_tx", @@ -1396,11 +1327,7 @@ static RPCCallTestData const rpcCallTestArray[] = { // Note: this really shouldn't throw, but does at the moment. "account_tx: non-integer offset.", __LINE__, - {"account_tx", - "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", - "-1", - "-1", - "decending"}, + {"account_tx", "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", "-1", "-1", "decending"}, RPCCallTestData::bad_cast, R"()", }, @@ -1408,26 +1335,14 @@ static RPCCallTestData const rpcCallTestArray[] = { // Note: this really shouldn't throw, but does at the moment. "account_tx: non-integer limit.", __LINE__, - {"account_tx", - "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", - "-1", - "-1", - "300", - "false"}, + {"account_tx", "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", "-1", "-1", "300", "false"}, RPCCallTestData::bad_cast, R"()", }, {// Note: this really shouldn't throw, but does at the moment. "account_tx: RIPD-1570.", __LINE__, - {"account_tx", - "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", - "-1", - "-1", - "2", - "false", - "false", - "false"}, + {"account_tx", "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", "-1", "-1", "2", "false", "false", "false"}, RPCCallTestData::bad_cast, R"()"}, @@ -1502,11 +1417,7 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"book_offers: add issuer and numeric ledger index.", __LINE__, - {"book_offers", - "USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", - "EUR", - "rnUy2SHTrB9DubsPmkJZUXTf5FcNDGrYEA", - "666"}, + {"book_offers", "USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", "EUR", "rnUy2SHTrB9DubsPmkJZUXTf5FcNDGrYEA", "666"}, RPCCallTestData::no_exception, R"({ "method" : "book_offers", @@ -1527,11 +1438,7 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"book_offers: add issuer and text ledger index.", __LINE__, - {"book_offers", - "USD", - "EUR/rnUy2SHTrB9DubsPmkJZUXTf5FcNDGrYEA", - "rnUy2SHTrB9DubsPmkJZUXTf5FcNDGrYEA", - "current"}, + {"book_offers", "USD", "EUR/rnUy2SHTrB9DubsPmkJZUXTf5FcNDGrYEA", "rnUy2SHTrB9DubsPmkJZUXTf5FcNDGrYEA", "current"}, RPCCallTestData::no_exception, R"({ "method" : "book_offers", @@ -2425,10 +2332,7 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"deposit_authorized: with text ledger index.", __LINE__, - {"deposit_authorized", - "source_account_NotValidated", - "destination_account_NotValidated", - "validated"}, + {"deposit_authorized", "source_account_NotValidated", "destination_account_NotValidated", "validated"}, RPCCallTestData::no_exception, R"({ "method" : "deposit_authorized", @@ -2761,9 +2665,7 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"gateway_balances: 1 hotwallet.", __LINE__, - {"gateway_balances", - "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", - "hotwallet_is_not_validated"}, + {"gateway_balances", "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", "hotwallet_is_not_validated"}, RPCCallTestData::no_exception, R"({ "method" : "gateway_balances", @@ -2934,11 +2836,7 @@ static RPCCallTestData const rpcCallTestArray[] = { }, RPCCallTestData::bad_cast, R"()"}, - {"get_counts: count too large.", - __LINE__, - {"get_counts", "4294967296"}, - RPCCallTestData::bad_cast, - R"()"}, + {"get_counts: count too large.", __LINE__, {"get_counts", "4294967296"}, RPCCallTestData::bad_cast, R"()"}, // json // ------------------------------------------------------------------------ @@ -3165,9 +3063,7 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"json2: too many arguments.", __LINE__, - {"json2", - R"({"jsonrpc":"2.0","ripplerpc":"2.0","id":"A1","method":"call_this"})", - "extra"}, + {"json2", R"({"jsonrpc":"2.0","ripplerpc":"2.0","id":"A1","method":"call_this"})", "extra"}, RPCCallTestData::no_exception, R"({ "method" : "json2", @@ -3463,8 +3359,7 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"ledger: ledger hash.", __LINE__, - {"ledger", - "ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789"}, + {"ledger", "ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789"}, RPCCallTestData::no_exception, R"({ "method" : "ledger", @@ -3645,8 +3540,7 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"ledger_header: ledger hash.", __LINE__, - {"ledger_header", - "ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789"}, + {"ledger_header", "ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789"}, RPCCallTestData::no_exception, R"({ "method" : "ledger_header", @@ -3744,8 +3638,7 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"ledger_request: ledger hash.", __LINE__, - {"ledger_request", - "ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789"}, + {"ledger_request", "ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789"}, RPCCallTestData::no_exception, R"({ "method" : "ledger_request", @@ -4253,10 +4146,7 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"peer_reservations_add: too many arguments.", __LINE__, - {"peer_reservations_add", - "public_key_string", - "public_key_description", - "spare"}, + {"peer_reservations_add", "public_key_string", "public_key_description", "spare"}, RPCCallTestData::no_exception, R"({ "method" : "peer_reservations_add", @@ -4300,10 +4190,7 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"peer_reservations_del: too many arguments.", __LINE__, - {"peer_reservations_del", - "public_key_string", - "public_key_description", - "spare"}, + {"peer_reservations_del", "public_key_string", "public_key_description", "spare"}, RPCCallTestData::no_exception, R"({ "method" : "peer_reservations_del", @@ -4650,12 +4537,7 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"sign: too many arguments.", __LINE__, - {"sign", - "my_secret", - R"({"json_argument":true})", - "offline", - "CounterpartySignature", - "extra"}, + {"sign", "my_secret", R"({"json_argument":true})", "offline", "CounterpartySignature", "extra"}, RPCCallTestData::no_exception, R"({ "method" : "sign", @@ -4730,11 +4612,7 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"sign_for: offline.", __LINE__, - {"sign_for", - "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", - "my_secret", - R"({"json_argument":true})", - "offline"}, + {"sign_for", "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", "my_secret", R"({"json_argument":true})", "offline"}, RPCCallTestData::no_exception, R"({ "method" : "sign_for", @@ -4770,12 +4648,7 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"sign_for: too many arguments.", __LINE__, - {"sign_for", - "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", - "my_secret", - R"({"json_argument":true})", - "offline", - "extra"}, + {"sign_for", "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", "my_secret", R"({"json_argument":true})", "offline", "extra"}, RPCCallTestData::no_exception, R"({ "method" : "sign_for", @@ -4808,11 +4681,7 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"sign_for: invalid final argument.", __LINE__, - {"sign_for", - "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", - "my_secret", - R"({"json_argument":true})", - "ofline"}, + {"sign_for", "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", "my_secret", R"({"json_argument":true})", "ofline"}, RPCCallTestData::no_exception, R"({ "method" : "sign_for", @@ -4915,12 +4784,7 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"submit: too many arguments.", __LINE__, - {"submit", - "my_secret", - R"({"json_argument":true})", - "offline", - "CounterpartySignature", - "extra"}, + {"submit", "my_secret", R"({"json_argument":true})", "offline", "CounterpartySignature", "extra"}, RPCCallTestData::no_exception, R"({ "method" : "submit", @@ -5185,9 +5049,7 @@ static RPCCallTestData const rpcCallTestArray[] = { // ----------------------------------------------------------- {"transaction_entry: ledger index.", __LINE__, - {"transaction_entry", - "0123456789ABCDEFGHIJKLMNOPQRSTUV0123456789ABCDEFGHIJKLMNOPQRSTUV", - "4294967295"}, + {"transaction_entry", "0123456789ABCDEFGHIJKLMNOPQRSTUV0123456789ABCDEFGHIJKLMNOPQRSTUV", "4294967295"}, RPCCallTestData::no_exception, R"({ "method" : "transaction_entry", @@ -5201,9 +5063,7 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"transaction_entry: text ledger index.", __LINE__, - {"transaction_entry", - "0123456789ABCDEFGHIJKLMNOPQRSTUV0123456789ABCDEFGHIJKLMNOPQRSTUV", - "current"}, + {"transaction_entry", "0123456789ABCDEFGHIJKLMNOPQRSTUV0123456789ABCDEFGHIJKLMNOPQRSTUV", "current"}, RPCCallTestData::no_exception, R"({ "method" : "transaction_entry", @@ -5250,10 +5110,7 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"transaction_entry: too many arguments.", __LINE__, - {"transaction_entry", - "0123456789ABCDEFGHIJKLMNOPQRSTUV0123456789ABCDEFGHIJKLMNOPQRSTUV", - "validated", - "extra"}, + {"transaction_entry", "0123456789ABCDEFGHIJKLMNOPQRSTUV0123456789ABCDEFGHIJKLMNOPQRSTUV", "validated", "extra"}, RPCCallTestData::no_exception, R"({ "method" : "transaction_entry", @@ -5716,13 +5573,7 @@ static RPCCallTestData const rpcCallTestArray[] = { })"}, {"internal: with parameters.", __LINE__, - {"internal", - "command_name", - "string_arg", - "1", - "-1", - "4294967296", - "3.14159"}, + {"internal", "command_name", "string_arg", "1", "-1", "4294967296", "3.14159"}, RPCCallTestData::no_exception, R"({ "method" : "internal", @@ -5908,13 +5759,10 @@ public: testRPCCall(unsigned apiVersion) { testcase << "RPCCall API version " << apiVersion; - if (!BEAST_EXPECT( - apiVersion >= RPC::apiMinimumSupportedVersion && - apiVersion <= RPC::apiMaximumValidVersion)) + if (!BEAST_EXPECT(apiVersion >= RPC::apiMinimumSupportedVersion && apiVersion <= RPC::apiMaximumValidVersion)) return; - test::jtx::Env env( - *this, makeNetworkConfig(11111)); // Used only for its Journal. + test::jtx::Env env(*this, makeNetworkConfig(11111)); // Used only for its Journal. // For each RPCCall test. for (RPCCallTestData const& rpcCallTest : rpcCallTestArray) @@ -5922,12 +5770,9 @@ public: if (!BEAST_EXPECT(!rpcCallTest.exp.empty())) break; - std::vector const args{ - rpcCallTest.args.begin(), rpcCallTest.args.end()}; + std::vector const args{rpcCallTest.args.begin(), rpcCallTest.args.end()}; - char const* const expVersioned = - (apiVersion - RPC::apiMinimumSupportedVersion) < - rpcCallTest.exp.size() + char const* const expVersioned = (apiVersion - RPC::apiMinimumSupportedVersion) < rpcCallTest.exp.size() ? rpcCallTest.exp[apiVersion - RPC::apiMinimumSupportedVersion] : rpcCallTest.exp.back(); @@ -5940,8 +5785,7 @@ public: } catch (std::bad_cast const&) { - if ((rpcCallTest.throwsWhat == RPCCallTestData::bad_cast) && - (std::strlen(expVersioned) == 0)) + if ((rpcCallTest.throwsWhat == RPCCallTestData::bad_cast) && (std::strlen(expVersioned) == 0)) { pass(); } @@ -5954,14 +5798,12 @@ public: } Json::Value exp; - Json::Reader{}.parse( - updateAPIVersionString(expVersioned, apiVersion), exp); + Json::Reader{}.parse(updateAPIVersionString(expVersioned, apiVersion), exp); // Lambda to remove the "params[0u]:error_code" field if present. // Error codes are not expected to be stable between releases. auto rmErrorCode = [](Json::Value& json) { - if (json.isMember(jss::params) && json[jss::params].isArray() && - json[jss::params].size() > 0 && + if (json.isMember(jss::params) && json[jss::params].isArray() && json[jss::params].size() > 0 && json[jss::params][0u].isObject()) { json[jss::params][0u].removeMember(jss::error_code); @@ -5971,8 +5813,7 @@ public: rmErrorCode(exp); // Pass if we didn't expect a throw and we got what we expected. - if ((rpcCallTest.throwsWhat == RPCCallTestData::no_exception) && - (got == exp)) + if ((rpcCallTest.throwsWhat == RPCCallTestData::no_exception) && (got == exp)) { pass(); } diff --git a/src/test/rpc/RPCOverload_test.cpp b/src/test/rpc/RPCOverload_test.cpp index d05dba4606..c8f02cd0a3 100644 --- a/src/test/rpc/RPCOverload_test.cpp +++ b/src/test/rpc/RPCOverload_test.cpp @@ -27,9 +27,8 @@ public: Account const bob{"bob"}; env.fund(XRP(10000), alice, bob); - std::unique_ptr client = useWS - ? makeWSClient(env.app().config()) - : makeJSONRPCClient(env.app().config()); + std::unique_ptr client = + useWS ? makeWSClient(env.app().config()) : makeJSONRPCClient(env.app().config()); Json::Value tx = Json::objectValue; tx[jss::tx_json] = pay(alice, bob, XRP(1)); @@ -47,8 +46,7 @@ public: // When booted, we just get a null json response if (jv.isNull()) booted = true; - else if (!(jv.isMember(jss::status) && - (jv[jss::status] == "success"))) + else if (!(jv.isMember(jss::status) && (jv[jss::status] == "success"))) { // Don't use BEAST_EXPECT above b/c it will be called a // non-deterministic number of times and the number of tests run diff --git a/src/test/rpc/RobustTransaction_test.cpp b/src/test/rpc/RobustTransaction_test.cpp index b0d0cdafd5..0934543fe0 100644 --- a/src/test/rpc/RobustTransaction_test.cpp +++ b/src/test/rpc/RobustTransaction_test.cpp @@ -30,10 +30,8 @@ public: BEAST_EXPECT(jv[jss::status] == "success"); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } } @@ -47,14 +45,11 @@ public: auto jv = wsc->invoke("submit", payment); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } - BEAST_EXPECT( - jv[jss::result][jss::engine_result] == "tefMAX_LEDGER"); + BEAST_EXPECT(jv[jss::result][jss::engine_result] == "tefMAX_LEDGER"); // Submit past sequence transaction payment[jss::tx_json] = pay("alice", "bob", XRP(1)); @@ -62,10 +57,8 @@ public: jv = wsc->invoke("submit", payment); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } BEAST_EXPECT(jv[jss::result][jss::engine_result] == "tefPAST_SEQ"); @@ -75,10 +68,8 @@ public: jv = wsc->invoke("submit", payment); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } BEAST_EXPECT(jv[jss::result][jss::engine_result] == "terPRE_SEQ"); @@ -88,10 +79,8 @@ public: jv = wsc->invoke("submit", payment); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } BEAST_EXPECT(jv[jss::result][jss::engine_result] == "tesSUCCESS"); @@ -103,10 +92,8 @@ public: jv = wsc->invoke("ledger_accept"); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } BEAST_EXPECT(jv[jss::result].isMember(jss::ledger_current_index)); @@ -115,17 +102,13 @@ public: { // Check balances BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { - auto const& ff = jv[jss::meta]["AffectedNodes"][1u] - ["ModifiedNode"]["FinalFields"]; - return ff[jss::Account] == Account("bob").human() && - ff["Balance"] == "10001000000"; + auto const& ff = jv[jss::meta]["AffectedNodes"][1u]["ModifiedNode"]["FinalFields"]; + return ff[jss::Account] == Account("bob").human() && ff["Balance"] == "10001000000"; })); BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { - auto const& ff = jv[jss::meta]["AffectedNodes"][1u] - ["ModifiedNode"]["FinalFields"]; - return ff[jss::Account] == Account("bob").human() && - ff["Balance"] == "10002000000"; + auto const& ff = jv[jss::meta]["AffectedNodes"][1u]["ModifiedNode"]["FinalFields"]; + return ff[jss::Account] == Account("bob").human() && ff["Balance"] == "10002000000"; })); } @@ -137,10 +120,8 @@ public: jv = wsc->invoke("unsubscribe", jv); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } BEAST_EXPECT(jv[jss::status] == "success"); @@ -175,10 +156,8 @@ public: jv = wsc->invoke("submit", jv); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } BEAST_EXPECT(jv[jss::result][jss::engine_result] == "tesSUCCESS"); @@ -200,16 +179,14 @@ public: jv = wsc->invoke("account_tx", jv); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } // Check balance - auto ff = jv[jss::result][jss::transactions][0u][jss::meta] - ["AffectedNodes"][1u]["ModifiedNode"]["FinalFields"]; + auto ff = + jv[jss::result][jss::transactions][0u][jss::meta]["AffectedNodes"][1u]["ModifiedNode"]["FinalFields"]; BEAST_EXPECT(ff[jss::Account] == Account("bob").human()); BEAST_EXPECT(ff["Balance"] == "10001000000"); } @@ -233,10 +210,8 @@ public: jv = wsc->invoke("submit", jv); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } BEAST_EXPECT(jv[jss::result][jss::engine_result] == "tesSUCCESS"); @@ -245,10 +220,8 @@ public: jv = wsc->invoke("ledger_accept"); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } BEAST_EXPECT(jv[jss::result].isMember(jss::ledger_current_index)); @@ -266,11 +239,8 @@ public: jv = wsc->invoke("subscribe", jv); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && - jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } BEAST_EXPECT(jv[jss::status] == "success"); @@ -282,22 +252,16 @@ public: auto jv = wsc->invoke("ledger_accept"); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && - jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } - BEAST_EXPECT( - jv[jss::result].isMember(jss::ledger_current_index)); + BEAST_EXPECT(jv[jss::result].isMember(jss::ledger_current_index)); // Wait for the jobqueue to process everything env.app().getJobQueue().rendezvous(); - BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jval) { - return jval[jss::type] == "ledgerClosed"; - })); + BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jval) { return jval[jss::type] == "ledgerClosed"; })); } { @@ -308,11 +272,8 @@ public: jv = wsc->invoke("unsubscribe", jv); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && - jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } BEAST_EXPECT(jv[jss::status] == "success"); @@ -330,11 +291,8 @@ public: jv = wsc->invoke("subscribe", jv); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && - jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } BEAST_EXPECT(jv[jss::status] == "success"); @@ -346,22 +304,16 @@ public: auto jv = wsc->invoke("ledger_accept"); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && - jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } - BEAST_EXPECT( - jv[jss::result].isMember(jss::ledger_current_index)); + BEAST_EXPECT(jv[jss::result].isMember(jss::ledger_current_index)); // Wait for the jobqueue to process everything env.app().getJobQueue().rendezvous(); - BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jval) { - return jval[jss::type] == "ledgerClosed"; - })); + BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jval) { return jval[jss::type] == "ledgerClosed"; })); } { @@ -372,11 +324,8 @@ public: jv = wsc->invoke("unsubscribe", jv); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && - jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } BEAST_EXPECT(jv[jss::status] == "success"); @@ -393,16 +342,14 @@ public: jv = wsc->invoke("account_tx", jv); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } // Check balance - auto ff = jv[jss::result][jss::transactions][0u][jss::meta] - ["AffectedNodes"][1u]["ModifiedNode"]["FinalFields"]; + auto ff = + jv[jss::result][jss::transactions][0u][jss::meta]["AffectedNodes"][1u]["ModifiedNode"]["FinalFields"]; BEAST_EXPECT(ff[jss::Account] == Account("bob").human()); BEAST_EXPECT(ff["Balance"] == "10001000000"); } @@ -426,10 +373,8 @@ public: jv = wsc->invoke("subscribe", jv); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } BEAST_EXPECT(jv[jss::status] == "success"); @@ -440,15 +385,12 @@ public: Json::Value jv; jv[jss::secret] = toBase58(generateSeed("alice")); jv[jss::tx_json] = fset("alice", 0); - jv[jss::tx_json][jss::Fee] = - static_cast(env.current()->fees().base.drops()); + jv[jss::tx_json][jss::Fee] = static_cast(env.current()->fees().base.drops()); jv = wsc->invoke("submit", jv); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } BEAST_EXPECT(jv[jss::result][jss::engine_result] == "tesSUCCESS"); @@ -456,10 +398,8 @@ public: { // Check stream update - BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { - return jv[jss::transaction][jss::TransactionType] == - jss::AccountSet; - })); + BEAST_EXPECT(wsc->findMsg( + 5s, [&](auto const& jv) { return jv[jss::transaction][jss::TransactionType] == jss::AccountSet; })); } { @@ -470,10 +410,8 @@ public: jv = wsc->invoke("unsubscribe", jv); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } BEAST_EXPECT(jv[jss::status] == "success"); diff --git a/src/test/rpc/Roles_test.cpp b/src/test/rpc/Roles_test.cpp index 4fa99b432b..1750532a10 100644 --- a/src/test/rpc/Roles_test.cpp +++ b/src/test/rpc/Roles_test.cpp @@ -29,27 +29,21 @@ class Roles_test : public beast::unit_test::suite Env env(*this); BEAST_EXPECT(env.rpc("ping")["result"]["role"] == "admin"); - BEAST_EXPECT(makeWSClient(env.app().config()) - ->invoke("ping")["result"]["unlimited"] - .asBool()); + BEAST_EXPECT(makeWSClient(env.app().config())->invoke("ping")["result"]["unlimited"].asBool()); } { Env env{*this, envconfig(no_admin)}; BEAST_EXPECT(!env.rpc("ping")["result"].isMember("role")); - auto wsRes = - makeWSClient(env.app().config())->invoke("ping")["result"]; - BEAST_EXPECT( - !wsRes.isMember("unlimited") || !wsRes["unlimited"].asBool()); + auto wsRes = makeWSClient(env.app().config())->invoke("ping")["result"]; + BEAST_EXPECT(!wsRes.isMember("unlimited") || !wsRes["unlimited"].asBool()); } { Env env{*this, envconfig(secure_gateway)}; BEAST_EXPECT(env.rpc("ping")["result"]["role"] == "proxied"); - auto wsRes = - makeWSClient(env.app().config())->invoke("ping")["result"]; - BEAST_EXPECT( - !wsRes.isMember("unlimited") || !wsRes["unlimited"].asBool()); + auto wsRes = makeWSClient(env.app().config())->invoke("ping")["result"]; + BEAST_EXPECT(!wsRes.isMember("unlimited") || !wsRes["unlimited"].asBool()); std::unordered_map headers; Json::Value rpcRes; @@ -112,10 +106,8 @@ class Roles_test : public beast::unit_test::suite BEAST_EXPECT(rpcRes["ip"] == "99.88.77.66"); BEAST_EXPECT(isValidIpAddress(rpcRes["ip"].asString())); - wsRes = makeWSClient(env.app().config(), true, 2, headers) - ->invoke("ping")["result"]; - BEAST_EXPECT( - !wsRes.isMember("unlimited") || !wsRes["unlimited"].asBool()); + wsRes = makeWSClient(env.app().config(), true, 2, headers)->invoke("ping")["result"]; + BEAST_EXPECT(!wsRes.isMember("unlimited") || !wsRes["unlimited"].asBool()); std::string const name = "xrposhi"; headers["X-User"] = name; @@ -124,18 +116,15 @@ class Roles_test : public beast::unit_test::suite BEAST_EXPECT(rpcRes["username"] == name); BEAST_EXPECT(rpcRes["ip"] == "99.88.77.66"); BEAST_EXPECT(isValidIpAddress(rpcRes["ip"].asString())); - wsRes = makeWSClient(env.app().config(), true, 2, headers) - ->invoke("ping")["result"]; + wsRes = makeWSClient(env.app().config(), true, 2, headers)->invoke("ping")["result"]; BEAST_EXPECT(wsRes["unlimited"].asBool()); // IPv6 tests. headers = {}; - headers["X-Forwarded-For"] = - "2001:db8:3333:4444:5555:6666:7777:8888"; + headers["X-Forwarded-For"] = "2001:db8:3333:4444:5555:6666:7777:8888"; rpcRes = env.rpc(headers, "ping")["result"]; BEAST_EXPECT(rpcRes["role"] == "proxied"); - BEAST_EXPECT( - rpcRes["ip"] == "2001:db8:3333:4444:5555:6666:7777:8888"); + BEAST_EXPECT(rpcRes["ip"] == "2001:db8:3333:4444:5555:6666:7777:8888"); BEAST_EXPECT(isValidIpAddress(rpcRes["ip"].asString())); headers["X-Forwarded-For"] = @@ -143,16 +132,13 @@ class Roles_test : public beast::unit_test::suite "g:h:i:j:k:l"; rpcRes = env.rpc(headers, "ping")["result"]; BEAST_EXPECT(rpcRes["role"] == "proxied"); - BEAST_EXPECT( - rpcRes["ip"] == "2001:db8:3333:4444:5555:6666:7777:9999"); + BEAST_EXPECT(rpcRes["ip"] == "2001:db8:3333:4444:5555:6666:7777:9999"); BEAST_EXPECT(isValidIpAddress(rpcRes["ip"].asString())); - headers["X-Forwarded-For"] = - "[2001:db8:3333:4444:5555:6666:7777:8888]"; + headers["X-Forwarded-For"] = "[2001:db8:3333:4444:5555:6666:7777:8888]"; rpcRes = env.rpc(headers, "ping")["result"]; BEAST_EXPECT(rpcRes["role"] == "proxied"); - BEAST_EXPECT( - rpcRes["ip"] == "2001:db8:3333:4444:5555:6666:7777:8888"); + BEAST_EXPECT(rpcRes["ip"] == "2001:db8:3333:4444:5555:6666:7777:8888"); BEAST_EXPECT(isValidIpAddress(rpcRes["ip"].asString())); headers["X-Forwarded-For"] = @@ -160,21 +146,17 @@ class Roles_test : public beast::unit_test::suite "[g:h:i:j:k:l]"; rpcRes = env.rpc(headers, "ping")["result"]; BEAST_EXPECT(rpcRes["role"] == "proxied"); - BEAST_EXPECT( - rpcRes["ip"] == "2001:db8:3333:4444:5555:6666:7777:9999"); + BEAST_EXPECT(rpcRes["ip"] == "2001:db8:3333:4444:5555:6666:7777:9999"); BEAST_EXPECT(isValidIpAddress(rpcRes["ip"].asString())); headers = {}; - headers["Forwarded"] = - "for=\"[2001:db8:3333:4444:5555:6666:7777:aaaa]\""; + headers["Forwarded"] = "for=\"[2001:db8:3333:4444:5555:6666:7777:aaaa]\""; rpcRes = env.rpc(headers, "ping")["result"]; BEAST_EXPECT(rpcRes["role"] == "proxied"); - BEAST_EXPECT( - rpcRes["ip"] == "2001:db8:3333:4444:5555:6666:7777:aaaa"); + BEAST_EXPECT(rpcRes["ip"] == "2001:db8:3333:4444:5555:6666:7777:aaaa"); BEAST_EXPECT(isValidIpAddress(rpcRes["ip"].asString())); - headers["Forwarded"] = - "For=\"[2001:db8:bb:cc:dd:ee:ff::]:2345\", for=99.00.11.22"; + headers["Forwarded"] = "For=\"[2001:db8:bb:cc:dd:ee:ff::]:2345\", for=99.00.11.22"; rpcRes = env.rpc(headers, "ping")["result"]; BEAST_EXPECT(rpcRes["role"] == "proxied"); BEAST_EXPECT(rpcRes["ip"] == "2001:db8:bb:cc:dd:ee:ff::"); @@ -193,8 +175,7 @@ class Roles_test : public beast::unit_test::suite headers["X-Forwarded-For"] = "2001:db8:3333:4444:5555:6666:1.2.3.4"; rpcRes = env.rpc(headers, "ping")["result"]; BEAST_EXPECT(rpcRes["role"] == "proxied"); - BEAST_EXPECT( - rpcRes["ip"] == "2001:db8:3333:4444:5555:6666:1.2.3.4"); + BEAST_EXPECT(rpcRes["ip"] == "2001:db8:3333:4444:5555:6666:1.2.3.4"); BEAST_EXPECT(isValidIpAddress(rpcRes["ip"].asString())); headers["X-Forwarded-For"] = @@ -202,16 +183,13 @@ class Roles_test : public beast::unit_test::suite "g:h:i:j:k:l"; rpcRes = env.rpc(headers, "ping")["result"]; BEAST_EXPECT(rpcRes["role"] == "proxied"); - BEAST_EXPECT( - rpcRes["ip"] == "2001:db8:3333:4444:5555:6666:5.6.7.8"); + BEAST_EXPECT(rpcRes["ip"] == "2001:db8:3333:4444:5555:6666:5.6.7.8"); BEAST_EXPECT(isValidIpAddress(rpcRes["ip"].asString())); - headers["X-Forwarded-For"] = - "[2001:db8:3333:4444:5555:6666:9.10.11.12]"; + headers["X-Forwarded-For"] = "[2001:db8:3333:4444:5555:6666:9.10.11.12]"; rpcRes = env.rpc(headers, "ping")["result"]; BEAST_EXPECT(rpcRes["role"] == "proxied"); - BEAST_EXPECT( - rpcRes["ip"] == "2001:db8:3333:4444:5555:6666:9.10.11.12"); + BEAST_EXPECT(rpcRes["ip"] == "2001:db8:3333:4444:5555:6666:9.10.11.12"); BEAST_EXPECT(isValidIpAddress(rpcRes["ip"].asString())); headers["X-Forwarded-For"] = @@ -219,21 +197,17 @@ class Roles_test : public beast::unit_test::suite "[g:h:i:j:k:l]"; rpcRes = env.rpc(headers, "ping")["result"]; BEAST_EXPECT(rpcRes["role"] == "proxied"); - BEAST_EXPECT( - rpcRes["ip"] == "2001:db8:3333:4444:5555:6666:13.14.15.16"); + BEAST_EXPECT(rpcRes["ip"] == "2001:db8:3333:4444:5555:6666:13.14.15.16"); BEAST_EXPECT(isValidIpAddress(rpcRes["ip"].asString())); headers = {}; - headers["Forwarded"] = - "for=\"[2001:db8:3333:4444:5555:6666:20.19.18.17]\""; + headers["Forwarded"] = "for=\"[2001:db8:3333:4444:5555:6666:20.19.18.17]\""; rpcRes = env.rpc(headers, "ping")["result"]; BEAST_EXPECT(rpcRes["role"] == "proxied"); - BEAST_EXPECT( - rpcRes["ip"] == "2001:db8:3333:4444:5555:6666:20.19.18.17"); + BEAST_EXPECT(rpcRes["ip"] == "2001:db8:3333:4444:5555:6666:20.19.18.17"); BEAST_EXPECT(isValidIpAddress(rpcRes["ip"].asString())); - headers["Forwarded"] = - "For=\"[2001:db8:bb:cc::24.23.22.21]\", for=99.00.11.22"; + headers["Forwarded"] = "For=\"[2001:db8:bb:cc::24.23.22.21]\", for=99.00.11.22"; rpcRes = env.rpc(headers, "ping")["result"]; BEAST_EXPECT(rpcRes["role"] == "proxied"); BEAST_EXPECT(rpcRes["ip"] == "2001:db8:bb:cc::24.23.22.21"); @@ -251,18 +225,14 @@ class Roles_test : public beast::unit_test::suite { Env env{*this, envconfig(admin_localnet)}; BEAST_EXPECT(env.rpc("ping")["result"]["role"] == "admin"); - BEAST_EXPECT(makeWSClient(env.app().config()) - ->invoke("ping")["result"]["unlimited"] - .asBool()); + BEAST_EXPECT(makeWSClient(env.app().config())->invoke("ping")["result"]["unlimited"].asBool()); } { Env env{*this, envconfig(secure_gateway_localnet)}; BEAST_EXPECT(env.rpc("ping")["result"]["role"] == "proxied"); - auto wsRes = - makeWSClient(env.app().config())->invoke("ping")["result"]; - BEAST_EXPECT( - !wsRes.isMember("unlimited") || !wsRes["unlimited"].asBool()); + auto wsRes = makeWSClient(env.app().config())->invoke("ping")["result"]; + BEAST_EXPECT(!wsRes.isMember("unlimited") || !wsRes["unlimited"].asBool()); std::unordered_map headers; headers["X-Forwarded-For"] = "12.34.56.78"; diff --git a/src/test/rpc/ServerDefinitions_test.cpp b/src/test/rpc/ServerDefinitions_test.cpp index ae2cccd908..20bd6ba363 100644 --- a/src/test/rpc/ServerDefinitions_test.cpp +++ b/src/test/rpc/ServerDefinitions_test.cpp @@ -24,8 +24,7 @@ public: BEAST_EXPECT(result[jss::result][jss::status] == "success"); BEAST_EXPECT(result[jss::result].isMember(jss::FIELDS)); BEAST_EXPECT(result[jss::result].isMember(jss::LEDGER_ENTRY_TYPES)); - BEAST_EXPECT( - result[jss::result].isMember(jss::TRANSACTION_RESULTS)); + BEAST_EXPECT(result[jss::result].isMember(jss::TRANSACTION_RESULTS)); BEAST_EXPECT(result[jss::result].isMember(jss::TRANSACTION_TYPES)); BEAST_EXPECT(result[jss::result].isMember(jss::TYPES)); BEAST_EXPECT(result[jss::result].isMember(jss::hash)); @@ -36,26 +35,17 @@ public: { auto const firstField = result[jss::result][jss::FIELDS][0u]; BEAST_EXPECT(firstField[0u].asString() == "Generic"); - BEAST_EXPECT( - firstField[1][jss::isSerialized].asBool() == false); - BEAST_EXPECT( - firstField[1][jss::isSigningField].asBool() == false); + BEAST_EXPECT(firstField[1][jss::isSerialized].asBool() == false); + BEAST_EXPECT(firstField[1][jss::isSigningField].asBool() == false); BEAST_EXPECT(firstField[1][jss::isVLEncoded].asBool() == false); BEAST_EXPECT(firstField[1][jss::nth].asUInt() == 0); BEAST_EXPECT(firstField[1][jss::type].asString() == "Unknown"); } - BEAST_EXPECT( - result[jss::result][jss::LEDGER_ENTRY_TYPES]["AccountRoot"] - .asUInt() == 97); - BEAST_EXPECT( - result[jss::result][jss::TRANSACTION_RESULTS]["tecDIR_FULL"] - .asUInt() == 121); - BEAST_EXPECT( - result[jss::result][jss::TRANSACTION_TYPES]["Payment"] - .asUInt() == 0); - BEAST_EXPECT( - result[jss::result][jss::TYPES]["AccountID"].asUInt() == 8); + BEAST_EXPECT(result[jss::result][jss::LEDGER_ENTRY_TYPES]["AccountRoot"].asUInt() == 97); + BEAST_EXPECT(result[jss::result][jss::TRANSACTION_RESULTS]["tecDIR_FULL"].asUInt() == 121); + BEAST_EXPECT(result[jss::result][jss::TRANSACTION_TYPES]["Payment"].asUInt() == 0); + BEAST_EXPECT(result[jss::result][jss::TYPES]["AccountID"].asUInt() == 8); // check exception SFields { @@ -96,18 +86,14 @@ public: Env env(*this); auto const firstResult = env.rpc("server_definitions"); auto const hash = firstResult[jss::result][jss::hash].asString(); - auto const hashParam = - std::string("{ ") + "\"hash\": \"" + hash + "\"}"; + auto const hashParam = std::string("{ ") + "\"hash\": \"" + hash + "\"}"; - auto const result = - env.rpc("json", "server_definitions", hashParam); + auto const result = env.rpc("json", "server_definitions", hashParam); BEAST_EXPECT(!result[jss::result].isMember(jss::error)); BEAST_EXPECT(result[jss::result][jss::status] == "success"); BEAST_EXPECT(!result[jss::result].isMember(jss::FIELDS)); - BEAST_EXPECT( - !result[jss::result].isMember(jss::LEDGER_ENTRY_TYPES)); - BEAST_EXPECT( - !result[jss::result].isMember(jss::TRANSACTION_RESULTS)); + BEAST_EXPECT(!result[jss::result].isMember(jss::LEDGER_ENTRY_TYPES)); + BEAST_EXPECT(!result[jss::result].isMember(jss::TRANSACTION_RESULTS)); BEAST_EXPECT(!result[jss::result].isMember(jss::TRANSACTION_TYPES)); BEAST_EXPECT(!result[jss::result].isMember(jss::TYPES)); BEAST_EXPECT(result[jss::result].isMember(jss::hash)); @@ -119,17 +105,14 @@ public: std::string const hash = "54296160385A27154BFA70A239DD8E8FD4CC2DB7BA32D970BA3A5B132CF749" "D1"; - auto const hashParam = - std::string("{ ") + "\"hash\": \"" + hash + "\"}"; + auto const hashParam = std::string("{ ") + "\"hash\": \"" + hash + "\"}"; - auto const result = - env.rpc("json", "server_definitions", hashParam); + auto const result = env.rpc("json", "server_definitions", hashParam); BEAST_EXPECT(!result[jss::result].isMember(jss::error)); BEAST_EXPECT(result[jss::result][jss::status] == "success"); BEAST_EXPECT(result[jss::result].isMember(jss::FIELDS)); BEAST_EXPECT(result[jss::result].isMember(jss::LEDGER_ENTRY_TYPES)); - BEAST_EXPECT( - result[jss::result].isMember(jss::TRANSACTION_RESULTS)); + BEAST_EXPECT(result[jss::result].isMember(jss::TRANSACTION_RESULTS)); BEAST_EXPECT(result[jss::result].isMember(jss::TRANSACTION_TYPES)); BEAST_EXPECT(result[jss::result].isMember(jss::TYPES)); BEAST_EXPECT(result[jss::result].isMember(jss::hash)); diff --git a/src/test/rpc/ServerInfo_test.cpp b/src/test/rpc/ServerInfo_test.cpp index 27b554e38b..c38844e8a6 100644 --- a/src/test/rpc/ServerInfo_test.cpp +++ b/src/test/rpc/ServerInfo_test.cpp @@ -1,10 +1,10 @@ #include -#include #include #include #include +#include #include @@ -13,8 +13,7 @@ namespace xrpl { namespace test { namespace validator_data { -static auto const public_key = - "nHBt9fsb4849WmZiCds4r5TXyBeQjqnH5kzPtqgMAQMgi39YZRPa"; +static auto const public_key = "nHBt9fsb4849WmZiCds4r5TXyBeQjqnH5kzPtqgMAQMgi39YZRPa"; static auto const token = "eyJ2YWxpZGF0aW9uX3NlY3JldF9rZXkiOiI5ZWQ0NWY4NjYyNDFjYzE4YTI3NDdiNT\n" @@ -52,8 +51,7 @@ protocol = wss2 admin = 127.0.0.1 )rippleConfig"); - p->loadFromString(boost::str( - toLoad % validator_data::token % validator_data::public_key)); + p->loadFromString(boost::str(toLoad % validator_data::token % validator_data::public_key)); setupConfigForUnitTests(*p); @@ -81,16 +79,12 @@ admin = 127.0.0.1 if (info.isMember(jss::git)) { auto const& git = info[jss::git]; + BEAST_EXPECT(git.isMember(jss::hash) || git.isMember(jss::branch)); BEAST_EXPECT( - git.isMember(jss::hash) || git.isMember(jss::branch)); - BEAST_EXPECT( - !git.isMember(jss::hash) || - (git[jss::hash].isString() && - git[jss::hash].asString().size() == 40)); + !git.isMember(jss::hash) || (git[jss::hash].isString() && git[jss::hash].asString().size() == 40)); BEAST_EXPECT( !git.isMember(jss::branch) || - (git[jss::branch].isString() && - git[jss::branch].asString().size() != 0)); + (git[jss::branch].isString() && git[jss::branch].asString().size() != 0)); } } @@ -98,8 +92,7 @@ admin = 127.0.0.1 Env env(*this); // Call NetworkOPs directly and set the admin flag to false. - auto const result = - env.app().getOPs().getServerInfo(true, false, 0); + auto const result = env.app().getOPs().getServerInfo(true, false, 0); // Expect that the admin ports are not included in the result. auto const& ports = result[jss::ports]; BEAST_EXPECT(ports.isArray() && ports.size() == 0); @@ -112,8 +105,7 @@ admin = 127.0.0.1 auto const& config = env.app().config(); auto const rpc_port = config["port_rpc"].get("port"); - auto const grpc_port = - config[SECTION_PORT_GRPC].get("port"); + auto const grpc_port = config[SECTION_PORT_GRPC].get("port"); auto const ws_port = config["port_ws"].get("port"); BEAST_EXPECT(grpc_port); BEAST_EXPECT(rpc_port); @@ -123,9 +115,7 @@ admin = 127.0.0.1 BEAST_EXPECT(!result[jss::result].isMember(jss::error)); BEAST_EXPECT(result[jss::result][jss::status] == "success"); BEAST_EXPECT(result[jss::result].isMember(jss::info)); - BEAST_EXPECT( - result[jss::result][jss::info][jss::pubkey_validator] == - validator_data::public_key); + BEAST_EXPECT(result[jss::result][jss::info][jss::pubkey_validator] == validator_data::public_key); auto const& ports = result[jss::result][jss::info][jss::ports]; BEAST_EXPECT(ports.isArray() && ports.size() == 3); diff --git a/src/test/rpc/Simulate_test.cpp b/src/test/rpc/Simulate_test.cpp index 7fe90fb9a1..194b0296ec 100644 --- a/src/test/rpc/Simulate_test.cpp +++ b/src/test/rpc/Simulate_test.cpp @@ -31,8 +31,7 @@ class Simulate_test : public beast::unit_test::suite BEAST_EXPECT(result.isMember(jss::engine_result)); BEAST_EXPECT(result.isMember(jss::engine_result_code)); BEAST_EXPECT(result.isMember(jss::engine_result_message)); - BEAST_EXPECT( - result.isMember(jss::tx_json) || result.isMember(jss::tx_blob)); + BEAST_EXPECT(result.isMember(jss::tx_json) || result.isMember(jss::tx_blob)); Json::Value tx_json; if (result.isMember(jss::tx_json)) @@ -43,18 +42,14 @@ class Simulate_test : public beast::unit_test::suite { auto const unHexed = strUnHex(result[jss::tx_blob].asString()); SerialIter sitTrans(makeSlice(*unHexed)); - tx_json = STObject(std::ref(sitTrans), sfGeneric) - .getJson(JsonOptions::none); + tx_json = STObject(std::ref(sitTrans), sfGeneric).getJson(JsonOptions::none); } BEAST_EXPECT(tx_json[jss::TransactionType] == tx[jss::TransactionType]); BEAST_EXPECT(tx_json[jss::Account] == tx[jss::Account]); - BEAST_EXPECT( - tx_json[jss::SigningPubKey] == tx.get(jss::SigningPubKey, "")); - BEAST_EXPECT( - tx_json[jss::TxnSignature] == tx.get(jss::TxnSignature, "")); + BEAST_EXPECT(tx_json[jss::SigningPubKey] == tx.get(jss::SigningPubKey, "")); + BEAST_EXPECT(tx_json[jss::TxnSignature] == tx.get(jss::TxnSignature, "")); BEAST_EXPECT(tx_json[jss::Fee] == tx.get(jss::Fee, expectedFee)); - BEAST_EXPECT( - tx_json[jss::Sequence] == tx.get(jss::Sequence, expectedSequence)); + BEAST_EXPECT(tx_json[jss::Sequence] == tx.get(jss::Sequence, expectedSequence)); } void @@ -64,16 +59,14 @@ class Simulate_test : public beast::unit_test::suite int const expectedSequence, XRPAmount const& expectedFee) { - return checkBasicReturnValidity( - result, tx, expectedSequence, expectedFee.jsonClipped().asString()); + return checkBasicReturnValidity(result, tx, expectedSequence, expectedFee.jsonClipped().asString()); } void testTx( jtx::Env& env, Json::Value const& tx, - std::function const& - validate, + std::function const& validate, bool testSerialized = true) { env.close(); @@ -93,8 +86,7 @@ class Simulate_test : public beast::unit_test::suite // It is technically not a valid STObject, so the following line // will crash STParsedJSONObject const parsed(std::string(jss::tx_json), tx); - auto const tx_blob = - strHex(parsed.object->getSerializer().peekData()); + auto const tx_blob = strHex(parsed.object->getSerializer().peekData()); if (BEAST_EXPECT(parsed.object.has_value())) { Json::Value params; @@ -107,20 +99,15 @@ class Simulate_test : public beast::unit_test::suite validate(env.rpc("simulate", tx_blob, "binary"), tx); } - BEAST_EXPECTS( - env.current()->txCount() == 0, - std::to_string(env.current()->txCount())); + BEAST_EXPECTS(env.current()->txCount() == 0, std::to_string(env.current()->txCount())); } void testTxJsonMetadataField( jtx::Env& env, Json::Value const& tx, - std::function const& validate, + std::function const& + validate, Json::Value const& expectedMetadataKey, Json::Value const& expectedMetadataValue) { @@ -128,20 +115,10 @@ class Simulate_test : public beast::unit_test::suite Json::Value params; params[jss::tx_json] = tx; - validate( - env.rpc("json", "simulate", to_string(params)), - tx, - expectedMetadataKey, - expectedMetadataValue); - validate( - env.rpc("simulate", to_string(tx)), - tx, - expectedMetadataKey, - expectedMetadataValue); + validate(env.rpc("json", "simulate", to_string(params)), tx, expectedMetadataKey, expectedMetadataValue); + validate(env.rpc("simulate", to_string(tx)), tx, expectedMetadataKey, expectedMetadataValue); - BEAST_EXPECTS( - env.current()->txCount() == 0, - std::to_string(env.current()->txCount())); + BEAST_EXPECTS(env.current()->txCount() == 0, std::to_string(env.current()->txCount())); } Json::Value @@ -151,8 +128,7 @@ class Simulate_test : public beast::unit_test::suite { auto unHexed = strUnHex(txResult[jss::meta_blob].asString()); SerialIter sitTrans(makeSlice(*unHexed)); - return STObject(std::ref(sitTrans), sfGeneric) - .getJson(JsonOptions::none); + return STObject(std::ref(sitTrans), sfGeneric).getJson(JsonOptions::none); } return txResult[jss::meta]; @@ -171,9 +147,7 @@ class Simulate_test : public beast::unit_test::suite // No params Json::Value const params = Json::objectValue; auto const resp = env.rpc("json", "simulate", to_string(params)); - BEAST_EXPECT( - resp[jss::result][jss::error_message] == - "Neither `tx_blob` nor `tx_json` included."); + BEAST_EXPECT(resp[jss::result][jss::error_message] == "Neither `tx_blob` nor `tx_json` included."); } { // Providing both `tx_json` and `tx_blob` @@ -182,9 +156,7 @@ class Simulate_test : public beast::unit_test::suite params[jss::tx_blob] = "1200"; auto const resp = env.rpc("json", "simulate", to_string(params)); - BEAST_EXPECT( - resp[jss::result][jss::error_message] == - "Can only include one of `tx_blob` and `tx_json`."); + BEAST_EXPECT(resp[jss::result][jss::error_message] == "Can only include one of `tx_blob` and `tx_json`."); } { // `binary` isn't a boolean @@ -192,9 +164,7 @@ class Simulate_test : public beast::unit_test::suite params[jss::tx_blob] = "1200"; params[jss::binary] = "100"; auto const resp = env.rpc("json", "simulate", to_string(params)); - BEAST_EXPECT( - resp[jss::result][jss::error_message] == - "Invalid field 'binary'."); + BEAST_EXPECT(resp[jss::result][jss::error_message] == "Invalid field 'binary'."); } { // Invalid `tx_blob` @@ -202,9 +172,7 @@ class Simulate_test : public beast::unit_test::suite params[jss::tx_blob] = "12"; auto const resp = env.rpc("json", "simulate", to_string(params)); - BEAST_EXPECT( - resp[jss::result][jss::error_message] == - "Invalid field 'tx_blob'."); + BEAST_EXPECT(resp[jss::result][jss::error_message] == "Invalid field 'tx_blob'."); } { // Empty `tx_json` @@ -212,9 +180,7 @@ class Simulate_test : public beast::unit_test::suite params[jss::tx_json] = Json::objectValue; auto const resp = env.rpc("json", "simulate", to_string(params)); - BEAST_EXPECT( - resp[jss::result][jss::error_message] == - "Missing field 'tx.TransactionType'."); + BEAST_EXPECT(resp[jss::result][jss::error_message] == "Missing field 'tx.TransactionType'."); } { // No tx.Account @@ -224,9 +190,7 @@ class Simulate_test : public beast::unit_test::suite params[jss::tx_json] = tx_json; auto const resp = env.rpc("json", "simulate", to_string(params)); - BEAST_EXPECT( - resp[jss::result][jss::error_message] == - "Missing field 'tx.Account'."); + BEAST_EXPECT(resp[jss::result][jss::error_message] == "Missing field 'tx.Account'."); } { // Empty `tx_blob` @@ -234,9 +198,7 @@ class Simulate_test : public beast::unit_test::suite params[jss::tx_blob] = ""; auto const resp = env.rpc("json", "simulate", to_string(params)); - BEAST_EXPECT( - resp[jss::result][jss::error_message] == - "Invalid field 'tx_blob'."); + BEAST_EXPECT(resp[jss::result][jss::error_message] == "Invalid field 'tx_blob'."); } { // Non-string `tx_blob` @@ -244,9 +206,7 @@ class Simulate_test : public beast::unit_test::suite params[jss::tx_blob] = 1.1; auto const resp = env.rpc("json", "simulate", to_string(params)); - BEAST_EXPECT( - resp[jss::result][jss::error_message] == - "Invalid field 'tx_blob'."); + BEAST_EXPECT(resp[jss::result][jss::error_message] == "Invalid field 'tx_blob'."); } { // Non-object `tx_json` @@ -254,9 +214,7 @@ class Simulate_test : public beast::unit_test::suite params[jss::tx_json] = ""; auto const resp = env.rpc("json", "simulate", to_string(params)); - BEAST_EXPECT( - resp[jss::result][jss::error_message] == - "Invalid field 'tx_json', not object."); + BEAST_EXPECT(resp[jss::result][jss::error_message] == "Invalid field 'tx_json', not object."); } { // `seed` field included @@ -267,9 +225,7 @@ class Simulate_test : public beast::unit_test::suite tx_json[jss::Account] = env.master.human(); params[jss::tx_json] = tx_json; auto const resp = env.rpc("json", "simulate", to_string(params)); - BEAST_EXPECT( - resp[jss::result][jss::error_message] == - "Invalid field 'seed'."); + BEAST_EXPECT(resp[jss::result][jss::error_message] == "Invalid field 'seed'."); } { // `secret` field included @@ -280,9 +236,7 @@ class Simulate_test : public beast::unit_test::suite tx_json[jss::Account] = env.master.human(); params[jss::tx_json] = tx_json; auto const resp = env.rpc("json", "simulate", to_string(params)); - BEAST_EXPECT( - resp[jss::result][jss::error_message] == - "Invalid field 'secret'."); + BEAST_EXPECT(resp[jss::result][jss::error_message] == "Invalid field 'secret'."); } { // `seed_hex` field included @@ -293,9 +247,7 @@ class Simulate_test : public beast::unit_test::suite tx_json[jss::Account] = env.master.human(); params[jss::tx_json] = tx_json; auto const resp = env.rpc("json", "simulate", to_string(params)); - BEAST_EXPECT( - resp[jss::result][jss::error_message] == - "Invalid field 'seed_hex'."); + BEAST_EXPECT(resp[jss::result][jss::error_message] == "Invalid field 'seed_hex'."); } { // `passphrase` field included @@ -306,9 +258,7 @@ class Simulate_test : public beast::unit_test::suite tx_json[jss::Account] = env.master.human(); params[jss::tx_json] = tx_json; auto const resp = env.rpc("json", "simulate", to_string(params)); - BEAST_EXPECT( - resp[jss::result][jss::error_message] == - "Invalid field 'passphrase'."); + BEAST_EXPECT(resp[jss::result][jss::error_message] == "Invalid field 'passphrase'."); } { // Invalid transaction @@ -319,9 +269,7 @@ class Simulate_test : public beast::unit_test::suite params[jss::tx_json] = tx_json; auto const resp = env.rpc("json", "simulate", to_string(params)); - BEAST_EXPECT( - resp[jss::result][jss::error_exception] == - "Field 'Destination' is required but missing."); + BEAST_EXPECT(resp[jss::result][jss::error_exception] == "Field 'Destination' is required but missing."); } { // Bad account @@ -333,11 +281,8 @@ class Simulate_test : public beast::unit_test::suite auto const resp = env.rpc("json", "simulate", to_string(params)); BEAST_EXPECTS( - resp[jss::result][jss::error] == "srcActMalformed", - resp[jss::result][jss::error].toStyledString()); - BEAST_EXPECT( - resp[jss::result][jss::error_message] == - "Invalid field 'tx.Account'."); + resp[jss::result][jss::error] == "srcActMalformed", resp[jss::result][jss::error].toStyledString()); + BEAST_EXPECT(resp[jss::result][jss::error_message] == "Invalid field 'tx.Account'."); } { // Account doesn't exist for Sequence autofill @@ -348,9 +293,7 @@ class Simulate_test : public beast::unit_test::suite params[jss::tx_json] = tx_json; auto const resp = env.rpc("json", "simulate", to_string(params)); - BEAST_EXPECT( - resp[jss::result][jss::error_message] == - "Source account not found."); + BEAST_EXPECT(resp[jss::result][jss::error_message] == "Source account not found."); } { // Invalid Signers field @@ -362,9 +305,7 @@ class Simulate_test : public beast::unit_test::suite params[jss::tx_json] = tx_json; auto const resp = env.rpc("json", "simulate", to_string(params)); - BEAST_EXPECT( - resp[jss::result][jss::error_message] == - "Invalid field 'tx.Signers'."); + BEAST_EXPECT(resp[jss::result][jss::error_message] == "Invalid field 'tx.Signers'."); } { // Invalid Signers field @@ -377,9 +318,7 @@ class Simulate_test : public beast::unit_test::suite params[jss::tx_json] = tx_json; auto const resp = env.rpc("json", "simulate", to_string(params)); - BEAST_EXPECT( - resp[jss::result][jss::error_message] == - "Invalid field 'tx.Signers[0]'."); + BEAST_EXPECT(resp[jss::result][jss::error_message] == "Invalid field 'tx.Signers[0]'."); } { // Invalid transaction @@ -391,9 +330,7 @@ class Simulate_test : public beast::unit_test::suite params[jss::tx_json] = tx_json; auto const resp = env.rpc("json", "simulate", to_string(params)); - BEAST_EXPECT( - resp[jss::result][jss::error_message] == - "Field 'tx_json.foo' is unknown."); + BEAST_EXPECT(resp[jss::result][jss::error_message] == "Field 'tx_json.foo' is unknown."); } { // non-`"binary"` second param for CLI @@ -413,9 +350,7 @@ class Simulate_test : public beast::unit_test::suite params[jss::tx_json] = tx_json; auto const resp = env.rpc("json", "simulate", to_string(params)); - BEAST_EXPECT( - resp[jss::result][jss::error_message] == - "Transaction should not be signed."); + BEAST_EXPECT(resp[jss::result][jss::error_message] == "Transaction should not be signed."); } { // Signed multisig transaction @@ -436,9 +371,7 @@ class Simulate_test : public beast::unit_test::suite params[jss::tx_json] = tx_json; auto const resp = env.rpc("json", "simulate", to_string(params)); - BEAST_EXPECT( - resp[jss::result][jss::error_message] == - "Transaction should not be signed."); + BEAST_EXPECT(resp[jss::result][jss::error_message] == "Transaction should not be signed."); } } @@ -450,8 +383,7 @@ class Simulate_test : public beast::unit_test::suite using namespace jtx; Env env(*this, envconfig([](std::unique_ptr cfg) { - cfg->section("transaction_queue") - .set("minimum_txn_in_ledger_standalone", "3"); + cfg->section("transaction_queue").set("minimum_txn_in_ledger_standalone", "3"); return cfg; })); @@ -504,8 +436,7 @@ class Simulate_test : public beast::unit_test::suite params[jss::tx_json] = jt.jv; auto const resp = env.rpc("json", "simulate", to_string(params)); BEAST_EXPECT(resp[jss::result][jss::error] == "notImpl"); - BEAST_EXPECT( - resp[jss::result][jss::error_message] == "Not implemented."); + BEAST_EXPECT(resp[jss::result][jss::error_message] == "Not implemented."); } void @@ -521,44 +452,33 @@ class Simulate_test : public beast::unit_test::suite static auto const newDomain = "123ABC"; { - auto validateOutput = [&](Json::Value const& resp, - Json::Value const& tx) { + auto validateOutput = [&](Json::Value const& resp, Json::Value const& tx) { auto result = resp[jss::result]; - checkBasicReturnValidity( - result, tx, 1, env.current()->fees().base); + checkBasicReturnValidity(result, tx, 1, env.current()->fees().base); BEAST_EXPECT(result[jss::engine_result] == "tesSUCCESS"); BEAST_EXPECT(result[jss::engine_result_code] == 0); BEAST_EXPECT( - result[jss::engine_result_message] == - "The simulated transaction would have been applied."); + result[jss::engine_result_message] == "The simulated transaction would have been applied."); - if (BEAST_EXPECT( - result.isMember(jss::meta) || - result.isMember(jss::meta_blob))) + if (BEAST_EXPECT(result.isMember(jss::meta) || result.isMember(jss::meta_blob))) { Json::Value const metadata = getJsonMetadata(result); - if (BEAST_EXPECT( - metadata.isMember(sfAffectedNodes.jsonName))) + if (BEAST_EXPECT(metadata.isMember(sfAffectedNodes.jsonName))) { - BEAST_EXPECT( - metadata[sfAffectedNodes.jsonName].size() == 1); + BEAST_EXPECT(metadata[sfAffectedNodes.jsonName].size() == 1); auto node = metadata[sfAffectedNodes.jsonName][0u]; - if (BEAST_EXPECT( - node.isMember(sfModifiedNode.jsonName))) + if (BEAST_EXPECT(node.isMember(sfModifiedNode.jsonName))) { auto modifiedNode = node[sfModifiedNode]; - BEAST_EXPECT( - modifiedNode[sfLedgerEntryType] == - "AccountRoot"); + BEAST_EXPECT(modifiedNode[sfLedgerEntryType] == "AccountRoot"); auto finalFields = modifiedNode[sfFinalFields]; BEAST_EXPECT(finalFields[sfDomain] == newDomain); } } BEAST_EXPECT(metadata[sfTransactionIndex.jsonName] == 0); - BEAST_EXPECT( - metadata[sfTransactionResult.jsonName] == "tesSUCCESS"); + BEAST_EXPECT(metadata[sfTransactionResult.jsonName] == "tesSUCCESS"); } }; @@ -591,22 +511,16 @@ class Simulate_test : public beast::unit_test::suite Account const alice("alice"); { - std::function const& - testSimulation = [&](Json::Value const& resp, - Json::Value const& tx) { + std::function const& testSimulation = + [&](Json::Value const& resp, Json::Value const& tx) { auto result = resp[jss::result]; - checkBasicReturnValidity( - result, tx, 1, env.current()->fees().base); + checkBasicReturnValidity(result, tx, 1, env.current()->fees().base); BEAST_EXPECT(result[jss::engine_result] == "temBAD_AMOUNT"); BEAST_EXPECT(result[jss::engine_result_code] == -298); - BEAST_EXPECT( - result[jss::engine_result_message] == - "Malformed: Bad amount."); + BEAST_EXPECT(result[jss::engine_result_message] == "Malformed: Bad amount."); - BEAST_EXPECT( - !result.isMember(jss::meta) && - !result.isMember(jss::meta_blob)); + BEAST_EXPECT(!result.isMember(jss::meta) && !result.isMember(jss::meta_blob)); }; Json::Value tx; @@ -639,15 +553,12 @@ class Simulate_test : public beast::unit_test::suite Account const alice("alice"); { - std::function const& - testSimulation = [&](Json::Value const& resp, - Json::Value const& tx) { + std::function const& testSimulation = + [&](Json::Value const& resp, Json::Value const& tx) { auto result = resp[jss::result]; - checkBasicReturnValidity( - result, tx, 1, env.current()->fees().base); + checkBasicReturnValidity(result, tx, 1, env.current()->fees().base); - BEAST_EXPECT( - result[jss::engine_result] == "tecNO_DST_INSUF_XRP"); + BEAST_EXPECT(result[jss::engine_result] == "tecNO_DST_INSUF_XRP"); BEAST_EXPECT(result[jss::engine_result_code] == 125); BEAST_EXPECT( result[jss::engine_result_message] == @@ -655,38 +566,26 @@ class Simulate_test : public beast::unit_test::suite "create " "it."); - if (BEAST_EXPECT( - result.isMember(jss::meta) || - result.isMember(jss::meta_blob))) + if (BEAST_EXPECT(result.isMember(jss::meta) || result.isMember(jss::meta_blob))) { Json::Value const metadata = getJsonMetadata(result); - if (BEAST_EXPECT( - metadata.isMember(sfAffectedNodes.jsonName))) + if (BEAST_EXPECT(metadata.isMember(sfAffectedNodes.jsonName))) { - BEAST_EXPECT( - metadata[sfAffectedNodes.jsonName].size() == 1); + BEAST_EXPECT(metadata[sfAffectedNodes.jsonName].size() == 1); auto node = metadata[sfAffectedNodes.jsonName][0u]; - if (BEAST_EXPECT( - node.isMember(sfModifiedNode.jsonName))) + if (BEAST_EXPECT(node.isMember(sfModifiedNode.jsonName))) { auto modifiedNode = node[sfModifiedNode]; - BEAST_EXPECT( - modifiedNode[sfLedgerEntryType] == - "AccountRoot"); + BEAST_EXPECT(modifiedNode[sfLedgerEntryType] == "AccountRoot"); auto finalFields = modifiedNode[sfFinalFields]; BEAST_EXPECT( finalFields[sfBalance] == - std::to_string( - 100'000'000'000'000'000 - - env.current()->fees().base.drops())); + std::to_string(100'000'000'000'000'000 - env.current()->fees().base.drops())); } } - BEAST_EXPECT( - metadata[sfTransactionIndex.jsonName] == 0); - BEAST_EXPECT( - metadata[sfTransactionResult.jsonName] == - "tecNO_DST_INSUF_XRP"); + BEAST_EXPECT(metadata[sfTransactionIndex.jsonName] == 0); + BEAST_EXPECT(metadata[sfTransactionResult.jsonName] == "tecNO_DST_INSUF_XRP"); } }; @@ -729,48 +628,37 @@ class Simulate_test : public beast::unit_test::suite env.close(); { - auto validateOutput = [&](Json::Value const& resp, - Json::Value const& tx) { + auto validateOutput = [&](Json::Value const& resp, Json::Value const& tx) { auto result = resp[jss::result]; checkBasicReturnValidity( result, tx, env.seq(alice), - tx.isMember(jss::Signers) ? env.current()->fees().base * 2 - : env.current()->fees().base); + tx.isMember(jss::Signers) ? env.current()->fees().base * 2 : env.current()->fees().base); BEAST_EXPECT(result[jss::engine_result] == "tesSUCCESS"); BEAST_EXPECT(result[jss::engine_result_code] == 0); BEAST_EXPECT( - result[jss::engine_result_message] == - "The simulated transaction would have been applied."); + result[jss::engine_result_message] == "The simulated transaction would have been applied."); - if (BEAST_EXPECT( - result.isMember(jss::meta) || - result.isMember(jss::meta_blob))) + if (BEAST_EXPECT(result.isMember(jss::meta) || result.isMember(jss::meta_blob))) { Json::Value const metadata = getJsonMetadata(result); - if (BEAST_EXPECT( - metadata.isMember(sfAffectedNodes.jsonName))) + if (BEAST_EXPECT(metadata.isMember(sfAffectedNodes.jsonName))) { - BEAST_EXPECT( - metadata[sfAffectedNodes.jsonName].size() == 1); + BEAST_EXPECT(metadata[sfAffectedNodes.jsonName].size() == 1); auto node = metadata[sfAffectedNodes.jsonName][0u]; - if (BEAST_EXPECT( - node.isMember(sfModifiedNode.jsonName))) + if (BEAST_EXPECT(node.isMember(sfModifiedNode.jsonName))) { auto modifiedNode = node[sfModifiedNode]; - BEAST_EXPECT( - modifiedNode[sfLedgerEntryType] == - "AccountRoot"); + BEAST_EXPECT(modifiedNode[sfLedgerEntryType] == "AccountRoot"); auto finalFields = modifiedNode[sfFinalFields]; BEAST_EXPECT(finalFields[sfDomain] == newDomain); } } BEAST_EXPECT(metadata[sfTransactionIndex.jsonName] == 0); - BEAST_EXPECT( - metadata[sfTransactionResult.jsonName] == "tesSUCCESS"); + BEAST_EXPECT(metadata[sfTransactionResult.jsonName] == "tesSUCCESS"); } }; @@ -799,8 +687,7 @@ class Simulate_test : public beast::unit_test::suite tx[sfTxnSignature] = ""; tx[sfSequence] = env.seq(alice); // transaction requires a non-base fee - tx[sfFee] = - (env.current()->fees().base * 2).jsonClipped().asString(); + tx[sfFee] = (env.current()->fees().base * 2).jsonClipped().asString(); tx[sfSigners][0u][sfSigner][jss::SigningPubKey] = ""; tx[sfSigners][0u][sfSigner][jss::TxnSignature] = ""; @@ -823,27 +710,17 @@ class Simulate_test : public beast::unit_test::suite env.close(); { - std::function const& - testSimulation = - [&](Json::Value const& resp, Json::Value const& tx) { - auto result = resp[jss::result]; - checkBasicReturnValidity( - result, - tx, - env.seq(env.master), - env.current()->fees().base); + std::function const& testSimulation = + [&](Json::Value const& resp, Json::Value const& tx) { + auto result = resp[jss::result]; + checkBasicReturnValidity(result, tx, env.seq(env.master), env.current()->fees().base); - BEAST_EXPECT( - result[jss::engine_result] == "tefMASTER_DISABLED"); - BEAST_EXPECT(result[jss::engine_result_code] == -188); - BEAST_EXPECT( - result[jss::engine_result_message] == - "Master key is disabled."); + BEAST_EXPECT(result[jss::engine_result] == "tefMASTER_DISABLED"); + BEAST_EXPECT(result[jss::engine_result_code] == -188); + BEAST_EXPECT(result[jss::engine_result_message] == "Master key is disabled."); - BEAST_EXPECT( - !result.isMember(jss::meta) && - !result.isMember(jss::meta_blob)); - }; + BEAST_EXPECT(!result.isMember(jss::meta) && !result.isMember(jss::meta_blob)); + }; Json::Value tx; @@ -886,25 +763,16 @@ class Simulate_test : public beast::unit_test::suite env.close(); { - std::function const& - testSimulation = [&](Json::Value const& resp, - Json::Value const& tx) { + std::function const& testSimulation = + [&](Json::Value const& resp, Json::Value const& tx) { auto result = resp[jss::result]; - checkBasicReturnValidity( - result, - tx, - env.seq(env.master), - env.current()->fees().base * 2); + checkBasicReturnValidity(result, tx, env.seq(env.master), env.current()->fees().base * 2); BEAST_EXPECT(result[jss::engine_result] == "temINVALID"); BEAST_EXPECT(result[jss::engine_result_code] == -277); - BEAST_EXPECT( - result[jss::engine_result_message] == - "The transaction is ill-formed."); + BEAST_EXPECT(result[jss::engine_result_message] == "The transaction is ill-formed."); - BEAST_EXPECT( - !result.isMember(jss::meta) && - !result.isMember(jss::meta_blob)); + BEAST_EXPECT(!result.isMember(jss::meta) && !result.isMember(jss::meta_blob)); }; Json::Value tx; @@ -929,8 +797,7 @@ class Simulate_test : public beast::unit_test::suite tx[sfTxnSignature] = ""; tx[sfSequence] = env.seq(env.master); tx[sfFee] = env.current()->fees().base.jsonClipped().asString(); - tx[sfSigners][0u][sfSigner][jss::SigningPubKey] = - strHex(becky.pk().slice()); + tx[sfSigners][0u][sfSigner][jss::SigningPubKey] = strHex(becky.pk().slice()); tx[sfSigners][0u][sfSigner][jss::TxnSignature] = ""; // test without autofill @@ -957,23 +824,16 @@ class Simulate_test : public beast::unit_test::suite env(signers(alice, 1, {{becky, 1}, {carol, 1}})); { - auto validateOutput = [&](Json::Value const& resp, - Json::Value const& tx) { + auto validateOutput = [&](Json::Value const& resp, Json::Value const& tx) { auto result = resp[jss::result]; - checkBasicReturnValidity( - result, tx, env.seq(alice), env.current()->fees().base * 2); + checkBasicReturnValidity(result, tx, env.seq(alice), env.current()->fees().base * 2); BEAST_EXPECTS( - result[jss::engine_result] == "tefBAD_SIGNATURE", - result[jss::engine_result].toStyledString()); + result[jss::engine_result] == "tefBAD_SIGNATURE", result[jss::engine_result].toStyledString()); BEAST_EXPECT(result[jss::engine_result_code] == -186); - BEAST_EXPECT( - result[jss::engine_result_message] == - "A signature is provided for a non-signer."); + BEAST_EXPECT(result[jss::engine_result_message] == "A signature is provided for a non-signer."); - BEAST_EXPECT( - !result.isMember(jss::meta) && - !result.isMember(jss::meta_blob)); + BEAST_EXPECT(!result.isMember(jss::meta) && !result.isMember(jss::meta_blob)); }; Json::Value tx; @@ -998,8 +858,7 @@ class Simulate_test : public beast::unit_test::suite tx[sfTxnSignature] = ""; tx[sfSequence] = env.seq(alice); // transaction requires a non-base fee - tx[sfFee] = - (env.current()->fees().base * 2).jsonClipped().asString(); + tx[sfFee] = (env.current()->fees().base * 2).jsonClipped().asString(); tx[sfSigners][0u][sfSigner][jss::TxnSignature] = ""; // test without autofill @@ -1026,57 +885,40 @@ class Simulate_test : public beast::unit_test::suite auto const credType = "123ABC"; auto jv = credentials::create(subject, issuer, credType); - uint32_t const t = - env.current()->header().parentCloseTime.time_since_epoch().count(); + uint32_t const t = env.current()->header().parentCloseTime.time_since_epoch().count(); jv[sfExpiration.jsonName] = t; env(jv); env.close(); { - auto validateOutput = [&](Json::Value const& resp, - Json::Value const& tx) { + auto validateOutput = [&](Json::Value const& resp, Json::Value const& tx) { auto result = resp[jss::result]; - checkBasicReturnValidity( - result, tx, env.seq(subject), env.current()->fees().base); + checkBasicReturnValidity(result, tx, env.seq(subject), env.current()->fees().base); BEAST_EXPECT(result[jss::engine_result] == "tecEXPIRED"); BEAST_EXPECT(result[jss::engine_result_code] == 148); - BEAST_EXPECT( - result[jss::engine_result_message] == - "Expiration time is passed."); + BEAST_EXPECT(result[jss::engine_result_message] == "Expiration time is passed."); - if (BEAST_EXPECT( - result.isMember(jss::meta) || - result.isMember(jss::meta_blob))) + if (BEAST_EXPECT(result.isMember(jss::meta) || result.isMember(jss::meta_blob))) { Json::Value const metadata = getJsonMetadata(result); - if (BEAST_EXPECT( - metadata.isMember(sfAffectedNodes.jsonName))) + if (BEAST_EXPECT(metadata.isMember(sfAffectedNodes.jsonName))) { - BEAST_EXPECT( - metadata[sfAffectedNodes.jsonName].size() == 5); + BEAST_EXPECT(metadata[sfAffectedNodes.jsonName].size() == 5); try { bool found = false; - for (auto const& node : - metadata[sfAffectedNodes.jsonName]) + for (auto const& node : metadata[sfAffectedNodes.jsonName]) { if (node.isMember(sfDeletedNode.jsonName) && - node[sfDeletedNode.jsonName] - [sfLedgerEntryType.jsonName] - .asString() == "Credential") + node[sfDeletedNode.jsonName][sfLedgerEntryType.jsonName].asString() == "Credential") { - auto const deleted = - node[sfDeletedNode.jsonName] - [sfFinalFields.jsonName]; - found = deleted[jss::Issuer] == - issuer.human() && - deleted[jss::Subject] == - subject.human() && - deleted["CredentialType"] == - strHex(std::string_view(credType)); + auto const deleted = node[sfDeletedNode.jsonName][sfFinalFields.jsonName]; + found = deleted[jss::Issuer] == issuer.human() && + deleted[jss::Subject] == subject.human() && + deleted["CredentialType"] == strHex(std::string_view(credType)); break; } } @@ -1088,8 +930,7 @@ class Simulate_test : public beast::unit_test::suite } } BEAST_EXPECT(metadata[sfTransactionIndex.jsonName] == 0); - BEAST_EXPECT( - metadata[sfTransactionResult.jsonName] == "tecEXPIRED"); + BEAST_EXPECT(metadata[sfTransactionResult.jsonName] == "tecEXPIRED"); } }; @@ -1108,18 +949,14 @@ class Simulate_test : public beast::unit_test::suite } // check that expired credentials weren't deleted - auto const jle = - credentials::ledgerEntry(env, subject, issuer, credType); + auto const jle = credentials::ledgerEntry(env, subject, issuer, credType); BEAST_EXPECT( - jle.isObject() && jle.isMember(jss::result) && - !jle[jss::result].isMember(jss::error) && - jle[jss::result].isMember(jss::node) && - jle[jss::result][jss::node].isMember("LedgerEntryType") && + jle.isObject() && jle.isMember(jss::result) && !jle[jss::result].isMember(jss::error) && + jle[jss::result].isMember(jss::node) && jle[jss::result][jss::node].isMember("LedgerEntryType") && jle[jss::result][jss::node]["LedgerEntryType"] == jss::Credential && jle[jss::result][jss::node][jss::Issuer] == issuer.human() && jle[jss::result][jss::node][jss::Subject] == subject.human() && - jle[jss::result][jss::node]["CredentialType"] == - strHex(std::string_view(credType))); + jle[jss::result][jss::node]["CredentialType"] == strHex(std::string_view(credType))); BEAST_EXPECT(ownerCount(env, issuer) == 1); BEAST_EXPECT(ownerCount(env, subject) == 0); @@ -1138,44 +975,33 @@ class Simulate_test : public beast::unit_test::suite static auto const newDomain = "123ABC"; { - auto validateOutput = [&](Json::Value const& resp, - Json::Value const& tx) { + auto validateOutput = [&](Json::Value const& resp, Json::Value const& tx) { auto result = resp[jss::result]; - checkBasicReturnValidity( - result, tx, 1, env.current()->fees().base); + checkBasicReturnValidity(result, tx, 1, env.current()->fees().base); BEAST_EXPECT(result[jss::engine_result] == "tesSUCCESS"); BEAST_EXPECT(result[jss::engine_result_code] == 0); BEAST_EXPECT( - result[jss::engine_result_message] == - "The simulated transaction would have been applied."); + result[jss::engine_result_message] == "The simulated transaction would have been applied."); - if (BEAST_EXPECT( - result.isMember(jss::meta) || - result.isMember(jss::meta_blob))) + if (BEAST_EXPECT(result.isMember(jss::meta) || result.isMember(jss::meta_blob))) { Json::Value const metadata = getJsonMetadata(result); - if (BEAST_EXPECT( - metadata.isMember(sfAffectedNodes.jsonName))) + if (BEAST_EXPECT(metadata.isMember(sfAffectedNodes.jsonName))) { - BEAST_EXPECT( - metadata[sfAffectedNodes.jsonName].size() == 1); + BEAST_EXPECT(metadata[sfAffectedNodes.jsonName].size() == 1); auto node = metadata[sfAffectedNodes.jsonName][0u]; - if (BEAST_EXPECT( - node.isMember(sfModifiedNode.jsonName))) + if (BEAST_EXPECT(node.isMember(sfModifiedNode.jsonName))) { auto modifiedNode = node[sfModifiedNode]; - BEAST_EXPECT( - modifiedNode[sfLedgerEntryType] == - "AccountRoot"); + BEAST_EXPECT(modifiedNode[sfLedgerEntryType] == "AccountRoot"); auto finalFields = modifiedNode[sfFinalFields]; BEAST_EXPECT(finalFields[sfDomain] == newDomain); } } BEAST_EXPECT(metadata[sfTransactionIndex.jsonName] == 0); - BEAST_EXPECT( - metadata[sfTransactionResult.jsonName] == "tesSUCCESS"); + BEAST_EXPECT(metadata[sfTransactionResult.jsonName] == "tesSUCCESS"); } }; @@ -1221,37 +1047,27 @@ class Simulate_test : public beast::unit_test::suite env.close(NetClock::time_point{446000000s}); { - auto validateOutput = - [&](Json::Value const& resp, - Json::Value const& tx, - Json::Value const& expectedMetadataKey, - Json::Value const& expectedMetadataValue) { - auto result = resp[jss::result]; + auto validateOutput = [&](Json::Value const& resp, + Json::Value const& tx, + Json::Value const& expectedMetadataKey, + Json::Value const& expectedMetadataValue) { + auto result = resp[jss::result]; - BEAST_EXPECT(result[jss::engine_result] == "tesSUCCESS"); - BEAST_EXPECT(result[jss::engine_result_code] == 0); - BEAST_EXPECT( - result[jss::engine_result_message] == - "The simulated transaction would have been applied."); + BEAST_EXPECT(result[jss::engine_result] == "tesSUCCESS"); + BEAST_EXPECT(result[jss::engine_result_code] == 0); + BEAST_EXPECT( + result[jss::engine_result_message] == "The simulated transaction would have been applied."); - if (BEAST_EXPECT( - result.isMember(jss::meta) || - result.isMember(jss::meta_blob))) - { - Json::Value const metadata = getJsonMetadata(result); + if (BEAST_EXPECT(result.isMember(jss::meta) || result.isMember(jss::meta_blob))) + { + Json::Value const metadata = getJsonMetadata(result); - BEAST_EXPECT( - metadata[sfTransactionIndex.jsonName] == 0); - BEAST_EXPECT( - metadata[sfTransactionResult.jsonName] == - "tesSUCCESS"); - BEAST_EXPECT( - metadata.isMember(expectedMetadataKey.asString())); - BEAST_EXPECT( - metadata[expectedMetadataKey.asString()] == - expectedMetadataValue); - } - }; + BEAST_EXPECT(metadata[sfTransactionIndex.jsonName] == 0); + BEAST_EXPECT(metadata[sfTransactionResult.jsonName] == "tesSUCCESS"); + BEAST_EXPECT(metadata.isMember(expectedMetadataKey.asString())); + BEAST_EXPECT(metadata[expectedMetadataKey.asString()] == expectedMetadataValue); + } + }; { Json::Value tx; @@ -1261,8 +1077,7 @@ class Simulate_test : public beast::unit_test::suite tx[sfAmount] = "100"; // test delivered amount - testTxJsonMetadataField( - env, tx, validateOutput, jss::delivered_amount, "100"); + testTxJsonMetadataField(env, tx, validateOutput, jss::delivered_amount, "100"); } { @@ -1271,11 +1086,9 @@ class Simulate_test : public beast::unit_test::suite tx[jss::TransactionType] = jss::NFTokenMint; tx[sfNFTokenTaxon] = 1; - Json::Value nftokenId = - to_string(token::getNextID(env, alice, 1)); + Json::Value nftokenId = to_string(token::getNextID(env, alice, 1)); // test nft synthetic - testTxJsonMetadataField( - env, tx, validateOutput, jss::nftoken_id, nftokenId); + testTxJsonMetadataField(env, tx, validateOutput, jss::nftoken_id, nftokenId); } { @@ -1283,15 +1096,9 @@ class Simulate_test : public beast::unit_test::suite tx[jss::Account] = alice.human(); tx[jss::TransactionType] = jss::MPTokenIssuanceCreate; - Json::Value mptIssuanceId = - to_string(makeMptID(env.seq(alice), alice)); + Json::Value mptIssuanceId = to_string(makeMptID(env.seq(alice), alice)); // test mpt issuance id - testTxJsonMetadataField( - env, - tx, - validateOutput, - jss::mpt_issuance_id, - mptIssuanceId); + testTxJsonMetadataField(env, tx, validateOutput, jss::mpt_issuance_id, mptIssuanceId); } } } diff --git a/src/test/rpc/Status_test.cpp b/src/test/rpc/Status_test.cpp index c2e9c836df..ac387196fe 100644 --- a/src/test/rpc/Status_test.cpp +++ b/src/test/rpc/Status_test.cpp @@ -112,11 +112,7 @@ private: template void - expectFill( - std::string const& label, - Type status, - Status::Strings messages, - std::string const& message) + expectFill(std::string const& label, Type status, Status::Strings messages, std::string const& message) { value_.clear(); fillJson(Status(status, messages)); @@ -128,20 +124,14 @@ private: expect(bool(error), prefix + "No error."); auto code = error[jss::code].asInt(); - expect( - status == code, - prefix + "Wrong status " + std::to_string(code) + - " != " + std::to_string(status)); + expect(status == code, prefix + "Wrong status " + std::to_string(code) + " != " + std::to_string(status)); auto m = error[jss::message].asString(); expect(m == message, m + " != " + message); auto d = error[jss::data]; size_t s1 = d.size(), s2 = messages.size(); - expect( - s1 == s2, - prefix + "Data sizes differ " + std::to_string(s1) + - " != " + std::to_string(s2)); + expect(s1 == s2, prefix + "Data sizes differ " + std::to_string(s1) + " != " + std::to_string(s2)); for (auto i = 0; i < std::min(s1, s2); ++i) { auto ds = d[i].asString(); @@ -153,17 +143,9 @@ private: test_error() { testcase("error"); - expectFill( - "temBAD_AMOUNT", - temBAD_AMOUNT, - {}, - "temBAD_AMOUNT: Malformed: Bad amount."); + expectFill("temBAD_AMOUNT", temBAD_AMOUNT, {}, "temBAD_AMOUNT: Malformed: Bad amount."); - expectFill( - "rpcBAD_SYNTAX", - rpcBAD_SYNTAX, - {"An error.", "Another error."}, - "badSyntax: Syntax error."); + expectFill("rpcBAD_SYNTAX", rpcBAD_SYNTAX, {"An error.", "Another error."}, "badSyntax: Syntax error."); expectFill("integer message", 23, {"Stuff."}, "23"); } diff --git a/src/test/rpc/Subscribe_test.cpp b/src/test/rpc/Subscribe_test.cpp index 5a58c27ea8..759b02dcc7 100644 --- a/src/test/rpc/Subscribe_test.cpp +++ b/src/test/rpc/Subscribe_test.cpp @@ -4,13 +4,13 @@ #include #include -#include #include #include #include #include #include +#include #include @@ -36,10 +36,8 @@ public: auto jv = wsc->invoke("subscribe", stream); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } BEAST_EXPECT(jv[jss::status] == "success"); @@ -59,9 +57,7 @@ public: env.app().getOPs().reportFeeChange(); // Check stream update - BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { - return jv[jss::type] == "serverStatus"; - })); + BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { return jv[jss::type] == "serverStatus"; })); } { @@ -69,10 +65,8 @@ public: auto jv = wsc->invoke("unsubscribe", stream); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } BEAST_EXPECT(jv[jss::status] == "success"); @@ -107,16 +101,12 @@ public: auto jv = wsc->invoke("subscribe", stream); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } BEAST_EXPECT(jv[jss::result][jss::ledger_index] == 2); - BEAST_EXPECT( - jv[jss::result][jss::network_id] == - env.app().config().NETWORK_ID); + BEAST_EXPECT(jv[jss::result][jss::network_id] == env.app().config().NETWORK_ID); } { @@ -125,8 +115,7 @@ public: // Check stream update BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { - return jv[jss::ledger_index] == 3 && - jv[jss::network_id] == env.app().config().NETWORK_ID; + return jv[jss::ledger_index] == 3 && jv[jss::network_id] == env.app().config().NETWORK_ID; })); } @@ -136,8 +125,7 @@ public: // Check stream update BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { - return jv[jss::ledger_index] == 4 && - jv[jss::network_id] == env.app().config().NETWORK_ID; + return jv[jss::ledger_index] == 4 && jv[jss::network_id] == env.app().config().NETWORK_ID; })); } @@ -145,10 +133,8 @@ public: auto jv = wsc->invoke("unsubscribe", stream); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } BEAST_EXPECT(jv[jss::status] == "success"); @@ -171,10 +157,8 @@ public: auto jv = wsc->invoke("subscribe", stream); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } BEAST_EXPECT(jv[jss::status] == "success"); @@ -186,8 +170,7 @@ public: // Check stream update for payment transaction BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { - return jv[jss::meta]["AffectedNodes"][1u]["CreatedNode"] - ["NewFields"][jss::Account] // + return jv[jss::meta]["AffectedNodes"][1u]["CreatedNode"]["NewFields"][jss::Account] // == Account("alice").human() && jv[jss::transaction][jss::TransactionType] // == jss::Payment && @@ -201,8 +184,7 @@ public: // Check stream update for accountset transaction BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { - return jv[jss::meta]["AffectedNodes"][0u]["ModifiedNode"] - ["FinalFields"][jss::Account] == + return jv[jss::meta]["AffectedNodes"][0u]["ModifiedNode"]["FinalFields"][jss::Account] == Account("alice").human(); })); @@ -211,8 +193,7 @@ public: // Check stream update for payment transaction BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { - return jv[jss::meta]["AffectedNodes"][1u]["CreatedNode"] - ["NewFields"][jss::Account] // + return jv[jss::meta]["AffectedNodes"][1u]["CreatedNode"]["NewFields"][jss::Account] // == Account("bob").human() && jv[jss::transaction][jss::TransactionType] // == jss::Payment && @@ -226,8 +207,7 @@ public: // Check stream update for accountset transaction BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { - return jv[jss::meta]["AffectedNodes"][0u]["ModifiedNode"] - ["FinalFields"][jss::Account] == + return jv[jss::meta]["AffectedNodes"][0u]["ModifiedNode"]["FinalFields"][jss::Account] == Account("bob").human(); })); } @@ -237,10 +217,8 @@ public: auto jv = wsc->invoke("unsubscribe", stream); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } BEAST_EXPECT(jv[jss::status] == "success"); @@ -254,10 +232,8 @@ public: auto jv = wsc->invoke("subscribe", stream); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } BEAST_EXPECT(jv[jss::status] == "success"); @@ -275,14 +251,12 @@ public: // Check stream updates BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { - return jv[jss::meta]["AffectedNodes"][1u]["ModifiedNode"] - ["FinalFields"][jss::Account] == + return jv[jss::meta]["AffectedNodes"][1u]["ModifiedNode"]["FinalFields"][jss::Account] == Account("alice").human(); })); BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { - return jv[jss::meta]["AffectedNodes"][1u]["CreatedNode"] - ["NewFields"]["LowLimit"][jss::issuer] == + return jv[jss::meta]["AffectedNodes"][1u]["CreatedNode"]["NewFields"]["LowLimit"][jss::issuer] == Account("alice").human(); })); } @@ -291,10 +265,8 @@ public: auto jv = wsc->invoke("unsubscribe", stream); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } BEAST_EXPECT(jv[jss::status] == "success"); @@ -322,10 +294,8 @@ public: auto jv = wsc->invoke("subscribe", stream); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } BEAST_EXPECT(jv[jss::status] == "success"); @@ -337,8 +307,7 @@ public: // Check stream update for payment transaction BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { - return jv[jss::meta]["AffectedNodes"][1u]["CreatedNode"] - ["NewFields"][jss::Account] // + return jv[jss::meta]["AffectedNodes"][1u]["CreatedNode"]["NewFields"][jss::Account] // == Account("alice").human() && jv[jss::close_time_iso] // == "2000-01-01T00:00:10Z" && @@ -361,8 +330,7 @@ public: // Check stream update for accountset transaction BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { - return jv[jss::meta]["AffectedNodes"][0u]["ModifiedNode"] - ["FinalFields"][jss::Account] == + return jv[jss::meta]["AffectedNodes"][0u]["ModifiedNode"]["FinalFields"][jss::Account] == Account("alice").human(); })); } @@ -372,10 +340,8 @@ public: auto jv = wsc->invoke("unsubscribe", stream); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } BEAST_EXPECT(jv[jss::status] == "success"); @@ -397,10 +363,8 @@ public: auto jv = wsc->invoke("subscribe", stream); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } BEAST_EXPECT(jv[jss::status] == "success"); @@ -410,10 +374,8 @@ public: auto jv = wsc->invoke("unsubscribe", stream); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } BEAST_EXPECT(jv[jss::status] == "success"); @@ -428,16 +390,13 @@ public: auto& cfg = env.app().config(); if (!BEAST_EXPECT(cfg.section(SECTION_VALIDATION_SEED).empty())) return; - auto const parsedseed = - parseBase58(cfg.section(SECTION_VALIDATION_SEED).values()[0]); + auto const parsedseed = parseBase58(cfg.section(SECTION_VALIDATION_SEED).values()[0]); if (!BEAST_EXPECT(parsedseed)) return; std::string const valPublicKey = toBase58( TokenType::NodePublic, - derivePublicKey( - KeyType::secp256k1, - generateSecretKey(KeyType::secp256k1, *parsedseed))); + derivePublicKey(KeyType::secp256k1, generateSecretKey(KeyType::secp256k1, *parsedseed))); auto wsc = makeWSClient(env.app().config()); Json::Value stream; @@ -449,10 +408,8 @@ public: auto jv = wsc->invoke("subscribe", stream); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } BEAST_EXPECT(jv[jss::status] == "success"); @@ -460,20 +417,17 @@ public: { // Lambda to check ledger validations from the stream. - auto validValidationFields = [&env, &valPublicKey]( - Json::Value const& jv) { + auto validValidationFields = [&env, &valPublicKey](Json::Value const& jv) { if (jv[jss::type] != "validationReceived") return false; if (jv[jss::validation_public_key].asString() != valPublicKey) return false; - if (jv[jss::ledger_hash] != - to_string(env.closed()->header().hash)) + if (jv[jss::ledger_hash] != to_string(env.closed()->header().hash)) return false; - if (jv[jss::ledger_index] != - std::to_string(env.closed()->header().seq)) + if (jv[jss::ledger_index] != std::to_string(env.closed()->header().seq)) return false; if (jv[jss::flags] != (vfFullyCanonicalSig | vfFullValidation)) @@ -498,13 +452,11 @@ public: return false; uint32_t netID = env.app().config().NETWORK_ID; - if (!jv.isMember(jss::network_id) || - jv[jss::network_id] != netID) + if (!jv.isMember(jss::network_id) || jv[jss::network_id] != netID) return false; // Certain fields are only added on a flag ledger. - bool const isFlagLedger = - (env.closed()->header().seq + 1) % 256 == 0; + bool const isFlagLedger = (env.closed()->header().seq + 1) % 256 == 0; if (jv.isMember(jss::server_version) != isFlagLedger) return false; @@ -532,10 +484,8 @@ public: auto jv = wsc->invoke("unsubscribe", stream); if (wsc->version() == 2) { - BEAST_EXPECT( - jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); - BEAST_EXPECT( - jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::jsonrpc) && jv[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jv.isMember(jss::ripplerpc) && jv[jss::ripplerpc] == "2.0"); BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5); } BEAST_EXPECT(jv[jss::status] == "success"); @@ -608,9 +558,7 @@ public: if (subscribe) { BEAST_EXPECT(jr[jss::error] == "invalidParams"); - BEAST_EXPECT( - jr[jss::error_message] == - "Only http and https is supported."); + BEAST_EXPECT(jr[jss::error_message] == "Only http and https is supported."); } } @@ -618,12 +566,9 @@ public: Env env_nonadmin{*this, no_admin(envconfig())}; Json::Value jv; jv[jss::url] = "no-url"; - auto jr = - env_nonadmin.rpc("json", method, to_string(jv))[jss::result]; + auto jr = env_nonadmin.rpc("json", method, to_string(jv))[jss::result]; BEAST_EXPECT(jr[jss::error] == "noPermission"); - BEAST_EXPECT( - jr[jss::error_message] == - "You don't have permission for this command."); + BEAST_EXPECT(jr[jss::error_message] == "You don't have permission for this command."); } std::initializer_list const nonArrays{ @@ -681,8 +626,7 @@ public: jv[jss::books][0u][jss::taker_pays] = Json::objectValue; auto jr = wsc->invoke(method, jv)[jss::result]; BEAST_EXPECT(jr[jss::error] == "srcCurMalformed"); - BEAST_EXPECT( - jr[jss::error_message] == "Source currency is malformed."); + BEAST_EXPECT(jr[jss::error_message] == "Source currency is malformed."); } { @@ -694,8 +638,7 @@ public: jv[jss::books][0u][jss::taker_pays][jss::currency] = "ZZZZ"; auto jr = wsc->invoke(method, jv)[jss::result]; BEAST_EXPECT(jr[jss::error] == "srcCurMalformed"); - BEAST_EXPECT( - jr[jss::error_message] == "Source currency is malformed."); + BEAST_EXPECT(jr[jss::error_message] == "Source currency is malformed."); } { @@ -708,8 +651,7 @@ public: jv[jss::books][0u][jss::taker_pays][jss::issuer] = 1; auto jr = wsc->invoke(method, jv)[jss::result]; BEAST_EXPECT(jr[jss::error] == "srcIsrMalformed"); - BEAST_EXPECT( - jr[jss::error_message] == "Source issuer is malformed."); + BEAST_EXPECT(jr[jss::error_message] == "Source issuer is malformed."); } { @@ -719,12 +661,10 @@ public: jv[jss::books][0u][jss::taker_gets] = Json::objectValue; jv[jss::books][0u][jss::taker_pays] = Json::objectValue; jv[jss::books][0u][jss::taker_pays][jss::currency] = "USD"; - jv[jss::books][0u][jss::taker_pays][jss::issuer] = - Account{"gateway"}.human() + "DEAD"; + jv[jss::books][0u][jss::taker_pays][jss::issuer] = Account{"gateway"}.human() + "DEAD"; auto jr = wsc->invoke(method, jv)[jss::result]; BEAST_EXPECT(jr[jss::error] == "srcIsrMalformed"); - BEAST_EXPECT( - jr[jss::error_message] == "Source issuer is malformed."); + BEAST_EXPECT(jr[jss::error_message] == "Source issuer is malformed."); } { @@ -732,16 +672,13 @@ public: jv[jss::books] = Json::arrayValue; jv[jss::books][0u] = Json::objectValue; jv[jss::books][0u][jss::taker_pays] = - Account{"gateway"}["USD"](1).value().getJson( - JsonOptions::include_date); + Account{"gateway"}["USD"](1).value().getJson(JsonOptions::include_date); jv[jss::books][0u][jss::taker_gets] = Json::objectValue; auto jr = wsc->invoke(method, jv)[jss::result]; // NOTE: this error is slightly incongruous with the // equivalent source currency error BEAST_EXPECT(jr[jss::error] == "dstAmtMalformed"); - BEAST_EXPECT( - jr[jss::error_message] == - "Destination amount/currency/issuer is malformed."); + BEAST_EXPECT(jr[jss::error_message] == "Destination amount/currency/issuer is malformed."); } { @@ -749,16 +686,13 @@ public: jv[jss::books] = Json::arrayValue; jv[jss::books][0u] = Json::objectValue; jv[jss::books][0u][jss::taker_pays] = - Account{"gateway"}["USD"](1).value().getJson( - JsonOptions::include_date); + Account{"gateway"}["USD"](1).value().getJson(JsonOptions::include_date); jv[jss::books][0u][jss::taker_gets][jss::currency] = "ZZZZ"; auto jr = wsc->invoke(method, jv)[jss::result]; // NOTE: this error is slightly incongruous with the // equivalent source currency error BEAST_EXPECT(jr[jss::error] == "dstAmtMalformed"); - BEAST_EXPECT( - jr[jss::error_message] == - "Destination amount/currency/issuer is malformed."); + BEAST_EXPECT(jr[jss::error_message] == "Destination amount/currency/issuer is malformed."); } { @@ -766,14 +700,12 @@ public: jv[jss::books] = Json::arrayValue; jv[jss::books][0u] = Json::objectValue; jv[jss::books][0u][jss::taker_pays] = - Account{"gateway"}["USD"](1).value().getJson( - JsonOptions::include_date); + Account{"gateway"}["USD"](1).value().getJson(JsonOptions::include_date); jv[jss::books][0u][jss::taker_gets][jss::currency] = "USD"; jv[jss::books][0u][jss::taker_gets][jss::issuer] = 1; auto jr = wsc->invoke(method, jv)[jss::result]; BEAST_EXPECT(jr[jss::error] == "dstIsrMalformed"); - BEAST_EXPECT( - jr[jss::error_message] == "Destination issuer is malformed."); + BEAST_EXPECT(jr[jss::error_message] == "Destination issuer is malformed."); } { @@ -781,15 +713,12 @@ public: jv[jss::books] = Json::arrayValue; jv[jss::books][0u] = Json::objectValue; jv[jss::books][0u][jss::taker_pays] = - Account{"gateway"}["USD"](1).value().getJson( - JsonOptions::include_date); + Account{"gateway"}["USD"](1).value().getJson(JsonOptions::include_date); jv[jss::books][0u][jss::taker_gets][jss::currency] = "USD"; - jv[jss::books][0u][jss::taker_gets][jss::issuer] = - Account{"gateway"}.human() + "DEAD"; + jv[jss::books][0u][jss::taker_gets][jss::issuer] = Account{"gateway"}.human() + "DEAD"; auto jr = wsc->invoke(method, jv)[jss::result]; BEAST_EXPECT(jr[jss::error] == "dstIsrMalformed"); - BEAST_EXPECT( - jr[jss::error_message] == "Destination issuer is malformed."); + BEAST_EXPECT(jr[jss::error_message] == "Destination issuer is malformed."); } { @@ -797,11 +726,9 @@ public: jv[jss::books] = Json::arrayValue; jv[jss::books][0u] = Json::objectValue; jv[jss::books][0u][jss::taker_pays] = - Account{"gateway"}["USD"](1).value().getJson( - JsonOptions::include_date); + Account{"gateway"}["USD"](1).value().getJson(JsonOptions::include_date); jv[jss::books][0u][jss::taker_gets] = - Account{"gateway"}["USD"](1).value().getJson( - JsonOptions::include_date); + Account{"gateway"}["USD"](1).value().getJson(JsonOptions::include_date); auto jr = wsc->invoke(method, jv)[jss::result]; BEAST_EXPECT(jr[jss::error] == "badMarket"); BEAST_EXPECT(jr[jss::error_message] == "No such market."); @@ -854,8 +781,7 @@ public: * return true if the subscribe or unsubscribe result is a success */ auto goodSubRPC = [](Json::Value const& subReply) -> bool { - return subReply.isMember(jss::result) && - subReply[jss::result].isMember(jss::status) && + return subReply.isMember(jss::result) && subReply[jss::result].isMember(jss::status) && subReply[jss::result][jss::status] == jss::success; }; @@ -864,9 +790,7 @@ public: * return {true, true} if received numReplies replies and also * received a tx with the account_history_tx_first == true */ - auto getTxHash = [](WSClient& wsc, - IdxHashVec& v, - int numReplies) -> std::pair { + auto getTxHash = [](WSClient& wsc, IdxHashVec& v, int numReplies) -> std::pair { bool first_flag = false; for (int i = 0; i < numReplies; ++i) @@ -882,12 +806,10 @@ public: first_flag = true; bool boundary = r.isMember(jss::account_history_boundary); int ledger_idx = r[jss::ledger_index].asInt(); - if (r.isMember(jss::transaction) && - r[jss::transaction].isMember(jss::hash)) + if (r.isMember(jss::transaction) && r[jss::transaction].isMember(jss::hash)) { auto t{r[jss::transaction]}; - v.emplace_back( - idx, t[jss::hash].asString(), boundary, ledger_idx); + v.emplace_back(idx, t[jss::hash].asString(), boundary, ledger_idx); continue; } } @@ -913,8 +835,7 @@ public: { auto& from = (i % 2 == 0) ? a : b; auto& to = (i % 2 == 0) ? b : a; - env.apply( - pay(from, to, jtx::XRP(numXRP)), + env(pay(from, to, jtx::XRP(numXRP)), jtx::seq(jtx::autofill), jtx::fee(jtx::autofill), jtx::sig(jtx::autofill)); @@ -929,9 +850,7 @@ public: * and in the same order. * If sizeCompare is false, txHistoryVec is allowed to be larger. */ - auto hashCompare = [](IdxHashVec const& accountVec, - IdxHashVec const& txHistoryVec, - bool sizeCompare) -> bool { + auto hashCompare = [](IdxHashVec const& accountVec, IdxHashVec const& txHistoryVec, bool sizeCompare) -> bool { if (accountVec.empty() || txHistoryVec.empty()) return false; if (sizeCompare && accountVec.size() != (txHistoryVec.size())) @@ -957,8 +876,7 @@ public: return false; for (std::size_t i = 1; i < accountVec.size(); ++i) { - if (auto idx = getHistoryIndex(i); - !idx || *idx != *firstHistoryIndex + i) + if (auto idx = getHistoryIndex(i); !idx || *idx != *firstHistoryIndex + i) return false; } return true; @@ -999,8 +917,7 @@ public: for (size_t i = 0; i < num_tx; ++i) { auto [idx, hash, boundary, ledger] = vec[i]; - if ((i + 1 == num_tx || ledger != std::get<3>(vec[i + 1])) != - boundary) + if ((i + 1 == num_tx || ledger != std::get<3>(vec[i + 1])) != boundary) return false; } return true; @@ -1019,8 +936,7 @@ public: auto wscTxHistory = makeWSClient(env.app().config()); Json::Value request; request[jss::account_history_tx_stream] = Json::objectValue; - request[jss::account_history_tx_stream][jss::account] = - alice.human(); + request[jss::account_history_tx_stream][jss::account] = alice.human(); auto jv = wscTxHistory->invoke("subscribe", request); if (!BEAST_EXPECT(goodSubRPC(jv))) return; @@ -1031,8 +947,7 @@ public: /* * unsubscribe history only, future txns should still be streamed */ - request[jss::account_history_tx_stream][jss::stop_history_tx_only] = - true; + request[jss::account_history_tx_stream][jss::stop_history_tx_only] = true; jv = wscTxHistory->invoke("unsubscribe", request); if (!BEAST_EXPECT(goodSubRPC(jv))) return; @@ -1047,8 +962,7 @@ public: /* * unsubscribe, future txns should not be streamed */ - request[jss::account_history_tx_stream][jss::stop_history_tx_only] = - false; + request[jss::account_history_tx_stream][jss::stop_history_tx_only] = false; jv = wscTxHistory->invoke("unsubscribe", request); BEAST_EXPECT(goodSubRPC(jv)); @@ -1065,14 +979,12 @@ public: auto wscTxHistory = makeWSClient(env.app().config()); Json::Value request; request[jss::account_history_tx_stream] = Json::objectValue; - request[jss::account_history_tx_stream][jss::account] = - "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; + request[jss::account_history_tx_stream][jss::account] = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; auto jv = wscTxHistory->invoke("subscribe", request); if (!BEAST_EXPECT(goodSubRPC(jv))) return; IdxHashVec genesisFullHistoryVec; - if (!BEAST_EXPECT( - !getTxHash(*wscTxHistory, genesisFullHistoryVec, 1).first)) + if (!BEAST_EXPECT(!getTxHash(*wscTxHistory, genesisFullHistoryVec, 1).first)) return; /* @@ -1093,9 +1005,7 @@ public: r = getTxHash(*wscTxHistory, bobFullHistoryVec, 1); if (!BEAST_EXPECT(r.first && r.second)) return; - BEAST_EXPECT( - std::get<1>(bobFullHistoryVec.back()) == - std::get<1>(genesisFullHistoryVec.back())); + BEAST_EXPECT(std::get<1>(bobFullHistoryVec.back()) == std::get<1>(genesisFullHistoryVec.back())); /* * unsubscribe to prepare next test @@ -1103,8 +1013,7 @@ public: jv = wscTxHistory->invoke("unsubscribe", request); if (!BEAST_EXPECT(goodSubRPC(jv))) return; - request[jss::account_history_tx_stream][jss::account] = - "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; + request[jss::account_history_tx_stream][jss::account] = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; jv = wscTxHistory->invoke("unsubscribe", request); BEAST_EXPECT(goodSubRPC(jv)); @@ -1118,21 +1027,16 @@ public: jv = wscTxHistory->invoke("subscribe", request); bobFullHistoryVec.clear(); - BEAST_EXPECT( - getTxHash(*wscTxHistory, bobFullHistoryVec, 31).second); + BEAST_EXPECT(getTxHash(*wscTxHistory, bobFullHistoryVec, 31).second); jv = wscTxHistory->invoke("unsubscribe", request); - request[jss::account_history_tx_stream][jss::account] = - "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; + request[jss::account_history_tx_stream][jss::account] = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; jv = wscTxHistory->invoke("subscribe", request); genesisFullHistoryVec.clear(); - BEAST_EXPECT( - getTxHash(*wscTxHistory, genesisFullHistoryVec, 31).second); + BEAST_EXPECT(getTxHash(*wscTxHistory, genesisFullHistoryVec, 31).second); jv = wscTxHistory->invoke("unsubscribe", request); - BEAST_EXPECT( - std::get<1>(bobFullHistoryVec.back()) == - std::get<1>(genesisFullHistoryVec.back())); + BEAST_EXPECT(std::get<1>(bobFullHistoryVec.back()) == std::get<1>(genesisFullHistoryVec.back())); } { @@ -1163,8 +1067,7 @@ public: // subscribe account tx history Json::Value request; request[jss::account_history_tx_stream] = Json::objectValue; - request[jss::account_history_tx_stream][jss::account] = - alice.human(); + request[jss::account_history_tx_stream][jss::account] = alice.human(); jv = wscTxHistory->invoke("subscribe", request); // compare historical txns @@ -1182,8 +1085,7 @@ public: { // take out all history txns from stream to prepare next test IdxHashVec initFundTxns; - if (!BEAST_EXPECT( - getTxHash(*wscTxHistory, initFundTxns, 10).second) || + if (!BEAST_EXPECT(getTxHash(*wscTxHistory, initFundTxns, 10).second) || !BEAST_EXPECT(checkBoundary(initFundTxns, false))) return; } @@ -1229,8 +1131,7 @@ public: // subscribe Json::Value request; request[jss::account_history_tx_stream] = Json::objectValue; - request[jss::account_history_tx_stream][jss::account] = - carol.human(); + request[jss::account_history_tx_stream][jss::account] = carol.human(); auto ws = makeWSClient(env.app().config()); auto jv = ws->invoke("subscribe", request); { @@ -1256,15 +1157,12 @@ public: env.close(); // many payments, and close lots of ledgers - auto oneRound = [&](int numPayments) { - return sendPayments(env, alice, carol, numPayments, 300); - }; + auto oneRound = [&](int numPayments) { return sendPayments(env, alice, carol, numPayments, 300); }; // subscribe Json::Value request; request[jss::account_history_tx_stream] = Json::objectValue; - request[jss::account_history_tx_stream][jss::account] = - carol.human(); + request[jss::account_history_tx_stream][jss::account] = carol.human(); auto wscLong = makeWSClient(env.app().config()); auto jv = wscLong->invoke("subscribe", request); { @@ -1301,8 +1199,7 @@ public: using namespace jtx; using namespace std::chrono_literals; FeatureBitset const all{ - jtx::testable_amendments() | featurePermissionedDomains | - featureCredentials | featurePermissionedDEX}; + jtx::testable_amendments() | featurePermissionedDomains | featureCredentials | featurePermissionedDEX}; Env env(*this, all); PermissionedDEX permDex(env); @@ -1322,15 +1219,10 @@ public: auto jv = wsc->invoke("subscribe", streams); if (!BEAST_EXPECT(jv[jss::status] == "success")) return; - env(offer(alice, XRP(10), USD(10)), - domain(domainID), - txflags(tfHybrid)); + env(offer(alice, XRP(10), USD(10)), domain(domainID), txflags(tfHybrid)); env.close(); - env(pay(bob, carol, USD(5)), - path(~USD), - sendmax(XRP(5)), - domain(domainID)); + env(pay(bob, carol, USD(5)), path(~USD), sendmax(XRP(5)), domain(domainID)); env.close(); BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { @@ -1338,12 +1230,9 @@ public: return false; auto const jrOffer = jv[jss::changes][0u]; - return (jv[jss::changes][0u][jss::domain]).asString() == - strHex(domainID) && - jrOffer[jss::currency_a].asString() == "XRP_drops" && - jrOffer[jss::volume_a].asString() == "5000000" && - jrOffer[jss::currency_b].asString() == - "rHUKYAZyUFn8PCZWbPfwHfbVQXTYrYKkHb/USD" && + return (jv[jss::changes][0u][jss::domain]).asString() == strHex(domainID) && + jrOffer[jss::currency_a].asString() == "XRP_drops" && jrOffer[jss::volume_a].asString() == "5000000" && + jrOffer[jss::currency_b].asString() == "rHUKYAZyUFn8PCZWbPfwHfbVQXTYrYKkHb/USD" && jrOffer[jss::volume_b].asString() == "5"; })); } @@ -1389,49 +1278,46 @@ public: auto verifyNFTokenID = [&](uint256 const& actualNftID) { BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { uint256 nftID; - BEAST_EXPECT( - nftID.parseHex(jv[jss::meta][jss::nftoken_id].asString())); + BEAST_EXPECT(nftID.parseHex(jv[jss::meta][jss::nftoken_id].asString())); return nftID == actualNftID; })); }; // Verify `nftoken_ids` value equals to the NFTokenIDs that were // changed in the most recent NFTokenCancelOffer transaction - auto verifyNFTokenIDsInCancelOffer = - [&](std::vector actualNftIDs) { - BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { - std::vector metaIDs; - std::transform( - jv[jss::meta][jss::nftoken_ids].begin(), - jv[jss::meta][jss::nftoken_ids].end(), - std::back_inserter(metaIDs), - [this](Json::Value id) { - uint256 nftID; - BEAST_EXPECT(nftID.parseHex(id.asString())); - return nftID; - }); - // Sort both array to prepare for comparison - std::sort(metaIDs.begin(), metaIDs.end()); - std::sort(actualNftIDs.begin(), actualNftIDs.end()); + auto verifyNFTokenIDsInCancelOffer = [&](std::vector actualNftIDs) { + BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { + std::vector metaIDs; + std::transform( + jv[jss::meta][jss::nftoken_ids].begin(), + jv[jss::meta][jss::nftoken_ids].end(), + std::back_inserter(metaIDs), + [this](Json::Value id) { + uint256 nftID; + BEAST_EXPECT(nftID.parseHex(id.asString())); + return nftID; + }); + // Sort both array to prepare for comparison + std::sort(metaIDs.begin(), metaIDs.end()); + std::sort(actualNftIDs.begin(), actualNftIDs.end()); - // Make sure the expect number of NFTs is correct - BEAST_EXPECT(metaIDs.size() == actualNftIDs.size()); + // Make sure the expect number of NFTs is correct + BEAST_EXPECT(metaIDs.size() == actualNftIDs.size()); - // Check the value of NFT ID in the meta with the - // actual values - for (size_t i = 0; i < metaIDs.size(); ++i) - BEAST_EXPECT(metaIDs[i] == actualNftIDs[i]); - return true; - })); - }; + // Check the value of NFT ID in the meta with the + // actual values + for (size_t i = 0; i < metaIDs.size(); ++i) + BEAST_EXPECT(metaIDs[i] == actualNftIDs[i]); + return true; + })); + }; // Verify `offer_id` value equals to the offerID that was // changed in the most recent NFTokenCreateOffer tx auto verifyNFTokenOfferID = [&](uint256 const& offerID) { BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) { uint256 metaOfferID; - BEAST_EXPECT(metaOfferID.parseHex( - jv[jss::meta][jss::offer_id].asString())); + BEAST_EXPECT(metaOfferID.parseHex(jv[jss::meta][jss::offer_id].asString())); return metaOfferID == offerID; })); }; @@ -1440,14 +1326,12 @@ public: { // Alice mints 2 NFTs // Verify the NFTokenIDs are correct in the NFTokenMint tx meta - uint256 const nftId1{ - token::getNextID(env, alice, 0u, tfTransferable)}; + uint256 const nftId1{token::getNextID(env, alice, 0u, tfTransferable)}; env(token::mint(alice, 0u), txflags(tfTransferable)); env.close(); verifyNFTokenID(nftId1); - uint256 const nftId2{ - token::getNextID(env, alice, 0u, tfTransferable)}; + uint256 const nftId2{token::getNextID(env, alice, 0u, tfTransferable)}; env(token::mint(alice, 0u), txflags(tfTransferable)); env.close(); verifyNFTokenID(nftId2); @@ -1455,32 +1339,26 @@ public: // Alice creates one sell offer for each NFT // Verify the offer indexes are correct in the NFTokenCreateOffer tx // meta - uint256 const aliceOfferIndex1 = - keylet::nftoffer(alice, env.seq(alice)).key; - env(token::createOffer(alice, nftId1, drops(1)), - txflags(tfSellNFToken)); + uint256 const aliceOfferIndex1 = keylet::nftoffer(alice, env.seq(alice)).key; + env(token::createOffer(alice, nftId1, drops(1)), txflags(tfSellNFToken)); env.close(); verifyNFTokenOfferID(aliceOfferIndex1); - uint256 const aliceOfferIndex2 = - keylet::nftoffer(alice, env.seq(alice)).key; - env(token::createOffer(alice, nftId2, drops(1)), - txflags(tfSellNFToken)); + uint256 const aliceOfferIndex2 = keylet::nftoffer(alice, env.seq(alice)).key; + env(token::createOffer(alice, nftId2, drops(1)), txflags(tfSellNFToken)); env.close(); verifyNFTokenOfferID(aliceOfferIndex2); // Alice cancels two offers she created // Verify the NFTokenIDs are correct in the NFTokenCancelOffer tx // meta - env(token::cancelOffer( - alice, {aliceOfferIndex1, aliceOfferIndex2})); + env(token::cancelOffer(alice, {aliceOfferIndex1, aliceOfferIndex2})); env.close(); verifyNFTokenIDsInCancelOffer({nftId1, nftId2}); // Bobs creates a buy offer for nftId1 // Verify the offer id is correct in the NFTokenCreateOffer tx meta - auto const bobBuyOfferIndex = - keylet::nftoffer(bob, env.seq(bob)).key; + auto const bobBuyOfferIndex = keylet::nftoffer(bob, env.seq(bob)).key; env(token::createOffer(bob, nftId1, drops(1)), token::owner(alice)); env.close(); verifyNFTokenOfferID(bobBuyOfferIndex); @@ -1495,31 +1373,25 @@ public: // Check `nftoken_ids` in brokered mode { // Alice mints a NFT - uint256 const nftId{ - token::getNextID(env, alice, 0u, tfTransferable)}; + uint256 const nftId{token::getNextID(env, alice, 0u, tfTransferable)}; env(token::mint(alice, 0u), txflags(tfTransferable)); env.close(); verifyNFTokenID(nftId); // Alice creates sell offer and set broker as destination - uint256 const offerAliceToBroker = - keylet::nftoffer(alice, env.seq(alice)).key; - env(token::createOffer(alice, nftId, drops(1)), - token::destination(broker), - txflags(tfSellNFToken)); + uint256 const offerAliceToBroker = keylet::nftoffer(alice, env.seq(alice)).key; + env(token::createOffer(alice, nftId, drops(1)), token::destination(broker), txflags(tfSellNFToken)); env.close(); verifyNFTokenOfferID(offerAliceToBroker); // Bob creates buy offer - uint256 const offerBobToBroker = - keylet::nftoffer(bob, env.seq(bob)).key; + uint256 const offerBobToBroker = keylet::nftoffer(bob, env.seq(bob)).key; env(token::createOffer(bob, nftId, drops(1)), token::owner(alice)); env.close(); verifyNFTokenOfferID(offerBobToBroker); // Check NFTokenID meta for NFTokenAcceptOffer in brokered mode - env(token::brokerOffers( - broker, offerBobToBroker, offerAliceToBroker)); + env(token::brokerOffers(broker, offerBobToBroker, offerAliceToBroker)); env.close(); verifyNFTokenID(nftId); } @@ -1528,39 +1400,32 @@ public: // multiple offers are cancelled for the same NFT { // Alice mints a NFT - uint256 const nftId{ - token::getNextID(env, alice, 0u, tfTransferable)}; + uint256 const nftId{token::getNextID(env, alice, 0u, tfTransferable)}; env(token::mint(alice, 0u), txflags(tfTransferable)); env.close(); verifyNFTokenID(nftId); // Alice creates 2 sell offers for the same NFT - uint256 const aliceOfferIndex1 = - keylet::nftoffer(alice, env.seq(alice)).key; - env(token::createOffer(alice, nftId, drops(1)), - txflags(tfSellNFToken)); + uint256 const aliceOfferIndex1 = keylet::nftoffer(alice, env.seq(alice)).key; + env(token::createOffer(alice, nftId, drops(1)), txflags(tfSellNFToken)); env.close(); verifyNFTokenOfferID(aliceOfferIndex1); - uint256 const aliceOfferIndex2 = - keylet::nftoffer(alice, env.seq(alice)).key; - env(token::createOffer(alice, nftId, drops(1)), - txflags(tfSellNFToken)); + uint256 const aliceOfferIndex2 = keylet::nftoffer(alice, env.seq(alice)).key; + env(token::createOffer(alice, nftId, drops(1)), txflags(tfSellNFToken)); env.close(); verifyNFTokenOfferID(aliceOfferIndex2); // Make sure the metadata only has 1 nft id, since both offers are // for the same nft - env(token::cancelOffer( - alice, {aliceOfferIndex1, aliceOfferIndex2})); + env(token::cancelOffer(alice, {aliceOfferIndex1, aliceOfferIndex2})); env.close(); verifyNFTokenIDsInCancelOffer({nftId}); } if (features[featureNFTokenMintOffer]) { - uint256 const aliceMintWithOfferIndex1 = - keylet::nftoffer(alice, env.seq(alice)).key; + uint256 const aliceMintWithOfferIndex1 = keylet::nftoffer(alice, env.seq(alice)).key; env(token::mint(alice), token::amount(XRP(0))); env.close(); verifyNFTokenOfferID(aliceMintWithOfferIndex1); diff --git a/src/test/rpc/TransactionEntry_test.cpp b/src/test/rpc/TransactionEntry_test.cpp index f81a04df6a..6302de4efa 100644 --- a/src/test/rpc/TransactionEntry_test.cpp +++ b/src/test/rpc/TransactionEntry_test.cpp @@ -23,8 +23,7 @@ class TransactionEntry_test : public beast::unit_test::suite { // no params - auto const result = - env.client().invoke("transaction_entry", {})[jss::result]; + auto const result = env.client().invoke("transaction_entry", {})[jss::result]; BEAST_EXPECT(result[jss::error] == "fieldNotFoundTransaction"); BEAST_EXPECT(result[jss::status] == "error"); } @@ -32,8 +31,7 @@ class TransactionEntry_test : public beast::unit_test::suite { Json::Value params{Json::objectValue}; params[jss::ledger] = 20; - auto const result = - env.client().invoke("transaction_entry", params)[jss::result]; + auto const result = env.client().invoke("transaction_entry", params)[jss::result]; BEAST_EXPECT(result[jss::error] == "lgrNotFound"); BEAST_EXPECT(result[jss::status] == "error"); } @@ -42,8 +40,7 @@ class TransactionEntry_test : public beast::unit_test::suite Json::Value params{Json::objectValue}; params[jss::ledger] = "current"; params[jss::tx_hash] = "DEADBEEF"; - auto const result = - env.client().invoke("transaction_entry", params)[jss::result]; + auto const result = env.client().invoke("transaction_entry", params)[jss::result]; BEAST_EXPECT(result[jss::error] == "notYetImplemented"); BEAST_EXPECT(result[jss::status] == "error"); } @@ -52,15 +49,13 @@ class TransactionEntry_test : public beast::unit_test::suite Json::Value params{Json::objectValue}; params[jss::ledger] = "closed"; params[jss::tx_hash] = "DEADBEEF"; - auto const result = - env.client().invoke("transaction_entry", params)[jss::result]; + auto const result = env.client().invoke("transaction_entry", params)[jss::result]; BEAST_EXPECT(!result[jss::ledger_hash].asString().empty()); BEAST_EXPECT(result[jss::error] == "malformedRequest"); BEAST_EXPECT(result[jss::status] == "error"); } - std::string const txHash{ - "E2FE8D4AF3FCC3944DDF6CD8CDDC5E3F0AD50863EF8919AFEF10CB6408CD4D05"}; + std::string const txHash{"E2FE8D4AF3FCC3944DDF6CD8CDDC5E3F0AD50863EF8919AFEF10CB6408CD4D05"}; // Command line format { @@ -80,24 +75,21 @@ class TransactionEntry_test : public beast::unit_test::suite { // First argument with too few characters - Json::Value const result{ - env.rpc("transaction_entry", txHash.substr(1), "closed")}; + Json::Value const result{env.rpc("transaction_entry", txHash.substr(1), "closed")}; BEAST_EXPECT(result[jss::error] == "invalidParams"); BEAST_EXPECT(result[jss::status] == "error"); } { // First argument with too many characters - Json::Value const result{ - env.rpc("transaction_entry", txHash + "A", "closed")}; + Json::Value const result{env.rpc("transaction_entry", txHash + "A", "closed")}; BEAST_EXPECT(result[jss::error] == "invalidParams"); BEAST_EXPECT(result[jss::status] == "error"); } { // Second argument not valid - Json::Value const result{ - env.rpc("transaction_entry", txHash, "closer")}; + Json::Value const result{env.rpc("transaction_entry", txHash, "closer")}; BEAST_EXPECT(result[jss::error] == "invalidParams"); BEAST_EXPECT(result[jss::status] == "error"); } @@ -111,20 +103,16 @@ class TransactionEntry_test : public beast::unit_test::suite { // Three arguments - Json::Value const result{ - env.rpc("transaction_entry", txHash, "closed", "extra")}; + Json::Value const result{env.rpc("transaction_entry", txHash, "closed", "extra")}; BEAST_EXPECT(result[jss::error] == "badSyntax"); BEAST_EXPECT(result[jss::status] == "error"); } { // Valid structure, but transaction not found. - Json::Value const result{ - env.rpc("transaction_entry", txHash, "closed")}; - BEAST_EXPECT( - !result[jss::result][jss::ledger_hash].asString().empty()); - BEAST_EXPECT( - result[jss::result][jss::error] == "transactionNotFound"); + Json::Value const result{env.rpc("transaction_entry", txHash, "closed")}; + BEAST_EXPECT(!result[jss::result][jss::ledger_hash].asString().empty()); + BEAST_EXPECT(result[jss::result][jss::error] == "transactionNotFound"); BEAST_EXPECT(result[jss::result][jss::status] == "error"); } } @@ -151,8 +139,7 @@ class TransactionEntry_test : public beast::unit_test::suite params[jss::ledger_index] = index; params[jss::tx_hash] = txhash; params[jss::api_version] = apiVersion; - return env.client().invoke( - "transaction_entry", params)[jss::result]; + return env.client().invoke("transaction_entry", params)[jss::result]; }()}; if (!BEAST_EXPECT(resIndex.isMember(jss::tx_json))) @@ -168,8 +155,7 @@ class TransactionEntry_test : public beast::unit_test::suite BEAST_EXPECT(!resIndex[jss::tx_json].isMember(jss::Amount)); if (BEAST_EXPECT(!close_time_iso.empty())) - BEAST_EXPECT( - resIndex[jss::close_time_iso] == close_time_iso); + BEAST_EXPECT(resIndex[jss::close_time_iso] == close_time_iso); } else { @@ -183,12 +169,9 @@ class TransactionEntry_test : public beast::unit_test::suite Json::Value expected; Json::Reader().parse(expected_json, expected); if (RPC::contains_error(expected)) - Throw( - "Internal JSONRPC_test error. Bad test JSON."); + Throw("Internal JSONRPC_test error. Bad test JSON."); - for (auto memberIt = expected.begin(); - memberIt != expected.end(); - memberIt++) + for (auto memberIt = expected.begin(); memberIt != expected.end(); memberIt++) { auto const name = memberIt.memberName(); if (BEAST_EXPECT(resIndex[jss::tx_json].isMember(name))) @@ -211,25 +194,17 @@ class TransactionEntry_test : public beast::unit_test::suite params[jss::ledger_hash] = resIndex[jss::ledger_hash]; params[jss::tx_hash] = txhash; params[jss::api_version] = apiVersion; - Json::Value const resHash = env.client().invoke( - "transaction_entry", params)[jss::result]; + Json::Value const resHash = env.client().invoke("transaction_entry", params)[jss::result]; BEAST_EXPECT(resHash == resIndex); } // Use the command line form with the index. - Json::Value const clIndex{env.rpc( - apiVersion, - "transaction_entry", - txhash, - std::to_string(index))}; + Json::Value const clIndex{env.rpc(apiVersion, "transaction_entry", txhash, std::to_string(index))}; BEAST_EXPECT(clIndex["result"] == resIndex); // Use the command line form with the ledger_hash. - Json::Value const clHash{env.rpc( - apiVersion, - "transaction_entry", - txhash, - resIndex[jss::ledger_hash].asString())}; + Json::Value const clHash{ + env.rpc(apiVersion, "transaction_entry", txhash, resIndex[jss::ledger_hash].asString())}; BEAST_EXPECT(clHash["result"] == resIndex); }; @@ -238,15 +213,11 @@ class TransactionEntry_test : public beast::unit_test::suite env.fund(XRP(10000), A1); auto fund_1_tx = to_string(env.tx()->getTransactionID()); - BEAST_EXPECT( - fund_1_tx == - "F4E9DF90D829A9E8B423FF68C34413E240D8D8BB0EFD080DF08114ED398E2506"); + BEAST_EXPECT(fund_1_tx == "F4E9DF90D829A9E8B423FF68C34413E240D8D8BB0EFD080DF08114ED398E2506"); env.fund(XRP(10000), A2); auto fund_2_tx = to_string(env.tx()->getTransactionID()); - BEAST_EXPECT( - fund_2_tx == - "6853CD8226A05068C951CB1F54889FF4E40C5B440DC1C5BA38F114C4E0B1E705"); + BEAST_EXPECT(fund_2_tx == "6853CD8226A05068C951CB1F54889FF4E40C5B440DC1C5BA38F114C4E0B1E705"); env.close(); @@ -286,16 +257,12 @@ class TransactionEntry_test : public beast::unit_test::suite // refunds fees with a payment after TrustSet..so just ignore the type // in the check below auto trust_tx = to_string(env.tx()->getTransactionID()); - BEAST_EXPECT( - trust_tx == - "C992D97D88FF444A1AB0C06B27557EC54B7F7DA28254778E60238BEA88E0C101"); + BEAST_EXPECT(trust_tx == "C992D97D88FF444A1AB0C06B27557EC54B7F7DA28254778E60238BEA88E0C101"); env(pay(A2, A1, A2["USD"](5))); auto pay_tx = to_string(env.tx()->getTransactionID()); env.close(); - BEAST_EXPECT( - pay_tx == - "988046D484ACE9F5F6A8C792D89C6EA2DB307B5DDA9864AEBA88E6782ABD0865"); + BEAST_EXPECT(pay_tx == "988046D484ACE9F5F6A8C792D89C6EA2DB307B5DDA9864AEBA88E6782ABD0865"); check_tx( env.closed()->seq(), @@ -338,9 +305,7 @@ class TransactionEntry_test : public beast::unit_test::suite env(offer(A2, XRP(100), A2["USD"](1))); auto offer_tx = to_string(env.tx()->getTransactionID()); - BEAST_EXPECT( - offer_tx == - "5FCC1A27A7664F82A0CC4BE5766FBBB7C560D52B93AA7B550CD33B27AEC7EFFB"); + BEAST_EXPECT(offer_tx == "5FCC1A27A7664F82A0CC4BE5766FBBB7C560D52B93AA7B550CD33B27AEC7EFFB"); env.close(); check_tx( @@ -370,8 +335,7 @@ public: run() override { testBadInput(); - forAllApiVersions( - std::bind_front(&TransactionEntry_test::testRequest, this)); + forAllApiVersions(std::bind_front(&TransactionEntry_test::testRequest, this)); } }; diff --git a/src/test/rpc/TransactionHistory_test.cpp b/src/test/rpc/TransactionHistory_test.cpp index 1dec83584d..1d555ecd8c 100644 --- a/src/test/rpc/TransactionHistory_test.cpp +++ b/src/test/rpc/TransactionHistory_test.cpp @@ -21,8 +21,7 @@ class TransactionHistory_test : public beast::unit_test::suite { // no params - auto const result = - env.client().invoke("tx_history", {})[jss::result]; + auto const result = env.client().invoke("tx_history", {})[jss::result]; BEAST_EXPECT(result[jss::error] == "invalidParams"); BEAST_EXPECT(result[jss::status] == "error"); } @@ -31,8 +30,7 @@ class TransactionHistory_test : public beast::unit_test::suite // test at 1 greater than the allowed non-admin limit Json::Value params{Json::objectValue}; params[jss::start] = 10001; // limited to <= 10000 for non admin - auto const result = - env.client().invoke("tx_history", params)[jss::result]; + auto const result = env.client().invoke("tx_history", params)[jss::result]; BEAST_EXPECT(result[jss::error] == "noPermission"); BEAST_EXPECT(result[jss::status] == "error"); } @@ -47,8 +45,7 @@ class TransactionHistory_test : public beast::unit_test::suite Json::Value params{Json::objectValue}; params[jss::api_version] = 2; - auto const result = - env.client().invoke("tx_history", params)[jss::result]; + auto const result = env.client().invoke("tx_history", params)[jss::result]; BEAST_EXPECT(result[jss::error] == "unknownCmd"); BEAST_EXPECT(result[jss::status] == "error"); } @@ -83,10 +80,8 @@ class TransactionHistory_test : public beast::unit_test::suite // is available in tx_history. Json::Value params{Json::objectValue}; params[jss::start] = 0; - auto result = - env.client().invoke("tx_history", params)[jss::result]; - if (!BEAST_EXPECT( - result[jss::txs].isArray() && result[jss::txs].size() > 0)) + auto result = env.client().invoke("tx_history", params)[jss::result]; + if (!BEAST_EXPECT(result[jss::txs].isArray() && result[jss::txs].size() > 0)) return; // search for a tx in history matching the last offer @@ -112,10 +107,8 @@ class TransactionHistory_test : public beast::unit_test::suite { Json::Value params{Json::objectValue}; params[jss::start] = start; - auto result = - env.client().invoke("tx_history", params)[jss::result]; - if (!BEAST_EXPECT( - result[jss::txs].isArray() && result[jss::txs].size() > 0)) + auto result = env.client().invoke("tx_history", params)[jss::result]; + if (!BEAST_EXPECT(result[jss::txs].isArray() && result[jss::txs].size() > 0)) break; total += result[jss::txs].size(); start += 20; @@ -134,8 +127,7 @@ class TransactionHistory_test : public beast::unit_test::suite { Json::Value params{Json::objectValue}; params[jss::start] = 10000; // limited to <= 10000 for non admin - auto const result = - env.client().invoke("tx_history", params)[jss::result]; + auto const result = env.client().invoke("tx_history", params)[jss::result]; BEAST_EXPECT(result[jss::status] == "success"); BEAST_EXPECT(result[jss::index] == 10000); } diff --git a/src/test/rpc/Transaction_test.cpp b/src/test/rpc/Transaction_test.cpp index 6947fc91c2..acc8bccf61 100644 --- a/src/test/rpc/Transaction_test.cpp +++ b/src/test/rpc/Transaction_test.cpp @@ -40,8 +40,7 @@ class Transaction_test : public beast::unit_test::suite char const* BINARY = jss::binary.c_str(); char const* NOT_FOUND = RPC::get_error_info(rpcTXN_NOT_FOUND).token; char const* INVALID = RPC::get_error_info(rpcINVALID_LGR_RANGE).token; - char const* EXCESSIVE = - RPC::get_error_info(rpcEXCESSIVE_LGR_RANGE).token; + char const* EXCESSIVE = RPC::get_error_info(rpcEXCESSIVE_LGR_RANGE).token; Env env{*this, features}; auto const alice = Account("alice"); @@ -56,8 +55,7 @@ class Transaction_test : public beast::unit_test::suite env(noop(alice)); txns.emplace_back(env.tx()); env.close(); - metas.emplace_back( - env.closed()->txRead(env.tx()->getTransactionID()).second); + metas.emplace_back(env.closed()->txRead(env.tx()->getTransactionID()).second); } auto const endLegSeq = env.closed()->header().seq; @@ -67,19 +65,11 @@ class Transaction_test : public beast::unit_test::suite auto const& tx = txns[i]; auto const& meta = metas[i]; auto const result = env.rpc( - COMMAND, - to_string(tx->getTransactionID()), - BINARY, - to_string(startLegSeq), - to_string(endLegSeq)); + COMMAND, to_string(tx->getTransactionID()), BINARY, to_string(startLegSeq), to_string(endLegSeq)); BEAST_EXPECT(result[jss::result][jss::status] == jss::success); - BEAST_EXPECT( - result[jss::result][jss::tx] == - strHex(tx->getSerializer().getData())); - BEAST_EXPECT( - result[jss::result][jss::meta] == - strHex(meta->getSerializer().getData())); + BEAST_EXPECT(result[jss::result][jss::tx] == strHex(tx->getSerializer().getData())); + BEAST_EXPECT(result[jss::result][jss::meta] == strHex(meta->getSerializer().getData())); } auto const tx = env.jt(noop(alice), seq(env.seq(alice))).stx; @@ -93,8 +83,7 @@ class Transaction_test : public beast::unit_test::suite to_string(endLegSeq + deltaEndSeq)); BEAST_EXPECT( - result[jss::result][jss::status] == jss::error && - result[jss::result][jss::error] == NOT_FOUND); + result[jss::result][jss::status] == jss::error && result[jss::result][jss::error] == NOT_FOUND); if (deltaEndSeq) BEAST_EXPECT(!result[jss::result][jss::searched_all].asBool()); @@ -119,8 +108,7 @@ class Transaction_test : public beast::unit_test::suite auto const deletedLedger = (startLegSeq + endLegSeq) / 2; { // Remove one of the ledgers from the database directly - dynamic_cast(&env.app().getRelationalDatabase()) - ->deleteTransactionByLedgerSeq(deletedLedger); + env.app().getRelationalDatabase().deleteTransactionByLedgerSeq(deletedLedger); } for (int deltaEndSeq = 0; deltaEndSeq < 2; ++deltaEndSeq) @@ -133,23 +121,18 @@ class Transaction_test : public beast::unit_test::suite to_string(endLegSeq + deltaEndSeq)); BEAST_EXPECT( - result[jss::result][jss::status] == jss::error && - result[jss::result][jss::error] == NOT_FOUND); + result[jss::result][jss::status] == jss::error && result[jss::result][jss::error] == NOT_FOUND); BEAST_EXPECT(!result[jss::result][jss::searched_all].asBool()); } // Provide range without providing the `binary` // field. (Tests parameter parsing) { - auto const result = env.rpc( - COMMAND, - to_string(tx->getTransactionID()), - to_string(startLegSeq), - to_string(endLegSeq)); + auto const result = + env.rpc(COMMAND, to_string(tx->getTransactionID()), to_string(startLegSeq), to_string(endLegSeq)); BEAST_EXPECT( - result[jss::result][jss::status] == jss::error && - result[jss::result][jss::error] == NOT_FOUND); + result[jss::result][jss::status] == jss::error && result[jss::result][jss::error] == NOT_FOUND); BEAST_EXPECT(!result[jss::result][jss::searched_all].asBool()); } @@ -158,14 +141,10 @@ class Transaction_test : public beast::unit_test::suite // field. (Tests parameter parsing) { auto const result = env.rpc( - COMMAND, - to_string(tx->getTransactionID()), - to_string(startLegSeq), - to_string(deletedLedger - 1)); + COMMAND, to_string(tx->getTransactionID()), to_string(startLegSeq), to_string(deletedLedger - 1)); BEAST_EXPECT( - result[jss::result][jss::status] == jss::error && - result[jss::result][jss::error] == NOT_FOUND); + result[jss::result][jss::status] == jss::error && result[jss::result][jss::error] == NOT_FOUND); BEAST_EXPECT(result[jss::result][jss::searched_all].asBool()); } @@ -174,10 +153,7 @@ class Transaction_test : public beast::unit_test::suite // field. (Tests parameter parsing) { auto const result = env.rpc( - COMMAND, - to_string(txns[0]->getTransactionID()), - to_string(startLegSeq), - to_string(deletedLedger - 1)); + COMMAND, to_string(txns[0]->getTransactionID()), to_string(startLegSeq), to_string(deletedLedger - 1)); BEAST_EXPECT(result[jss::result][jss::status] == jss::success); BEAST_EXPECT(!result[jss::result].isMember(jss::searched_all)); @@ -192,9 +168,7 @@ class Transaction_test : public beast::unit_test::suite to_string(deletedLedger - 1), to_string(startLegSeq)); - BEAST_EXPECT( - result[jss::result][jss::status] == jss::error && - result[jss::result][jss::error] == INVALID); + BEAST_EXPECT(result[jss::result][jss::status] == jss::error && result[jss::result][jss::error] == INVALID); BEAST_EXPECT(!result[jss::result].isMember(jss::searched_all)); } @@ -202,54 +176,35 @@ class Transaction_test : public beast::unit_test::suite // Provide an invalid range: (min < 0) { auto const result = env.rpc( - COMMAND, - to_string(tx->getTransactionID()), - BINARY, - to_string(-1), - to_string(deletedLedger - 1)); + COMMAND, to_string(tx->getTransactionID()), BINARY, to_string(-1), to_string(deletedLedger - 1)); - BEAST_EXPECT( - result[jss::result][jss::status] == jss::error && - result[jss::result][jss::error] == INVALID); + BEAST_EXPECT(result[jss::result][jss::status] == jss::error && result[jss::result][jss::error] == INVALID); BEAST_EXPECT(!result[jss::result].isMember(jss::searched_all)); } // Provide an invalid range: (min < 0, max < 0) { - auto const result = env.rpc( - COMMAND, - to_string(tx->getTransactionID()), - BINARY, - to_string(-20), - to_string(-10)); + auto const result = + env.rpc(COMMAND, to_string(tx->getTransactionID()), BINARY, to_string(-20), to_string(-10)); - BEAST_EXPECT( - result[jss::result][jss::status] == jss::error && - result[jss::result][jss::error] == INVALID); + BEAST_EXPECT(result[jss::result][jss::status] == jss::error && result[jss::result][jss::error] == INVALID); BEAST_EXPECT(!result[jss::result].isMember(jss::searched_all)); } // Provide an invalid range: (only one value) { - auto const result = env.rpc( - COMMAND, - to_string(tx->getTransactionID()), - BINARY, - to_string(20)); + auto const result = env.rpc(COMMAND, to_string(tx->getTransactionID()), BINARY, to_string(20)); - BEAST_EXPECT( - result[jss::result][jss::status] == jss::error && - result[jss::result][jss::error] == INVALID); + BEAST_EXPECT(result[jss::result][jss::status] == jss::error && result[jss::result][jss::error] == INVALID); BEAST_EXPECT(!result[jss::result].isMember(jss::searched_all)); } // Provide an invalid range: (only one value) { - auto const result = env.rpc( - COMMAND, to_string(tx->getTransactionID()), to_string(20)); + auto const result = env.rpc(COMMAND, to_string(tx->getTransactionID()), to_string(20)); // Since we only provided one value for the range, // the interface parses it as a false binary flag, @@ -271,8 +226,7 @@ class Transaction_test : public beast::unit_test::suite to_string(startLegSeq + 1001)); BEAST_EXPECT( - result[jss::result][jss::status] == jss::error && - result[jss::result][jss::error] == EXCESSIVE); + result[jss::result][jss::status] == jss::error && result[jss::result][jss::error] == EXCESSIVE); BEAST_EXPECT(!result[jss::result].isMember(jss::searched_all)); } @@ -290,8 +244,7 @@ class Transaction_test : public beast::unit_test::suite char const* BINARY = jss::binary.c_str(); char const* NOT_FOUND = RPC::get_error_info(rpcTXN_NOT_FOUND).token; char const* INVALID = RPC::get_error_info(rpcINVALID_LGR_RANGE).token; - char const* EXCESSIVE = - RPC::get_error_info(rpcEXCESSIVE_LGR_RANGE).token; + char const* EXCESSIVE = RPC::get_error_info(rpcEXCESSIVE_LGR_RANGE).token; Env env{*this, makeNetworkConfig(11111)}; uint32_t netID = env.app().config().NETWORK_ID; @@ -308,8 +261,7 @@ class Transaction_test : public beast::unit_test::suite env(noop(alice)); txns.emplace_back(env.tx()); env.close(); - metas.emplace_back( - env.closed()->txRead(env.tx()->getTransactionID()).second); + metas.emplace_back(env.closed()->txRead(env.tx()->getTransactionID()).second); } auto const endLegSeq = env.closed()->header().seq; @@ -327,28 +279,19 @@ class Transaction_test : public beast::unit_test::suite to_string(endLegSeq)); BEAST_EXPECT(result[jss::result][jss::status] == jss::success); - BEAST_EXPECT( - result[jss::result][jss::tx] == - strHex(tx->getSerializer().getData())); - BEAST_EXPECT( - result[jss::result][jss::meta] == - strHex(meta->getSerializer().getData())); + BEAST_EXPECT(result[jss::result][jss::tx] == strHex(tx->getSerializer().getData())); + BEAST_EXPECT(result[jss::result][jss::meta] == strHex(meta->getSerializer().getData())); } auto const tx = env.jt(noop(alice), seq(env.seq(alice))).stx; auto const ctid = *RPC::encodeCTID(endLegSeq, tx->getSeqValue(), netID); for (int deltaEndSeq = 0; deltaEndSeq < 2; ++deltaEndSeq) { - auto const result = env.rpc( - COMMAND, - ctid, - BINARY, - to_string(startLegSeq), - to_string(endLegSeq + deltaEndSeq)); + auto const result = + env.rpc(COMMAND, ctid, BINARY, to_string(startLegSeq), to_string(endLegSeq + deltaEndSeq)); BEAST_EXPECT( - result[jss::result][jss::status] == jss::error && - result[jss::result][jss::error] == NOT_FOUND); + result[jss::result][jss::status] == jss::error && result[jss::result][jss::error] == NOT_FOUND); if (deltaEndSeq) BEAST_EXPECT(!result[jss::result][jss::searched_all].asBool()); @@ -376,34 +319,26 @@ class Transaction_test : public beast::unit_test::suite auto const deletedLedger = (startLegSeq + endLegSeq) / 2; { // Remove one of the ledgers from the database directly - dynamic_cast(&env.app().getRelationalDatabase()) - ->deleteTransactionByLedgerSeq(deletedLedger); + env.app().getRelationalDatabase().deleteTransactionByLedgerSeq(deletedLedger); } for (int deltaEndSeq = 0; deltaEndSeq < 2; ++deltaEndSeq) { - auto const result = env.rpc( - COMMAND, - ctid, - BINARY, - to_string(startLegSeq), - to_string(endLegSeq + deltaEndSeq)); + auto const result = + env.rpc(COMMAND, ctid, BINARY, to_string(startLegSeq), to_string(endLegSeq + deltaEndSeq)); BEAST_EXPECT( - result[jss::result][jss::status] == jss::error && - result[jss::result][jss::error] == NOT_FOUND); + result[jss::result][jss::status] == jss::error && result[jss::result][jss::error] == NOT_FOUND); BEAST_EXPECT(!result[jss::result][jss::searched_all].asBool()); } // Provide range without providing the `binary` // field. (Tests parameter parsing) { - auto const result = env.rpc( - COMMAND, ctid, to_string(startLegSeq), to_string(endLegSeq)); + auto const result = env.rpc(COMMAND, ctid, to_string(startLegSeq), to_string(endLegSeq)); BEAST_EXPECT( - result[jss::result][jss::status] == jss::error && - result[jss::result][jss::error] == NOT_FOUND); + result[jss::result][jss::status] == jss::error && result[jss::result][jss::error] == NOT_FOUND); BEAST_EXPECT(!result[jss::result][jss::searched_all].asBool()); } @@ -411,15 +346,10 @@ class Transaction_test : public beast::unit_test::suite // Provide range without providing the `binary` // field. (Tests parameter parsing) { - auto const result = env.rpc( - COMMAND, - ctid, - to_string(startLegSeq), - to_string(deletedLedger - 1)); + auto const result = env.rpc(COMMAND, ctid, to_string(startLegSeq), to_string(deletedLedger - 1)); BEAST_EXPECT( - result[jss::result][jss::status] == jss::error && - result[jss::result][jss::error] == NOT_FOUND); + result[jss::result][jss::status] == jss::error && result[jss::result][jss::error] == NOT_FOUND); BEAST_EXPECT(!result[jss::result][jss::searched_all].asBool()); } @@ -441,44 +371,27 @@ class Transaction_test : public beast::unit_test::suite // Provide an invalid range: (min > max) { - auto const result = env.rpc( - COMMAND, - ctid, - BINARY, - to_string(deletedLedger - 1), - to_string(startLegSeq)); + auto const result = env.rpc(COMMAND, ctid, BINARY, to_string(deletedLedger - 1), to_string(startLegSeq)); - BEAST_EXPECT( - result[jss::result][jss::status] == jss::error && - result[jss::result][jss::error] == INVALID); + BEAST_EXPECT(result[jss::result][jss::status] == jss::error && result[jss::result][jss::error] == INVALID); BEAST_EXPECT(!result[jss::result].isMember(jss::searched_all)); } // Provide an invalid range: (min < 0) { - auto const result = env.rpc( - COMMAND, - ctid, - BINARY, - to_string(-1), - to_string(deletedLedger - 1)); + auto const result = env.rpc(COMMAND, ctid, BINARY, to_string(-1), to_string(deletedLedger - 1)); - BEAST_EXPECT( - result[jss::result][jss::status] == jss::error && - result[jss::result][jss::error] == INVALID); + BEAST_EXPECT(result[jss::result][jss::status] == jss::error && result[jss::result][jss::error] == INVALID); BEAST_EXPECT(!result[jss::result].isMember(jss::searched_all)); } // Provide an invalid range: (min < 0, max < 0) { - auto const result = - env.rpc(COMMAND, ctid, BINARY, to_string(-20), to_string(-10)); + auto const result = env.rpc(COMMAND, ctid, BINARY, to_string(-20), to_string(-10)); - BEAST_EXPECT( - result[jss::result][jss::status] == jss::error && - result[jss::result][jss::error] == INVALID); + BEAST_EXPECT(result[jss::result][jss::status] == jss::error && result[jss::result][jss::error] == INVALID); BEAST_EXPECT(!result[jss::result].isMember(jss::searched_all)); } @@ -487,9 +400,7 @@ class Transaction_test : public beast::unit_test::suite { auto const result = env.rpc(COMMAND, ctid, BINARY, to_string(20)); - BEAST_EXPECT( - result[jss::result][jss::status] == jss::error && - result[jss::result][jss::error] == INVALID); + BEAST_EXPECT(result[jss::result][jss::status] == jss::error && result[jss::result][jss::error] == INVALID); BEAST_EXPECT(!result[jss::result].isMember(jss::searched_all)); } @@ -510,16 +421,10 @@ class Transaction_test : public beast::unit_test::suite // Provide an invalid range: (max - min > 1000) { - auto const result = env.rpc( - COMMAND, - ctid, - BINARY, - to_string(startLegSeq), - to_string(startLegSeq + 1001)); + auto const result = env.rpc(COMMAND, ctid, BINARY, to_string(startLegSeq), to_string(startLegSeq + 1001)); BEAST_EXPECT( - result[jss::result][jss::status] == jss::error && - result[jss::result][jss::error] == EXCESSIVE); + result[jss::result][jss::status] == jss::error && result[jss::result][jss::error] == EXCESSIVE); BEAST_EXPECT(!result[jss::result].isMember(jss::searched_all)); } @@ -537,8 +442,7 @@ class Transaction_test : public beast::unit_test::suite // Test case 1: Valid input values auto const expected11 = std::optional("CFFFFFFFFFFFFFFF"); - BEAST_EXPECT( - RPC::encodeCTID(0x0FFF'FFFFUL, 0xFFFFU, 0xFFFFU) == expected11); + BEAST_EXPECT(RPC::encodeCTID(0x0FFF'FFFFUL, 0xFFFFU, 0xFFFFU) == expected11); auto const expected12 = std::optional("C000000000000000"); BEAST_EXPECT(RPC::encodeCTID(0, 0, 0) == expected12); auto const expected13 = std::optional("C000000100020003"); @@ -556,17 +460,12 @@ class Transaction_test : public beast::unit_test::suite BEAST_EXPECT(!RPC::encodeCTID(0x0FFF'FFFFUL, 0xFFFFU, 0x1'0000U)); // Test case 5: Valid input values - auto const expected51 = - std::optional>( - std::make_tuple(0, 0, 0)); + auto const expected51 = std::optional>(std::make_tuple(0, 0, 0)); BEAST_EXPECT(RPC::decodeCTID("C000000000000000") == expected51); - auto const expected52 = - std::optional>( - std::make_tuple(1U, 2U, 3U)); + auto const expected52 = std::optional>(std::make_tuple(1U, 2U, 3U)); BEAST_EXPECT(RPC::decodeCTID("C000000100020003") == expected52); auto const expected53 = - std::optional>( - std::make_tuple(13249191UL, 12911U, 49221U)); + std::optional>(std::make_tuple(13249191UL, 12911U, 49221U)); BEAST_EXPECT(RPC::decodeCTID("C0CA2AA7326FC045") == expected53); // Test case 6: ctid not a string or big int @@ -587,20 +486,16 @@ class Transaction_test : public beast::unit_test::suite // Test case 11: Valid input values BEAST_EXPECT( (RPC::decodeCTID(0xCFFF'FFFF'FFFF'FFFFULL) == - std::optional>( - std::make_tuple(0x0FFF'FFFFUL, 0xFFFFU, 0xFFFFU)))); + std::optional>(std::make_tuple(0x0FFF'FFFFUL, 0xFFFFU, 0xFFFFU)))); BEAST_EXPECT( (RPC::decodeCTID(0xC000'0000'0000'0000ULL) == - std::optional>( - std::make_tuple(0, 0, 0)))); + std::optional>(std::make_tuple(0, 0, 0)))); BEAST_EXPECT( (RPC::decodeCTID(0xC000'0001'0002'0003ULL) == - std::optional>( - std::make_tuple(1U, 2U, 3U)))); + std::optional>(std::make_tuple(1U, 2U, 3U)))); BEAST_EXPECT( (RPC::decodeCTID(0xC0CA'2AA7'326F'C045ULL) == - std::optional>( - std::make_tuple(1324'9191UL, 12911U, 49221U)))); + std::optional>(std::make_tuple(1324'9191UL, 12911U, 49221U)))); // Test case 12: ctid not exactly 16 nibbles BEAST_EXPECT(!RPC::decodeCTID(0xC003'FFFF'FFFF'FFF)); @@ -615,7 +510,7 @@ class Transaction_test : public beast::unit_test::suite } void - testCTIDRPC(FeatureBitset features) + testRPCsForCTID(FeatureBitset features) { testcase("CTID RPC"); @@ -647,8 +542,7 @@ class Transaction_test : public beast::unit_test::suite jsonTx[jss::binary] = false; jsonTx[jss::ctid] = *ctid; jsonTx[jss::id] = 1; - auto const jrr = - env.rpc("json", "tx", to_string(jsonTx))[jss::result]; + auto const jrr = env.rpc("json", "tx", to_string(jsonTx))[jss::result]; BEAST_EXPECT(jrr[jss::ctid] == ctid); BEAST_EXPECT(jrr.isMember(jss::hash)); } @@ -671,14 +565,12 @@ class Transaction_test : public beast::unit_test::suite // Verify that there are at least two upper case letters in ctid and // test a mixed case - if (BEAST_EXPECT( - std::count_if(ctid.begin(), ctid.end(), isUpper) > 1)) + if (BEAST_EXPECT(std::count_if(ctid.begin(), ctid.end(), isUpper) > 1)) { // Change the first upper case letter to lower case. std::string mixedCase = ctid; { - auto const iter = std::find_if( - mixedCase.begin(), mixedCase.end(), isUpper); + auto const iter = std::find_if(mixedCase.begin(), mixedCase.end(), isUpper); *iter = std::tolower(*iter); } BEAST_EXPECT(ctid != mixedCase); @@ -687,8 +579,7 @@ class Transaction_test : public beast::unit_test::suite jsonTx[jss::binary] = false; jsonTx[jss::ctid] = mixedCase; jsonTx[jss::id] = 1; - Json::Value const jrr = - env.rpc("json", "tx", to_string(jsonTx))[jss::result]; + Json::Value const jrr = env.rpc("json", "tx", to_string(jsonTx))[jss::result]; BEAST_EXPECT(jrr[jss::ctid] == ctid); BEAST_EXPECT(jrr[jss::hash]); } @@ -718,8 +609,7 @@ class Transaction_test : public beast::unit_test::suite params[jss::id] = 1; auto const hash = env.tx()->getJson(JsonOptions::none)[jss::hash]; params[jss::transaction] = hash; - auto const jrr = - env.rpc("json", "tx", to_string(params))[jss::result]; + auto const jrr = env.rpc("json", "tx", to_string(params))[jss::result]; BEAST_EXPECT(jrr[jss::hash] == hash); BEAST_EXPECT(jrr.isMember(jss::ctid) == (netID <= 0xFFFF)); @@ -748,8 +638,7 @@ class Transaction_test : public beast::unit_test::suite jsonTx[jss::binary] = false; jsonTx[jss::ctid] = ctid; jsonTx[jss::id] = 1; - auto const jrr = - env.rpc("json", "tx", to_string(jsonTx))[jss::result]; + auto const jrr = env.rpc("json", "tx", to_string(jsonTx))[jss::result]; BEAST_EXPECT(jrr[jss::error] == "wrongNetwork"); BEAST_EXPECT(jrr[jss::error_code] == rpcWRONG_NETWORK); BEAST_EXPECT( @@ -787,8 +676,7 @@ class Transaction_test : public beast::unit_test::suite std::shared_ptr txn = env.tx(); env.close(); - std::shared_ptr meta = - env.closed()->txRead(env.tx()->getTransactionID()).second; + std::shared_ptr meta = env.closed()->txRead(env.tx()->getTransactionID()).second; Json::Value expected = txn->getJson(JsonOptions::none); expected[jss::DeliverMax] = expected[jss::Amount]; @@ -809,12 +697,8 @@ class Transaction_test : public beast::unit_test::suite BEAST_EXPECT(result[jss::result][jss::status] == jss::success); if (apiVersion > 1) { - BEAST_EXPECT( - result[jss::result][jss::close_time_iso] == - "2000-01-01T00:00:20Z"); - BEAST_EXPECT( - result[jss::result][jss::hash] == - to_string(txn->getTransactionID())); + BEAST_EXPECT(result[jss::result][jss::close_time_iso] == "2000-01-01T00:00:20Z"); + BEAST_EXPECT(result[jss::result][jss::hash] == to_string(txn->getTransactionID())); BEAST_EXPECT(result[jss::result][jss::validated] == true); BEAST_EXPECT(result[jss::result][jss::ledger_index] == 4); BEAST_EXPECT( @@ -823,13 +707,10 @@ class Transaction_test : public beast::unit_test::suite "D2"); } - for (auto memberIt = expected.begin(); memberIt != expected.end(); - memberIt++) + for (auto memberIt = expected.begin(); memberIt != expected.end(); memberIt++) { std::string const name = memberIt.memberName(); - auto const& result_transaction = - (apiVersion > 1 ? result[jss::result][jss::tx_json] - : result[jss::result]); + auto const& result_transaction = (apiVersion > 1 ? result[jss::result][jss::tx_json] : result[jss::result]); if (BEAST_EXPECT(result_transaction.isMember(name))) { auto const received = result_transaction[name]; @@ -846,8 +727,7 @@ class Transaction_test : public beast::unit_test::suite void testBinaryRequest(unsigned apiVersion) { - testcase( - "Test binary request API version " + std::to_string(apiVersion)); + testcase("Test binary request API version " + std::to_string(apiVersion)); using namespace test::jtx; using std::to_string; @@ -863,11 +743,9 @@ class Transaction_test : public beast::unit_test::suite env.fund(XRP(1000000), alice, gw); std::shared_ptr const txn = env.tx(); BEAST_EXPECT( - to_string(txn->getTransactionID()) == - "3F8BDE5A5F82C4F4708E5E9255B713E303E6E1A371FD5C7A704AFD1387C23981"); + to_string(txn->getTransactionID()) == "3F8BDE5A5F82C4F4708E5E9255B713E303E6E1A371FD5C7A704AFD1387C23981"); env.close(); - std::shared_ptr meta = - env.closed()->txRead(txn->getTransactionID()).second; + std::shared_ptr meta = env.closed()->txRead(txn->getTransactionID()).second; std::string const expected_tx_blob = serializeHex(*txn); std::string const expected_meta_blob = serializeHex(*meta); @@ -884,31 +762,24 @@ class Transaction_test : public beast::unit_test::suite { BEAST_EXPECT(result[jss::result][jss::status] == "success"); BEAST_EXPECT(result[jss::result][jss::validated] == true); - BEAST_EXPECT( - result[jss::result][jss::hash] == - to_string(txn->getTransactionID())); + BEAST_EXPECT(result[jss::result][jss::hash] == to_string(txn->getTransactionID())); BEAST_EXPECT(result[jss::result][jss::ledger_index] == 3); BEAST_EXPECT(result[jss::result][jss::ctid] == "C000000300030000"); if (apiVersion > 1) { - BEAST_EXPECT( - result[jss::result][jss::tx_blob] == expected_tx_blob); - BEAST_EXPECT( - result[jss::result][jss::meta_blob] == expected_meta_blob); + BEAST_EXPECT(result[jss::result][jss::tx_blob] == expected_tx_blob); + BEAST_EXPECT(result[jss::result][jss::meta_blob] == expected_meta_blob); BEAST_EXPECT( result[jss::result][jss::ledger_hash] == "2D5150E5A5AA436736A732291E437ABF01BC9E206C2DF3C77C4F856915" "7905AA"); - BEAST_EXPECT( - result[jss::result][jss::close_time_iso] == - "2000-01-01T00:00:10Z"); + BEAST_EXPECT(result[jss::result][jss::close_time_iso] == "2000-01-01T00:00:10Z"); } else { BEAST_EXPECT(result[jss::result][jss::tx] == expected_tx_blob); - BEAST_EXPECT( - result[jss::result][jss::meta] == expected_meta_blob); + BEAST_EXPECT(result[jss::result][jss::meta] == expected_meta_blob); BEAST_EXPECT(result[jss::result][jss::date] == 10); } } @@ -919,8 +790,7 @@ public: run() override { using namespace test::jtx; - forAllApiVersions( - std::bind_front(&Transaction_test::testBinaryRequest, this)); + forAllApiVersions(std::bind_front(&Transaction_test::testBinaryRequest, this)); FeatureBitset const all{testable_amendments()}; testWithFeats(all); @@ -932,9 +802,8 @@ public: testRangeRequest(features); testRangeCTIDRequest(features); testCTIDValidation(features); - testCTIDRPC(features); - forAllApiVersions( - std::bind_front(&Transaction_test::testRequest, this, features)); + testRPCsForCTID(features); + forAllApiVersions(std::bind_front(&Transaction_test::testRequest, this, features)); } }; diff --git a/src/test/rpc/ValidatorInfo_test.cpp b/src/test/rpc/ValidatorInfo_test.cpp index a8fccc724b..41fa95940b 100644 --- a/src/test/rpc/ValidatorInfo_test.cpp +++ b/src/test/rpc/ValidatorInfo_test.cpp @@ -25,8 +25,7 @@ public: { Env env(*this); auto const info = env.rpc("validator_info"); - BEAST_EXPECT( - info[jss::result][jss::error_message] == "not a validator"); + BEAST_EXPECT(info[jss::result][jss::error_message] == "not a validator"); } } @@ -69,10 +68,8 @@ public: "VUSmEydzBpMjFlcTNNWXl3TFZKWm5GT3I3QzBrdzJBaVR6U0NqSXpkaXRROD0ifQ==" "\n"}; - std::string const master_key = - "nHBt9fsb4849WmZiCds4r5TXyBeQjqnH5kzPtqgMAQMgi39YZRPa"; - std::string const ephemeral_key = - "n9KsDYGKhABVc4wK5u3MnVhgPinyJimyKGpr9VJYuBaY8EnJXR2x"; + std::string const master_key = "nHBt9fsb4849WmZiCds4r5TXyBeQjqnH5kzPtqgMAQMgi39YZRPa"; + std::string const ephemeral_key = "n9KsDYGKhABVc4wK5u3MnVhgPinyJimyKGpr9VJYuBaY8EnJXR2x"; std::string const manifest = "JAAAAAFxIe1FtwmimvGtH2iCcMJqC9gVFKilGfw1/" "vCxHXXLplc2GnMhAkE1agqXxBwDwDbID6OMSYuM0FDAlpAgNk8SKFn7MO2fdkcwRQI" @@ -90,8 +87,7 @@ public: BEAST_EXPECT(info[jss::result][jss::seq] == 1); BEAST_EXPECT(info[jss::result][jss::master_key] == master_key); BEAST_EXPECT(info[jss::result][jss::manifest] == manifest); - BEAST_EXPECT( - info[jss::result][jss::ephemeral_key] == ephemeral_key); + BEAST_EXPECT(info[jss::result][jss::ephemeral_key] == ephemeral_key); } } diff --git a/src/test/rpc/ValidatorRPC_test.cpp b/src/test/rpc/ValidatorRPC_test.cpp index cf8741e507..a46d198b5a 100644 --- a/src/test/rpc/ValidatorRPC_test.cpp +++ b/src/test/rpc/ValidatorRPC_test.cpp @@ -51,17 +51,14 @@ public: Env env{*this, isAdmin ? envconfig() : envconfig(no_admin)}; auto const jrr = env.rpc("server_info")[jss::result]; BEAST_EXPECT(jrr[jss::status] == "success"); - BEAST_EXPECT( - jrr[jss::info].isMember(jss::validator_list) == isAdmin); + BEAST_EXPECT(jrr[jss::info].isMember(jss::validator_list) == isAdmin); } { Env env{*this, isAdmin ? envconfig() : envconfig(no_admin)}; auto const jrr = env.rpc("server_state")[jss::result]; BEAST_EXPECT(jrr[jss::status] == "success"); - BEAST_EXPECT( - jrr[jss::state].isMember(jss::validator_list_expires) == - isAdmin); + BEAST_EXPECT(jrr[jss::state].isMember(jss::validator_list_expires) == isAdmin); } } } @@ -86,9 +83,7 @@ public: // Server info reports maximum expiration since not dynamic { auto const jrr = env.rpc("server_info")[jss::result]; - BEAST_EXPECT( - jrr[jss::info][jss::validator_list][jss::expiration] == - "never"); + BEAST_EXPECT(jrr[jss::info][jss::validator_list][jss::expiration] == "never"); } { auto const jrr = env.rpc("server_state")[jss::result]; @@ -101,8 +96,7 @@ public: auto const jrr = env.rpc("validators")[jss::result]; BEAST_EXPECT(jrr[jss::validator_list][jss::expiration] == "never"); BEAST_EXPECT(jrr[jss::validation_quorum].asUInt() == keys.size()); - BEAST_EXPECT( - jrr[jss::trusted_validator_keys].size() == keys.size()); + BEAST_EXPECT(jrr[jss::trusted_validator_keys].size() == keys.size()); BEAST_EXPECT(jrr[jss::publisher_lists].size() == 0); BEAST_EXPECT(jrr[jss::local_static_keys].size() == keys.size()); for (auto const& jKey : jrr[jss::local_static_keys]) @@ -136,12 +130,10 @@ public: BEAST_EXPECT(jrrnUnlSize == 2); for (std::uint32_t x = 0; x < jrrnUnlSize; ++x) { - auto parsedKey = parseBase58( - TokenType::NodePublic, jrrnUnl[x].asString()); + auto parsedKey = parseBase58(TokenType::NodePublic, jrrnUnl[x].asString()); BEAST_EXPECT(parsedKey); if (parsedKey) - BEAST_EXPECT( - disabledKeys.find(*parsedKey) != disabledKeys.end()); + BEAST_EXPECT(disabledKeys.find(*parsedKey) != disabledKeys.end()); } disabledKeys.clear(); @@ -156,14 +148,11 @@ public: { using namespace test::jtx; - auto toStr = [](PublicKey const& publicKey) { - return toBase58(TokenType::NodePublic, publicKey); - }; + auto toStr = [](PublicKey const& publicKey) { return toBase58(TokenType::NodePublic, publicKey); }; // Validator keys that will be in the published list std::vector validators = { - TrustedPublisherServer::randomValidator(), - TrustedPublisherServer::randomValidator()}; + TrustedPublisherServer::randomValidator(), TrustedPublisherServer::randomValidator()}; std::set expectedKeys; for (auto const& val : validators) expectedKeys.insert(toStr(val.masterPublic)); @@ -175,28 +164,20 @@ public: NetClock::time_point const validFrom2{validUntil - 60s}; NetClock::time_point const validUntil2{validFrom2 + 3600s}; auto server = make_TrustedPublisherServer( - worker.get_io_context(), - validators, - validUntil, - {{validFrom2, validUntil2}}, - false, - 1, - false); + worker.get_io_context(), validators, validUntil, {{validFrom2, validUntil2}}, false, 1, false); //---------------------------------------------------------------------- // Publisher list site unavailable v1 { // Publisher site information using namespace std::string_literals; - std::string siteURI = - "http://"s + getEnvLocalhostAddr() + ":1234/validators"; + std::string siteURI = "http://"s + getEnvLocalhostAddr() + ":1234/validators"; Env env{ *this, envconfig([&](std::unique_ptr cfg) { cfg->section(SECTION_VALIDATOR_LIST_SITES).append(siteURI); - cfg->section(SECTION_VALIDATOR_LIST_KEYS) - .append(strHex(server->publisherPublic())); + cfg->section(SECTION_VALIDATOR_LIST_KEYS).append(strHex(server->publisherPublic())); return cfg; }), }; @@ -206,24 +187,18 @@ public: { auto const jrr = env.rpc("server_info")[jss::result]; - BEAST_EXPECT( - jrr[jss::info][jss::validator_list][jss::expiration] == - "unknown"); + BEAST_EXPECT(jrr[jss::info][jss::validator_list][jss::expiration] == "unknown"); } { auto const jrr = env.rpc("server_state")[jss::result]; - BEAST_EXPECT( - jrr[jss::state][jss::validator_list_expires].asInt() == 0); + BEAST_EXPECT(jrr[jss::state][jss::validator_list_expires].asInt() == 0); } { auto const jrr = env.rpc("validators")[jss::result]; - BEAST_EXPECT( - jrr[jss::validation_quorum].asUInt() == - std::numeric_limits::max()); + BEAST_EXPECT(jrr[jss::validation_quorum].asUInt() == std::numeric_limits::max()); BEAST_EXPECT(jrr[jss::local_static_keys].size() == 0); BEAST_EXPECT(jrr[jss::trusted_validator_keys].size() == 0); - BEAST_EXPECT( - jrr[jss::validator_list][jss::expiration] == "unknown"); + BEAST_EXPECT(jrr[jss::validator_list][jss::expiration] == "unknown"); if (BEAST_EXPECT(jrr[jss::publisher_lists].size() == 1)) { @@ -233,9 +208,7 @@ public: BEAST_EXPECT(!jp.isMember(jss::seq)); BEAST_EXPECT(!jp.isMember(jss::expiration)); BEAST_EXPECT(!jp.isMember(jss::version)); - BEAST_EXPECT( - jp[jss::pubkey_publisher] == - strHex(server->publisherPublic())); + BEAST_EXPECT(jp[jss::pubkey_publisher] == strHex(server->publisherPublic())); } BEAST_EXPECT(jrr[jss::signing_keys].size() == 0); } @@ -255,15 +228,13 @@ public: { // Publisher site information using namespace std::string_literals; - std::string siteURI = - "http://"s + getEnvLocalhostAddr() + ":1234/validators2"; + std::string siteURI = "http://"s + getEnvLocalhostAddr() + ":1234/validators2"; Env env{ *this, envconfig([&](std::unique_ptr cfg) { cfg->section(SECTION_VALIDATOR_LIST_SITES).append(siteURI); - cfg->section(SECTION_VALIDATOR_LIST_KEYS) - .append(strHex(server->publisherPublic())); + cfg->section(SECTION_VALIDATOR_LIST_KEYS).append(strHex(server->publisherPublic())); return cfg; }), }; @@ -273,24 +244,18 @@ public: { auto const jrr = env.rpc("server_info")[jss::result]; - BEAST_EXPECT( - jrr[jss::info][jss::validator_list][jss::expiration] == - "unknown"); + BEAST_EXPECT(jrr[jss::info][jss::validator_list][jss::expiration] == "unknown"); } { auto const jrr = env.rpc("server_state")[jss::result]; - BEAST_EXPECT( - jrr[jss::state][jss::validator_list_expires].asInt() == 0); + BEAST_EXPECT(jrr[jss::state][jss::validator_list_expires].asInt() == 0); } { auto const jrr = env.rpc("validators")[jss::result]; - BEAST_EXPECT( - jrr[jss::validation_quorum].asUInt() == - std::numeric_limits::max()); + BEAST_EXPECT(jrr[jss::validation_quorum].asUInt() == std::numeric_limits::max()); BEAST_EXPECT(jrr[jss::local_static_keys].size() == 0); BEAST_EXPECT(jrr[jss::trusted_validator_keys].size() == 0); - BEAST_EXPECT( - jrr[jss::validator_list][jss::expiration] == "unknown"); + BEAST_EXPECT(jrr[jss::validator_list][jss::expiration] == "unknown"); if (BEAST_EXPECT(jrr[jss::publisher_lists].size() == 1)) { @@ -300,9 +265,7 @@ public: BEAST_EXPECT(!jp.isMember(jss::seq)); BEAST_EXPECT(!jp.isMember(jss::expiration)); BEAST_EXPECT(!jp.isMember(jss::version)); - BEAST_EXPECT( - jp[jss::pubkey_publisher] == - strHex(server->publisherPublic())); + BEAST_EXPECT(jp[jss::pubkey_publisher] == strHex(server->publisherPublic())); } BEAST_EXPECT(jrr[jss::signing_keys].size() == 0); } @@ -331,8 +294,7 @@ public: *this, envconfig([&](std::unique_ptr cfg) { cfg->section(SECTION_VALIDATOR_LIST_SITES).append(siteURI); - cfg->section(SECTION_VALIDATOR_LIST_KEYS) - .append(strHex(server->publisherPublic())); + cfg->section(SECTION_VALIDATOR_LIST_KEYS).append(strHex(server->publisherPublic())); return cfg; }), }; @@ -344,35 +306,24 @@ public: startKeys.insert(calcNodeID(val.masterPublic)); env.app().validators().updateTrusted( - startKeys, - env.timeKeeper().now(), - env.app().getOPs(), - env.app().overlay(), - env.app().getHashRouter()); + startKeys, env.timeKeeper().now(), env.app().getOPs(), env.app().overlay(), env.app().getHashRouter()); { auto const jrr = env.rpc("server_info")[jss::result]; - BEAST_EXPECT( - jrr[jss::info][jss::validator_list][jss::expiration] == - to_string(validUntil)); + BEAST_EXPECT(jrr[jss::info][jss::validator_list][jss::expiration] == to_string(validUntil)); } { auto const jrr = env.rpc("server_state")[jss::result]; BEAST_EXPECT( - jrr[jss::state][jss::validator_list_expires].asUInt() == - validUntil.time_since_epoch().count()); + jrr[jss::state][jss::validator_list_expires].asUInt() == validUntil.time_since_epoch().count()); } { auto const jrr = env.rpc("validators")[jss::result]; BEAST_EXPECT(jrr[jss::validation_quorum].asUInt() == 2); - BEAST_EXPECT( - jrr[jss::validator_list][jss::expiration] == - to_string(validUntil)); + BEAST_EXPECT(jrr[jss::validator_list][jss::expiration] == to_string(validUntil)); BEAST_EXPECT(jrr[jss::local_static_keys].size() == 0); - BEAST_EXPECT( - jrr[jss::trusted_validator_keys].size() == - expectedKeys.size()); + BEAST_EXPECT(jrr[jss::trusted_validator_keys].size() == expectedKeys.size()); for (auto const& jKey : jrr[jss::trusted_validator_keys]) { BEAST_EXPECT(expectedKeys.count(jKey.asString()) == 1); @@ -393,9 +344,7 @@ public: BEAST_EXPECT(foundKeys == expectedKeys); } BEAST_EXPECT(jp[jss::seq].asUInt() == 1); - BEAST_EXPECT( - jp[jss::pubkey_publisher] == - strHex(server->publisherPublic())); + BEAST_EXPECT(jp[jss::pubkey_publisher] == strHex(server->publisherPublic())); BEAST_EXPECT(jp[jss::expiration] == to_string(validUntil)); BEAST_EXPECT(jp[jss::version] == 1); } @@ -404,9 +353,7 @@ public: for (auto const& val : validators) { BEAST_EXPECT(jsk.isMember(toStr(val.masterPublic))); - BEAST_EXPECT( - jsk[toStr(val.masterPublic)] == - toStr(val.signingPublic)); + BEAST_EXPECT(jsk[toStr(val.masterPublic)] == toStr(val.signingPublic)); } } { @@ -433,8 +380,7 @@ public: *this, envconfig([&](std::unique_ptr cfg) { cfg->section(SECTION_VALIDATOR_LIST_SITES).append(siteURI); - cfg->section(SECTION_VALIDATOR_LIST_KEYS) - .append(strHex(server->publisherPublic())); + cfg->section(SECTION_VALIDATOR_LIST_KEYS).append(strHex(server->publisherPublic())); return cfg; }), }; @@ -446,35 +392,24 @@ public: startKeys.insert(calcNodeID(val.masterPublic)); env.app().validators().updateTrusted( - startKeys, - env.timeKeeper().now(), - env.app().getOPs(), - env.app().overlay(), - env.app().getHashRouter()); + startKeys, env.timeKeeper().now(), env.app().getOPs(), env.app().overlay(), env.app().getHashRouter()); { auto const jrr = env.rpc("server_info")[jss::result]; - BEAST_EXPECT( - jrr[jss::info][jss::validator_list][jss::expiration] == - to_string(validUntil2)); + BEAST_EXPECT(jrr[jss::info][jss::validator_list][jss::expiration] == to_string(validUntil2)); } { auto const jrr = env.rpc("server_state")[jss::result]; BEAST_EXPECT( - jrr[jss::state][jss::validator_list_expires].asUInt() == - validUntil2.time_since_epoch().count()); + jrr[jss::state][jss::validator_list_expires].asUInt() == validUntil2.time_since_epoch().count()); } { auto const jrr = env.rpc("validators")[jss::result]; BEAST_EXPECT(jrr[jss::validation_quorum].asUInt() == 2); - BEAST_EXPECT( - jrr[jss::validator_list][jss::expiration] == - to_string(validUntil2)); + BEAST_EXPECT(jrr[jss::validator_list][jss::expiration] == to_string(validUntil2)); BEAST_EXPECT(jrr[jss::local_static_keys].size() == 0); - BEAST_EXPECT( - jrr[jss::trusted_validator_keys].size() == - expectedKeys.size()); + BEAST_EXPECT(jrr[jss::trusted_validator_keys].size() == expectedKeys.size()); for (auto const& jKey : jrr[jss::trusted_validator_keys]) { BEAST_EXPECT(expectedKeys.count(jKey.asString()) == 1); @@ -495,13 +430,10 @@ public: BEAST_EXPECT(foundKeys == expectedKeys); } BEAST_EXPECT(jp[jss::seq].asUInt() == 1); - BEAST_EXPECT( - jp[jss::pubkey_publisher] == - strHex(server->publisherPublic())); + BEAST_EXPECT(jp[jss::pubkey_publisher] == strHex(server->publisherPublic())); BEAST_EXPECT(jp[jss::expiration] == to_string(validUntil)); BEAST_EXPECT(jp[jss::version] == 2); - if (BEAST_EXPECT(jp.isMember(jss::remaining)) && - BEAST_EXPECT(jp[jss::remaining].isArray()) && + if (BEAST_EXPECT(jp.isMember(jss::remaining)) && BEAST_EXPECT(jp[jss::remaining].isArray()) && BEAST_EXPECT(jp[jss::remaining].size() == 1)) { auto const& r = jp[jss::remaining][0u]; @@ -516,10 +448,8 @@ public: BEAST_EXPECT(foundKeys == expectedKeys); } BEAST_EXPECT(r[jss::seq].asUInt() == 2); - BEAST_EXPECT( - r[jss::effective] == to_string(validFrom2)); - BEAST_EXPECT( - r[jss::expiration] == to_string(validUntil2)); + BEAST_EXPECT(r[jss::effective] == to_string(validFrom2)); + BEAST_EXPECT(r[jss::expiration] == to_string(validUntil2)); } } auto jsk = jrr[jss::signing_keys]; @@ -527,9 +457,7 @@ public: for (auto const& val : validators) { BEAST_EXPECT(jsk.isMember(toStr(val.masterPublic))); - BEAST_EXPECT( - jsk[toStr(val.masterPublic)] == - toStr(val.signingPublic)); + BEAST_EXPECT(jsk[toStr(val.masterPublic)] == toStr(val.signingPublic)); } } { @@ -554,15 +482,9 @@ public: using namespace test::jtx; Env env{*this}; auto result = env.rpc("validation_create"); - BEAST_EXPECT( - result.isMember(jss::result) && - result[jss::result][jss::status] == "success"); - result = env.rpc( - "validation_create", - "BAWL MAN JADE MOON DOVE GEM SON NOW HAD ADEN GLOW TIRE"); - BEAST_EXPECT( - result.isMember(jss::result) && - result[jss::result][jss::status] == "success"); + BEAST_EXPECT(result.isMember(jss::result) && result[jss::result][jss::status] == "success"); + result = env.rpc("validation_create", "BAWL MAN JADE MOON DOVE GEM SON NOW HAD ADEN GLOW TIRE"); + BEAST_EXPECT(result.isMember(jss::result) && result[jss::result][jss::status] == "success"); } void diff --git a/src/test/rpc/Version_test.cpp b/src/test/rpc/Version_test.cpp index fd4bfdd565..1dec8627ed 100644 --- a/src/test/rpc/Version_test.cpp +++ b/src/test/rpc/Version_test.cpp @@ -24,9 +24,7 @@ class Version_test : public beast::unit_test::suite auto jrr = env.rpc( "json", "version", - "{\"api_version\": " + - std::to_string(RPC::apiMaximumSupportedVersion) + - "}")[jss::result]; + "{\"api_version\": " + std::to_string(RPC::apiMaximumSupportedVersion) + "}")[jss::result]; BEAST_EXPECT(isCorrectReply(jrr)); jrr = env.rpc("version")[jss::result]; @@ -45,17 +43,13 @@ class Version_test : public beast::unit_test::suite if (re.isMember("error_what")) if (re["error_what"].isString()) { - return re["error_what"].asString().find( - jss::invalid_API_version.c_str()) == 0; + return re["error_what"].asString().find(jss::invalid_API_version.c_str()) == 0; } return false; }; auto re = env.rpc( - "json", - "version", - "{\"api_version\": " + - std::to_string(RPC::apiMinimumSupportedVersion - 1) + "}"); + "json", "version", "{\"api_version\": " + std::to_string(RPC::apiMinimumSupportedVersion - 1) + "}"); BEAST_EXPECT(badVersion(re)); BEAST_EXPECT(env.app().config().BETA_RPC_API); @@ -63,12 +57,7 @@ class Version_test : public beast::unit_test::suite "json", "version", "{\"api_version\": " + - std::to_string( - std::max( - RPC::apiMaximumSupportedVersion.value, - RPC::apiBetaVersion.value) + - 1) + - "}"); + std::to_string(std::max(RPC::apiMaximumSupportedVersion.value, RPC::apiBetaVersion.value) + 1) + "}"); BEAST_EXPECT(badVersion(re)); re = env.rpc("json", "version", "{\"api_version\": \"a\"}"); @@ -80,57 +69,38 @@ class Version_test : public beast::unit_test::suite { testcase("test getAPIVersionNumber function"); - unsigned int versionIfUnspecified = - RPC::apiVersionIfUnspecified < RPC::apiMinimumSupportedVersion + unsigned int versionIfUnspecified = RPC::apiVersionIfUnspecified < RPC::apiMinimumSupportedVersion ? RPC::apiInvalidVersion : RPC::apiVersionIfUnspecified; Json::Value j_array = Json::Value(Json::arrayValue); Json::Value j_null = Json::Value(Json::nullValue); - BEAST_EXPECT( - RPC::getAPIVersionNumber(j_array, false) == versionIfUnspecified); - BEAST_EXPECT( - RPC::getAPIVersionNumber(j_null, false) == versionIfUnspecified); + BEAST_EXPECT(RPC::getAPIVersionNumber(j_array, false) == versionIfUnspecified); + BEAST_EXPECT(RPC::getAPIVersionNumber(j_null, false) == versionIfUnspecified); Json::Value j_object = Json::Value(Json::objectValue); - BEAST_EXPECT( - RPC::getAPIVersionNumber(j_object, false) == versionIfUnspecified); + BEAST_EXPECT(RPC::getAPIVersionNumber(j_object, false) == versionIfUnspecified); j_object[jss::api_version] = RPC::apiVersionIfUnspecified.value; - BEAST_EXPECT( - RPC::getAPIVersionNumber(j_object, false) == versionIfUnspecified); + BEAST_EXPECT(RPC::getAPIVersionNumber(j_object, false) == versionIfUnspecified); j_object[jss::api_version] = RPC::apiMinimumSupportedVersion.value; - BEAST_EXPECT( - RPC::getAPIVersionNumber(j_object, false) == - RPC::apiMinimumSupportedVersion); + BEAST_EXPECT(RPC::getAPIVersionNumber(j_object, false) == RPC::apiMinimumSupportedVersion); j_object[jss::api_version] = RPC::apiMaximumSupportedVersion.value; - BEAST_EXPECT( - RPC::getAPIVersionNumber(j_object, false) == - RPC::apiMaximumSupportedVersion); + BEAST_EXPECT(RPC::getAPIVersionNumber(j_object, false) == RPC::apiMaximumSupportedVersion); j_object[jss::api_version] = RPC::apiMinimumSupportedVersion - 1; - BEAST_EXPECT( - RPC::getAPIVersionNumber(j_object, false) == - RPC::apiInvalidVersion); + BEAST_EXPECT(RPC::getAPIVersionNumber(j_object, false) == RPC::apiInvalidVersion); j_object[jss::api_version] = RPC::apiMaximumSupportedVersion + 1; - BEAST_EXPECT( - RPC::getAPIVersionNumber(j_object, false) == - RPC::apiInvalidVersion); + BEAST_EXPECT(RPC::getAPIVersionNumber(j_object, false) == RPC::apiInvalidVersion); j_object[jss::api_version] = RPC::apiBetaVersion.value; - BEAST_EXPECT( - RPC::getAPIVersionNumber(j_object, true) == RPC::apiBetaVersion); + BEAST_EXPECT(RPC::getAPIVersionNumber(j_object, true) == RPC::apiBetaVersion); j_object[jss::api_version] = RPC::apiBetaVersion + 1; - BEAST_EXPECT( - RPC::getAPIVersionNumber(j_object, true) == RPC::apiInvalidVersion); + BEAST_EXPECT(RPC::getAPIVersionNumber(j_object, true) == RPC::apiInvalidVersion); j_object[jss::api_version] = RPC::apiInvalidVersion.value; - BEAST_EXPECT( - RPC::getAPIVersionNumber(j_object, false) == - RPC::apiInvalidVersion); + BEAST_EXPECT(RPC::getAPIVersionNumber(j_object, false) == RPC::apiInvalidVersion); j_object[jss::api_version] = "a"; - BEAST_EXPECT( - RPC::getAPIVersionNumber(j_object, false) == - RPC::apiInvalidVersion); + BEAST_EXPECT(RPC::getAPIVersionNumber(j_object, false) == RPC::apiInvalidVersion); } void @@ -155,19 +125,14 @@ class Version_test : public beast::unit_test::suite "\"params\": { " "\"api_version\": " + std::to_string(RPC::apiMaximumSupportedVersion) + "}}"; - auto re = env.rpc( - "json2", '[' + without_api_verion + ", " + with_api_verion + ']'); + auto re = env.rpc("json2", '[' + without_api_verion + ", " + with_api_verion + ']'); if (!BEAST_EXPECT(re.isArray())) return; if (!BEAST_EXPECT(re.size() == 2)) return; - BEAST_EXPECT( - re[0u].isMember(jss::result) && - re[0u][jss::result].isMember(jss::version)); - BEAST_EXPECT( - re[1u].isMember(jss::result) && - re[1u][jss::result].isMember(jss::version)); + BEAST_EXPECT(re[0u].isMember(jss::result) && re[0u][jss::result].isMember(jss::version)); + BEAST_EXPECT(re[1u].isMember(jss::result) && re[1u][jss::result].isMember(jss::version)); } void @@ -192,22 +157,14 @@ class Version_test : public beast::unit_test::suite "\"method\": \"version\", " "\"params\": { " "\"api_version\": " + - std::to_string(std::max( - RPC::apiMaximumSupportedVersion.value, - RPC::apiBetaVersion.value) + - 1) + - "}}"; - auto re = env.rpc( - "json2", - '[' + without_api_verion + ", " + with_wrong_api_verion + ']'); + std::to_string(std::max(RPC::apiMaximumSupportedVersion.value, RPC::apiBetaVersion.value) + 1) + "}}"; + auto re = env.rpc("json2", '[' + without_api_verion + ", " + with_wrong_api_verion + ']'); if (!BEAST_EXPECT(re.isArray())) return; if (!BEAST_EXPECT(re.size() == 2)) return; - BEAST_EXPECT( - re[0u].isMember(jss::result) && - re[0u][jss::result].isMember(jss::version)); + BEAST_EXPECT(re[0u].isMember(jss::result) && re[0u][jss::result].isMember(jss::version)); BEAST_EXPECT(re[1u].isMember(jss::error)); } @@ -246,20 +203,14 @@ class Version_test : public beast::unit_test::suite if (!BEAST_EXPECT(env.app().config().BETA_RPC_API == true)) return; - auto jrr = env.rpc( - "json", - "version", - "{\"api_version\": " + std::to_string(RPC::apiBetaVersion) + - "}")[jss::result]; + auto jrr = + env.rpc("json", "version", "{\"api_version\": " + std::to_string(RPC::apiBetaVersion) + "}")[jss::result]; if (!BEAST_EXPECT(jrr.isMember(jss::version))) return; - if (!BEAST_EXPECT(jrr[jss::version].isMember(jss::first)) && - jrr[jss::version].isMember(jss::last)) + if (!BEAST_EXPECT(jrr[jss::version].isMember(jss::first)) && jrr[jss::version].isMember(jss::last)) return; - BEAST_EXPECT( - jrr[jss::version][jss::first] == - RPC::apiMinimumSupportedVersion.value); + BEAST_EXPECT(jrr[jss::version][jss::first] == RPC::apiMinimumSupportedVersion.value); BEAST_EXPECT(jrr[jss::version][jss::last] == RPC::apiBetaVersion.value); } diff --git a/src/test/server/ServerStatus_test.cpp b/src/test/server/ServerStatus_test.cpp index a2516126de..5a91ad4b03 100644 --- a/src/test/server/ServerStatus_test.cpp +++ b/src/test/server/ServerStatus_test.cpp @@ -5,12 +5,12 @@ #include #include -#include #include #include #include #include +#include #include #include @@ -27,21 +27,16 @@ namespace xrpl { namespace test { -class ServerStatus_test : public beast::unit_test::suite, - public beast::test::enable_yield_to +class ServerStatus_test : public beast::unit_test::suite, public beast::test::enable_yield_to { class myFields : public boost::beast::http::fields { }; auto - makeConfig( - std::string const& proto, - bool admin = true, - bool credentials = false) + makeConfig(std::string const& proto, bool admin = true, bool credentials = false) { - auto const section_name = - boost::starts_with(proto, "h") ? "port_rpc" : "port_ws"; + auto const section_name = boost::starts_with(proto, "h") ? "port_rpc" : "port_ws"; auto p = jtx::envconfig(); p->overwrite(section_name, "protocol", proto); @@ -95,8 +90,7 @@ class ServerStatus_test : public beast::unit_test::suite, std::array key; for (auto& v : key) v = d(e); - req.insert( - "Sec-WebSocket-Key", base64_encode(key.data(), key.size())); + req.insert("Sec-WebSocket-Key", base64_encode(key.data(), key.size())); }; req.insert("Sec-WebSocket-Version", "13"); req.insert(boost::beast::http::field::connection, "upgrade"); @@ -104,11 +98,7 @@ class ServerStatus_test : public beast::unit_test::suite, } auto - makeHTTPRequest( - std::string const& host, - uint16_t port, - std::string const& body, - myFields const& fields) + makeHTTPRequest(std::string const& host, uint16_t port, std::string const& body, myFields const& fields) { using namespace boost::asio; using namespace boost::beast::http; @@ -199,11 +189,9 @@ class ServerStatus_test : public beast::unit_test::suite, boost::beast::http::response& resp, boost::system::error_code& ec) { - auto const port = - env.app().config()["port_ws"].get("port"); + auto const port = env.app().config()["port_ws"].get("port"); auto ip = env.app().config()["port_ws"].get("ip"); - doRequest( - yield, makeWSUpgrade(*ip, *port), *ip, *port, secure, resp, ec); + doRequest(yield, makeWSUpgrade(*ip, *port), *ip, *port, secure, resp, ec); return; } @@ -217,17 +205,9 @@ class ServerStatus_test : public beast::unit_test::suite, std::string const& body = "", myFields const& fields = {}) { - auto const port = - env.app().config()["port_rpc"].get("port"); + auto const port = env.app().config()["port_rpc"].get("port"); auto const ip = env.app().config()["port_rpc"].get("ip"); - doRequest( - yield, - makeHTTPRequest(*ip, *port, body, fields), - *ip, - *port, - secure, - resp, - ec); + doRequest(yield, makeHTTPRequest(*ip, *port, body, fields), *ip, *port, secure, resp, ec); return; } @@ -279,9 +259,8 @@ class ServerStatus_test : public beast::unit_test::suite, void testAdminRequest(std::string const& proto, bool admin, bool credentials) { - testcase << "Admin request over " << proto << ", config " - << (admin ? "enabled" : "disabled") << ", credentials " - << (credentials ? "" : "not ") << "set"; + testcase << "Admin request over " << proto << ", config " << (admin ? "enabled" : "disabled") + << ", credentials " << (credentials ? "" : "not ") << "set"; using namespace jtx; Env env{*this, makeConfig(proto, admin, credentials)}; @@ -293,53 +272,34 @@ class ServerStatus_test : public beast::unit_test::suite, if (admin && credentials) { - auto const user = env.app() - .config()[proto_ws ? "port_ws" : "port_rpc"] - .get("admin_user"); + auto const user = env.app().config()[proto_ws ? "port_ws" : "port_rpc"].get("admin_user"); auto const password = - env.app() - .config()[proto_ws ? "port_ws" : "port_rpc"] - .get("admin_password"); + env.app().config()[proto_ws ? "port_ws" : "port_rpc"].get("admin_password"); // 1 - FAILS with wrong pass - jrr = makeAdminRequest( - env, proto, *user, *password + "_")[jss::result]; + jrr = makeAdminRequest(env, proto, *user, *password + "_")[jss::result]; + BEAST_EXPECT(jrr["error"] == proto_ws ? "forbidden" : "noPermission"); BEAST_EXPECT( - jrr["error"] == proto_ws ? "forbidden" : "noPermission"); - BEAST_EXPECT( - jrr["error_message"] == proto_ws - ? "Bad credentials." - : "You don't have permission for this command."); + jrr["error_message"] == proto_ws ? "Bad credentials." : "You don't have permission for this command."); // 2 - FAILS with password in an object - jrr = makeAdminRequest( - env, proto, *user, *password, true)[jss::result]; + jrr = makeAdminRequest(env, proto, *user, *password, true)[jss::result]; + BEAST_EXPECT(jrr["error"] == proto_ws ? "forbidden" : "noPermission"); BEAST_EXPECT( - jrr["error"] == proto_ws ? "forbidden" : "noPermission"); - BEAST_EXPECT( - jrr["error_message"] == proto_ws - ? "Bad credentials." - : "You don't have permission for this command."); + jrr["error_message"] == proto_ws ? "Bad credentials." : "You don't have permission for this command."); // 3 - FAILS with wrong user - jrr = makeAdminRequest( - env, proto, *user + "_", *password)[jss::result]; + jrr = makeAdminRequest(env, proto, *user + "_", *password)[jss::result]; + BEAST_EXPECT(jrr["error"] == proto_ws ? "forbidden" : "noPermission"); BEAST_EXPECT( - jrr["error"] == proto_ws ? "forbidden" : "noPermission"); - BEAST_EXPECT( - jrr["error_message"] == proto_ws - ? "Bad credentials." - : "You don't have permission for this command."); + jrr["error_message"] == proto_ws ? "Bad credentials." : "You don't have permission for this command."); // 4 - FAILS no credentials jrr = makeAdminRequest(env, proto, "", "")[jss::result]; + BEAST_EXPECT(jrr["error"] == proto_ws ? "forbidden" : "noPermission"); BEAST_EXPECT( - jrr["error"] == proto_ws ? "forbidden" : "noPermission"); - BEAST_EXPECT( - jrr["error_message"] == proto_ws - ? "Bad credentials." - : "You don't have permission for this command."); + jrr["error_message"] == proto_ws ? "Bad credentials." : "You don't have permission for this command."); // 5 - SUCCEEDS with proper credentials jrr = makeAdminRequest(env, proto, *user, *password)[jss::result]; @@ -359,12 +319,9 @@ class ServerStatus_test : public beast::unit_test::suite, { // 1 - FAILS - admin disabled jrr = makeAdminRequest(env, proto, "", "")[jss::result]; + BEAST_EXPECT(jrr["error"] == proto_ws ? "forbidden" : "noPermission"); BEAST_EXPECT( - jrr["error"] == proto_ws ? "forbidden" : "noPermission"); - BEAST_EXPECT( - jrr["error_message"] == proto_ws - ? "Bad credentials." - : "You don't have permission for this command."); + jrr["error_message"] == proto_ws ? "Bad credentials." : "You don't have permission for this command."); } } @@ -385,8 +342,7 @@ class ServerStatus_test : public beast::unit_test::suite, doWSRequest(env, yield, false, resp, ec); if (!BEAST_EXPECTS(!ec, ec.message())) return; - BEAST_EXPECT( - resp.result() == boost::beast::http::status::unauthorized); + BEAST_EXPECT(resp.result() == boost::beast::http::status::unauthorized); } // secure request @@ -396,8 +352,7 @@ class ServerStatus_test : public beast::unit_test::suite, doWSRequest(env, yield, true, resp, ec); if (!BEAST_EXPECTS(!ec, ec.message())) return; - BEAST_EXPECT( - resp.result() == boost::beast::http::status::unauthorized); + BEAST_EXPECT(resp.result() == boost::beast::http::status::unauthorized); } } @@ -445,8 +400,7 @@ class ServerStatus_test : public beast::unit_test::suite, return cfg; })}; - auto const port = - env.app().config()["port_ws"].get("port"); + auto const port = env.app().config()["port_ws"].get("port"); auto const ip = env.app().config()["port_ws"].get("ip"); boost::system::error_code ec; @@ -487,8 +441,7 @@ class ServerStatus_test : public beast::unit_test::suite, // The essence of this test is to have a client and server configured // out-of-phase with respect to ssl (secure client and insecure server // or vice-versa) - testcase << "Connect fails: " << client_protocol << " client to " - << server_protocol << " server"; + testcase << "Connect fails: " << client_protocol << " client to " << server_protocol << " server"; using namespace jtx; Env env{*this, makeConfig(server_protocol)}; @@ -501,12 +454,7 @@ class ServerStatus_test : public beast::unit_test::suite, } else { - doWSRequest( - env, - yield, - client_protocol == "wss" || client_protocol == "wss2", - resp, - ec); + doWSRequest(env, yield, client_protocol == "wss" || client_protocol == "wss2", resp, ec); BEAST_EXPECT(ec); } } @@ -514,15 +462,13 @@ class ServerStatus_test : public beast::unit_test::suite, void testAuth(bool secure, boost::asio::yield_context& yield) { - testcase << "Server with authorization, " - << (secure ? "secure" : "non-secure"); + testcase << "Server with authorization, " << (secure ? "secure" : "non-secure"); using namespace test::jtx; Env env{*this, envconfig([secure](std::unique_ptr cfg) { (*cfg)["port_rpc"].set("user", "me"); (*cfg)["port_rpc"].set("password", "secret"); - (*cfg)["port_rpc"].set( - "protocol", secure ? "https" : "http"); + (*cfg)["port_rpc"].set("protocol", secure ? "https" : "http"); if (secure) (*cfg)["port_ws"].set("protocol", "http,ws"); return cfg; @@ -548,16 +494,8 @@ class ServerStatus_test : public beast::unit_test::suite, doHTTPRequest(env, yield, secure, resp, ec, to_string(jr), auth); BEAST_EXPECT(resp.result() == boost::beast::http::status::forbidden); - auto const user = env.app() - .config() - .section("port_rpc") - .get("user") - .value(); - auto const pass = env.app() - .config() - .section("port_rpc") - .get("password") - .value(); + auto const user = env.app().config().section("port_rpc").get("user").value(); + auto const pass = env.app().config().section("port_rpc").get("password").value(); // try with the correct user/pass, but not encoded auth.set("Authorization", "Basic " + user + ":" + pass); @@ -584,10 +522,8 @@ class ServerStatus_test : public beast::unit_test::suite, return cfg; })}; - auto const port = - env.app().config()["port_rpc"].get("port").value(); - auto const ip = - env.app().config()["port_rpc"].get("ip").value(); + auto const port = env.app().config()["port_rpc"].get("port").value(); + auto const ip = env.app().config()["port_rpc"].get("ip").value(); boost::system::error_code ec; io_context& ios = get_io_context(); @@ -599,8 +535,7 @@ class ServerStatus_test : public beast::unit_test::suite, auto it = r.async_resolve(ip, std::to_string(port), yield[ec]); BEAST_EXPECT(!ec); - std::vector> - clients; + std::vector> clients; int connectionCount{1}; // starts at 1 because the Env already has one // for JSONRPCCLient @@ -612,8 +547,7 @@ class ServerStatus_test : public beast::unit_test::suite, int testTo = (limit == 0) ? 50 : limit + 1; while (connectionCount < testTo) { - clients.emplace_back(std::make_pair( - ip::tcp::socket{ios}, boost::beast::multi_buffer{})); + clients.emplace_back(std::make_pair(ip::tcp::socket{ios}, boost::beast::multi_buffer{})); async_connect(clients.back().first, it, yield[ec]); BEAST_EXPECT(!ec); auto req = makeHTTPRequest(ip, port, to_string(jr), {}); @@ -630,8 +564,7 @@ class ServerStatus_test : public beast::unit_test::suite, ++readCount; // expect the reads to fail for the clients that connected at or // above the limit. If limit is 0, all reads should succeed - BEAST_EXPECT( - (limit == 0 || readCount < limit - 1) ? (!ec) : bool(ec)); + BEAST_EXPECT((limit == 0 || readCount < limit - 1) ? (!ec) : bool(ec)); } } @@ -646,21 +579,14 @@ class ServerStatus_test : public beast::unit_test::suite, return cfg; })}; - auto const port = - env.app().config()["port_ws"].get("port").value(); - auto const ip = - env.app().config()["port_ws"].get("ip").value(); + auto const port = env.app().config()["port_ws"].get("port").value(); + auto const ip = env.app().config()["port_ws"].get("ip").value(); boost::beast::http::response resp; boost::system::error_code ec; doRequest(yield, makeWSUpgrade(ip, port), ip, port, true, resp, ec); - BEAST_EXPECT( - resp.result() == boost::beast::http::status::switching_protocols); - BEAST_EXPECT( - resp.find("Upgrade") != resp.end() && - resp["Upgrade"] == "websocket"); - BEAST_EXPECT( - resp.find("Connection") != resp.end() && - boost::iequals(resp["Connection"], "upgrade")); + BEAST_EXPECT(resp.result() == boost::beast::http::status::switching_protocols); + BEAST_EXPECT(resp.find("Upgrade") != resp.end() && resp["Upgrade"] == "websocket"); + BEAST_EXPECT(resp.find("Connection") != resp.end() && boost::iequals(resp["Connection"], "upgrade")); } void @@ -671,22 +597,13 @@ class ServerStatus_test : public beast::unit_test::suite, using namespace test::jtx; Env env{*this}; - auto const port = - env.app().config()["port_ws"].get("port").value(); - auto const ip = - env.app().config()["port_ws"].get("ip").value(); + auto const port = env.app().config()["port_ws"].get("port").value(); + auto const ip = env.app().config()["port_ws"].get("ip").value(); boost::beast::http::response resp; boost::system::error_code ec; // body content is required here to avoid being // detected as a status request - doRequest( - yield, - makeHTTPRequest(ip, port, "foo", {}), - ip, - port, - false, - resp, - ec); + doRequest(yield, makeHTTPRequest(ip, port, "foo", {}), ip, port, false, resp, ec); BEAST_EXPECT(resp.result() == boost::beast::http::status::forbidden); BEAST_EXPECT(resp.body() == "Forbidden\r\n"); } @@ -701,10 +618,8 @@ class ServerStatus_test : public beast::unit_test::suite, using namespace boost::beast::http; Env env{*this}; - auto const port = - env.app().config()["port_ws"].get("port").value(); - auto const ip = - env.app().config()["port_ws"].get("ip").value(); + auto const port = env.app().config()["port_ws"].get("port").value(); + auto const ip = env.app().config()["port_ws"].get("ip").value(); boost::system::error_code ec; io_context& ios = get_io_context(); @@ -735,10 +650,8 @@ class ServerStatus_test : public beast::unit_test::suite, Json::Value resp; Json::Reader jr; - if (!BEAST_EXPECT(jr.parse( - boost::lexical_cast( - boost::beast::make_printable(sb.data())), - resp))) + if (!BEAST_EXPECT( + jr.parse(boost::lexical_cast(boost::beast::make_printable(sb.data())), resp))) return Json::objectValue; sb.consume(sb.size()); return resp; @@ -746,8 +659,7 @@ class ServerStatus_test : public beast::unit_test::suite, { // send invalid json auto resp = sendAndParse("NOT JSON"); - BEAST_EXPECT( - resp.isMember(jss::error) && resp[jss::error] == "jsonInvalid"); + BEAST_EXPECT(resp.isMember(jss::error) && resp[jss::error] == "jsonInvalid"); BEAST_EXPECT(!resp.isMember(jss::status)); } @@ -756,22 +668,17 @@ class ServerStatus_test : public beast::unit_test::suite, jv[jss::command] = "foo"; jv[jss::method] = "bar"; auto resp = sendAndParse(to_string(jv)); - BEAST_EXPECT( - resp.isMember(jss::error) && - resp[jss::error] == "missingCommand"); - BEAST_EXPECT( - resp.isMember(jss::status) && resp[jss::status] == "error"); + BEAST_EXPECT(resp.isMember(jss::error) && resp[jss::error] == "missingCommand"); + BEAST_EXPECT(resp.isMember(jss::status) && resp[jss::status] == "error"); } { // send a ping (not an error) Json::Value jv; jv[jss::command] = "ping"; auto resp = sendAndParse(to_string(jv)); + BEAST_EXPECT(resp.isMember(jss::status) && resp[jss::status] == "success"); BEAST_EXPECT( - resp.isMember(jss::status) && resp[jss::status] == "success"); - BEAST_EXPECT( - resp.isMember(jss::result) && - resp[jss::result].isMember(jss::role) && + resp.isMember(jss::result) && resp[jss::result].isMember(jss::role) && resp[jss::result][jss::role] == "admin"); } } @@ -779,8 +686,7 @@ class ServerStatus_test : public beast::unit_test::suite, void testAmendmentWarning(boost::asio::yield_context& yield) { - testcase( - "Status request over WS and RPC with/without Amendment Warning"); + testcase("Status request over WS and RPC with/without Amendment Warning"); using namespace jtx; using namespace boost::asio; using namespace boost::beast::http; @@ -805,8 +711,7 @@ class ServerStatus_test : public beast::unit_test::suite, auto si = env.rpc("server_info")[jss::result]; BEAST_EXPECT(si.isMember(jss::info)); BEAST_EXPECT(!si[jss::info].isMember(jss::amendment_blocked)); - BEAST_EXPECT( - env.app().getOPs().getConsensusInfo()["validating"] == true); + BEAST_EXPECT(env.app().getOPs().getConsensusInfo()["validating"] == true); BEAST_EXPECT(!si.isMember(jss::warnings)); // make an RPC server state request and look for @@ -814,39 +719,28 @@ class ServerStatus_test : public beast::unit_test::suite, si = env.rpc("server_state")[jss::result]; BEAST_EXPECT(si.isMember(jss::state)); BEAST_EXPECT(!si[jss::state].isMember(jss::amendment_blocked)); - BEAST_EXPECT( - env.app().getOPs().getConsensusInfo()["validating"] == true); + BEAST_EXPECT(env.app().getOPs().getConsensusInfo()["validating"] == true); BEAST_EXPECT(!si[jss::state].isMember(jss::warnings)); - auto const port_ws = - env.app().config()["port_ws"].get("port"); + auto const port_ws = env.app().config()["port_ws"].get("port"); auto const ip_ws = env.app().config()["port_ws"].get("ip"); boost::system::error_code ec; response resp; - doRequest( - yield, - makeHTTPRequest(*ip_ws, *port_ws, "", {}), - *ip_ws, - *port_ws, - false, - resp, - ec); + doRequest(yield, makeHTTPRequest(*ip_ws, *port_ws, "", {}), *ip_ws, *port_ws, false, resp, ec); if (!BEAST_EXPECTS(!ec, ec.message())) return; BEAST_EXPECT(resp.result() == boost::beast::http::status::ok); - BEAST_EXPECT( - resp.body().find("connectivity is working.") != std::string::npos); + BEAST_EXPECT(resp.body().find("connectivity is working.") != std::string::npos); // mark the Network as having an Amendment Warning, but won't fail env.app().getOPs().setAmendmentWarned(); env.app().getOPs().beginConsensus(env.closed()->header().hash, {}); // consensus doesn't change - BEAST_EXPECT( - env.app().getOPs().getConsensusInfo()["validating"] == true); + BEAST_EXPECT(env.app().getOPs().getConsensusInfo()["validating"] == true); // RPC request server_info again, now unsupported majority should be // returned @@ -854,11 +748,9 @@ class ServerStatus_test : public beast::unit_test::suite, BEAST_EXPECT(si.isMember(jss::info)); BEAST_EXPECT(!si[jss::info].isMember(jss::amendment_blocked)); BEAST_EXPECT( - si[jss::info].isMember(jss::warnings) && - si[jss::info][jss::warnings].isArray() && + si[jss::info].isMember(jss::warnings) && si[jss::info][jss::warnings].isArray() && si[jss::info][jss::warnings].size() == 1 && - si[jss::info][jss::warnings][0u][jss::id].asInt() == - warnRPC_UNSUPPORTED_MAJORITY); + si[jss::info][jss::warnings][0u][jss::id].asInt() == warnRPC_UNSUPPORTED_MAJORITY); // RPC request server_state again, now unsupported majority should be // returned @@ -866,45 +758,27 @@ class ServerStatus_test : public beast::unit_test::suite, BEAST_EXPECT(si.isMember(jss::state)); BEAST_EXPECT(!si[jss::state].isMember(jss::amendment_blocked)); BEAST_EXPECT( - si[jss::state].isMember(jss::warnings) && - si[jss::state][jss::warnings].isArray() && + si[jss::state].isMember(jss::warnings) && si[jss::state][jss::warnings].isArray() && si[jss::state][jss::warnings].size() == 1 && - si[jss::state][jss::warnings][0u][jss::id].asInt() == - warnRPC_UNSUPPORTED_MAJORITY); + si[jss::state][jss::warnings][0u][jss::id].asInt() == warnRPC_UNSUPPORTED_MAJORITY); // but status does not indicate a problem - doRequest( - yield, - makeHTTPRequest(*ip_ws, *port_ws, "", {}), - *ip_ws, - *port_ws, - false, - resp, - ec); + doRequest(yield, makeHTTPRequest(*ip_ws, *port_ws, "", {}), *ip_ws, *port_ws, false, resp, ec); if (!BEAST_EXPECTS(!ec, ec.message())) return; BEAST_EXPECT(resp.result() == boost::beast::http::status::ok); - BEAST_EXPECT( - resp.body().find("connectivity is working.") != std::string::npos); + BEAST_EXPECT(resp.body().find("connectivity is working.") != std::string::npos); // with ELB_SUPPORT, status still does not indicate a problem env.app().config().ELB_SUPPORT = true; - doRequest( - yield, - makeHTTPRequest(*ip_ws, *port_ws, "", {}), - *ip_ws, - *port_ws, - false, - resp, - ec); + doRequest(yield, makeHTTPRequest(*ip_ws, *port_ws, "", {}), *ip_ws, *port_ws, false, resp, ec); if (!BEAST_EXPECTS(!ec, ec.message())) return; BEAST_EXPECT(resp.result() == boost::beast::http::status::ok); - BEAST_EXPECT( - resp.body().find("connectivity is working.") != std::string::npos); + BEAST_EXPECT(resp.body().find("connectivity is working.") != std::string::npos); } void @@ -935,8 +809,7 @@ class ServerStatus_test : public beast::unit_test::suite, auto si = env.rpc("server_info")[jss::result]; BEAST_EXPECT(si.isMember(jss::info)); BEAST_EXPECT(!si[jss::info].isMember(jss::amendment_blocked)); - BEAST_EXPECT( - env.app().getOPs().getConsensusInfo()["validating"] == true); + BEAST_EXPECT(env.app().getOPs().getConsensusInfo()["validating"] == true); BEAST_EXPECT(!si.isMember(jss::warnings)); // make an RPC server state request and look for @@ -944,31 +817,21 @@ class ServerStatus_test : public beast::unit_test::suite, si = env.rpc("server_state")[jss::result]; BEAST_EXPECT(si.isMember(jss::state)); BEAST_EXPECT(!si[jss::state].isMember(jss::amendment_blocked)); - BEAST_EXPECT( - env.app().getOPs().getConsensusInfo()["validating"] == true); + BEAST_EXPECT(env.app().getOPs().getConsensusInfo()["validating"] == true); BEAST_EXPECT(!si[jss::state].isMember(jss::warnings)); - auto const port_ws = - env.app().config()["port_ws"].get("port"); + auto const port_ws = env.app().config()["port_ws"].get("port"); auto const ip_ws = env.app().config()["port_ws"].get("ip"); boost::system::error_code ec; response resp; - doRequest( - yield, - makeHTTPRequest(*ip_ws, *port_ws, "", {}), - *ip_ws, - *port_ws, - false, - resp, - ec); + doRequest(yield, makeHTTPRequest(*ip_ws, *port_ws, "", {}), *ip_ws, *port_ws, false, resp, ec); if (!BEAST_EXPECTS(!ec, ec.message())) return; BEAST_EXPECT(resp.result() == boost::beast::http::status::ok); - BEAST_EXPECT( - resp.body().find("connectivity is working.") != std::string::npos); + BEAST_EXPECT(resp.body().find("connectivity is working.") != std::string::npos); // mark the Network as Amendment Blocked, but still won't fail until // ELB is enabled (next step) @@ -976,70 +839,43 @@ class ServerStatus_test : public beast::unit_test::suite, env.app().getOPs().beginConsensus(env.closed()->header().hash, {}); // consensus now sees validation disabled - BEAST_EXPECT( - env.app().getOPs().getConsensusInfo()["validating"] == false); + BEAST_EXPECT(env.app().getOPs().getConsensusInfo()["validating"] == false); // RPC request server_info again, now AB should be returned si = env.rpc("server_info")[jss::result]; BEAST_EXPECT(si.isMember(jss::info)); + BEAST_EXPECT(si[jss::info].isMember(jss::amendment_blocked) && si[jss::info][jss::amendment_blocked] == true); BEAST_EXPECT( - si[jss::info].isMember(jss::amendment_blocked) && - si[jss::info][jss::amendment_blocked] == true); - BEAST_EXPECT( - si[jss::info].isMember(jss::warnings) && - si[jss::info][jss::warnings].isArray() && + si[jss::info].isMember(jss::warnings) && si[jss::info][jss::warnings].isArray() && si[jss::info][jss::warnings].size() == 1 && - si[jss::info][jss::warnings][0u][jss::id].asInt() == - warnRPC_AMENDMENT_BLOCKED); + si[jss::info][jss::warnings][0u][jss::id].asInt() == warnRPC_AMENDMENT_BLOCKED); // RPC request server_state again, now AB should be returned si = env.rpc("server_state")[jss::result]; + BEAST_EXPECT(si[jss::state].isMember(jss::amendment_blocked) && si[jss::state][jss::amendment_blocked] == true); BEAST_EXPECT( - si[jss::state].isMember(jss::amendment_blocked) && - si[jss::state][jss::amendment_blocked] == true); - BEAST_EXPECT( - si[jss::state].isMember(jss::warnings) && - si[jss::state][jss::warnings].isArray() && + si[jss::state].isMember(jss::warnings) && si[jss::state][jss::warnings].isArray() && si[jss::state][jss::warnings].size() == 1 && - si[jss::state][jss::warnings][0u][jss::id].asInt() == - warnRPC_AMENDMENT_BLOCKED); + si[jss::state][jss::warnings][0u][jss::id].asInt() == warnRPC_AMENDMENT_BLOCKED); // but status does not indicate because it still relies on ELB // being enabled - doRequest( - yield, - makeHTTPRequest(*ip_ws, *port_ws, "", {}), - *ip_ws, - *port_ws, - false, - resp, - ec); + doRequest(yield, makeHTTPRequest(*ip_ws, *port_ws, "", {}), *ip_ws, *port_ws, false, resp, ec); if (!BEAST_EXPECTS(!ec, ec.message())) return; BEAST_EXPECT(resp.result() == boost::beast::http::status::ok); - BEAST_EXPECT( - resp.body().find("connectivity is working.") != std::string::npos); + BEAST_EXPECT(resp.body().find("connectivity is working.") != std::string::npos); env.app().config().ELB_SUPPORT = true; - doRequest( - yield, - makeHTTPRequest(*ip_ws, *port_ws, "", {}), - *ip_ws, - *port_ws, - false, - resp, - ec); + doRequest(yield, makeHTTPRequest(*ip_ws, *port_ws, "", {}), *ip_ws, *port_ws, false, resp, ec); if (!BEAST_EXPECTS(!ec, ec.message())) return; - BEAST_EXPECT( - resp.result() == boost::beast::http::status::internal_server_error); - BEAST_EXPECT( - resp.body().find("cannot accept clients:") != std::string::npos); - BEAST_EXPECT( - resp.body().find("Server version too old") != std::string::npos); + BEAST_EXPECT(resp.result() == boost::beast::http::status::internal_server_error); + BEAST_EXPECT(resp.body().find("cannot accept clients:") != std::string::npos); + BEAST_EXPECT(resp.body().find("Server version too old") != std::string::npos); } void @@ -1054,8 +890,7 @@ class ServerStatus_test : public beast::unit_test::suite, { boost::beast::http::response resp; doHTTPRequest(env, yield, false, resp, ec, "{}"); - BEAST_EXPECT( - resp.result() == boost::beast::http::status::bad_request); + BEAST_EXPECT(resp.result() == boost::beast::http::status::bad_request); BEAST_EXPECT(resp.body() == "Unable to parse request: \r\n"); } @@ -1064,8 +899,7 @@ class ServerStatus_test : public beast::unit_test::suite, Json::Value jv; jv["invalid"] = 1; doHTTPRequest(env, yield, false, resp, ec, to_string(jv)); - BEAST_EXPECT( - resp.result() == boost::beast::http::status::bad_request); + BEAST_EXPECT(resp.result() == boost::beast::http::status::bad_request); BEAST_EXPECT(resp.body() == "Null method\r\n"); } @@ -1074,8 +908,7 @@ class ServerStatus_test : public beast::unit_test::suite, Json::Value jv(Json::arrayValue); jv.append("invalid"); doHTTPRequest(env, yield, false, resp, ec, to_string(jv)); - BEAST_EXPECT( - resp.result() == boost::beast::http::status::bad_request); + BEAST_EXPECT(resp.result() == boost::beast::http::status::bad_request); BEAST_EXPECT(resp.body() == "Unable to parse request: \r\n"); } @@ -1086,8 +919,7 @@ class ServerStatus_test : public beast::unit_test::suite, j["invalid"] = 1; jv.append(j); doHTTPRequest(env, yield, false, resp, ec, to_string(jv)); - BEAST_EXPECT( - resp.result() == boost::beast::http::status::bad_request); + BEAST_EXPECT(resp.result() == boost::beast::http::status::bad_request); BEAST_EXPECT(resp.body() == "Unable to parse request: \r\n"); } @@ -1097,8 +929,7 @@ class ServerStatus_test : public beast::unit_test::suite, jv[jss::method] = "batch"; jv[jss::params] = 2; doHTTPRequest(env, yield, false, resp, ec, to_string(jv)); - BEAST_EXPECT( - resp.result() == boost::beast::http::status::bad_request); + BEAST_EXPECT(resp.result() == boost::beast::http::status::bad_request); BEAST_EXPECT(resp.body() == "Malformed batch request\r\n"); } @@ -1109,8 +940,7 @@ class ServerStatus_test : public beast::unit_test::suite, jv[jss::params] = Json::objectValue; jv[jss::params]["invalid"] = 3; doHTTPRequest(env, yield, false, resp, ec, to_string(jv)); - BEAST_EXPECT( - resp.result() == boost::beast::http::status::bad_request); + BEAST_EXPECT(resp.result() == boost::beast::http::status::bad_request); BEAST_EXPECT(resp.body() == "Malformed batch request\r\n"); } @@ -1119,8 +949,7 @@ class ServerStatus_test : public beast::unit_test::suite, boost::beast::http::response resp; jv[jss::method] = Json::nullValue; doHTTPRequest(env, yield, false, resp, ec, to_string(jv)); - BEAST_EXPECT( - resp.result() == boost::beast::http::status::bad_request); + BEAST_EXPECT(resp.result() == boost::beast::http::status::bad_request); BEAST_EXPECT(resp.body() == "Null method\r\n"); } @@ -1128,8 +957,7 @@ class ServerStatus_test : public beast::unit_test::suite, boost::beast::http::response resp; jv[jss::method] = 1; doHTTPRequest(env, yield, false, resp, ec, to_string(jv)); - BEAST_EXPECT( - resp.result() == boost::beast::http::status::bad_request); + BEAST_EXPECT(resp.result() == boost::beast::http::status::bad_request); BEAST_EXPECT(resp.body() == "method is not string\r\n"); } @@ -1137,8 +965,7 @@ class ServerStatus_test : public beast::unit_test::suite, boost::beast::http::response resp; jv[jss::method] = ""; doHTTPRequest(env, yield, false, resp, ec, to_string(jv)); - BEAST_EXPECT( - resp.result() == boost::beast::http::status::bad_request); + BEAST_EXPECT(resp.result() == boost::beast::http::status::bad_request); BEAST_EXPECT(resp.body() == "method is empty\r\n"); } @@ -1147,8 +974,7 @@ class ServerStatus_test : public beast::unit_test::suite, jv[jss::method] = "some_method"; jv[jss::params] = "params"; doHTTPRequest(env, yield, false, resp, ec, to_string(jv)); - BEAST_EXPECT( - resp.result() == boost::beast::http::status::bad_request); + BEAST_EXPECT(resp.result() == boost::beast::http::status::bad_request); BEAST_EXPECT(resp.body() == "params unparsable\r\n"); } @@ -1157,8 +983,7 @@ class ServerStatus_test : public beast::unit_test::suite, jv[jss::params] = Json::arrayValue; jv[jss::params][0u] = "not an object"; doHTTPRequest(env, yield, false, resp, ec, to_string(jv)); - BEAST_EXPECT( - resp.result() == boost::beast::http::status::bad_request); + BEAST_EXPECT(resp.result() == boost::beast::http::status::bad_request); BEAST_EXPECT(resp.body() == "params unparsable\r\n"); } } @@ -1180,8 +1005,7 @@ class ServerStatus_test : public beast::unit_test::suite, boost::beast::http::response resp; boost::system::error_code ec; doHTTPRequest(env, yield, false, resp, ec); - BEAST_EXPECT( - resp.result() == boost::beast::http::status::internal_server_error); + BEAST_EXPECT(resp.result() == boost::beast::http::status::internal_server_error); std::regex body{"Server cannot accept clients"}; BEAST_EXPECT(std::regex_search(resp.body(), body)); } diff --git a/src/test/server/Server_test.cpp b/src/test/server/Server_test.cpp index 2a4bb49d34..7347bf238c 100644 --- a/src/test/server/Server_test.cpp +++ b/src/test/server/Server_test.cpp @@ -35,9 +35,7 @@ public: { private: boost::asio::io_context io_context_; - std::optional> - work_; + std::optional> work_; std::thread thread_; public: @@ -67,14 +65,12 @@ public: beast::unit_test::suite& suite_; public: - explicit TestSink(beast::unit_test::suite& suite) - : Sink(beast::severities::kWarning, false), suite_(suite) + explicit TestSink(beast::unit_test::suite& suite) : Sink(beast::severities::kWarning, false), suite_(suite) { } void - write(beast::severities::Severity level, std::string const& text) - override + write(beast::severities::Severity level, std::string const& text) override { if (level < threshold()) return; @@ -83,8 +79,7 @@ public: } void - writeAlways(beast::severities::Severity level, std::string const& text) - override + writeAlways(beast::severities::Severity level, std::string const& text) override { suite_.log << text << std::endl; } @@ -111,10 +106,7 @@ public: } Handoff - onHandoff( - Session& session, - http_request_type&& request, - boost::asio::ip::tcp::endpoint remote_address) + onHandoff(Session& session, http_request_type&& request, boost::asio::ip::tcp::endpoint remote_address) { return Handoff{}; } @@ -130,9 +122,7 @@ public: } void - onWSMessage( - std::shared_ptr session, - std::vector const&) + onWSMessage(std::shared_ptr session, std::vector const&) { } @@ -199,8 +189,7 @@ public: { std::string got; got.resize(n); - boost::asio::buffer_copy( - boost::asio::buffer(&got[0], n), b.data()); + boost::asio::buffer_copy(boost::asio::buffer(&got[0], n), b.data()); return BEAST_EXPECT(got == match); } } @@ -286,9 +275,7 @@ public: TestHandler handler; auto s = make_Server(handler, thread.get_io_context(), journal); std::vector serverPort(1); - serverPort.back().ip = - boost::asio::ip::make_address(getEnvLocalhostAddr()), - serverPort.back().port = 0; + serverPort.back().ip = boost::asio::ip::make_address(getEnvLocalhostAddr()), serverPort.back().port = 0; serverPort.back().protocol.insert("http"); auto eps = s->ports(serverPort); test_request(eps.begin()->second); @@ -321,10 +308,7 @@ public: } Handoff - onHandoff( - Session& session, - http_request_type&& request, - boost::asio::ip::tcp::endpoint remote_address) + onHandoff(Session& session, http_request_type&& request, boost::asio::ip::tcp::endpoint remote_address) { return Handoff{}; } @@ -335,9 +319,7 @@ public: } void - onWSMessage( - std::shared_ptr session, - std::vector const& buffers) + onWSMessage(std::shared_ptr session, std::vector const& buffers) { } @@ -361,9 +343,7 @@ public: TestThread thread; auto s = make_Server(h, thread.get_io_context(), journal); std::vector serverPort(1); - serverPort.back().ip = - boost::asio::ip::make_address(getEnvLocalhostAddr()), - serverPort.back().port = 0; + serverPort.back().ip = boost::asio::ip::make_address(getEnvLocalhostAddr()), serverPort.back().port = 0; serverPort.back().protocol.insert("http"); s->ports(serverPort); } @@ -387,8 +367,7 @@ public: }), std::make_unique(&messages)}; }); - BEAST_EXPECT( - messages.find("Missing 'ip' in [port_rpc]") != std::string::npos); + BEAST_EXPECT(messages.find("Missing 'ip' in [port_rpc]") != std::string::npos); except([&] { Env env{ @@ -400,8 +379,7 @@ public: }), std::make_unique(&messages)}; }); - BEAST_EXPECT( - messages.find("Missing 'port' in [port_rpc]") != std::string::npos); + BEAST_EXPECT(messages.find("Missing 'port' in [port_rpc]") != std::string::npos); except([&] { Env env{ @@ -414,9 +392,7 @@ public: }), std::make_unique(&messages)}; }); - BEAST_EXPECT( - messages.find("Invalid value '0' for key 'port' in [port_rpc]") == - std::string::npos); + BEAST_EXPECT(messages.find("Invalid value '0' for key 'port' in [port_rpc]") == std::string::npos); except([&] { Env env{ @@ -427,9 +403,7 @@ public: }), std::make_unique(&messages)}; }); - BEAST_EXPECT( - messages.find("Invalid value '0' for key 'port' in [server]") != - std::string::npos); + BEAST_EXPECT(messages.find("Invalid value '0' for key 'port' in [server]") != std::string::npos); except([&] { Env env{ @@ -443,44 +417,36 @@ public: }), std::make_unique(&messages)}; }); - BEAST_EXPECT( - messages.find("Missing 'protocol' in [port_rpc]") != - std::string::npos); + BEAST_EXPECT(messages.find("Missing 'protocol' in [port_rpc]") != std::string::npos); - except( - [&] // this creates a standard test config without the server - // section - { - Env env{ - *this, - envconfig([](std::unique_ptr cfg) { - cfg = std::make_unique(); - cfg->overwrite( - ConfigSection::nodeDatabase(), "type", "memory"); - cfg->overwrite( - ConfigSection::nodeDatabase(), "path", "main"); - cfg->deprecatedClearSection( - ConfigSection::importNodeDatabase()); - cfg->legacy("database_path", ""); - cfg->setupControl(true, true, true); - (*cfg)["port_peer"].set("ip", getEnvLocalhostAddr()); - (*cfg)["port_peer"].set("port", "8080"); - (*cfg)["port_peer"].set("protocol", "peer"); - (*cfg)["port_rpc"].set("ip", getEnvLocalhostAddr()); - (*cfg)["port_rpc"].set("port", "8081"); - (*cfg)["port_rpc"].set("protocol", "http,ws2"); - (*cfg)["port_rpc"].set("admin", getEnvLocalhostAddr()); - (*cfg)["port_ws"].set("ip", getEnvLocalhostAddr()); - (*cfg)["port_ws"].set("port", "8082"); - (*cfg)["port_ws"].set("protocol", "ws"); - (*cfg)["port_ws"].set("admin", getEnvLocalhostAddr()); - return cfg; - }), - std::make_unique(&messages)}; - }); - BEAST_EXPECT( - messages.find("Required section [server] is missing") != - std::string::npos); + except([&] // this creates a standard test config without the server + // section + { + Env env{ + *this, + envconfig([](std::unique_ptr cfg) { + cfg = std::make_unique(); + cfg->overwrite(ConfigSection::nodeDatabase(), "type", "memory"); + cfg->overwrite(ConfigSection::nodeDatabase(), "path", "main"); + cfg->deprecatedClearSection(ConfigSection::importNodeDatabase()); + cfg->legacy("database_path", ""); + cfg->setupControl(true, true, true); + (*cfg)["port_peer"].set("ip", getEnvLocalhostAddr()); + (*cfg)["port_peer"].set("port", "8080"); + (*cfg)["port_peer"].set("protocol", "peer"); + (*cfg)["port_rpc"].set("ip", getEnvLocalhostAddr()); + (*cfg)["port_rpc"].set("port", "8081"); + (*cfg)["port_rpc"].set("protocol", "http,ws2"); + (*cfg)["port_rpc"].set("admin", getEnvLocalhostAddr()); + (*cfg)["port_ws"].set("ip", getEnvLocalhostAddr()); + (*cfg)["port_ws"].set("port", "8082"); + (*cfg)["port_ws"].set("protocol", "ws"); + (*cfg)["port_ws"].set("admin", getEnvLocalhostAddr()); + return cfg; + }), + std::make_unique(&messages)}; + }); + BEAST_EXPECT(messages.find("Required section [server] is missing") != std::string::npos); except([&] // this creates a standard test config without some of the // port sections @@ -489,12 +455,9 @@ public: *this, envconfig([](std::unique_ptr cfg) { cfg = std::make_unique(); - cfg->overwrite( - ConfigSection::nodeDatabase(), "type", "memory"); - cfg->overwrite( - ConfigSection::nodeDatabase(), "path", "main"); - cfg->deprecatedClearSection( - ConfigSection::importNodeDatabase()); + cfg->overwrite(ConfigSection::nodeDatabase(), "type", "memory"); + cfg->overwrite(ConfigSection::nodeDatabase(), "path", "main"); + cfg->deprecatedClearSection(ConfigSection::importNodeDatabase()); cfg->legacy("database_path", ""); cfg->setupControl(true, true, true); (*cfg)["server"].append("port_peer"); @@ -504,8 +467,7 @@ public: }), std::make_unique(&messages)}; }); - BEAST_EXPECT( - messages.find("Missing section: [port_peer]") != std::string::npos); + BEAST_EXPECT(messages.find("Missing section: [port_peer]") != std::string::npos); } void diff --git a/src/test/shamap/FetchPack_test.cpp b/src/test/shamap/FetchPack_test.cpp index dc51616015..8919241996 100644 --- a/src/test/shamap/FetchPack_test.cpp +++ b/src/test/shamap/FetchPack_test.cpp @@ -36,8 +36,7 @@ public: struct TestFilter : SHAMapSyncFilter { - TestFilter(Map& map, beast::Journal journal) - : mMap(map), mJournal(journal) + TestFilter(Map& map, beast::Journal journal) : mMap(map), mJournal(journal) { } @@ -81,8 +80,7 @@ public: { while (n--) { - auto const result(t.addItem( - SHAMapNodeType::tnACCOUNT_STATE, make_random_item(r))); + auto const result(t.addItem(SHAMapNodeType::tnACCOUNT_STATE, make_random_item(r))); assert(result); (void)result; } diff --git a/src/test/shamap/SHAMapSync_test.cpp b/src/test/shamap/SHAMapSync_test.cpp index 912768e618..1add7a629e 100644 --- a/src/test/shamap/SHAMapSync_test.cpp +++ b/src/test/shamap/SHAMapSync_test.cpp @@ -57,8 +57,7 @@ public: if (beforeHash != map.getHash()) { - log << "Hashes do not match " << beforeHash << " " << map.getHash() - << std::endl; + log << "Hashes do not match " << beforeHash << " " << map.getHash() << std::endl; return false; } @@ -106,16 +105,11 @@ public: { std::vector> a; - BEAST_EXPECT(source.getNodeFat( - SHAMapNodeID(), a, rand_bool(eng_), rand_int(eng_, 2))); + BEAST_EXPECT(source.getNodeFat(SHAMapNodeID(), a, rand_bool(eng_), rand_int(eng_, 2))); unexpected(a.size() < 1, "NodeSize"); - BEAST_EXPECT( - destination - .addRootNode( - source.getHash(), makeSlice(a[0].second), nullptr) - .isGood()); + BEAST_EXPECT(destination.addRootNode(source.getHash(), makeSlice(a[0].second), nullptr).isGood()); } do @@ -136,8 +130,7 @@ public: // Don't use BEAST_EXPECT here b/c it will be called a // non-deterministic number of times and the number of tests run // should be deterministic - if (!source.getNodeFat( - it.first, b, rand_bool(eng_), rand_int(eng_, 2))) + if (!source.getNodeFat(it.first, b, rand_bool(eng_), rand_int(eng_, 2))) fail("", __FILE__, __LINE__); } @@ -152,10 +145,7 @@ public: // Don't use BEAST_EXPECT here b/c it will be called a // non-deterministic number of times and the number of tests run // should be deterministic - if (!destination - .addKnownNode( - b[i].first, makeSlice(b[i].second), nullptr) - .isUseful()) + if (!destination.addKnownNode(b[i].first, makeSlice(b[i].second), nullptr).isUseful()) fail("", __FILE__, __LINE__); } } while (true); diff --git a/src/test/shamap/SHAMap_test.cpp b/src/test/shamap/SHAMap_test.cpp index ade7a692f8..c91cc63749 100644 --- a/src/test/shamap/SHAMap_test.cpp +++ b/src/test/shamap/SHAMap_test.cpp @@ -117,16 +117,11 @@ public: tests::TestNodeFamily f(journal); // h3 and h4 differ only in the leaf, same terminal node (level 19) - constexpr uint256 h1( - "092891fe4ef6cee585fdc6fda0e09eb4d386363158ec3321b8123e5a772c6ca7"); - constexpr uint256 h2( - "436ccbac3347baa1f1e53baeef1f43334da88f1f6d70d963b833afd6dfa289fe"); - constexpr uint256 h3( - "b92891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e5a772c6ca8"); - constexpr uint256 h4( - "b92891fe4ef6cee585fdc6fda2e09eb4d386363158ec3321b8123e5a772c6ca8"); - constexpr uint256 h5( - "a92891fe4ef6cee585fdc6fda0e09eb4d386363158ec3321b8123e5a772c6ca7"); + constexpr uint256 h1("092891fe4ef6cee585fdc6fda0e09eb4d386363158ec3321b8123e5a772c6ca7"); + constexpr uint256 h2("436ccbac3347baa1f1e53baeef1f43334da88f1f6d70d963b833afd6dfa289fe"); + constexpr uint256 h3("b92891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e5a772c6ca8"); + constexpr uint256 h4("b92891fe4ef6cee585fdc6fda2e09eb4d386363158ec3321b8123e5a772c6ca8"); + constexpr uint256 h5("a92891fe4ef6cee585fdc6fda0e09eb4d386363158ec3321b8123e5a772c6ca7"); SHAMap sMap(SHAMapType::FREE, f); sMap.invariants(); @@ -139,15 +134,9 @@ public: auto i4 = make_shamapitem(h4, IntToVUC(4)); auto i5 = make_shamapitem(h5, IntToVUC(5)); - unexpected( - !sMap.addItem( - SHAMapNodeType::tnTRANSACTION_NM, make_shamapitem(*i2)), - "no add"); + unexpected(!sMap.addItem(SHAMapNodeType::tnTRANSACTION_NM, make_shamapitem(*i2)), "no add"); sMap.invariants(); - unexpected( - !sMap.addItem( - SHAMapNodeType::tnTRANSACTION_NM, make_shamapitem(*i1)), - "no add"); + unexpected(!sMap.addItem(SHAMapNodeType::tnTRANSACTION_NM, make_shamapitem(*i1)), "no add"); sMap.invariants(); auto i = sMap.begin(); @@ -249,9 +238,7 @@ public: BEAST_EXPECT(map.getHash() == beast::zero); for (int k = 0; k < keys.size(); ++k) { - BEAST_EXPECT(map.addItem( - SHAMapNodeType::tnTRANSACTION_NM, - make_shamapitem(keys[k], IntToVUC(k)))); + BEAST_EXPECT(map.addItem(SHAMapNodeType::tnTRANSACTION_NM, make_shamapitem(keys[k], IntToVUC(k)))); BEAST_EXPECT(map.getHash().as_uint256() == hashes[k]); map.invariants(); } @@ -294,9 +281,7 @@ public: map.setUnbacked(); for (auto const& k : keys) { - map.addItem( - SHAMapNodeType::tnTRANSACTION_NM, - make_shamapitem(k, IntToVUC(0))); + map.addItem(SHAMapNodeType::tnTRANSACTION_NM, make_shamapitem(k, IntToVUC(0))); map.invariants(); } @@ -328,9 +313,7 @@ class SHAMapPathProof_test : public beast::unit_test::suite for (unsigned char c = 1; c < 100; ++c) { uint256 k(c); - map.addItem( - SHAMapNodeType::tnACCOUNT_STATE, - make_shamapitem(k, Slice{k.data(), k.size()})); + map.addItem(SHAMapNodeType::tnACCOUNT_STATE, make_shamapitem(k, Slice{k.data(), k.size()})); map.invariants(); auto root = map.getHash().as_uint256(); diff --git a/src/test/shamap/common.h b/src/test/shamap/common.h index add2c79243..fe2a1884da 100644 --- a/src/test/shamap/common.h +++ b/src/test/shamap/common.h @@ -1,5 +1,4 @@ -#ifndef XRPL_SHAMAP_TESTS_COMMON_H_INCLUDED -#define XRPL_SHAMAP_TESTS_COMMON_H_INCLUDED +#pragma once #include #include @@ -24,23 +23,15 @@ private: public: TestNodeFamily(beast::Journal j) - : fbCache_(std::make_shared( - "App family full below cache", - clock_, - j)) - , tnCache_(std::make_shared( - "App family tree node cache", - 65536, - std::chrono::minutes{1}, - clock_, - j)) + : fbCache_(std::make_shared("App family full below cache", clock_, j)) + , tnCache_( + std::make_shared("App family tree node cache", 65536, std::chrono::minutes{1}, clock_, j)) , j_(j) { Section testSection; testSection.set("type", "memory"); testSection.set("path", "SHAMap_test"); - db_ = NodeStore::Manager::instance().make_Database( - megabytes(4), scheduler_, 1, testSection, j); + db_ = NodeStore::Manager::instance().make_Database(megabytes(4), scheduler_, 1, testSection, j); } NodeStore::Database& @@ -81,15 +72,13 @@ public: } void - missingNodeAcquireBySeq(std::uint32_t refNum, uint256 const& nodeHash) - override + missingNodeAcquireBySeq(std::uint32_t refNum, uint256 const& nodeHash) override { Throw("missing node"); } void - missingNodeAcquireByHash(uint256 const& refHash, std::uint32_t refNum) - override + missingNodeAcquireByHash(uint256 const& refHash, std::uint32_t refNum) override { Throw("missing node"); } @@ -110,5 +99,3 @@ public: } // namespace tests } // namespace xrpl - -#endif diff --git a/src/test/unit_test/FileDirGuard.h b/src/test/unit_test/FileDirGuard.h index 94ca5948bd..cf2eab7adb 100644 --- a/src/test/unit_test/FileDirGuard.h +++ b/src/test/unit_test/FileDirGuard.h @@ -1,5 +1,4 @@ -#ifndef TEST_UNIT_TEST_DIRGUARD_H -#define TEST_UNIT_TEST_DIRGUARD_H +#pragma once #include @@ -33,8 +32,7 @@ protected: if (is_directory(toRm) && is_empty(toRm)) remove(toRm); else - test_.log << "Expected " << toRm.string() - << " to be an empty existing directory." << std::endl; + test_.log << "Expected " << toRm.string() << " to be an empty existing directory." << std::endl; } public: @@ -57,8 +55,7 @@ public: { // Cannot run the test. Someone created a file where we want to // put our directory - Throw( - "Cannot create directory: " + subDir_.string()); + Throw("Cannot create directory: " + subDir_.string()); } } @@ -102,8 +99,7 @@ public: std::string const& contents, bool useCounter = true, bool create = true) - : DirGuard(test, subDir, useCounter) - , file_(file.is_absolute() ? file : subdir() / file) + : DirGuard(test, subDir, useCounter), file_(file.is_absolute() ? file : subdir() / file) { if (!exists(file_)) { @@ -116,8 +112,7 @@ public: } else { - Throw( - "Refusing to overwrite existing file: " + file_.string()); + Throw("Refusing to overwrite existing file: " + file_.string()); } } @@ -133,8 +128,7 @@ public: else { if (created_) - test_.log << "Expected " << file_.string() - << " to be an existing file." << std::endl; + test_.log << "Expected " << file_.string() << " to be an existing file." << std::endl; } } catch (std::exception& e) @@ -159,5 +153,3 @@ public: } // namespace detail } // namespace xrpl - -#endif // TEST_UNIT_TEST_DIRGUARD_H diff --git a/src/test/unit_test/SuiteJournal.h b/src/test/unit_test/SuiteJournal.h index d64be9ea9b..ad5f298b74 100644 --- a/src/test/unit_test/SuiteJournal.h +++ b/src/test/unit_test/SuiteJournal.h @@ -1,5 +1,4 @@ -#ifndef TEST_UNIT_TEST_SUITE_JOURNAL_H -#define TEST_UNIT_TEST_SUITE_JOURNAL_H +#pragma once #include #include @@ -33,14 +32,11 @@ public: write(beast::severities::Severity level, std::string const& text) override; void - writeAlways(beast::severities::Severity level, std::string const& text) - override; + writeAlways(beast::severities::Severity level, std::string const& text) override; }; inline void -SuiteJournalSink::write( - beast::severities::Severity level, - std::string const& text) +SuiteJournalSink::write(beast::severities::Severity level, std::string const& text) { // Only write the string if the level at least equals the threshold. if (level >= threshold()) @@ -48,9 +44,7 @@ SuiteJournalSink::write( } inline void -SuiteJournalSink::writeAlways( - beast::severities::Severity level, - std::string const& text) +SuiteJournalSink::writeAlways(beast::severities::Severity level, std::string const& text) { using namespace beast::severities; @@ -111,9 +105,7 @@ class StreamSink : public beast::Journal::Sink std::stringstream strm_; public: - StreamSink( - beast::severities::Severity threshold = beast::severities::kDebug) - : Sink(threshold, false) + StreamSink(beast::severities::Severity threshold = beast::severities::kDebug) : Sink(threshold, false) { } @@ -126,8 +118,7 @@ public: } inline void - writeAlways(beast::severities::Severity level, std::string const& text) - override + writeAlways(beast::severities::Severity level, std::string const& text) override { strm_ << text << std::endl; } @@ -141,5 +132,3 @@ public: } // namespace test } // namespace xrpl - -#endif diff --git a/src/test/unit_test/multi_runner.cpp b/src/test/unit_test/multi_runner.cpp index 4b1a82cd3f..eefd0c8250 100644 --- a/src/test/unit_test/multi_runner.cpp +++ b/src/test/unit_test/multi_runner.cpp @@ -49,10 +49,7 @@ results::add(suite_results const& r) if (elapsed >= std::chrono::seconds{1}) { auto const iter = std::lower_bound( - top.begin(), - top.end(), - elapsed, - [](run_time const& t1, typename clock_type::duration const& t2) { + top.begin(), top.end(), elapsed, [](run_time const& t1, typename clock_type::duration const& t2) { return t1.second > t2; }); @@ -61,25 +58,18 @@ results::add(suite_results const& r) if (top.size() == max_top && iter == top.end() - 1) { // avoid invalidating the iterator - *iter = run_time{ - static_string{static_string::string_view_type{r.name}}, - elapsed}; + *iter = run_time{static_string{static_string::string_view_type{r.name}}, elapsed}; } else { if (top.size() == max_top) top.resize(top.size() - 1); - top.emplace( - iter, - static_string{static_string::string_view_type{r.name}}, - elapsed); + top.emplace(iter, static_string{static_string::string_view_type{r.name}}, elapsed); } } else if (top.size() < max_top) { - top.emplace_back( - static_string{static_string::string_view_type{r.name}}, - elapsed); + top.emplace_back(static_string{static_string::string_view_type{r.name}}, elapsed); } } } @@ -101,9 +91,7 @@ results::merge(results const& r) r.top.begin(), r.top.end(), top_result.begin(), - [](run_time const& t1, run_time const& t2) { - return t1.second > t2.second; - }); + [](run_time const& t1, run_time const& t2) { return t1.second > t2.second; }); if (top_result.size() > max_top) top_result.resize(max_top); @@ -125,9 +113,8 @@ results::print(S& s) } auto const elapsed = clock_type::now() - start; - s << fmtdur(elapsed) << ", " << amount{suites, "suite"} << ", " - << amount{cases, "case"} << ", " << amount{total, "test"} << " total, " - << amount{failed, "failure"} << std::endl; + s << fmtdur(elapsed) << ", " << amount{suites, "suite"} << ", " << amount{cases, "case"} << ", " + << amount{total, "test"} << " total, " << amount{failed, "failure"} << std::endl; } //------------------------------------------------------------------------------ @@ -220,32 +207,26 @@ multi_runner_base::multi_runner_base() } shared_mem_ = boost::interprocess::shared_memory_object{ - std::conditional_t< - IsParent, - boost::interprocess::create_only_t, - boost::interprocess::open_only_t>{}, + std::conditional_t{}, shared_mem_name_, boost::interprocess::read_write}; if (IsParent) { shared_mem_.truncate(sizeof(inner)); - message_queue_ = - std::make_unique( - boost::interprocess::create_only, - message_queue_name_, - /*max messages*/ 16, - /*max message size*/ 1 << 20); + message_queue_ = std::make_unique( + boost::interprocess::create_only, + message_queue_name_, + /*max messages*/ 16, + /*max message size*/ 1 << 20); } else { - message_queue_ = - std::make_unique( - boost::interprocess::open_only, message_queue_name_); + message_queue_ = std::make_unique( + boost::interprocess::open_only, message_queue_name_); } - region_ = boost::interprocess::mapped_region{ - shared_mem_, boost::interprocess::read_write}; + region_ = boost::interprocess::mapped_region{shared_mem_, boost::interprocess::read_write}; if (IsParent) inner_ = new (region_.get_address()) inner{}; else @@ -332,9 +313,7 @@ multi_runner_base::print_results(S& s) template void -multi_runner_base::message_queue_send( - MessageType mt, - std::string const& s) +multi_runner_base::message_queue_send(MessageType mt, std::string const& s) { // must use a mutex since the two "sends" must happen in order std::lock_guard l{inner_->m_}; @@ -376,8 +355,7 @@ multi_runner_parent::multi_runner_parent() : os_(std::cout) { message_queue_thread_ = std::thread([this] { std::vector buf(1 << 20); - while (this->continue_message_queue_ || - this->message_queue_->get_num_msg()) + while (this->continue_message_queue_ || this->message_queue_->get_num_msg()) { // let children know the parent is still alive this->inc_keep_alive_count(); @@ -394,15 +372,13 @@ multi_runner_parent::multi_runner_parent() : os_(std::cout) { std::size_t recvd_size = 0; unsigned int priority = 0; - this->message_queue_->receive( - buf.data(), buf.size(), recvd_size, priority); + this->message_queue_->receive(buf.data(), buf.size(), recvd_size, priority); if (!recvd_size) continue; assert(recvd_size == 1); MessageType mt{*reinterpret_cast(buf.data())}; - this->message_queue_->receive( - buf.data(), buf.size(), recvd_size, priority); + this->message_queue_->receive(buf.data(), buf.size(), recvd_size, priority); if (recvd_size) { std::string s{buf.data(), recvd_size}; @@ -425,8 +401,7 @@ multi_runner_parent::multi_runner_parent() : os_(std::cout) } catch (std::exception const& e) { - std::cerr << "Error: " << e.what() - << " reading unit test message queue.\n"; + std::cerr << "Error: " << e.what() << " reading unit test message queue.\n"; return; } catch (...) @@ -451,8 +426,7 @@ multi_runner_parent::~multi_runner_parent() for (auto const& s : running_suites_) { - os_ << "\nSuite: " << s - << " failed to complete. The child process may have crashed.\n"; + os_ << "\nSuite: " << s << " failed to complete. The child process may have crashed.\n"; } } @@ -482,14 +456,8 @@ multi_runner_parent::add_failures(std::size_t failures) //------------------------------------------------------------------------------ -multi_runner_child::multi_runner_child( - std::size_t num_jobs, - bool quiet, - bool print_log) - : job_index_{checkout_job_index()} - , num_jobs_{num_jobs} - , quiet_{quiet} - , print_log_{!quiet || print_log} +multi_runner_child::multi_runner_child(std::size_t num_jobs, bool quiet, bool print_log) + : job_index_{checkout_job_index()}, num_jobs_{num_jobs}, quiet_{quiet}, print_log_{!quiet || print_log} { if (num_jobs_ > 1) { @@ -510,8 +478,7 @@ multi_runner_child::multi_runner_child( if (cur_count == last_count) { // assume parent process is no longer alive - std::cerr << "multi_runner_child " << job_index_ - << ": Assuming parent died, exiting.\n"; + std::cerr << "multi_runner_child " << job_index_ << ": Assuming parent died, exiting.\n"; std::exit(EXIT_FAILURE); } } @@ -566,8 +533,7 @@ multi_runner_child::on_suite_end() std::stringstream s; if (num_jobs_ > 1) s << job_index_ << "> "; - s << (suite_results_.failed > 0 ? "failed: " : "") - << suite_results_.name << " had " << suite_results_.failed + s << (suite_results_.failed > 0 ? "failed: " : "") << suite_results_.name << " had " << suite_results_.failed << " failures." << std::endl; message_queue_send(MessageType::log, s.str()); } @@ -586,8 +552,7 @@ multi_runner_child::on_case_begin(std::string const& name) std::stringstream s; if (num_jobs_ > 1) s << job_index_ << "> "; - s << suite_results_.name - << (case_results_.name.empty() ? "" : (" " + case_results_.name)) << '\n'; + s << suite_results_.name << (case_results_.name.empty() ? "" : (" " + case_results_.name)) << '\n'; message_queue_send(MessageType::log, s.str()); } @@ -611,8 +576,7 @@ multi_runner_child::on_fail(std::string const& reason) std::stringstream s; if (num_jobs_ > 1) s << job_index_ << "> "; - s << "#" << case_results_.total << " failed" << (reason.empty() ? "" : ": ") - << reason << '\n'; + s << "#" << case_results_.total << " failed" << (reason.empty() ? "" : ": ") << reason << '\n'; message_queue_send(MessageType::log, s.str()); } diff --git a/src/test/unit_test/multi_runner.h b/src/test/unit_test/multi_runner.h index 813af61572..28ecaf85f9 100644 --- a/src/test/unit_test/multi_runner.h +++ b/src/test/unit_test/multi_runner.h @@ -1,5 +1,4 @@ -#ifndef TEST_UNIT_TEST_MULTI_RUNNER_H -#define TEST_UNIT_TEST_MULTI_RUNNER_H +#pragma once #include #include @@ -135,8 +134,7 @@ class multi_runner_base static constexpr char const* shared_mem_name_ = "RippledUnitTestSharedMem"; // name of the message queue a multi_runner_child will use to communicate // with multi_runner_parent - static constexpr char const* message_queue_name_ = - "RippledUnitTestMessageQueue"; + static constexpr char const* message_queue_name_ = "RippledUnitTestMessageQueue"; // `inner_` will be created in shared memory inner* inner_; @@ -233,8 +231,7 @@ public: /** A class to run a subset of unit tests */ -class multi_runner_child : public beast::unit_test::runner, - private detail::multi_runner_base +class multi_runner_child : public beast::unit_test::runner, private detail::multi_runner_base { private: std::size_t job_index_; @@ -336,5 +333,3 @@ multi_runner_child::run_multi(Pred pred) } // namespace test } // namespace xrpl - -#endif diff --git a/src/tests/libxrpl/CMakeLists.txt b/src/tests/libxrpl/CMakeLists.txt index 74dc184700..cfa056b0aa 100644 --- a/src/tests/libxrpl/CMakeLists.txt +++ b/src/tests/libxrpl/CMakeLists.txt @@ -6,9 +6,15 @@ find_package(GTest REQUIRED) # Custom target for all tests defined in this file add_custom_target(xrpl.tests) +# Test helpers +add_library(xrpl.helpers.test STATIC) +target_sources(xrpl.helpers.test PRIVATE helpers/TestSink.cpp) +target_include_directories(xrpl.helpers.test PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) +target_link_libraries(xrpl.helpers.test PRIVATE xrpl.libxrpl) + # Common library dependencies for the rest of the tests. add_library(xrpl.imports.test INTERFACE) -target_link_libraries(xrpl.imports.test INTERFACE gtest::gtest xrpl.libxrpl) +target_link_libraries(xrpl.imports.test INTERFACE gtest::gtest xrpl.libxrpl xrpl.helpers.test) # One test for each module. xrpl_add_test(basics) @@ -24,8 +30,8 @@ target_link_libraries(xrpl.test.json PRIVATE xrpl.imports.test) add_dependencies(xrpl.tests xrpl.test.json) # Network unit tests are currently not supported on Windows -if(NOT WIN32) - xrpl_add_test(net) - target_link_libraries(xrpl.test.net PRIVATE xrpl.imports.test) - add_dependencies(xrpl.tests xrpl.test.net) -endif() +if (NOT WIN32) + xrpl_add_test(net) + target_link_libraries(xrpl.test.net PRIVATE xrpl.imports.test) + add_dependencies(xrpl.tests xrpl.test.net) +endif () diff --git a/src/tests/libxrpl/basics/Slice.cpp b/src/tests/libxrpl/basics/Slice.cpp index b36abe596d..4373f98168 100644 --- a/src/tests/libxrpl/basics/Slice.cpp +++ b/src/tests/libxrpl/basics/Slice.cpp @@ -7,10 +7,9 @@ using namespace xrpl; -static std::uint8_t const data[] = { - 0xa8, 0xa1, 0x38, 0x45, 0x23, 0xec, 0xe4, 0x23, 0x71, 0x6d, 0x2a, - 0x18, 0xb4, 0x70, 0xcb, 0xf5, 0xac, 0x2d, 0x89, 0x4d, 0x19, 0x9c, - 0xf0, 0x2c, 0x15, 0xd1, 0xf9, 0x9b, 0x66, 0xd2, 0x30, 0xd3}; +static std::uint8_t const data[] = {0xa8, 0xa1, 0x38, 0x45, 0x23, 0xec, 0xe4, 0x23, 0x71, 0x6d, 0x2a, + 0x18, 0xb4, 0x70, 0xcb, 0xf5, 0xac, 0x2d, 0x89, 0x4d, 0x19, 0x9c, + 0xf0, 0x2c, 0x15, 0xd1, 0xf9, 0x9b, 0x66, 0xd2, 0x30, 0xd3}; TEST(Slice, equality_and_inequality) { diff --git a/src/tests/libxrpl/basics/tagged_integer.cpp b/src/tests/libxrpl/basics/tagged_integer.cpp index 09f8b6787b..e24b299442 100644 --- a/src/tests/libxrpl/basics/tagged_integer.cpp +++ b/src/tests/libxrpl/basics/tagged_integer.cpp @@ -53,25 +53,15 @@ static_assert( !std::is_assignable::value, "TagUInt3 should not be assignable with a std::uint64_t"); -static_assert( - std::is_assignable::value, - "TagUInt1 should be assignable with a TagUInt1"); +static_assert(std::is_assignable::value, "TagUInt1 should be assignable with a TagUInt1"); -static_assert( - !std::is_assignable::value, - "TagUInt1 should not be assignable with a TagUInt2"); +static_assert(!std::is_assignable::value, "TagUInt1 should not be assignable with a TagUInt2"); -static_assert( - std::is_assignable::value, - "TagUInt3 should be assignable with a TagUInt1"); +static_assert(std::is_assignable::value, "TagUInt3 should be assignable with a TagUInt1"); -static_assert( - !std::is_assignable::value, - "TagUInt1 should not be assignable with a TagUInt3"); +static_assert(!std::is_assignable::value, "TagUInt1 should not be assignable with a TagUInt3"); -static_assert( - !std::is_assignable::value, - "TagUInt3 should not be assignable with a TagUInt1"); +static_assert(!std::is_assignable::value, "TagUInt3 should not be assignable with a TagUInt1"); // Check convertibility of tagged_integers static_assert( @@ -90,17 +80,11 @@ static_assert( !std::is_convertible::value, "std::uint64_t should not be convertible to a TagUInt2"); -static_assert( - !std::is_convertible::value, - "TagUInt1 should not be convertible to TagUInt2"); +static_assert(!std::is_convertible::value, "TagUInt1 should not be convertible to TagUInt2"); -static_assert( - !std::is_convertible::value, - "TagUInt1 should not be convertible to TagUInt3"); +static_assert(!std::is_convertible::value, "TagUInt1 should not be convertible to TagUInt3"); -static_assert( - !std::is_convertible::value, - "TagUInt2 should not be convertible to a TagUInt3"); +static_assert(!std::is_convertible::value, "TagUInt2 should not be convertible to a TagUInt3"); using TagInt = tagged_integer; diff --git a/src/tests/libxrpl/helpers/TestSink.cpp b/src/tests/libxrpl/helpers/TestSink.cpp new file mode 100644 index 0000000000..17cc110429 --- /dev/null +++ b/src/tests/libxrpl/helpers/TestSink.cpp @@ -0,0 +1,124 @@ +#include + +#include + +#include // for getenv + +#if BOOST_OS_WINDOWS +#include // for _isatty, _fileno +#include // for stdout +#else +#include // for isatty, STDOUT_FILENO +#endif + +#include + +namespace xrpl { + +TestSink::TestSink(beast::severities::Severity threshold) : Sink(threshold, false) +{ +} + +void +TestSink::write(beast::severities::Severity level, std::string const& text) +{ + if (level < threshold()) + return; + writeAlways(level, text); +} + +void +TestSink::writeAlways(beast::severities::Severity level, std::string const& text) +{ + auto supportsColor = [] { + // 1. Check for "NO_COLOR" environment variable (Standard convention) + if (std::getenv("NO_COLOR") != nullptr) + { + return false; + } + + // 2. Check for "CLICOLOR_FORCE" (Force color) + if (std::getenv("CLICOLOR_FORCE") != nullptr) + { + return true; + } + + // 3. Platform-specific check to see if stdout is a terminal +#if BOOST_OS_WINDOWS + // Windows: Check if the output handle is a character device + // _fileno(stdout) is usually 1 + // _isatty returns non-zero if the handle is a character device, 0 + // otherwise. + return _isatty(_fileno(stdout)) != 0; +#else + // Linux/macOS: Check if file descriptor 1 (stdout) is a TTY + // STDOUT_FILENO is 1 + // isatty returns 1 if the file descriptor is a TTY, 0 otherwise. + return isatty(STDOUT_FILENO) != 0; +#endif + }(); + + auto color = [level]() { + switch (level) + { + case beast::severities::kTrace: + return "\033[34m"; // blue + case beast::severities::kDebug: + return "\033[32m"; // green + case beast::severities::kInfo: + return "\033[36m"; // cyan + case beast::severities::kWarning: + return "\033[33m"; // yellow + case beast::severities::kError: + return "\033[31m"; // red + case beast::severities::kFatal: + default: + break; + } + return "\033[31m"; // red + }(); + + auto prefix = [level]() { + switch (level) + { + case beast::severities::kTrace: + return "TRC:"; + case beast::severities::kDebug: + return "DBG:"; + case beast::severities::kInfo: + return "INF:"; + case beast::severities::kWarning: + return "WRN:"; + case beast::severities::kError: + return "ERR:"; + case beast::severities::kFatal: + default: + break; + } + return "FTL:"; + }(); + + auto& stream = [level]() -> std::ostream& { + switch (level) + { + case beast::severities::kError: + case beast::severities::kFatal: + return std::cerr; + default: + return std::cout; + } + }(); + + constexpr auto reset = "\033[0m"; + + if (supportsColor) + { + stream << color << prefix << " " << text << reset << std::endl; + } + else + { + stream << prefix << " " << text << std::endl; + } +} + +} // namespace xrpl diff --git a/src/tests/libxrpl/helpers/TestSink.h b/src/tests/libxrpl/helpers/TestSink.h new file mode 100644 index 0000000000..daa40d014f --- /dev/null +++ b/src/tests/libxrpl/helpers/TestSink.h @@ -0,0 +1,24 @@ +#pragma once + +#include + +namespace xrpl { +class TestSink : public beast::Journal::Sink +{ +public: + static TestSink& + instance() + { + static TestSink sink{}; + return sink; + } + + TestSink(beast::severities::Severity threshold = beast::severities::kDebug); + + void + write(beast::severities::Severity level, std::string const& text) override; + + void + writeAlways(beast::severities::Severity level, std::string const& text) override; +}; +} // namespace xrpl diff --git a/src/tests/libxrpl/json/Value.cpp b/src/tests/libxrpl/json/Value.cpp index 4db1274a4d..1d1131b209 100644 --- a/src/tests/libxrpl/json/Value.cpp +++ b/src/tests/libxrpl/json/Value.cpp @@ -32,8 +32,7 @@ TEST(json_value, construct_and_compare_Json_StaticString) EXPECT_EQ(addrTest1, &sample[0]); EXPECT_EQ(test1.c_str(), &sample[0]); - static constexpr Json::StaticString test2{ - "Contents of a Json::StaticString"}; + static constexpr Json::StaticString test2{"Contents of a Json::StaticString"}; static constexpr Json::StaticString test3{"Another StaticString"}; EXPECT_EQ(test1, test2); @@ -202,11 +201,7 @@ TEST(json_value, different_types) TEST(json_value, compare_strings) { - auto doCompare = [&](Json::Value const& lhs, - Json::Value const& rhs, - bool lhsEqRhs, - bool lhsLtRhs, - int line) { + auto doCompare = [&](Json::Value const& lhs, Json::Value const& rhs, bool lhsEqRhs, bool lhsLtRhs, int line) { SCOPED_TRACE(line); EXPECT_EQ((lhs == rhs), lhsEqRhs); EXPECT_NE((lhs != rhs), lhsEqRhs); @@ -615,8 +610,7 @@ TEST(json_value, edge_cases) EXPECT_EQ(j1["max_int"].asInt(), max_int); EXPECT_EQ(j1["max_int"].asAbsUInt(), max_int); EXPECT_EQ(j1["min_int"].asInt(), min_int); - EXPECT_EQ( - j1["min_int"].asAbsUInt(), static_cast(min_int) * -1); + EXPECT_EQ(j1["min_int"].asAbsUInt(), static_cast(min_int) * -1); EXPECT_EQ(j1["a_uint"].asUInt(), a_uint); EXPECT_EQ(j1["a_uint"].asAbsUInt(), a_uint); EXPECT_GT(j1["a_uint"], a_large_int); @@ -626,9 +620,7 @@ TEST(json_value, edge_cases) EXPECT_EQ(j1["a_large_int"].asUInt(), a_large_int); EXPECT_LT(j1["a_large_int"], a_uint); EXPECT_EQ(j1["a_small_int"].asInt(), a_small_int); - EXPECT_EQ( - j1["a_small_int"].asAbsUInt(), - static_cast(a_small_int) * -1); + EXPECT_EQ(j1["a_small_int"].asAbsUInt(), static_cast(a_small_int) * -1); EXPECT_LT(j1["a_small_int"], a_uint); } @@ -839,9 +831,7 @@ TEST(json_value, compact) char const* s("{\"array\":[{\"12\":23},{},null,false,0.5]}"); auto countLines = [](std::string const& str) { - return 1 + std::count_if(str.begin(), str.end(), [](char c) { - return c == '\n'; - }); + return 1 + std::count_if(str.begin(), str.end(), [](char c) { return c == '\n'; }); }; EXPECT_TRUE(r.parse(s, j)); diff --git a/src/tests/libxrpl/json/Writer.cpp b/src/tests/libxrpl/json/Writer.cpp index 7016b4322d..54c3221858 100644 --- a/src/tests/libxrpl/json/Writer.cpp +++ b/src/tests/libxrpl/json/Writer.cpp @@ -156,8 +156,7 @@ TEST_F(WriterFixture, complex_object) writer->startSet(Writer::array, "subarray"); writer->append(23.5); writer->finishAll(); - checkOutputAndReset( - R"({"hello":"world","array":[true,12,[{"goodbye":"cruel world.","subarray":[23.5]}]]})"); + checkOutputAndReset(R"({"hello":"world","array":[true,12,[{"goodbye":"cruel world.","subarray":[23.5]}]]})"); } TEST_F(WriterFixture, json_value) diff --git a/src/tests/libxrpl/net/HTTPClient.cpp b/src/tests/libxrpl/net/HTTPClient.cpp index cfd206edde..72a351f9b7 100644 --- a/src/tests/libxrpl/net/HTTPClient.cpp +++ b/src/tests/libxrpl/net/HTTPClient.cpp @@ -2,15 +2,22 @@ #include #include +#include +#include #include +#include +#include #include #include #include #include +#include #include #include +#include +#include #include using namespace xrpl; @@ -24,16 +31,19 @@ private: boost::asio::io_context ioc_; boost::asio::ip::tcp::acceptor acceptor_; boost::asio::ip::tcp::endpoint endpoint_; - std::atomic running_{true}; + bool running_{true}; + bool finished_{false}; unsigned short port_; // Custom headers to return - std::map custom_headers_; - std::string response_body_; - unsigned int status_code_{200}; + std::map customHeaders_; + std::string responseBody_; + unsigned int statusCode_{200}; + + beast::Journal j_; public: - TestHTTPServer() : acceptor_(ioc_), port_(0) + TestHTTPServer() : acceptor_(ioc_), port_(0), j_(TestSink::instance()) { // Bind to any available port endpoint_ = {boost::asio::ip::tcp::v4(), 0}; @@ -45,12 +55,17 @@ public: // Get the actual port that was assigned port_ = acceptor_.local_endpoint().port(); - accept(); + // Start the accept coroutine + boost::asio::co_spawn(ioc_, accept(), boost::asio::detached); } + TestHTTPServer(TestHTTPServer&&) = delete; + TestHTTPServer& + operator=(TestHTTPServer&&) = delete; + ~TestHTTPServer() { - stop(); + XRPL_ASSERT(finished(), "xrpl::TestHTTPServer::~TestHTTPServer : accept future ready"); } boost::asio::io_context& @@ -68,22 +83,21 @@ public: void setHeader(std::string const& name, std::string const& value) { - custom_headers_[name] = value; + customHeaders_[name] = value; } void setResponseBody(std::string const& body) { - response_body_ = body; + responseBody_ = body; } void setStatusCode(unsigned int code) { - status_code_ = code; + statusCode_ = code; } -private: void stop() { @@ -91,78 +105,80 @@ private: acceptor_.close(); } - void - accept() + bool + finished() const { - if (!running_) - return; - - acceptor_.async_accept( - ioc_, - endpoint_, - [&](boost::system::error_code const& error, - boost::asio::ip::tcp::socket peer) { - if (!running_) - return; - - if (!error) - { - handleConnection(std::move(peer)); - } - }); + return finished_; } - void +private: + boost::asio::awaitable + accept() + { + while (running_) + { + try + { + auto socket = co_await acceptor_.async_accept(boost::asio::use_awaitable); + + if (!running_) + break; + + // Handle this connection + co_await handleConnection(std::move(socket)); + } + catch (std::exception const& e) + { + // Accept or handle failed, stop accepting + JLOG(j_.debug()) << "Error: " << e.what(); + break; + } + } + + finished_ = true; + } + + boost::asio::awaitable handleConnection(boost::asio::ip::tcp::socket socket) { try { - // Read the HTTP request boost::beast::flat_buffer buffer; boost::beast::http::request req; - boost::beast::http::read(socket, buffer, req); + + // Read the HTTP request asynchronously + co_await boost::beast::http::async_read(socket, buffer, req, boost::asio::use_awaitable); // Create response boost::beast::http::response res; res.version(req.version()); - res.result(status_code_); + res.result(statusCode_); res.set(boost::beast::http::field::server, "TestServer"); - // Add custom headers - for (auto const& [name, value] : custom_headers_) + // Set body and prepare payload first + res.body() = responseBody_; + res.prepare_payload(); + + // Override Content-Length with custom headers after + // prepare_payload. This allows us to test case-insensitive + // header parsing. + for (auto const& [name, value] : customHeaders_) { res.set(name, value); } - // Set body and prepare payload first - res.body() = response_body_; - res.prepare_payload(); - - // Override Content-Length with custom headers after prepare_payload - // This allows us to test case-insensitive header parsing - for (auto const& [name, value] : custom_headers_) - { - if (boost::iequals(name, "Content-Length")) - { - res.erase(boost::beast::http::field::content_length); - res.set(name, value); - } - } - - // Send response - boost::beast::http::write(socket, res); + // Send response asynchronously + co_await boost::beast::http::async_write(socket, res, boost::asio::use_awaitable); // Shutdown socket gracefully - boost::system::error_code ec; - socket.shutdown(boost::asio::ip::tcp::socket::shutdown_send, ec); + boost::system::error_code shutdownEc; + socket.shutdown(boost::asio::ip::tcp::socket::shutdown_send, shutdownEc); } - catch (std::exception const&) + catch (std::exception const& e) { - // Connection handling errors are expected + // Error reading or writing, just close the connection + JLOG(j_.debug()) << "Connection error: " << e.what(); } - - if (running_) - accept(); } }; @@ -171,13 +187,13 @@ bool runHTTPTest( TestHTTPServer& server, std::string const& path, - std::atomic& completed, - std::atomic& result_status, - std::string& result_data, - boost::system::error_code& result_error) + bool& completed, + int& resultStatus, + std::string& resultData, + boost::system::error_code& resultError) { // Create a null journal for testing - beast::Journal j{beast::Journal::getNullSink()}; + beast::Journal j{TestSink::instance()}; // Initialize HTTPClient SSL context HTTPClient::initializeSSLContext("", "", false, j); @@ -190,12 +206,10 @@ runHTTPTest( path, 1024, // max response size std::chrono::seconds(5), - [&](boost::system::error_code const& ec, - int status, - std::string const& data) -> bool { - result_error = ec; - result_status = status; - result_data = data; + [&](boost::system::error_code const& ec, int status, std::string const& data) -> bool { + resultError = ec; + resultStatus = status; + resultData = data; completed = true; return false; // don't retry }, @@ -203,13 +217,17 @@ runHTTPTest( // Run the IO context until completion auto start = std::chrono::steady_clock::now(); - while (!completed && - std::chrono::steady_clock::now() - start < std::chrono::seconds(10)) + while (server.ioc().run_one() != 0) { - if (server.ioc().run_one() == 0) + if (std::chrono::steady_clock::now() - start >= std::chrono::seconds(10) || server.finished()) { break; } + + if (completed) + { + server.stop(); + } } return completed; @@ -220,7 +238,7 @@ runHTTPTest( TEST(HTTPClient, case_insensitive_content_length) { // Test different cases of Content-Length header - std::vector header_cases = { + std::vector headerCases = { "Content-Length", // Standard case "content-length", // Lowercase - this tests the regex icase fix "CONTENT-LENGTH", // Uppercase @@ -228,53 +246,46 @@ TEST(HTTPClient, case_insensitive_content_length) "content-Length" // Mixed case 2 }; - for (auto const& header_name : header_cases) + for (auto const& headerName : headerCases) { TestHTTPServer server; - std::string test_body = "Hello World!"; - server.setResponseBody(test_body); - server.setHeader(header_name, std::to_string(test_body.size())); + std::string testBody = "Hello World!"; + server.setResponseBody(testBody); + server.setHeader(headerName, std::to_string(testBody.size())); - std::atomic completed{false}; - std::atomic result_status{0}; - std::string result_data; - boost::system::error_code result_error; + bool completed{false}; + int resultStatus{0}; + std::string resultData; + boost::system::error_code resultError; - bool test_completed = runHTTPTest( - server, - "/test", - completed, - result_status, - result_data, - result_error); + bool testCompleted = runHTTPTest(server, "/test", completed, resultStatus, resultData, resultError); // Verify results - EXPECT_TRUE(test_completed); - EXPECT_FALSE(result_error); - EXPECT_EQ(result_status, 200); - EXPECT_EQ(result_data, test_body); + EXPECT_TRUE(testCompleted); + EXPECT_FALSE(resultError); + EXPECT_EQ(resultStatus, 200); + EXPECT_EQ(resultData, testBody); } } TEST(HTTPClient, basic_http_request) { TestHTTPServer server; - std::string test_body = "Test response body"; - server.setResponseBody(test_body); + std::string testBody = "Test response body"; + server.setResponseBody(testBody); server.setHeader("Content-Type", "text/plain"); - std::atomic completed{false}; - std::atomic result_status{0}; - std::string result_data; - boost::system::error_code result_error; + bool completed{false}; + int resultStatus{0}; + std::string resultData; + boost::system::error_code resultError; - bool test_completed = runHTTPTest( - server, "/basic", completed, result_status, result_data, result_error); + bool testCompleted = runHTTPTest(server, "/basic", completed, resultStatus, resultData, resultError); - EXPECT_TRUE(test_completed); - EXPECT_FALSE(result_error); - EXPECT_EQ(result_status, 200); - EXPECT_EQ(result_data, test_body); + EXPECT_TRUE(testCompleted); + EXPECT_FALSE(resultError); + EXPECT_EQ(resultStatus, 200); + EXPECT_EQ(resultData, testBody); } TEST(HTTPClient, empty_response) @@ -283,45 +294,38 @@ TEST(HTTPClient, empty_response) server.setResponseBody(""); // Empty body server.setHeader("Content-Length", "0"); - std::atomic completed{false}; - std::atomic result_status{0}; - std::string result_data; - boost::system::error_code result_error; + bool completed{false}; + int resultStatus{0}; + std::string resultData; + boost::system::error_code resultError; - bool test_completed = runHTTPTest( - server, "/empty", completed, result_status, result_data, result_error); + bool testCompleted = runHTTPTest(server, "/empty", completed, resultStatus, resultData, resultError); - EXPECT_TRUE(test_completed); - EXPECT_FALSE(result_error); - EXPECT_EQ(result_status, 200); - EXPECT_TRUE(result_data.empty()); + EXPECT_TRUE(testCompleted); + EXPECT_FALSE(resultError); + EXPECT_EQ(resultStatus, 200); + EXPECT_TRUE(resultData.empty()); } TEST(HTTPClient, different_status_codes) { - std::vector status_codes = {200, 404, 500}; + std::vector statusCodes = {200, 404, 500}; - for (auto status : status_codes) + for (auto status : statusCodes) { TestHTTPServer server; server.setStatusCode(status); server.setResponseBody("Status " + std::to_string(status)); - std::atomic completed{false}; - std::atomic result_status{0}; - std::string result_data; - boost::system::error_code result_error; + bool completed{false}; + int resultStatus{0}; + std::string resultData; + boost::system::error_code resultError; - bool test_completed = runHTTPTest( - server, - "/status", - completed, - result_status, - result_data, - result_error); + bool testCompleted = runHTTPTest(server, "/status", completed, resultStatus, resultData, resultError); - EXPECT_TRUE(test_completed); - EXPECT_FALSE(result_error); - EXPECT_EQ(result_status, static_cast(status)); + EXPECT_TRUE(testCompleted); + EXPECT_FALSE(resultError); + EXPECT_EQ(resultStatus, static_cast(status)); } } diff --git a/src/xrpld/app/consensus/RCLCensorshipDetector.h b/src/xrpld/app/consensus/RCLCensorshipDetector.h index 97d2743dc1..fbdc6c2397 100644 --- a/src/xrpld/app/consensus/RCLCensorshipDetector.h +++ b/src/xrpld/app/consensus/RCLCensorshipDetector.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_CONSENSUS_RCLCENSORSHIPDETECTOR_H_INCLUDED -#define XRPL_APP_CONSENSUS_RCLCENSORSHIPDETECTOR_H_INCLUDED +#pragma once #include #include @@ -19,8 +18,7 @@ public: TxID txid; Sequence seq; - TxIDSeq(TxID const& txid_, Sequence const& seq_) - : txid(txid_), seq(seq_) + TxIDSeq(TxID const& txid_, Sequence const& seq_) : txid(txid_), seq(seq_) { } }; @@ -123,5 +121,3 @@ public: }; } // namespace xrpl - -#endif diff --git a/src/xrpld/app/consensus/RCLConsensus.cpp b/src/xrpld/app/consensus/RCLConsensus.cpp index 99cc140056..ad581585b1 100644 --- a/src/xrpld/app/consensus/RCLConsensus.cpp +++ b/src/xrpld/app/consensus/RCLConsensus.cpp @@ -8,10 +8,8 @@ #include #include #include -#include #include #include -#include #include #include #include @@ -22,9 +20,11 @@ #include #include #include +#include #include #include #include +#include #include #include @@ -41,14 +41,7 @@ RCLConsensus::RCLConsensus( Consensus::clock_type const& clock, ValidatorKeys const& validatorKeys, beast::Journal journal) - : adaptor_( - app, - std::move(feeVote), - ledgerMaster, - localTxs, - inboundTransactions, - validatorKeys, - journal) + : adaptor_(app, std::move(feeVote), ledgerMaster, localTxs, inboundTransactions, validatorKeys, journal) , consensus_(clock, adaptor_, journal) , j_(journal) { @@ -69,36 +62,25 @@ RCLConsensus::Adaptor::Adaptor( , inboundTransactions_{inboundTransactions} , j_(journal) , validatorKeys_(validatorKeys) - , valCookie_( - 1 + - rand_int( - crypto_prng(), - std::numeric_limits::max() - 1)) + , valCookie_(1 + rand_int(crypto_prng(), std::numeric_limits::max() - 1)) , nUnlVote_(validatorKeys_.nodeID, j_) { - XRPL_ASSERT( - valCookie_, "xrpl::RCLConsensus::Adaptor::Adaptor : nonzero cookie"); + XRPL_ASSERT(valCookie_, "xrpl::RCLConsensus::Adaptor::Adaptor : nonzero cookie"); - JLOG(j_.info()) << "Consensus engine started (cookie: " + - std::to_string(valCookie_) + ")"; + JLOG(j_.info()) << "Consensus engine started (cookie: " + std::to_string(valCookie_) + ")"; if (validatorKeys_.nodeID != beast::zero && validatorKeys_.keys) { std::stringstream ss; JLOG(j_.info()) << "Validator identity: " - << toBase58( - TokenType::NodePublic, - validatorKeys_.keys->masterPublicKey); + << toBase58(TokenType::NodePublic, validatorKeys_.keys->masterPublicKey); - if (validatorKeys_.keys->masterPublicKey != - validatorKeys_.keys->publicKey) + if (validatorKeys_.keys->masterPublicKey != validatorKeys_.keys->publicKey) { - JLOG(j_.debug()) - << "Validator ephemeral signing key: " - << toBase58( - TokenType::NodePublic, validatorKeys_.keys->publicKey) - << " (seq: " << std::to_string(validatorKeys_.sequence) << ")"; + JLOG(j_.debug()) << "Validator ephemeral signing key: " + << toBase58(TokenType::NodePublic, validatorKeys_.keys->publicKey) + << " (seq: " << std::to_string(validatorKeys_.sequence) << ")"; } } } @@ -118,25 +100,17 @@ RCLConsensus::Adaptor::acquireLedger(LedgerHash const& hash) // Tell the ledger acquire system that we need the consensus ledger acquiringLedger_ = hash; - app_.getJobQueue().addJob( - jtADVANCE, - "getConsensusLedger1", - [id = hash, &app = app_, this]() { - JLOG(j_.debug()) - << "JOB advanceLedger getConsensusLedger1 started"; - app.getInboundLedgers().acquireAsync( - id, 0, InboundLedger::Reason::CONSENSUS); - }); + app_.getJobQueue().addJob(jtADVANCE, "GetConsL1", [id = hash, &app = app_, this]() { + JLOG(j_.debug()) << "JOB advanceLedger getConsensusLedger1 started"; + app.getInboundLedgers().acquireAsync(id, 0, InboundLedger::Reason::CONSENSUS); + }); } return std::nullopt; } XRPL_ASSERT( - !built->open() && built->isImmutable(), - "xrpl::RCLConsensus::Adaptor::acquireLedger : valid ledger state"); - XRPL_ASSERT( - built->header().hash == hash, - "xrpl::RCLConsensus::Adaptor::acquireLedger : ledger hash match"); + !built->open() && built->isImmutable(), "xrpl::RCLConsensus::Adaptor::acquireLedger : valid ledger state"); + XRPL_ASSERT(built->header().hash == hash, "xrpl::RCLConsensus::Adaptor::acquireLedger : ledger hash match"); // Notify inbound transactions of the new ledger sequence number inboundTransactions_.newRound(built->header().seq); @@ -154,10 +128,8 @@ RCLConsensus::Adaptor::share(RCLCxPeerPos const& peerPos) prop.set_proposeseq(proposal.proposeSeq()); prop.set_closetime(proposal.closeTime().time_since_epoch().count()); - prop.set_currenttxhash( - proposal.position().begin(), proposal.position().size()); - prop.set_previousledger( - proposal.prevLedger().begin(), proposal.position().size()); + prop.set_currenttxhash(proposal.position().begin(), proposal.position().size()); + prop.set_previousledger(proposal.prevLedger().begin(), proposal.position().size()); auto const pk = peerPos.publicKey().slice(); prop.set_nodepubkey(pk.data(), pk.size()); @@ -179,8 +151,7 @@ RCLConsensus::Adaptor::share(RCLCxTx const& tx) protocol::TMTransaction msg; msg.set_rawtransaction(slice.data(), slice.size()); msg.set_status(protocol::tsNEW); - msg.set_receivetimestamp( - app_.timeKeeper().now().time_since_epoch().count()); + msg.set_receivetimestamp(app_.timeKeeper().now().time_since_epoch().count()); static std::set skip{}; app_.overlay().relay(tx.id(), msg, skip); } @@ -193,15 +164,12 @@ void RCLConsensus::Adaptor::propose(RCLCxPeerPos::Proposal const& proposal) { JLOG(j_.trace()) << (proposal.isBowOut() ? "We bow out: " : "We propose: ") - << xrpl::to_string(proposal.prevLedger()) << " -> " - << xrpl::to_string(proposal.position()); + << xrpl::to_string(proposal.prevLedger()) << " -> " << xrpl::to_string(proposal.position()); protocol::TMProposeSet prop; - prop.set_currenttxhash( - proposal.position().begin(), proposal.position().size()); - prop.set_previousledger( - proposal.prevLedger().begin(), proposal.prevLedger().size()); + prop.set_currenttxhash(proposal.position().begin(), proposal.position().size()); + prop.set_previousledger(proposal.prevLedger().begin(), proposal.prevLedger().size()); prop.set_proposeseq(proposal.proposeSeq()); prop.set_closetime(proposal.closeTime().time_since_epoch().count()); @@ -216,18 +184,12 @@ RCLConsensus::Adaptor::propose(RCLCxPeerPos::Proposal const& proposal) prop.set_nodepubkey(keys.publicKey.data(), keys.publicKey.size()); - auto sig = - signDigest(keys.publicKey, keys.secretKey, proposal.signingHash()); + auto sig = signDigest(keys.publicKey, keys.secretKey, proposal.signingHash()); prop.set_signature(sig.data(), sig.size()); auto const suppression = proposalUniqueId( - proposal.position(), - proposal.prevLedger(), - proposal.proposeSeq(), - proposal.closeTime(), - keys.publicKey, - sig); + proposal.position(), proposal.prevLedger(), proposal.proposeSeq(), proposal.closeTime(), keys.publicKey, sig); app_.getHashRouter().addSuppression(suppression); @@ -263,25 +225,18 @@ RCLConsensus::Adaptor::proposersValidated(LedgerHash const& h) const } std::size_t -RCLConsensus::Adaptor::proposersFinished( - RCLCxLedger const& ledger, - LedgerHash const& h) const +RCLConsensus::Adaptor::proposersFinished(RCLCxLedger const& ledger, LedgerHash const& h) const { RCLValidations& vals = app_.getValidations(); - return vals.getNodesAfter( - RCLValidatedLedger(ledger.ledger_, vals.adaptor().journal()), h); + return vals.getNodesAfter(RCLValidatedLedger(ledger.ledger_, vals.adaptor().journal()), h); } uint256 -RCLConsensus::Adaptor::getPrevLedger( - uint256 ledgerID, - RCLCxLedger const& ledger, - ConsensusMode mode) +RCLConsensus::Adaptor::getPrevLedger(uint256 ledgerID, RCLCxLedger const& ledger, ConsensusMode mode) { RCLValidations& vals = app_.getValidations(); uint256 netLgr = vals.getPreferred( - RCLValidatedLedger{ledger.ledger_, vals.adaptor().journal()}, - ledgerMaster_.getValidLedgerIndex()); + RCLValidatedLedger{ledger.ledger_, vals.adaptor().journal()}, ledgerMaster_.getValidLedgerIndex()); if (netLgr != ledgerID) { @@ -295,10 +250,8 @@ RCLConsensus::Adaptor::getPrevLedger( } auto -RCLConsensus::Adaptor::onClose( - RCLCxLedger const& ledger, - NetClock::time_point const& closeTime, - ConsensusMode mode) -> Result +RCLConsensus::Adaptor::onClose(RCLCxLedger const& ledger, NetClock::time_point const& closeTime, ConsensusMode mode) + -> Result { bool const wrongLCL = mode == ConsensusMode::wrongLedger; bool const proposing = mode == ConsensusMode::proposing; @@ -313,20 +266,16 @@ RCLConsensus::Adaptor::onClose( auto initialLedger = app_.openLedger().current(); - auto initialSet = - std::make_shared(SHAMapType::TRANSACTION, app_.getNodeFamily()); + auto initialSet = std::make_shared(SHAMapType::TRANSACTION, app_.getNodeFamily()); initialSet->setUnbacked(); // Build SHAMap containing all transactions in our open ledger for (auto const& tx : initialLedger->txs) { - JLOG(j_.trace()) << "Adding open ledger TX " - << tx.first->getTransactionID(); + JLOG(j_.trace()) << "Adding open ledger TX " << tx.first->getTransactionID(); Serializer s(2048); tx.first->add(s); - initialSet->addItem( - SHAMapNodeType::tnTRANSACTION_NM, - make_shamapitem(tx.first->getTransactionID(), s.slice())); + initialSet->addItem(SHAMapNodeType::tnTRANSACTION_NM, make_shamapitem(tx.first->getTransactionID(), s.slice())); } // Add pseudo-transactions to the set @@ -337,13 +286,11 @@ RCLConsensus::Adaptor::onClose( // previous ledger was flag ledger, add fee and amendment // pseudo-transactions auto validations = app_.validators().negativeUNLFilter( - app_.getValidations().getTrustedForLedger( - prevLedger->header().parentHash, prevLedger->seq() - 1)); + app_.getValidations().getTrustedForLedger(prevLedger->header().parentHash, prevLedger->seq() - 1)); if (validations.size() >= app_.validators().quorum()) { feeVote_->doVoting(prevLedger, validations, initialSet); - app_.getAmendmentTable().doVoting( - prevLedger, validations, initialSet, j_); + app_.getAmendmentTable().doVoting(prevLedger, validations, initialSet, j_); } } else if (prevLedger->isVotingLedger()) @@ -351,11 +298,7 @@ RCLConsensus::Adaptor::onClose( // previous ledger was a voting ledger, // so the current consensus session is for a flag ledger, // add negative UNL pseudo-transactions - nUnlVote_.doVoting( - prevLedger, - app_.validators().getTrustedMasterKeys(), - app_.getValidations(), - initialSet); + nUnlVote_.doVoting(prevLedger, app_.validators().getTrustedMasterKeys(), app_.getValidations(), initialSet); } } @@ -367,11 +310,9 @@ RCLConsensus::Adaptor::onClose( LedgerIndex const seq = prevLedger->header().seq + 1; RCLCensorshipDetector::TxIDSeqVec proposed; - initialSet->visitLeaves( - [&proposed, - seq](boost::intrusive_ptr const& item) { - proposed.emplace_back(item->key(), seq); - }); + initialSet->visitLeaves([&proposed, seq](boost::intrusive_ptr const& item) { + proposed.emplace_back(item->key(), seq); + }); censorshipDetector_.propose(std::move(proposed)); } @@ -399,13 +340,7 @@ RCLConsensus::Adaptor::onForceAccept( ConsensusMode const& mode, Json::Value&& consensusJson) { - doAccept( - result, - prevLedger, - closeResolution, - rawCloseTimes, - mode, - std::move(consensusJson)); + doAccept(result, prevLedger, closeResolution, rawCloseTimes, mode, std::move(consensusJson)); } void @@ -418,25 +353,16 @@ RCLConsensus::Adaptor::onAccept( Json::Value&& consensusJson, bool const validating) { - app_.getJobQueue().addJob( - jtACCEPT, - "acceptLedger", - [=, this, cj = std::move(consensusJson)]() mutable { - // Note that no lock is held or acquired during this job. - // This is because generic Consensus guarantees that once a ledger - // is accepted, the consensus results and capture by reference state - // will not change until startRound is called (which happens via - // endConsensus). - RclConsensusLogger clog("onAccept", validating, j_); - this->doAccept( - result, - prevLedger, - closeResolution, - rawCloseTimes, - mode, - std::move(cj)); - this->app_.getOPs().endConsensus(clog.ss()); - }); + app_.getJobQueue().addJob(jtACCEPT, "AcceptLedger", [=, this, cj = std::move(consensusJson)]() mutable { + // Note that no lock is held or acquired during this job. + // This is because generic Consensus guarantees that once a ledger + // is accepted, the consensus results and capture by reference state + // will not change until startRound is called (which happens via + // endConsensus). + RclConsensusLogger clog("onAccept", validating, j_); + this->doAccept(result, prevLedger, closeResolution, rawCloseTimes, mode, std::move(cj)); + this->app_.getOPs().endConsensus(clog.ss()); + }); } void @@ -469,17 +395,13 @@ RCLConsensus::Adaptor::doAccept( else { // We agreed on a close time - consensusCloseTime = effCloseTime( - consensusCloseTime, closeResolution, prevLedger.closeTime()); + consensusCloseTime = effCloseTime(consensusCloseTime, closeResolution, prevLedger.closeTime()); closeTimeCorrect = true; } - JLOG(j_.debug()) << "Report: Prop=" << (proposing ? "yes" : "no") - << " val=" << (validating_ ? "yes" : "no") - << " corLCL=" << (haveCorrectLCL ? "yes" : "no") - << " fail=" << (consensusFail ? "yes" : "no"); - JLOG(j_.debug()) << "Report: Prev = " << prevLedger.id() << ":" - << prevLedger.seq(); + JLOG(j_.debug()) << "Report: Prop=" << (proposing ? "yes" : "no") << " val=" << (validating_ ? "yes" : "no") + << " corLCL=" << (haveCorrectLCL ? "yes" : "no") << " fail=" << (consensusFail ? "yes" : "no"); + JLOG(j_.debug()) << "Report: Prev = " << prevLedger.id() << ":" << prevLedger.seq(); //-------------------------------------------------------------------------- std::set failed; @@ -496,15 +418,13 @@ RCLConsensus::Adaptor::doAccept( { try { - retriableTxs.insert( - std::make_shared(SerialIter{item.slice()})); + retriableTxs.insert(std::make_shared(SerialIter{item.slice()})); JLOG(j_.debug()) << " Tx: " << item.key(); } catch (std::exception const& ex) { failed.insert(item.key()); - JLOG(j_.warn()) - << " Tx: " << item.key() << " throws: " << ex.what(); + JLOG(j_.warn()) << " Tx: " << item.key() << " throws: " << ex.what(); } } @@ -531,9 +451,7 @@ RCLConsensus::Adaptor::doAccept( std::vector accepted; result.txns.map_->visitLeaves( - [&accepted](boost::intrusive_ptr const& item) { - accepted.push_back(item->key()); - }); + [&accepted](boost::intrusive_ptr const& item) { accepted.push_back(item->key()); }); // Track all the transactions which failed or were marked as retriable for (auto const& r : retriableTxs) @@ -541,9 +459,7 @@ RCLConsensus::Adaptor::doAccept( censorshipDetector_.check( std::move(accepted), - [curr = built.seq(), - j = app_.journal("CensorshipDetector"), - &failed](uint256 const& id, LedgerIndex seq) { + [curr = built.seq(), j = app_.journal("CensorshipDetector"), &failed](uint256 const& id, LedgerIndex seq) { if (failed.count(id)) return true; @@ -552,8 +468,7 @@ RCLConsensus::Adaptor::doAccept( if (wait && (wait % censorshipWarnInternal == 0)) { std::ostringstream ss; - ss << "Potential Censorship: Eligible tx " << id - << ", which we are tracking since ledger " << seq + ss << "Potential Censorship: Eligible tx " << id << ", which we are tracking since ledger " << seq << " has not been included as of ledger " << curr << "."; JLOG(j.warn()) << ss.str(); @@ -564,11 +479,9 @@ RCLConsensus::Adaptor::doAccept( } if (validating_) - validating_ = ledgerMaster_.isCompatible( - *built.ledger_, j_.warn(), "Not validating"); + validating_ = ledgerMaster_.isCompatible(*built.ledger_, j_.warn(), "Not validating"); - if (validating_ && !consensusFail && - app_.getValidations().canValidateSeq(built.seq())) + if (validating_ && !consensusFail && app_.getValidations().canValidateSeq(built.seq())) { validate(built, result.txns, proposing); JLOG(j_.info()) << "CNF Val " << newLCLHash; @@ -577,8 +490,7 @@ RCLConsensus::Adaptor::doAccept( JLOG(j_.info()) << "CNF buildLCL " << newLCLHash; // See if we can accept a ledger as fully-validated - ledgerMaster_.consensusBuilt( - built.ledger_, result.txns.id(), std::move(consensusJson)); + ledgerMaster_.consensusBuilt(built.ledger_, result.txns.id(), std::move(consensusJson)); //------------------------------------------------------------------------- { @@ -602,9 +514,8 @@ RCLConsensus::Adaptor::doAccept( // we voted NO try { - JLOG(j_.debug()) - << "Test applying disputed transaction that did" - << " not get in " << dispute.tx().id(); + JLOG(j_.debug()) << "Test applying disputed transaction that did" + << " not get in " << dispute.tx().id(); SerialIter sit(dispute.tx().tx_->slice()); auto txn = std::make_shared(sit); @@ -674,26 +585,20 @@ RCLConsensus::Adaptor::doAccept( // we entered the round with the network, // see how close our close time is to other node's // close time reports, and update our clock. - if ((mode == ConsensusMode::proposing || - mode == ConsensusMode::observing) && - !consensusFail) + if ((mode == ConsensusMode::proposing || mode == ConsensusMode::observing) && !consensusFail) { auto closeTime = rawCloseTimes.self; - JLOG(j_.info()) << "We closed at " - << closeTime.time_since_epoch().count(); + JLOG(j_.info()) << "We closed at " << closeTime.time_since_epoch().count(); using usec64_t = std::chrono::duration; - usec64_t closeTotal = - std::chrono::duration_cast(closeTime.time_since_epoch()); + usec64_t closeTotal = std::chrono::duration_cast(closeTime.time_since_epoch()); int closeCount = 1; for (auto const& [t, v] : rawCloseTimes.peers) { - JLOG(j_.info()) << std::to_string(v) << " time votes for " - << std::to_string(t.time_since_epoch().count()); + JLOG(j_.info()) << std::to_string(v) << " time votes for " << std::to_string(t.time_since_epoch().count()); closeCount += v; - closeTotal += - std::chrono::duration_cast(t.time_since_epoch()) * v; + closeTotal += std::chrono::duration_cast(t.time_since_epoch()) * v; } closeTotal += usec64_t(closeCount / 2); // for round to nearest @@ -702,20 +607,15 @@ RCLConsensus::Adaptor::doAccept( // Use signed times since we are subtracting using duration = std::chrono::duration; using time_point = std::chrono::time_point; - auto offset = time_point{closeTotal} - - std::chrono::time_point_cast(closeTime); - JLOG(j_.info()) << "Our close offset is estimated at " << offset.count() - << " (" << closeCount << ")"; + auto offset = time_point{closeTotal} - std::chrono::time_point_cast(closeTime); + JLOG(j_.info()) << "Our close offset is estimated at " << offset.count() << " (" << closeCount << ")"; app_.timeKeeper().adjustCloseTime(offset); } } void -RCLConsensus::Adaptor::notify( - protocol::NodeEvent ne, - RCLCxLedger const& ledger, - bool haveCorrectLCL) +RCLConsensus::Adaptor::notify(protocol::NodeEvent ne, RCLCxLedger const& ledger, bool haveCorrectLCL) { protocol::TMStatusChange s; @@ -726,11 +626,8 @@ RCLConsensus::Adaptor::notify( s.set_ledgerseq(ledger.seq()); s.set_networktime(app_.timeKeeper().now().time_since_epoch().count()); - s.set_ledgerhashprevious( - ledger.parentID().begin(), - std::decay_t::bytes); - s.set_ledgerhash( - ledger.id().begin(), std::decay_t::bytes); + s.set_ledgerhashprevious(ledger.parentID().begin(), std::decay_t::bytes); + s.set_ledgerhash(ledger.id().begin(), std::decay_t::bytes); std::uint32_t uMin, uMax; if (!ledgerMaster_.getFullValidatedRange(uMin, uMax)) @@ -745,8 +642,7 @@ RCLConsensus::Adaptor::notify( } s.set_firstseq(uMin); s.set_lastseq(uMax); - app_.overlay().foreach( - send_always(std::make_shared(s, protocol::mtSTATUS_CHANGE))); + app_.overlay().foreach(send_always(std::make_shared(s, protocol::mtSTATUS_CHANGE))); JLOG(j_.trace()) << "send status change to peer"; } @@ -769,14 +665,7 @@ RCLConsensus::Adaptor::buildLCL( return buildLedger(*replayData, tapNONE, app_, j_); } return buildLedger( - previousLedger.ledger_, - closeTime, - closeTimeCorrect, - closeResolution, - app_, - retriableTxs, - failedTxs, - j_); + previousLedger.ledger_, closeTime, closeTimeCorrect, closeResolution, app_, retriableTxs, failedTxs, j_); }(); // Update fee computations based on accepted txs @@ -794,10 +683,7 @@ RCLConsensus::Adaptor::buildLCL( } void -RCLConsensus::Adaptor::validate( - RCLCxLedger const& ledger, - RCLTxSet const& txns, - bool proposing) +RCLConsensus::Adaptor::validate(RCLCxLedger const& ledger, RCLTxSet const& txns, bool proposing) { using namespace std::chrono_literals; @@ -816,11 +702,7 @@ RCLConsensus::Adaptor::validate( auto const& keys = *validatorKeys_.keys; auto v = std::make_shared( - lastValidationTime_, - keys.publicKey, - keys.secretKey, - validatorKeys_.nodeID, - [&](STValidation& v) { + lastValidationTime_, keys.publicKey, keys.secretKey, validatorKeys_.nodeID, [&](STValidation& v) { v.setFieldH256(sfLedgerHash, ledger.id()); v.setFieldH256(sfConsensusHash, txns.id()); @@ -854,18 +736,15 @@ RCLConsensus::Adaptor::validate( if (ledger.ledger_->isVotingLedger()) { // Fees: - feeVote_->doValidation( - ledger.ledger_->fees(), ledger.ledger_->rules(), v); + feeVote_->doValidation(ledger.ledger_->fees(), ledger.ledger_->rules(), v); // Amendments // FIXME: pass `v` and have the function insert the array // directly? - auto const amendments = app_.getAmendmentTable().doValidation( - getEnabledAmendments(*ledger.ledger_)); + auto const amendments = app_.getAmendmentTable().doValidation(getEnabledAmendments(*ledger.ledger_)); if (!amendments.empty()) - v.setFieldV256( - sfAmendments, STVector256(sfAmendments, amendments)); + v.setFieldV256(sfAmendments, STVector256(sfAmendments, amendments)); } }); @@ -888,14 +767,11 @@ RCLConsensus::Adaptor::validate( void RCLConsensus::Adaptor::onModeChange(ConsensusMode before, ConsensusMode after) { - JLOG(j_.info()) << "Consensus mode change before=" << to_string(before) - << ", after=" << to_string(after); + JLOG(j_.info()) << "Consensus mode change before=" << to_string(before) << ", after=" << to_string(after); // If we were proposing but aren't any longer, we need to reset the // censorship tracking to avoid bogus warnings. - if ((before == ConsensusMode::proposing || - before == ConsensusMode::observing) && - before != after) + if ((before == ConsensusMode::proposing || before == ConsensusMode::observing) && before != after) censorshipDetector_.reset(); mode_ = after; @@ -914,9 +790,7 @@ RCLConsensus::getJson(bool full) const } void -RCLConsensus::timerEntry( - NetClock::time_point const& now, - std::unique_ptr const& clog) +RCLConsensus::timerEntry(NetClock::time_point const& now, std::unique_ptr const& clog) { try { @@ -953,33 +827,25 @@ RCLConsensus::gotTxSet(NetClock::time_point const& now, RCLTxSet const& txSet) //! @see Consensus::simulate void -RCLConsensus::simulate( - NetClock::time_point const& now, - std::optional consensusDelay) +RCLConsensus::simulate(NetClock::time_point const& now, std::optional consensusDelay) { std::lock_guard _{mutex_}; consensus_.simulate(now, consensusDelay); } bool -RCLConsensus::peerProposal( - NetClock::time_point const& now, - RCLCxPeerPos const& newProposal) +RCLConsensus::peerProposal(NetClock::time_point const& now, RCLCxPeerPos const& newProposal) { std::lock_guard _{mutex_}; return consensus_.peerProposal(now, newProposal); } bool -RCLConsensus::Adaptor::preStartRound( - RCLCxLedger const& prevLgr, - hash_set const& nowTrusted) +RCLConsensus::Adaptor::preStartRound(RCLCxLedger const& prevLgr, hash_set const& nowTrusted) { // We have a key, we do not want out of sync validations after a restart // and are not amendment blocked. - validating_ = validatorKeys_.keys && - prevLgr.seq() >= app_.getMaxDisallowedLedger() && - !app_.getOPs().isBlocked(); + validating_ = validatorKeys_.keys && prevLgr.seq() >= app_.getMaxDisallowedLedger() && !app_.getOPs().isBlocked(); // If we are not running in standalone mode and there's a configured UNL, // check to make sure that it's not expired. @@ -999,14 +865,12 @@ RCLConsensus::Adaptor::preStartRound( if (validating_) { - JLOG(j_.info()) << "Entering consensus process, validating, synced=" - << (synced ? "yes" : "no"); + JLOG(j_.info()) << "Entering consensus process, validating, synced=" << (synced ? "yes" : "no"); } else { // Otherwise we just want to monitor the validation process. - JLOG(j_.info()) << "Entering consensus process, watching, synced=" - << (synced ? "yes" : "no"); + JLOG(j_.info()) << "Entering consensus process, watching, synced=" << (synced ? "yes" : "no"); } // Notify inbound ledgers that we are starting a new round @@ -1039,9 +903,7 @@ RCLConsensus::Adaptor::getQuorumKeys() const } std::size_t -RCLConsensus::Adaptor::laggards( - Ledger_t::Seq const seq, - hash_set& trustedKeys) const +RCLConsensus::Adaptor::laggards(Ledger_t::Seq const seq, hash_set& trustedKeys) const { return app_.getValidations().laggards(seq, trustedKeys); } @@ -1069,20 +931,10 @@ RCLConsensus::startRound( std::unique_ptr const& clog) { std::lock_guard _{mutex_}; - consensus_.startRound( - now, - prevLgrId, - prevLgr, - nowUntrusted, - adaptor_.preStartRound(prevLgr, nowTrusted), - clog); + consensus_.startRound(now, prevLgrId, prevLgr, nowUntrusted, adaptor_.preStartRound(prevLgr, nowTrusted), clog); } -RclConsensusLogger::RclConsensusLogger( - char const* label, - bool const validating, - beast::Journal j) - : j_(j) +RclConsensusLogger::RclConsensusLogger(char const* label, bool const validating, beast::Journal j) : j_(j) { if (!validating && !j.info()) return; @@ -1097,12 +949,11 @@ RclConsensusLogger::~RclConsensusLogger() { if (!ss_) return; - auto const duration = std::chrono::duration_cast( - std::chrono::steady_clock::now() - start_); + auto const duration = + std::chrono::duration_cast(std::chrono::steady_clock::now() - start_); std::stringstream outSs; - outSs << header_ << "duration " << (duration.count() / 1000) << '.' - << std::setw(3) << std::setfill('0') << (duration.count() % 1000) - << "s. " << ss_->str(); + outSs << header_ << "duration " << (duration.count() / 1000) << '.' << std::setw(3) << std::setfill('0') + << (duration.count() % 1000) << "s. " << ss_->str(); j_.sink().writeAlways(beast::severities::kInfo, outSs.str()); } diff --git a/src/xrpld/app/consensus/RCLConsensus.h b/src/xrpld/app/consensus/RCLConsensus.h index 2e33bbae14..3e1b27cd9c 100644 --- a/src/xrpld/app/consensus/RCLConsensus.h +++ b/src/xrpld/app/consensus/RCLConsensus.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_CONSENSUS_RCLCONSENSUS_H_INCLUDED -#define XRPL_APP_CONSENSUS_RCLCONSENSUS_H_INCLUDED +#pragma once #include #include @@ -63,8 +62,7 @@ class RCLConsensus // thread safety. std::atomic validating_{false}; std::atomic prevProposers_{0}; - std::atomic prevRoundTime_{ - std::chrono::milliseconds{0}}; + std::atomic prevRoundTime_{std::chrono::milliseconds{0}}; std::atomic mode_{ConsensusMode::observing}; RCLCensorshipDetector censorshipDetector_; @@ -119,9 +117,7 @@ class RCLConsensus @return Whether we enter the round proposing */ bool - preStartRound( - RCLCxLedger const& prevLedger, - hash_set const& nowTrusted); + preStartRound(RCLCxLedger const& prevLedger, hash_set const& nowTrusted); bool haveValidated() const; @@ -133,8 +129,7 @@ class RCLConsensus getQuorumKeys() const; std::size_t - laggards(Ledger_t::Seq const seq, hash_set& trustedKeys) - const; + laggards(Ledger_t::Seq const seq, hash_set& trustedKeys) const; /** Whether I am a validator. * @@ -262,10 +257,7 @@ class RCLConsensus the ledger matching ledgerID from the network */ uint256 - getPrevLedger( - uint256 ledgerID, - RCLCxLedger const& ledger, - ConsensusMode mode); + getPrevLedger(uint256 ledgerID, RCLCxLedger const& ledger, ConsensusMode mode); /** Notified of change in consensus mode @@ -283,10 +275,7 @@ class RCLConsensus @return Tentative consensus result */ Result - onClose( - RCLCxLedger const& ledger, - NetClock::time_point const& closeTime, - ConsensusMode mode); + onClose(RCLCxLedger const& ledger, NetClock::time_point const& closeTime, ConsensusMode mode); /** Process the accepted ledger. @@ -332,10 +321,7 @@ class RCLConsensus @param haveCorrectLCL Whether we believe we have the correct LCL. */ void - notify( - protocol::NodeEvent ne, - RCLCxLedger const& ledger, - bool haveCorrectLCL); + notify(protocol::NodeEvent ne, RCLCxLedger const& ledger, bool haveCorrectLCL); /** Accept a new ledger based on the given transactions. @@ -392,10 +378,7 @@ class RCLConsensus but are still around and trying to catch up. */ void - validate( - RCLCxLedger const& ledger, - RCLTxSet const& txns, - bool proposing); + validate(RCLCxLedger const& ledger, RCLTxSet const& txns, bool proposing); }; public: @@ -474,9 +457,7 @@ public: //! @see Consensus::timerEntry void - timerEntry( - NetClock::time_point const& now, - std::unique_ptr const& clog = {}); + timerEntry(NetClock::time_point const& now, std::unique_ptr const& clog = {}); //! @see Consensus::gotTxSet void @@ -492,15 +473,11 @@ public: //! @see Consensus::simulate void - simulate( - NetClock::time_point const& now, - std::optional consensusDelay); + simulate(NetClock::time_point const& now, std::optional consensusDelay); //! @see Consensus::proposal bool - peerProposal( - NetClock::time_point const& now, - RCLCxPeerPos const& newProposal); + peerProposal(NetClock::time_point const& now, RCLCxPeerPos const& newProposal); ConsensusParms const& parms() const @@ -536,10 +513,7 @@ class RclConsensusLogger std::chrono::steady_clock::time_point start_; public: - explicit RclConsensusLogger( - char const* label, - bool validating, - beast::Journal j); + explicit RclConsensusLogger(char const* label, bool validating, beast::Journal j); ~RclConsensusLogger(); std::unique_ptr const& @@ -549,5 +523,3 @@ public: } }; } // namespace xrpl - -#endif diff --git a/src/xrpld/app/consensus/RCLCxLedger.h b/src/xrpld/app/consensus/RCLCxLedger.h index 4413fee7fc..6b96fc8af3 100644 --- a/src/xrpld/app/consensus/RCLCxLedger.h +++ b/src/xrpld/app/consensus/RCLCxLedger.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_CONSENSUS_RCLCXLEDGER_H_INCLUDED -#define XRPL_APP_CONSENSUS_RCLCXLEDGER_H_INCLUDED +#pragma once #include #include @@ -101,4 +100,3 @@ public: std::shared_ptr ledger_; }; } // namespace xrpl -#endif diff --git a/src/xrpld/app/consensus/RCLCxPeerPos.cpp b/src/xrpld/app/consensus/RCLCxPeerPos.cpp index 5f227b00a9..4128d65c49 100644 --- a/src/xrpld/app/consensus/RCLCxPeerPos.cpp +++ b/src/xrpld/app/consensus/RCLCxPeerPos.cpp @@ -11,9 +11,7 @@ RCLCxPeerPos::RCLCxPeerPos( Slice const& signature, uint256 const& suppression, Proposal&& proposal) - : publicKey_(publicKey) - , suppression_(suppression) - , proposal_(std::move(proposal)) + : publicKey_(publicKey), suppression_(suppression), proposal_(std::move(proposal)) { // The maximum allowed size of a signature is 72 bytes; we verify // this elsewhere, but we want to be extra careful here: @@ -28,8 +26,7 @@ RCLCxPeerPos::RCLCxPeerPos( bool RCLCxPeerPos::checkSign() const { - return verifyDigest( - publicKey(), proposal_.signingHash(), signature(), false); + return verifyDigest(publicKey(), proposal_.signingHash(), signature(), false); } Json::Value diff --git a/src/xrpld/app/consensus/RCLCxPeerPos.h b/src/xrpld/app/consensus/RCLCxPeerPos.h index 08b93d4ba9..b9ef492aae 100644 --- a/src/xrpld/app/consensus/RCLCxPeerPos.h +++ b/src/xrpld/app/consensus/RCLCxPeerPos.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_CONSENSUS_RCLCXPEERPOS_H_INCLUDED -#define XRPL_APP_CONSENSUS_RCLCXPEERPOS_H_INCLUDED +#pragma once #include @@ -37,11 +36,7 @@ public: @param proposal The consensus proposal */ - RCLCxPeerPos( - PublicKey const& publicKey, - Slice const& signature, - uint256 const& suppress, - Proposal&& proposal); + RCLCxPeerPos(PublicKey const& publicKey, Slice const& signature, uint256 const& suppress, Proposal&& proposal); //! Verify the signing hash of the proposal bool @@ -129,5 +124,3 @@ proposalUniqueId( Slice const& signature); } // namespace xrpl - -#endif diff --git a/src/xrpld/app/consensus/RCLCxTx.h b/src/xrpld/app/consensus/RCLCxTx.h index 5e92aea8a6..b7bde11a3b 100644 --- a/src/xrpld/app/consensus/RCLCxTx.h +++ b/src/xrpld/app/consensus/RCLCxTx.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_CONSENSUS_RCLCXTX_H_INCLUDED -#define XRPL_APP_CONSENSUS_RCLCXTX_H_INCLUDED +#pragma once #include @@ -89,8 +88,7 @@ public: */ RCLTxSet(std::shared_ptr m) : map_{std::move(m)} { - XRPL_ASSERT( - map_, "xrpl::RCLTxSet::MutableTxSet::RCLTxSet : non-null input"); + XRPL_ASSERT(map_, "xrpl::RCLTxSet::MutableTxSet::RCLTxSet : non-null input"); } /** Constructor from a previously created MutableTxSet @@ -157,8 +155,7 @@ public: for (auto const& [k, v] : delta) { XRPL_ASSERT( - (v.first && !v.second) || (v.second && !v.first), - "xrpl::RCLTxSet::compare : either side is set"); + (v.first && !v.second) || (v.second && !v.first), "xrpl::RCLTxSet::compare : either side is set"); ret[k] = static_cast(v.first); } @@ -169,4 +166,3 @@ public: std::shared_ptr map_; }; } // namespace xrpl -#endif diff --git a/src/xrpld/app/consensus/RCLValidations.cpp b/src/xrpld/app/consensus/RCLValidations.cpp index eb10765ba3..8c99ea9939 100644 --- a/src/xrpld/app/consensus/RCLValidations.cpp +++ b/src/xrpld/app/consensus/RCLValidations.cpp @@ -15,14 +15,11 @@ namespace xrpl { -RCLValidatedLedger::RCLValidatedLedger(MakeGenesis) - : ledgerID_{0}, ledgerSeq_{0}, j_{beast::Journal::getNullSink()} +RCLValidatedLedger::RCLValidatedLedger(MakeGenesis) : ledgerID_{0}, ledgerSeq_{0}, j_{beast::Journal::getNullSink()} { } -RCLValidatedLedger::RCLValidatedLedger( - std::shared_ptr const& ledger, - beast::Journal j) +RCLValidatedLedger::RCLValidatedLedger(std::shared_ptr const& ledger, beast::Journal j) : ledgerID_{ledger->header().hash}, ledgerSeq_{ledger->seq()}, j_{j} { auto const hashIndex = ledger->read(keylet::skip()); @@ -35,8 +32,7 @@ RCLValidatedLedger::RCLValidatedLedger( ancestors_ = hashIndex->getFieldV256(sfHashes).value(); } else - JLOG(j_.warn()) << "Ledger " << ledgerSeq_ << ":" << ledgerID_ - << " missing recent ancestor hashes"; + JLOG(j_.warn()) << "Ledger " << ledgerSeq_ << ":" << ledgerID_ << " missing recent ancestor hashes"; } auto @@ -67,10 +63,8 @@ RCLValidatedLedger::operator[](Seq const& s) const -> ID return ancestors_[ancestors_.size() - diff]; } - JLOG(j_.warn()) << "Unable to determine hash of ancestor seq=" << s - << " from ledger hash=" << ledgerID_ - << " seq=" << ledgerSeq_ << " (available: " << minSeq() - << "-" << seq() << ")"; + JLOG(j_.warn()) << "Unable to determine hash of ancestor seq=" << s << " from ledger hash=" << ledgerID_ + << " seq=" << ledgerSeq_ << " (available: " << minSeq() << "-" << seq() << ")"; // Default ID that is less than all others return ID{0}; } @@ -94,8 +88,7 @@ mismatch(RCLValidatedLedger const& a, RCLValidatedLedger const& b) return (curr < lower) ? Seq{1} : (curr + Seq{1}); } -RCLValidationsAdaptor::RCLValidationsAdaptor(Application& app, beast::Journal j) - : app_(app), j_(j) +RCLValidationsAdaptor::RCLValidationsAdaptor(Application& app, beast::Journal j) : app_(app), j_(j) { } @@ -110,34 +103,23 @@ RCLValidationsAdaptor::acquire(LedgerHash const& hash) { using namespace std::chrono_literals; auto ledger = perf::measureDurationAndLog( - [&]() { return app_.getLedgerMaster().getLedgerByHash(hash); }, - "getLedgerByHash", - 10ms, - j_); + [&]() { return app_.getLedgerMaster().getLedgerByHash(hash); }, "getLedgerByHash", 10ms, j_); if (!ledger) { - JLOG(j_.warn()) - << "Need validated ledger for preferred ledger analysis " << hash; + JLOG(j_.warn()) << "Need validated ledger for preferred ledger analysis " << hash; Application* pApp = &app_; - app_.getJobQueue().addJob( - jtADVANCE, "getConsensusLedger2", [pApp, hash, this]() { - JLOG(j_.debug()) - << "JOB advanceLedger getConsensusLedger2 started"; - pApp->getInboundLedgers().acquireAsync( - hash, 0, InboundLedger::Reason::CONSENSUS); - }); + app_.getJobQueue().addJob(jtADVANCE, "GetConsL2", [pApp, hash, this]() { + JLOG(j_.debug()) << "JOB advanceLedger getConsensusLedger2 started"; + pApp->getInboundLedgers().acquireAsync(hash, 0, InboundLedger::Reason::CONSENSUS); + }); return std::nullopt; } - XRPL_ASSERT( - !ledger->open() && ledger->isImmutable(), - "xrpl::RCLValidationsAdaptor::acquire : valid ledger state"); - XRPL_ASSERT( - ledger->header().hash == hash, - "xrpl::RCLValidationsAdaptor::acquire : ledger hash match"); + XRPL_ASSERT(!ledger->open() && ledger->isImmutable(), "xrpl::RCLValidationsAdaptor::acquire : valid ledger state"); + XRPL_ASSERT(ledger->header().hash == hash, "xrpl::RCLValidationsAdaptor::acquire : ledger hash match"); return RCLValidatedLedger(std::move(ledger), j_); } @@ -167,8 +149,7 @@ handleNewValidation( auto& validations = app.getValidations(); // masterKey is seated only if validator is trusted or listed - auto const outcome = - validations.add(calcNodeID(masterKey.value_or(signingKey)), val); + auto const outcome = validations.add(calcNodeID(masterKey.value_or(signingKey)), val); if (outcome == ValStatus::current) { @@ -176,12 +157,10 @@ handleNewValidation( { if (bypassAccept == BypassAccept::yes) { - XRPL_ASSERT( - j, "xrpl::handleNewValidation : journal is available"); + XRPL_ASSERT(j, "xrpl::handleNewValidation : journal is available"); if (j.has_value()) { - JLOG(j->trace()) << "Bypassing checkAccept for validation " - << val->getLedgerHash(); + JLOG(j->trace()) << "Bypassing checkAccept for validation " << val->getLedgerHash(); } } else @@ -200,9 +179,8 @@ handleNewValidation( // counterintuitively, we *especially* want to forward such validations, // so that our peers will also observe them and take independent notice of // such validators, informing their operators. - if (auto const ls = val->isTrusted() - ? validations.adaptor().journal().error() - : validations.adaptor().journal().info(); + if (auto const ls = + val->isTrusted() ? validations.adaptor().journal().error() : validations.adaptor().journal().info(); ls.active()) { auto const id = [&masterKey, &signingKey]() { @@ -215,16 +193,12 @@ handleNewValidation( }(); if (outcome == ValStatus::conflicting) - ls << "Byzantine Behavior Detector: " - << (val->isTrusted() ? "trusted " : "untrusted ") << id - << ": Conflicting validation for " << seq << "!\n[" - << val->getSerializer().slice() << "]"; + ls << "Byzantine Behavior Detector: " << (val->isTrusted() ? "trusted " : "untrusted ") << id + << ": Conflicting validation for " << seq << "!\n[" << val->getSerializer().slice() << "]"; if (outcome == ValStatus::multiple) - ls << "Byzantine Behavior Detector: " - << (val->isTrusted() ? "trusted " : "untrusted ") << id - << ": Multiple validations for " << seq << "/" << hash << "!\n[" - << val->getSerializer().slice() << "]"; + ls << "Byzantine Behavior Detector: " << (val->isTrusted() ? "trusted " : "untrusted ") << id + << ": Multiple validations for " << seq << "/" << hash << "!\n[" << val->getSerializer().slice() << "]"; } } diff --git a/src/xrpld/app/consensus/RCLValidations.h b/src/xrpld/app/consensus/RCLValidations.h index 62dd52b1dd..35c1686f9e 100644 --- a/src/xrpld/app/consensus/RCLValidations.h +++ b/src/xrpld/app/consensus/RCLValidations.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_CONSENSUSS_VALIDATIONS_H_INCLUDED -#define XRPL_APP_CONSENSUSS_VALIDATIONS_H_INCLUDED +#pragma once #include #include @@ -148,9 +147,7 @@ public: RCLValidatedLedger(MakeGenesis); - RCLValidatedLedger( - std::shared_ptr const& ledger, - beast::Journal j); + RCLValidatedLedger(std::shared_ptr const& ledger, beast::Journal j); /// The sequence (index) of the ledger Seq @@ -239,5 +236,3 @@ handleNewValidation( std::optional j = std::nullopt); } // namespace xrpl - -#endif diff --git a/src/xrpld/app/ledger/AbstractFetchPackContainer.h b/src/xrpld/app/ledger/AbstractFetchPackContainer.h index d2cdd1e920..3adc435bd6 100644 --- a/src/xrpld/app/ledger/AbstractFetchPackContainer.h +++ b/src/xrpld/app/ledger/AbstractFetchPackContainer.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_LEDGER_ABSTRACTFETCHPACKCONTAINER_H_INCLUDED -#define XRPL_APP_LEDGER_ABSTRACTFETCHPACKCONTAINER_H_INCLUDED +#pragma once #include #include @@ -27,5 +26,3 @@ public: }; } // namespace xrpl - -#endif diff --git a/src/xrpld/app/ledger/AcceptedLedger.cpp b/src/xrpld/app/ledger/AcceptedLedger.cpp index 76099ff864..7ad43b2d81 100644 --- a/src/xrpld/app/ledger/AcceptedLedger.cpp +++ b/src/xrpld/app/ledger/AcceptedLedger.cpp @@ -4,28 +4,21 @@ namespace xrpl { -AcceptedLedger::AcceptedLedger( - std::shared_ptr const& ledger, - Application& app) - : mLedger(ledger) +AcceptedLedger::AcceptedLedger(std::shared_ptr const& ledger) : mLedger(ledger) { transactions_.reserve(256); auto insertAll = [&](auto const& txns) { for (auto const& item : txns) - transactions_.emplace_back(std::make_unique( - ledger, item.first, item.second)); + transactions_.emplace_back(std::make_unique(ledger, item.first, item.second)); }; transactions_.reserve(256); insertAll(ledger->txs); - std::sort( - transactions_.begin(), - transactions_.end(), - [](auto const& a, auto const& b) { - return a->getTxnSeq() < b->getTxnSeq(); - }); + std::sort(transactions_.begin(), transactions_.end(), [](auto const& a, auto const& b) { + return a->getTxnSeq() < b->getTxnSeq(); + }); } } // namespace xrpl diff --git a/src/xrpld/app/ledger/AcceptedLedger.h b/src/xrpld/app/ledger/AcceptedLedger.h index 41177e7078..23cee6ce35 100644 --- a/src/xrpld/app/ledger/AcceptedLedger.h +++ b/src/xrpld/app/ledger/AcceptedLedger.h @@ -1,7 +1,8 @@ -#ifndef XRPL_APP_LEDGER_ACCEPTEDLEDGER_H_INCLUDED -#define XRPL_APP_LEDGER_ACCEPTEDLEDGER_H_INCLUDED +#pragma once -#include +#include +#include +#include namespace xrpl { @@ -24,9 +25,7 @@ namespace xrpl { class AcceptedLedger : public CountedObject { public: - AcceptedLedger( - std::shared_ptr const& ledger, - Application& app); + AcceptedLedger(std::shared_ptr const& ledger); std::shared_ptr const& getLedger() const @@ -58,5 +57,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/src/xrpld/app/ledger/AccountStateSF.cpp b/src/xrpld/app/ledger/AccountStateSF.cpp index 44f18b5cd3..048a46e810 100644 --- a/src/xrpld/app/ledger/AccountStateSF.cpp +++ b/src/xrpld/app/ledger/AccountStateSF.cpp @@ -3,15 +3,10 @@ namespace xrpl { void -AccountStateSF::gotNode( - bool, - SHAMapHash const& nodeHash, - std::uint32_t ledgerSeq, - Blob&& nodeData, - SHAMapNodeType) const +AccountStateSF::gotNode(bool, SHAMapHash const& nodeHash, std::uint32_t ledgerSeq, Blob&& nodeData, SHAMapNodeType) + const { - db_.store( - hotACCOUNT_NODE, std::move(nodeData), nodeHash.as_uint256(), ledgerSeq); + db_.store(hotACCOUNT_NODE, std::move(nodeData), nodeHash.as_uint256(), ledgerSeq); } std::optional diff --git a/src/xrpld/app/ledger/AccountStateSF.h b/src/xrpld/app/ledger/AccountStateSF.h index 84738f6e1f..fb9da3a616 100644 --- a/src/xrpld/app/ledger/AccountStateSF.h +++ b/src/xrpld/app/ledger/AccountStateSF.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_LEDGER_ACCOUNTSTATESF_H_INCLUDED -#define XRPL_APP_LEDGER_ACCOUNTSTATESF_H_INCLUDED +#pragma once #include @@ -13,18 +12,13 @@ namespace xrpl { class AccountStateSF : public SHAMapSyncFilter { public: - AccountStateSF(NodeStore::Database& db, AbstractFetchPackContainer& fp) - : db_(db), fp_(fp) + AccountStateSF(NodeStore::Database& db, AbstractFetchPackContainer& fp) : db_(db), fp_(fp) { } void - gotNode( - bool fromFilter, - SHAMapHash const& nodeHash, - std::uint32_t ledgerSeq, - Blob&& nodeData, - SHAMapNodeType type) const override; + gotNode(bool fromFilter, SHAMapHash const& nodeHash, std::uint32_t ledgerSeq, Blob&& nodeData, SHAMapNodeType type) + const override; std::optional getNode(SHAMapHash const& nodeHash) const override; @@ -35,5 +29,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/src/xrpld/app/ledger/BuildLedger.h b/src/xrpld/app/ledger/BuildLedger.h index ad6aba3288..7b4b85c4aa 100644 --- a/src/xrpld/app/ledger/BuildLedger.h +++ b/src/xrpld/app/ledger/BuildLedger.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_LEDGER_BUILD_LEDGER_H_INCLUDED -#define XRPL_APP_LEDGER_BUILD_LEDGER_H_INCLUDED +#pragma once #include #include @@ -51,11 +50,6 @@ buildLedger( @return The newly built ledger */ std::shared_ptr -buildLedger( - LedgerReplay const& replayData, - ApplyFlags applyFlags, - Application& app, - beast::Journal j); +buildLedger(LedgerReplay const& replayData, ApplyFlags applyFlags, Application& app, beast::Journal j); } // namespace xrpl -#endif diff --git a/src/xrpld/app/ledger/ConsensusTransSetSF.cpp b/src/xrpld/app/ledger/ConsensusTransSetSF.cpp index b52cee2927..a99960fd3a 100644 --- a/src/xrpld/app/ledger/ConsensusTransSetSF.cpp +++ b/src/xrpld/app/ledger/ConsensusTransSetSF.cpp @@ -1,6 +1,5 @@ #include #include -#include #include #include @@ -8,6 +7,7 @@ #include #include #include +#include namespace xrpl { @@ -32,8 +32,7 @@ ConsensusTransSetSF::gotNode( if ((type == SHAMapNodeType::tnTRANSACTION_NM) && (nodeData.size() > 16)) { // this is a transaction, and we didn't have it - JLOG(j_.debug()) - << "Node on our acquiring TX set is TXN we may not have"; + JLOG(j_.debug()) << "Node on our acquiring TX set is TXN we may not have"; try { @@ -46,15 +45,12 @@ ConsensusTransSetSF::gotNode( "xrpl::ConsensusTransSetSF::gotNode : transaction hash " "match"); auto const pap = &app_; - app_.getJobQueue().addJob(jtTRANSACTION, "TXS->TXN", [pap, stx]() { - pap->getOPs().submitTransaction(stx); - }); + app_.getJobQueue().addJob( + jtTRANSACTION, "TxsToTxn", [pap, stx]() { pap->getOPs().submitTransaction(stx); }); } catch (std::exception const& ex) { - JLOG(j_.warn()) - << "Fetched invalid transaction in proposed set. Exception: " - << ex.what(); + JLOG(j_.warn()) << "Fetched invalid transaction in proposed set. Exception: " << ex.what(); } } } @@ -66,8 +62,7 @@ ConsensusTransSetSF::getNode(SHAMapHash const& nodeHash) const if (m_nodeCache.retrieve(nodeHash, nodeData)) return nodeData; - auto txn = - app_.getMasterTransaction().fetch_from_cache(nodeHash.as_uint256()); + auto txn = app_.getMasterTransaction().fetch_from_cache(nodeHash.as_uint256()); if (txn) { diff --git a/src/xrpld/app/ledger/ConsensusTransSetSF.h b/src/xrpld/app/ledger/ConsensusTransSetSF.h index cdb1c47183..855577ecee 100644 --- a/src/xrpld/app/ledger/ConsensusTransSetSF.h +++ b/src/xrpld/app/ledger/ConsensusTransSetSF.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_LEDGER_CONSENSUSTRANSSETSF_H_INCLUDED -#define XRPL_APP_LEDGER_CONSENSUSTRANSSETSF_H_INCLUDED +#pragma once #include @@ -22,12 +21,8 @@ public: // Note that the nodeData is overwritten by this call void - gotNode( - bool fromFilter, - SHAMapHash const& nodeHash, - std::uint32_t ledgerSeq, - Blob&& nodeData, - SHAMapNodeType type) const override; + gotNode(bool fromFilter, SHAMapHash const& nodeHash, std::uint32_t ledgerSeq, Blob&& nodeData, SHAMapNodeType type) + const override; std::optional getNode(SHAMapHash const& nodeHash) const override; @@ -39,5 +34,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/src/xrpld/app/ledger/InboundLedger.h b/src/xrpld/app/ledger/InboundLedger.h index 1b4353b260..46a8cf19b5 100644 --- a/src/xrpld/app/ledger/InboundLedger.h +++ b/src/xrpld/app/ledger/InboundLedger.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_LEDGER_INBOUNDLEDGER_H_INCLUDED -#define XRPL_APP_LEDGER_INBOUNDLEDGER_H_INCLUDED +#pragma once #include #include @@ -75,12 +74,9 @@ public: init(ScopedLockType& collectionLock); bool - gotData( - std::weak_ptr, - std::shared_ptr const&); + gotData(std::weak_ptr, std::shared_ptr const&); - using neededHash_t = - std::pair; + using neededHash_t = std::pair; /** Return a Json::objectValue. */ Json::Value @@ -105,9 +101,7 @@ private: enum class TriggerReason { added, reply, timeout }; void - filterNodes( - std::vector>& nodes, - TriggerReason reason); + filterNodes(std::vector>& nodes, TriggerReason reason); void trigger(std::shared_ptr const&, TriggerReason); @@ -172,13 +166,9 @@ private: // Data we have received from peers std::mutex mReceivedDataLock; - std::vector< - std::pair, std::shared_ptr>> - mReceivedData; + std::vector, std::shared_ptr>> mReceivedData; bool mReceiveDispatched; std::unique_ptr mPeerSet; }; } // namespace xrpl - -#endif diff --git a/src/xrpld/app/ledger/InboundLedgers.h b/src/xrpld/app/ledger/InboundLedgers.h index 0e4d9996bb..30eb69ab7a 100644 --- a/src/xrpld/app/ledger/InboundLedgers.h +++ b/src/xrpld/app/ledger/InboundLedgers.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_LEDGER_INBOUNDLEDGERS_H_INCLUDED -#define XRPL_APP_LEDGER_INBOUNDLEDGERS_H_INCLUDED +#pragma once #include @@ -27,10 +26,7 @@ public: // Queue. TODO review whether all callers of acquire() can use this // instead. Inbound ledger acquisition is asynchronous anyway. virtual void - acquireAsync( - uint256 const& hash, - std::uint32_t seq, - InboundLedger::Reason reason) = 0; + acquireAsync(uint256 const& hash, std::uint32_t seq, InboundLedger::Reason reason) = 0; virtual std::shared_ptr find(LedgerHash const& hash) = 0; @@ -38,10 +34,7 @@ public: // VFALCO TODO Remove the dependency on the Peer object. // virtual bool - gotLedgerData( - LedgerHash const& ledgerHash, - std::shared_ptr, - std::shared_ptr) = 0; + gotLedgerData(LedgerHash const& ledgerHash, std::shared_ptr, std::shared_ptr) = 0; virtual void gotStaleData(std::shared_ptr packet) = 0; @@ -85,5 +78,3 @@ make_InboundLedgers( beast::insight::Collector::ptr const& collector); } // namespace xrpl - -#endif diff --git a/src/xrpld/app/ledger/InboundTransactions.h b/src/xrpld/app/ledger/InboundTransactions.h index 6c0281e26f..7b85f56c5f 100644 --- a/src/xrpld/app/ledger/InboundTransactions.h +++ b/src/xrpld/app/ledger/InboundTransactions.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_LEDGER_INBOUNDTRANSACTIONS_H_INCLUDED -#define XRPL_APP_LEDGER_INBOUNDTRANSACTIONS_H_INCLUDED +#pragma once #include @@ -45,10 +44,7 @@ public: * @param message The LedgerData message. */ virtual void - gotData( - uint256 const& setHash, - std::shared_ptr peer, - std::shared_ptr message) = 0; + gotData(uint256 const& setHash, std::shared_ptr peer, std::shared_ptr message) = 0; /** Add a transaction set. * @@ -58,10 +54,7 @@ public: * or constructed by ourself during consensus. */ virtual void - giveSet( - uint256 const& setHash, - std::shared_ptr const& set, - bool acquired) = 0; + giveSet(uint256 const& setHash, std::shared_ptr const& set, bool acquired) = 0; /** Informs the container if a new consensus round */ @@ -79,5 +72,3 @@ make_InboundTransactions( std::function const&, bool)> gotSet); } // namespace xrpl - -#endif diff --git a/src/xrpld/app/ledger/Ledger.cpp b/src/xrpld/app/ledger/Ledger.cpp index e21cbb6d54..d75e4dd22e 100644 --- a/src/xrpld/app/ledger/Ledger.cpp +++ b/src/xrpld/app/ledger/Ledger.cpp @@ -3,15 +3,13 @@ #include #include #include -#include -#include #include #include -#include #include #include #include +#include #include #include #include @@ -23,6 +21,7 @@ #include #include #include +#include #include #include @@ -109,8 +108,7 @@ public: txs_iter_impl(txs_iter_impl const&) = default; - txs_iter_impl(bool metadata, SHAMap::const_iterator iter) - : metadata_(metadata), iter_(std::move(iter)) + txs_iter_impl(bool metadata, SHAMap::const_iterator iter) : metadata_(metadata), iter_(std::move(iter)) { } @@ -146,11 +144,7 @@ public: //------------------------------------------------------------------------------ -Ledger::Ledger( - create_genesis_t, - Config const& config, - std::vector const& amendments, - Family& family) +Ledger::Ledger(create_genesis_t, Config const& config, std::vector const& amendments, Family& family) : mImmutable(false) , txMap_(SHAMapType::TRANSACTION, family) , stateMap_(SHAMapType::STATE, family) @@ -161,9 +155,7 @@ Ledger::Ledger( header_.drops = INITIAL_XRP; header_.closeTimeResolution = ledgerGenesisTimeResolution; - static auto const id = calcAccountID( - generateKeyPair(KeyType::secp256k1, generateSeed("masterpassphrase")) - .first); + static auto const id = calcAccountID(generateKeyPair(KeyType::secp256k1, generateSeed("masterpassphrase")).first); { auto const sle = std::make_shared(keylet::account(id)); sle->setFieldU32(sfSequence, 1); @@ -182,8 +174,7 @@ Ledger::Ledger( { auto sle = std::make_shared(keylet::fees()); // Whether featureXRPFees is supported will depend on startup options. - if (std::find(amendments.begin(), amendments.end(), featureXRPFees) != - amendments.end()) + if (std::find(amendments.begin(), amendments.end(), featureXRPFees) != amendments.end()) { sle->at(sfBaseFeeDrops) = config.FEES.reference_fee; sle->at(sfReserveBaseDrops) = config.FEES.account_reserve; @@ -191,14 +182,11 @@ Ledger::Ledger( } else { - if (auto const f = - config.FEES.reference_fee.dropsAs()) + if (auto const f = config.FEES.reference_fee.dropsAs()) sle->at(sfBaseFee) = *f; - if (auto const f = - config.FEES.account_reserve.dropsAs()) + if (auto const f = config.FEES.account_reserve.dropsAs()) sle->at(sfReserveBase) = *f; - if (auto const f = - config.FEES.owner_reserve.dropsAs()) + if (auto const f = config.FEES.owner_reserve.dropsAs()) sle->at(sfReserveIncrement) = *f; sle->at(sfReferenceFeeUnits) = Config::FEE_UNITS_DEPRECATED; } @@ -225,20 +213,16 @@ Ledger::Ledger( { loaded = true; - if (header_.txHash.isNonZero() && - !txMap_.fetchRoot(SHAMapHash{header_.txHash}, nullptr)) + if (header_.txHash.isNonZero() && !txMap_.fetchRoot(SHAMapHash{header_.txHash}, nullptr)) { loaded = false; - JLOG(j.warn()) << "Don't have transaction root for ledger" - << header_.seq; + JLOG(j.warn()) << "Don't have transaction root for ledger" << header_.seq; } - if (header_.accountHash.isNonZero() && - !stateMap_.fetchRoot(SHAMapHash{header_.accountHash}, nullptr)) + if (header_.accountHash.isNonZero() && !stateMap_.fetchRoot(SHAMapHash{header_.accountHash}, nullptr)) { loaded = false; - JLOG(j.warn()) << "Don't have state data root for ledger" - << header_.seq; + JLOG(j.warn()) << "Don't have state data root for ledger" << header_.seq; } txMap_.setImmutable(); @@ -272,19 +256,15 @@ Ledger::Ledger(Ledger const& prevLedger, NetClock::time_point closeTime) header_.closeTimeResolution = prevLedger.header_.closeTimeResolution; header_.parentHash = prevLedger.header().hash; header_.closeTimeResolution = getNextLedgerTimeResolution( - prevLedger.header_.closeTimeResolution, - getCloseAgree(prevLedger.header()), - header_.seq); + prevLedger.header_.closeTimeResolution, getCloseAgree(prevLedger.header()), header_.seq); if (prevLedger.header_.closeTime == NetClock::time_point{}) { - header_.closeTime = - roundCloseTime(closeTime, header_.closeTimeResolution); + header_.closeTime = roundCloseTime(closeTime, header_.closeTimeResolution); } else { - header_.closeTime = - prevLedger.header_.closeTime + header_.closeTimeResolution; + header_.closeTime = prevLedger.header_.closeTime + header_.closeTimeResolution; } } @@ -299,11 +279,7 @@ Ledger::Ledger(LedgerHeader const& info, Config const& config, Family& family) header_.hash = calculateLedgerHash(header_); } -Ledger::Ledger( - std::uint32_t ledgerSeq, - NetClock::time_point closeTime, - Config const& config, - Family& family) +Ledger::Ledger(std::uint32_t ledgerSeq, NetClock::time_point closeTime, Config const& config, Family& family) : mImmutable(false) , txMap_(SHAMapType::TRANSACTION, family) , stateMap_(SHAMapType::STATE, family) @@ -338,10 +314,7 @@ Ledger::setImmutable(bool rehash) } void -Ledger::setAccepted( - NetClock::time_point closeTime, - NetClock::duration closeResolution, - bool correctCloseTime) +Ledger::setAccepted(NetClock::time_point closeTime, NetClock::duration closeResolution, bool correctCloseTime) { // Used when we witnessed the consensus. XRPL_ASSERT(!open(), "xrpl::Ledger::setAccepted : valid ledger state"); @@ -356,8 +329,7 @@ bool Ledger::addSLE(SLE const& sle) { auto const s = sle.getSerializer(); - return stateMap_.addItem( - SHAMapNodeType::tnACCOUNT_STATE, make_shamapitem(sle.key(), s.slice())); + return stateMap_.addItem(SHAMapNodeType::tnACCOUNT_STATE, make_shamapitem(sle.key(), s.slice())); } //------------------------------------------------------------------------------ @@ -372,8 +344,7 @@ deserializeTx(SHAMapItem const& item) std::pair, std::shared_ptr> deserializeTxPlusMeta(SHAMapItem const& item) { - std::pair, std::shared_ptr> - result; + std::pair, std::shared_ptr> result; SerialIter sit(item.slice()); { SerialIter s(sit.getSlice(sit.getVLDataLength())); @@ -446,8 +417,7 @@ Ledger::slesEnd() const -> std::unique_ptr } auto -Ledger::slesUpperBound(uint256 const& key) const - -> std::unique_ptr +Ledger::slesUpperBound(uint256 const& key) const -> std::unique_ptr { return std::make_unique(stateMap_.upper_bound(key)); } @@ -516,9 +486,7 @@ Ledger::rawInsert(std::shared_ptr const& sle) { Serializer ss; sle->add(ss); - if (!stateMap_.addGiveItem( - SHAMapNodeType::tnACCOUNT_STATE, - make_shamapitem(sle->key(), ss.slice()))) + if (!stateMap_.addGiveItem(SHAMapNodeType::tnACCOUNT_STATE, make_shamapitem(sle->key(), ss.slice()))) LogicError("Ledger::rawInsert: key already exists"); } @@ -527,9 +495,7 @@ Ledger::rawReplace(std::shared_ptr const& sle) { Serializer ss; sle->add(ss); - if (!stateMap_.updateGiveItem( - SHAMapNodeType::tnACCOUNT_STATE, - make_shamapitem(sle->key(), ss.slice()))) + if (!stateMap_.updateGiveItem(SHAMapNodeType::tnACCOUNT_STATE, make_shamapitem(sle->key(), ss.slice()))) LogicError("Ledger::rawReplace: key not found"); } @@ -539,15 +505,13 @@ Ledger::rawTxInsert( std::shared_ptr const& txn, std::shared_ptr const& metaData) { - XRPL_ASSERT( - metaData, "xrpl::Ledger::rawTxInsert : non-null metadata input"); + XRPL_ASSERT(metaData, "xrpl::Ledger::rawTxInsert : non-null metadata input"); // low-level - just add to table Serializer s(txn->getDataLength() + metaData->getDataLength() + 16); s.addVL(txn->peekData()); s.addVL(metaData->peekData()); - if (!txMap_.addGiveItem( - SHAMapNodeType::tnTRANSACTION_MD, make_shamapitem(key, s.slice()))) + if (!txMap_.addGiveItem(SHAMapNodeType::tnTRANSACTION_MD, make_shamapitem(key, s.slice()))) LogicError("duplicate_tx: " + to_string(key)); } @@ -557,9 +521,7 @@ Ledger::rawTxInsertWithHash( std::shared_ptr const& txn, std::shared_ptr const& metaData) { - XRPL_ASSERT( - metaData, - "xrpl::Ledger::rawTxInsertWithHash : non-null metadata input"); + XRPL_ASSERT(metaData, "xrpl::Ledger::rawTxInsertWithHash : non-null metadata input"); // low-level - just add to table Serializer s(txn->getDataLength() + metaData->getDataLength() + 16); @@ -613,11 +575,8 @@ Ledger::setup() { auto const baseFeeXRP = sle->at(~sfBaseFeeDrops); auto const reserveBaseXRP = sle->at(~sfReserveBaseDrops); - auto const reserveIncrementXRP = - sle->at(~sfReserveIncrementDrops); - auto assign = [&ret]( - XRPAmount& dest, - std::optional const& src) { + auto const reserveIncrementXRP = sle->at(~sfReserveIncrementDrops); + auto assign = [&ret](XRPAmount& dest, std::optional const& src) { if (src) { if (src->native()) @@ -655,9 +614,7 @@ Ledger::setup() void Ledger::defaultFees(Config const& config) { - XRPL_ASSERT( - fees_.base == 0 && fees_.reserve == 0 && fees_.increment == 0, - "xrpl::Ledger::defaultFees : zero fees"); + XRPL_ASSERT(fees_.base == 0 && fees_.reserve == 0 && fees_.increment == 0, "xrpl::Ledger::defaultFees : zero fees"); if (fees_.base == 0) fees_.base = config.FEES.reference_fee; if (fees_.reserve == 0) @@ -682,8 +639,7 @@ hash_set Ledger::negativeUNL() const { hash_set negUnl; - if (auto sle = read(keylet::negativeUNL()); - sle && sle->isFieldPresent(sfDisabledValidators)) + if (auto sle = read(keylet::negativeUNL()); sle && sle->isFieldPresent(sfDisabledValidators)) { auto const& nUnlData = sle->getFieldArray(sfDisabledValidators); for (auto const& n : nUnlData) @@ -707,8 +663,7 @@ Ledger::negativeUNL() const std::optional Ledger::validatorToDisable() const { - if (auto sle = read(keylet::negativeUNL()); - sle && sle->isFieldPresent(sfValidatorToDisable)) + if (auto sle = read(keylet::negativeUNL()); sle && sle->isFieldPresent(sfValidatorToDisable)) { auto d = sle->getFieldVL(sfValidatorToDisable); auto s = makeSlice(d); @@ -722,8 +677,7 @@ Ledger::validatorToDisable() const std::optional Ledger::validatorToReEnable() const { - if (auto sle = read(keylet::negativeUNL()); - sle && sle->isFieldPresent(sfValidatorToReEnable)) + if (auto sle = read(keylet::negativeUNL()); sle && sle->isFieldPresent(sfValidatorToReEnable)) { auto d = sle->getFieldVL(sfValidatorToReEnable); auto s = makeSlice(d); @@ -754,8 +708,7 @@ Ledger::updateNegativeUNL() for (auto v : oldNUnl) { if (hasToReEnable && v.isFieldPresent(sfPublicKey) && - v.getFieldVL(sfPublicKey) == - sle->getFieldVL(sfValidatorToReEnable)) + v.getFieldVL(sfPublicKey) == sle->getFieldVL(sfValidatorToReEnable)) continue; newNUnl.push_back(v); } @@ -764,8 +717,7 @@ Ledger::updateNegativeUNL() if (hasToDisable) { newNUnl.push_back(STObject::makeInnerObject(sfDisabledValidator)); - newNUnl.back().setFieldVL( - sfPublicKey, sle->getFieldVL(sfValidatorToDisable)); + newNUnl.back().setFieldVL(sfPublicKey, sle->getFieldVL(sfValidatorToDisable)); newNUnl.back().setFieldU32(sfFirstLedgerSequence, seq()); } @@ -794,8 +746,7 @@ Ledger::walkLedger(beast::Journal j, bool parallel) const if (stateMap_.getHash().isZero() && !header_.accountHash.isZero() && !stateMap_.fetchRoot(SHAMapHash{header_.accountHash}, nullptr)) { - missingNodes1.emplace_back( - SHAMapType::STATE, SHAMapHash{header_.accountHash}); + missingNodes1.emplace_back(SHAMapType::STATE, SHAMapHash{header_.accountHash}); } else { @@ -817,8 +768,7 @@ Ledger::walkLedger(beast::Journal j, bool parallel) const if (txMap_.getHash().isZero() && header_.txHash.isNonZero() && !txMap_.fetchRoot(SHAMapHash{header_.txHash}, nullptr)) { - missingNodes2.emplace_back( - SHAMapType::TRANSACTION, SHAMapHash{header_.txHash}); + missingNodes2.emplace_back(SHAMapType::TRANSACTION, SHAMapHash{header_.txHash}); } else { @@ -840,8 +790,7 @@ bool Ledger::assertSensible(beast::Journal ledgerJ) const { if (header_.hash.isNonZero() && header_.accountHash.isNonZero() && - (header_.accountHash == stateMap_.getHash().as_uint256()) && - (header_.txHash == txMap_.getHash().as_uint256())) + (header_.accountHash == stateMap_.getHash().as_uint256()) && (header_.txHash == txMap_.getHash().as_uint256())) { return true; } @@ -889,9 +838,7 @@ Ledger::updateSkipList() created = false; } - XRPL_ASSERT( - hashes.size() <= 256, - "xrpl::Ledger::updateSkipList : first maximum hashes size"); + XRPL_ASSERT(hashes.size() <= 256, "xrpl::Ledger::updateSkipList : first maximum hashes size"); hashes.push_back(header_.parentHash); sle->setFieldV256(sfHashes, STVector256(hashes)); sle->setFieldU32(sfLastLedgerSequence, prevIndex); @@ -916,9 +863,7 @@ Ledger::updateSkipList() hashes = static_cast(sle->getFieldV256(sfHashes)); created = false; } - XRPL_ASSERT( - hashes.size() <= 256, - "xrpl::Ledger::updateSkipList : second maximum hashes size"); + XRPL_ASSERT(hashes.size() <= 256, "xrpl::Ledger::updateSkipList : second maximum hashes size"); if (hashes.size() == 256) hashes.erase(hashes.begin()); hashes.push_back(header_.parentHash); @@ -948,10 +893,7 @@ isFlagLedger(LedgerIndex seq) } static bool -saveValidatedLedger( - Application& app, - std::shared_ptr const& ledger, - bool current) +saveValidatedLedger(Application& app, std::shared_ptr const& ledger, bool current) { auto j = app.journal("Ledger"); auto seq = ledger->header().seq; @@ -962,11 +904,9 @@ saveValidatedLedger( return true; } - auto const db = dynamic_cast(&app.getRelationalDatabase()); - if (!db) - Throw("Failed to get relational database"); + auto& db = app.getRelationalDatabase(); - auto const res = db->saveValidatedLedger(ledger, current); + auto const res = db.saveValidatedLedger(ledger, current); // Clients can now trust the database for // information about this ledger sequence. @@ -978,14 +918,9 @@ saveValidatedLedger( Returns false on error */ bool -pendSaveValidated( - Application& app, - std::shared_ptr const& ledger, - bool isSynchronous, - bool isCurrent) +pendSaveValidated(Application& app, std::shared_ptr const& ledger, bool isSynchronous, bool isCurrent) { - if (!app.getHashRouter().setFlags( - ledger->header().hash, HashRouterFlags::SAVED)) + if (!app.getHashRouter().setFlags(ledger->header().hash, HashRouterFlags::SAVED)) { // We have tried to save this ledger recently auto stream = app.journal("Ledger").debug(); @@ -999,14 +934,12 @@ pendSaveValidated( } } - XRPL_ASSERT( - ledger->isImmutable(), "xrpl::pendSaveValidated : immutable ledger"); + XRPL_ASSERT(ledger->isImmutable(), "xrpl::pendSaveValidated : immutable ledger"); if (!app.pendingSaves().shouldWork(ledger->header().seq, isSynchronous)) { auto stream = app.journal("Ledger").debug(); - JLOG(stream) << "Pend save with seq in pending saves " - << ledger->header().seq; + JLOG(stream) << "Pend save with seq in pending saves " << ledger->header().seq; return true; } @@ -1014,9 +947,7 @@ pendSaveValidated( // See if we can use the JobQueue. if (!isSynchronous && app.getJobQueue().addJob( - isCurrent ? jtPUBLEDGER : jtPUBOLDLEDGER, - std::to_string(ledger->seq()), - [&app, ledger, isCurrent]() { + isCurrent ? jtPUBLEDGER : jtPUBOLDLEDGER, std::to_string(ledger->seq()), [&app, ledger, isCurrent]() { saveValidatedLedger(app, ledger, isCurrent); })) { @@ -1054,13 +985,8 @@ std::shared_ptr loadLedgerHelper(LedgerHeader const& info, Application& app, bool acquire) { bool loaded; - auto ledger = std::make_shared( - info, - loaded, - acquire, - app.config(), - app.getNodeFamily(), - app.journal("Ledger")); + auto ledger = + std::make_shared(info, loaded, acquire, app.config(), app.getNodeFamily(), app.journal("Ledger")); if (!loaded) ledger.reset(); @@ -1069,17 +995,13 @@ loadLedgerHelper(LedgerHeader const& info, Application& app, bool acquire) } static void -finishLoadByIndexOrHash( - std::shared_ptr const& ledger, - Config const& config, - beast::Journal j) +finishLoadByIndexOrHash(std::shared_ptr const& ledger, Config const& config, beast::Journal j) { if (!ledger) return; XRPL_ASSERT( - ledger->header().seq < XRP_LEDGER_EARLIEST_FEES || - ledger->read(keylet::fees()), + ledger->header().seq < XRP_LEDGER_EARLIEST_FEES || ledger->read(keylet::fees()), "xrpl::finishLoadByIndexOrHash : valid ledger fees"); ledger->setImmutable(); @@ -1091,8 +1013,7 @@ finishLoadByIndexOrHash( std::tuple, std::uint32_t, uint256> getLatestLedger(Application& app) { - std::optional const info = - app.getRelationalDatabase().getNewestLedgerInfo(); + std::optional const info = app.getRelationalDatabase().getNewestLedgerInfo(); if (!info) return {std::shared_ptr(), {}, {}}; return {loadLedgerHelper(*info, app, true), info->seq, info->hash}; @@ -1101,8 +1022,7 @@ getLatestLedger(Application& app) std::shared_ptr loadByIndex(std::uint32_t ledgerIndex, Application& app, bool acquire) { - if (std::optional info = - app.getRelationalDatabase().getLedgerInfoByIndex(ledgerIndex)) + if (std::optional info = app.getRelationalDatabase().getLedgerInfoByIndex(ledgerIndex)) { std::shared_ptr ledger = loadLedgerHelper(*info, app, acquire); finishLoadByIndexOrHash(ledger, app.config(), app.journal("Ledger")); @@ -1114,14 +1034,11 @@ loadByIndex(std::uint32_t ledgerIndex, Application& app, bool acquire) std::shared_ptr loadByHash(uint256 const& ledgerHash, Application& app, bool acquire) { - if (std::optional info = - app.getRelationalDatabase().getLedgerInfoByHash(ledgerHash)) + if (std::optional info = app.getRelationalDatabase().getLedgerInfoByHash(ledgerHash)) { std::shared_ptr ledger = loadLedgerHelper(*info, app, acquire); finishLoadByIndexOrHash(ledger, app.config(), app.journal("Ledger")); - XRPL_ASSERT( - !ledger || ledger->header().hash == ledgerHash, - "xrpl::loadByHash : ledger hash match if loaded"); + XRPL_ASSERT(!ledger || ledger->header().hash == ledgerHash, "xrpl::loadByHash : ledger hash match if loaded"); return ledger; } return {}; diff --git a/src/xrpld/app/ledger/Ledger.h b/src/xrpld/app/ledger/Ledger.h index a17281f2c7..cbfbc0030f 100644 --- a/src/xrpld/app/ledger/Ledger.h +++ b/src/xrpld/app/ledger/Ledger.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_LEDGER_LEDGER_H_INCLUDED -#define XRPL_APP_LEDGER_LEDGER_H_INCLUDED +#pragma once #include #include @@ -82,11 +81,7 @@ public: Amendments specified are enabled in the genesis ledger */ - Ledger( - create_genesis_t, - Config const& config, - std::vector const& amendments, - Family& family); + Ledger(create_genesis_t, Config const& config, std::vector const& amendments, Family& family); Ledger(LedgerHeader const& info, Config const& config, Family& family); @@ -111,11 +106,7 @@ public: Ledger(Ledger const& previous, NetClock::time_point closeTime); // used for database ledgers - Ledger( - std::uint32_t ledgerSeq, - NetClock::time_point closeTime, - Config const& config, - Family& family); + Ledger(std::uint32_t ledgerSeq, NetClock::time_point closeTime, Config const& config, Family& family); ~Ledger() = default; @@ -160,8 +151,7 @@ public: exists(uint256 const& key) const; std::optional - succ(uint256 const& key, std::optional const& last = std::nullopt) - const override; + succ(uint256 const& key, std::optional const& last = std::nullopt) const override; std::shared_ptr read(Keylet const& k) const override; @@ -248,10 +238,7 @@ public: } void - setAccepted( - NetClock::time_point closeTime, - NetClock::duration closeResolution, - bool correctCloseTime); + setAccepted(NetClock::time_point closeTime, NetClock::duration closeResolution, bool correctCloseTime); void setImmutable(bool rehash = true); @@ -416,11 +403,7 @@ isFlagLedger(LedgerIndex seq); //------------------------------------------------------------------------------ extern bool -pendSaveValidated( - Application& app, - std::shared_ptr const& ledger, - bool isSynchronous, - bool isCurrent); +pendSaveValidated(Application& app, std::shared_ptr const& ledger, bool isSynchronous, bool isCurrent); std::shared_ptr loadLedgerHelper(LedgerHeader const& sinfo, Application& app, bool acquire); @@ -460,5 +443,3 @@ uint256 calculateLedgerHash(LedgerHeader const& info); } // namespace xrpl - -#endif diff --git a/src/xrpld/app/ledger/LedgerCleaner.h b/src/xrpld/app/ledger/LedgerCleaner.h index 2377485f22..aa8d042c24 100644 --- a/src/xrpld/app/ledger/LedgerCleaner.h +++ b/src/xrpld/app/ledger/LedgerCleaner.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_LEDGER_LEDGERCLEANER_H_INCLUDED -#define XRPL_APP_LEDGER_LEDGERCLEANER_H_INCLUDED +#pragma once #include @@ -44,5 +43,3 @@ std::unique_ptr make_LedgerCleaner(Application& app, beast::Journal journal); } // namespace xrpl - -#endif diff --git a/src/xrpld/app/ledger/LedgerHistory.cpp b/src/xrpld/app/ledger/LedgerHistory.cpp index 2654e25d7b..50fe56fd90 100644 --- a/src/xrpld/app/ledger/LedgerHistory.cpp +++ b/src/xrpld/app/ledger/LedgerHistory.cpp @@ -10,9 +10,7 @@ namespace xrpl { // FIXME: Need to clean up ledgers by index at some point -LedgerHistory::LedgerHistory( - beast::insight::Collector::ptr const& collector, - Application& app) +LedgerHistory::LedgerHistory(beast::insight::Collector::ptr const& collector, Application& app) : app_(app) , collector_(collector) , mismatch_counter_(collector->make_counter("ledger.history", "mismatch")) @@ -22,32 +20,22 @@ LedgerHistory::LedgerHistory( std::chrono::seconds{app_.config().getValueFor(SizedItem::ledgerAge)}, stopwatch(), app_.journal("TaggedCache")) - , m_consensus_validated( - "ConsensusValidated", - 64, - std::chrono::minutes{5}, - stopwatch(), - app_.journal("TaggedCache")) + , m_consensus_validated("ConsensusValidated", 64, std::chrono::minutes{5}, stopwatch(), app_.journal("TaggedCache")) , j_(app.journal("LedgerHistory")) { } bool -LedgerHistory::insert( - std::shared_ptr const& ledger, - bool validated) +LedgerHistory::insert(std::shared_ptr const& ledger, bool validated) { if (!ledger->isImmutable()) LogicError("mutable Ledger in insert"); - XRPL_ASSERT( - ledger->stateMap().getHash().isNonZero(), - "xrpl::LedgerHistory::insert : nonzero hash"); + XRPL_ASSERT(ledger->stateMap().getHash().isNonZero(), "xrpl::LedgerHistory::insert : nonzero hash"); std::unique_lock sl(m_ledgers_by_hash.peekMutex()); - bool const alreadyHad = m_ledgers_by_hash.canonicalize_replace_cache( - ledger->header().hash, ledger); + bool const alreadyHad = m_ledgers_by_hash.canonicalize_replace_cache(ledger->header().hash, ledger); if (validated) mLedgersByIndex[ledger->header().seq] = ledger->header().hash; @@ -83,17 +71,13 @@ LedgerHistory::getLedgerBySeq(LedgerIndex index) if (!ret) return ret; - XRPL_ASSERT( - ret->header().seq == index, - "xrpl::LedgerHistory::getLedgerBySeq : result sequence match"); + XRPL_ASSERT(ret->header().seq == index, "xrpl::LedgerHistory::getLedgerBySeq : result sequence match"); { // Add this ledger to the local tracking by index std::unique_lock sl(m_ledgers_by_hash.peekMutex()); - XRPL_ASSERT( - ret->isImmutable(), - "xrpl::LedgerHistory::getLedgerBySeq : immutable result ledger"); + XRPL_ASSERT(ret->isImmutable(), "xrpl::LedgerHistory::getLedgerBySeq : immutable result ledger"); m_ledgers_by_hash.canonicalize_replace_client(ret->header().hash, ret); mLedgersByIndex[ret->header().seq] = ret->header().hash; return (ret->header().seq == index) ? ret : nullptr; @@ -123,48 +107,32 @@ LedgerHistory::getLedgerByHash(LedgerHash const& hash) if (!ret) return ret; - XRPL_ASSERT( - ret->isImmutable(), - "xrpl::LedgerHistory::getLedgerByHash : immutable loaded ledger"); - XRPL_ASSERT( - ret->header().hash == hash, - "xrpl::LedgerHistory::getLedgerByHash : loaded ledger hash match"); + XRPL_ASSERT(ret->isImmutable(), "xrpl::LedgerHistory::getLedgerByHash : immutable loaded ledger"); + XRPL_ASSERT(ret->header().hash == hash, "xrpl::LedgerHistory::getLedgerByHash : loaded ledger hash match"); m_ledgers_by_hash.canonicalize_replace_client(ret->header().hash, ret); - XRPL_ASSERT( - ret->header().hash == hash, - "xrpl::LedgerHistory::getLedgerByHash : result hash match"); + XRPL_ASSERT(ret->header().hash == hash, "xrpl::LedgerHistory::getLedgerByHash : result hash match"); return ret; } static void -log_one( - ReadView const& ledger, - uint256 const& tx, - char const* msg, - beast::Journal& j) +log_one(ReadView const& ledger, uint256 const& tx, char const* msg, beast::Journal& j) { auto metaData = ledger.txRead(tx).second; if (metaData != nullptr) { - JLOG(j.debug()) << "MISMATCH on TX " << tx << ": " << msg - << " is missing this transaction:\n" + JLOG(j.debug()) << "MISMATCH on TX " << tx << ": " << msg << " is missing this transaction:\n" << metaData->getJson(JsonOptions::none); } else { - JLOG(j.debug()) << "MISMATCH on TX " << tx << ": " << msg - << " is missing this transaction."; + JLOG(j.debug()) << "MISMATCH on TX " << tx << ": " << msg << " is missing this transaction."; } } static void -log_metadata_difference( - ReadView const& builtLedger, - ReadView const& validLedger, - uint256 const& tx, - beast::Journal j) +log_metadata_difference(ReadView const& builtLedger, ReadView const& validLedger, uint256 const& tx, beast::Journal j) { auto getMeta = [](ReadView const& ledger, uint256 const& txID) { std::optional ret; @@ -176,27 +144,22 @@ log_metadata_difference( auto validMetaData = getMeta(validLedger, tx); auto builtMetaData = getMeta(builtLedger, tx); - XRPL_ASSERT( - validMetaData || builtMetaData, - "xrpl::log_metadata_difference : some metadata present"); + XRPL_ASSERT(validMetaData || builtMetaData, "xrpl::log_metadata_difference : some metadata present"); if (validMetaData && builtMetaData) { auto const& validNodes = validMetaData->getNodes(); auto const& builtNodes = builtMetaData->getNodes(); - bool const result_diff = - validMetaData->getResultTER() != builtMetaData->getResultTER(); + bool const result_diff = validMetaData->getResultTER() != builtMetaData->getResultTER(); - bool const index_diff = - validMetaData->getIndex() != builtMetaData->getIndex(); + bool const index_diff = validMetaData->getIndex() != builtMetaData->getIndex(); bool const nodes_diff = validNodes != builtNodes; if (!result_diff && !index_diff && !nodes_diff) { - JLOG(j.error()) << "MISMATCH on TX " << tx - << ": No apparent mismatches detected!"; + JLOG(j.error()) << "MISMATCH on TX " << tx << ": No apparent mismatches detected!"; return; } @@ -204,19 +167,15 @@ log_metadata_difference( { if (result_diff && index_diff) { - JLOG(j.debug()) << "MISMATCH on TX " << tx - << ": Different result and index!"; + JLOG(j.debug()) << "MISMATCH on TX " << tx << ": Different result and index!"; JLOG(j.debug()) << " Built:" - << " Result: " << builtMetaData->getResult() - << " Index: " << builtMetaData->getIndex(); + << " Result: " << builtMetaData->getResult() << " Index: " << builtMetaData->getIndex(); JLOG(j.debug()) << " Valid:" - << " Result: " << validMetaData->getResult() - << " Index: " << validMetaData->getIndex(); + << " Result: " << validMetaData->getResult() << " Index: " << validMetaData->getIndex(); } else if (result_diff) { - JLOG(j.debug()) - << "MISMATCH on TX " << tx << ": Different result!"; + JLOG(j.debug()) << "MISMATCH on TX " << tx << ": Different result!"; JLOG(j.debug()) << " Built:" << " Result: " << builtMetaData->getResult(); JLOG(j.debug()) << " Valid:" @@ -224,8 +183,7 @@ log_metadata_difference( } else if (index_diff) { - JLOG(j.debug()) - << "MISMATCH on TX " << tx << ": Different index!"; + JLOG(j.debug()) << "MISMATCH on TX " << tx << ": Different index!"; JLOG(j.debug()) << " Built:" << " Index: " << builtMetaData->getIndex(); JLOG(j.debug()) << " Valid:" @@ -236,43 +194,33 @@ log_metadata_difference( { if (result_diff && index_diff) { - JLOG(j.debug()) << "MISMATCH on TX " << tx - << ": Different result, index and nodes!"; - JLOG(j.debug()) << " Built:\n" - << builtMetaData->getJson(JsonOptions::none); - JLOG(j.debug()) << " Valid:\n" - << validMetaData->getJson(JsonOptions::none); + JLOG(j.debug()) << "MISMATCH on TX " << tx << ": Different result, index and nodes!"; + JLOG(j.debug()) << " Built:\n" << builtMetaData->getJson(JsonOptions::none); + JLOG(j.debug()) << " Valid:\n" << validMetaData->getJson(JsonOptions::none); } else if (result_diff) { - JLOG(j.debug()) << "MISMATCH on TX " << tx - << ": Different result and nodes!"; - JLOG(j.debug()) - << " Built:" - << " Result: " << builtMetaData->getResult() << " Nodes:\n" - << builtNodes.getJson(JsonOptions::none); - JLOG(j.debug()) - << " Valid:" - << " Result: " << validMetaData->getResult() << " Nodes:\n" - << validNodes.getJson(JsonOptions::none); + JLOG(j.debug()) << "MISMATCH on TX " << tx << ": Different result and nodes!"; + JLOG(j.debug()) << " Built:" + << " Result: " << builtMetaData->getResult() << " Nodes:\n" + << builtNodes.getJson(JsonOptions::none); + JLOG(j.debug()) << " Valid:" + << " Result: " << validMetaData->getResult() << " Nodes:\n" + << validNodes.getJson(JsonOptions::none); } else if (index_diff) { - JLOG(j.debug()) << "MISMATCH on TX " << tx - << ": Different index and nodes!"; - JLOG(j.debug()) - << " Built:" - << " Index: " << builtMetaData->getIndex() << " Nodes:\n" - << builtNodes.getJson(JsonOptions::none); - JLOG(j.debug()) - << " Valid:" - << " Index: " << validMetaData->getIndex() << " Nodes:\n" - << validNodes.getJson(JsonOptions::none); + JLOG(j.debug()) << "MISMATCH on TX " << tx << ": Different index and nodes!"; + JLOG(j.debug()) << " Built:" + << " Index: " << builtMetaData->getIndex() << " Nodes:\n" + << builtNodes.getJson(JsonOptions::none); + JLOG(j.debug()) << " Valid:" + << " Index: " << validMetaData->getIndex() << " Nodes:\n" + << validNodes.getJson(JsonOptions::none); } else // nodes_diff { - JLOG(j.debug()) - << "MISMATCH on TX " << tx << ": Different nodes!"; + JLOG(j.debug()) << "MISMATCH on TX " << tx << ": Different nodes!"; JLOG(j.debug()) << " Built:" << " Nodes:\n" << builtNodes.getJson(JsonOptions::none); @@ -287,15 +235,13 @@ log_metadata_difference( if (validMetaData) { - JLOG(j.error()) << "MISMATCH on TX " << tx - << ": Metadata Difference. Valid=\n" + JLOG(j.error()) << "MISMATCH on TX " << tx << ": Metadata Difference. Valid=\n" << validMetaData->getJson(JsonOptions::none); } if (builtMetaData) { - JLOG(j.error()) << "MISMATCH on TX " << tx - << ": Metadata Difference. Built=\n" + JLOG(j.error()) << "MISMATCH on TX " << tx << ": Metadata Difference. Built=\n" << builtMetaData->getJson(JsonOptions::none); } } @@ -309,10 +255,7 @@ leaves(SHAMap const& sm) std::vector v; for (auto const& item : sm) v.push_back(&item); - std::sort( - v.begin(), v.end(), [](SHAMapItem const* lhs, SHAMapItem const* rhs) { - return lhs->key() < rhs->key(); - }); + std::sort(v.begin(), v.end(), [](SHAMapItem const* lhs, SHAMapItem const* rhs) { return lhs->key() < rhs->key(); }); return v; } @@ -324,8 +267,7 @@ LedgerHistory::handleMismatch( std::optional const& validatedConsensusHash, Json::Value const& consensus) { - XRPL_ASSERT( - built != valid, "xrpl::LedgerHistory::handleMismatch : unequal hashes"); + XRPL_ASSERT(built != valid, "xrpl::LedgerHistory::handleMismatch : unequal hashes"); ++mismatch_counter_; auto builtLedger = getLedgerByHash(built); @@ -334,15 +276,13 @@ LedgerHistory::handleMismatch( if (!builtLedger || !validLedger) { JLOG(j_.error()) << "MISMATCH cannot be analyzed:" - << " builtLedger: " << to_string(built) << " -> " - << builtLedger << " validLedger: " << to_string(valid) - << " -> " << validLedger; + << " builtLedger: " << to_string(built) << " -> " << builtLedger + << " validLedger: " << to_string(valid) << " -> " << validLedger; return; } XRPL_ASSERT( - builtLedger->header().seq == validLedger->header().seq, - "xrpl::LedgerHistory::handleMismatch : sequence match"); + builtLedger->header().seq == validLedger->header().seq, "xrpl::LedgerHistory::handleMismatch : sequence match"); if (auto stream = j_.debug()) { @@ -371,13 +311,11 @@ LedgerHistory::handleMismatch( if (builtConsensusHash && validatedConsensusHash) { if (builtConsensusHash != validatedConsensusHash) - JLOG(j_.error()) - << "MISMATCH on consensus transaction set " - << " built: " << to_string(*builtConsensusHash) - << " validated: " << to_string(*validatedConsensusHash); + JLOG(j_.error()) << "MISMATCH on consensus transaction set " + << " built: " << to_string(*builtConsensusHash) + << " validated: " << to_string(*validatedConsensusHash); else - JLOG(j_.error()) << "MISMATCH with same consensus transaction set: " - << to_string(*builtConsensusHash); + JLOG(j_.error()) << "MISMATCH with same consensus transaction set: " << to_string(*builtConsensusHash); } // Find differences between built and valid ledgers @@ -385,11 +323,10 @@ LedgerHistory::handleMismatch( auto const validTx = leaves(validLedger->txMap()); if (builtTx == validTx) - JLOG(j_.error()) << "MISMATCH with same " << builtTx.size() - << " transactions"; + JLOG(j_.error()) << "MISMATCH with same " << builtTx.size() << " transactions"; else - JLOG(j_.error()) << "MISMATCH with " << builtTx.size() << " built and " - << validTx.size() << " valid transactions."; + JLOG(j_.error()) << "MISMATCH with " << builtTx.size() << " built and " << validTx.size() + << " valid transactions."; JLOG(j_.error()) << "built\n" << getJson({*builtLedger, {}}); JLOG(j_.error()) << "valid\n" << getJson({*validLedger, {}}); @@ -414,8 +351,7 @@ LedgerHistory::handleMismatch( if ((*b)->slice() != (*v)->slice()) { // Same transaction with different metadata - log_metadata_difference( - *builtLedger, *validLedger, (*b)->key(), j_); + log_metadata_difference(*builtLedger, *validLedger, (*b)->key(), j_); } ++b; ++v; @@ -435,8 +371,7 @@ LedgerHistory::builtLedger( { LedgerIndex index = ledger->header().seq; LedgerHash hash = ledger->header().hash; - XRPL_ASSERT( - !hash.isZero(), "xrpl::LedgerHistory::builtLedger : nonzero hash"); + XRPL_ASSERT(!hash.isZero(), "xrpl::LedgerHistory::builtLedger : nonzero hash"); std::unique_lock sl(m_consensus_validated.peekMutex()); @@ -447,15 +382,9 @@ LedgerHistory::builtLedger( { if (entry->validated.value() != hash) { - JLOG(j_.error()) << "MISMATCH: seq=" << index - << " validated:" << entry->validated.value() + JLOG(j_.error()) << "MISMATCH: seq=" << index << " validated:" << entry->validated.value() << " then:" << hash; - handleMismatch( - hash, - entry->validated.value(), - consensusHash, - entry->validatedConsensusHash, - consensus); + handleMismatch(hash, entry->validated.value(), consensusHash, entry->validatedConsensusHash, consensus); } else { @@ -470,14 +399,11 @@ LedgerHistory::builtLedger( } void -LedgerHistory::validatedLedger( - std::shared_ptr const& ledger, - std::optional const& consensusHash) +LedgerHistory::validatedLedger(std::shared_ptr const& ledger, std::optional const& consensusHash) { LedgerIndex index = ledger->header().seq; LedgerHash hash = ledger->header().hash; - XRPL_ASSERT( - !hash.isZero(), "xrpl::LedgerHistory::validatedLedger : nonzero hash"); + XRPL_ASSERT(!hash.isZero(), "xrpl::LedgerHistory::validatedLedger : nonzero hash"); std::unique_lock sl(m_consensus_validated.peekMutex()); @@ -488,15 +414,9 @@ LedgerHistory::validatedLedger( { if (entry->built.value() != hash) { - JLOG(j_.error()) - << "MISMATCH: seq=" << index - << " built:" << entry->built.value() << " then:" << hash; + JLOG(j_.error()) << "MISMATCH: seq=" << index << " built:" << entry->built.value() << " then:" << hash; handleMismatch( - entry->built.value(), - hash, - entry->builtConsensusHash, - consensusHash, - entry->consensus.value()); + entry->built.value(), hash, entry->builtConsensusHash, consensusHash, entry->consensus.value()); } else { diff --git a/src/xrpld/app/ledger/LedgerHistory.h b/src/xrpld/app/ledger/LedgerHistory.h index 279d009429..e8784eb599 100644 --- a/src/xrpld/app/ledger/LedgerHistory.h +++ b/src/xrpld/app/ledger/LedgerHistory.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_LEDGER_LEDGERHISTORY_H_INCLUDED -#define XRPL_APP_LEDGER_LEDGERHISTORY_H_INCLUDED +#pragma once #include #include @@ -17,9 +16,7 @@ namespace xrpl { class LedgerHistory { public: - LedgerHistory( - beast::insight::Collector::ptr const& collector, - Application& app); + LedgerHistory(beast::insight::Collector::ptr const& collector, Application& app); /** Track a ledger @return `true` if the ledger was already tracked @@ -62,16 +59,11 @@ public: /** Report that we have locally built a particular ledger */ void - builtLedger( - std::shared_ptr const&, - uint256 const& consensusHash, - Json::Value); + builtLedger(std::shared_ptr const&, uint256 const& consensusHash, Json::Value); /** Report that we have validated a particular ledger */ void - validatedLedger( - std::shared_ptr const&, - std::optional const& consensusHash); + validatedLedger(std::shared_ptr const&, std::optional const& consensusHash); /** Repair a hash to index mapping @param ledgerIndex The index whose mapping is to be repaired @@ -136,5 +128,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/src/xrpld/app/ledger/LedgerHolder.h b/src/xrpld/app/ledger/LedgerHolder.h index c0a81778ae..8d2ac9f308 100644 --- a/src/xrpld/app/ledger/LedgerHolder.h +++ b/src/xrpld/app/ledger/LedgerHolder.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_LEDGER_LEDGERHOLDER_H_INCLUDED -#define XRPL_APP_LEDGER_LEDGERHOLDER_H_INCLUDED +#pragma once #include #include @@ -54,5 +53,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/src/xrpld/app/ledger/LedgerMaster.h b/src/xrpld/app/ledger/LedgerMaster.h index 38dff835b7..ceb9fa9045 100644 --- a/src/xrpld/app/ledger/LedgerMaster.h +++ b/src/xrpld/app/ledger/LedgerMaster.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_LEDGER_LEDGERMASTER_H_INCLUDED -#define XRPL_APP_LEDGER_LEDGERMASTER_H_INCLUDED +#pragma once #include #include @@ -89,10 +88,7 @@ public: storeLedger(std::shared_ptr ledger); void - setFullLedger( - std::shared_ptr const& ledger, - bool isSynchronous, - bool isCurrent); + setFullLedger(std::shared_ptr const& ledger, bool isSynchronous, bool isCurrent); /** Check the sequence number and parent close time of a ledger against our clock and last validated ledger to @@ -189,10 +185,7 @@ public: void checkAccept(uint256 const& hash, std::uint32_t seq); void - consensusBuilt( - std::shared_ptr const& ledger, - uint256 const& consensusHash, - Json::Value consensus); + consensusBuilt(std::shared_ptr const& ledger, uint256 const& consensusHash, Json::Value consensus); void setBuildingLedger(LedgerIndex index); @@ -338,8 +331,7 @@ private: int mPathFindThread{0}; // Pathfinder jobs dispatched bool mPathFindNewRequest{false}; - std::atomic_flag mGotFetchPackThread = - ATOMIC_FLAG_INIT; // GotFetchPack jobs dispatched + std::atomic_flag mGotFetchPackThread = ATOMIC_FLAG_INIT; // GotFetchPack jobs dispatched std::atomic mPubLedgerClose{0}; std::atomic mPubLedgerSeq{0}; @@ -373,14 +365,10 @@ private: struct Stats { template - Stats( - Handler const& handler, - beast::insight::Collector::ptr const& collector) + Stats(Handler const& handler, beast::insight::Collector::ptr const& collector) : hook(collector->make_hook(handler)) - , validatedLedgerAge( - collector->make_gauge("LedgerMaster", "Validated_Ledger_Age")) - , publishedLedgerAge( - collector->make_gauge("LedgerMaster", "Published_Ledger_Age")) + , validatedLedgerAge(collector->make_gauge("LedgerMaster", "Validated_Ledger_Age")) + , publishedLedgerAge(collector->make_gauge("LedgerMaster", "Published_Ledger_Age")) { } @@ -402,5 +390,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/src/xrpld/app/ledger/LedgerReplay.h b/src/xrpld/app/ledger/LedgerReplay.h index 29e8a835fe..f4cbf9c69e 100644 --- a/src/xrpld/app/ledger/LedgerReplay.h +++ b/src/xrpld/app/ledger/LedgerReplay.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_LEDGER_LEDGERREPLAY_H_INCLUDED -#define XRPL_APP_LEDGER_LEDGERREPLAY_H_INCLUDED +#pragma once #include @@ -18,9 +17,7 @@ class LedgerReplay : public CountedObject std::map> orderedTxns_; public: - LedgerReplay( - std::shared_ptr parent, - std::shared_ptr replay); + LedgerReplay(std::shared_ptr parent, std::shared_ptr replay); LedgerReplay( std::shared_ptr parent, @@ -53,5 +50,3 @@ public: }; } // namespace xrpl - -#endif diff --git a/src/xrpld/app/ledger/LedgerReplayTask.h b/src/xrpld/app/ledger/LedgerReplayTask.h index 623a193d93..94eeee5f51 100644 --- a/src/xrpld/app/ledger/LedgerReplayTask.h +++ b/src/xrpld/app/ledger/LedgerReplayTask.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_LEDGER_LEDGERREPLAYTASK_H_INCLUDED -#define XRPL_APP_LEDGER_LEDGERREPLAYTASK_H_INCLUDED +#pragma once #include #include @@ -17,10 +16,9 @@ namespace test { class LedgerReplayClient; } // namespace test -class LedgerReplayTask final - : public TimeoutCounter, - public std::enable_shared_from_this, - public CountedObject +class LedgerReplayTask final : public TimeoutCounter, + public std::enable_shared_from_this, + public CountedObject { public: class TaskParameter @@ -44,10 +42,7 @@ public: * @param finishLedgerHash hash of the last ledger in the range * @param totalNumLedgers number of ledgers to download */ - TaskParameter( - InboundLedger::Reason r, - uint256 const& finishLedgerHash, - std::uint32_t totalNumLedgers); + TaskParameter(InboundLedger::Reason r, uint256 const& finishLedgerHash, std::uint32_t totalNumLedgers); /** * fill all the fields that was not filled during construction @@ -59,10 +54,7 @@ public: * true on success */ bool - update( - uint256 const& hash, - std::uint32_t seq, - std::vector const& sList); + update(uint256 const& hash, std::uint32_t seq, std::vector const& sList); /** check if this task can be merged into an existing task */ bool @@ -123,10 +115,7 @@ private: * @param sList skip list */ void - updateSkipList( - uint256 const& hash, - std::uint32_t seq, - std::vector const& sList); + updateSkipList(uint256 const& hash, std::uint32_t seq, std::vector const& sList); /** * Notify this task (by a LedgerDeltaAcquire subtask) that a delta is ready @@ -162,5 +151,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/src/xrpld/app/ledger/LedgerReplayer.h b/src/xrpld/app/ledger/LedgerReplayer.h index b0e0692019..0d08e5a76f 100644 --- a/src/xrpld/app/ledger/LedgerReplayer.h +++ b/src/xrpld/app/ledger/LedgerReplayer.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_LEDGER_LEDGERREPLAYER_H_INCLUDED -#define XRPL_APP_LEDGER_LEDGERREPLAYER_H_INCLUDED +#pragma once #include #include @@ -53,10 +52,7 @@ std::uint32_t constexpr MAX_QUEUED_TASKS = 100; class LedgerReplayer final { public: - LedgerReplayer( - Application& app, - InboundLedgers& inboundLedgers, - std::unique_ptr peerSetBuilder); + LedgerReplayer(Application& app, InboundLedgers& inboundLedgers, std::unique_ptr peerSetBuilder); ~LedgerReplayer(); @@ -68,10 +64,7 @@ public: * @note totalNumLedgers must > 0 && totalNumLedgers must <= 256 */ void - replay( - InboundLedger::Reason r, - uint256 const& finishLedgerHash, - std::uint32_t totalNumLedgers); + replay(InboundLedger::Reason r, uint256 const& finishLedgerHash, std::uint32_t totalNumLedgers); /** Create LedgerDeltaAcquire subtasks for the LedgerReplayTask task */ void @@ -84,9 +77,7 @@ public: * @note info and data must have been verified against the ledger hash */ void - gotSkipList( - LedgerHeader const& info, - boost::intrusive_ptr const& data); + gotSkipList(LedgerHeader const& info, boost::intrusive_ptr const& data); /** * Process a ledger delta (extracted from a TMReplayDeltaResponse message) @@ -95,9 +86,7 @@ public: * @note info and txns must have been verified against the ledger hash */ void - gotReplayDelta( - LedgerHeader const& info, - std::map>&& txns); + gotReplayDelta(LedgerHeader const& info, std::map>&& txns); /** Remove completed tasks */ void @@ -142,5 +131,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/src/xrpld/app/ledger/LedgerToJson.h b/src/xrpld/app/ledger/LedgerToJson.h index 7b7e267d81..8cde134d23 100644 --- a/src/xrpld/app/ledger/LedgerToJson.h +++ b/src/xrpld/app/ledger/LedgerToJson.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_LEDGER_LEDGERTOJSON_H_INCLUDED -#define XRPL_APP_LEDGER_LEDGERTOJSON_H_INCLUDED +#pragma once #include #include @@ -13,26 +12,14 @@ namespace xrpl { struct LedgerFill { - LedgerFill( - ReadView const& l, - RPC::Context const* ctx, - int o = 0, - std::vector q = {}) + LedgerFill(ReadView const& l, RPC::Context const* ctx, int o = 0, std::vector q = {}) : ledger(l), options(o), txQueue(std::move(q)), context(ctx) { if (context) closeTime = context->ledgerMaster.getCloseTimeBySeq(ledger.seq()); } - enum Options { - dumpTxrp = 1, - dumpState = 2, - expand = 4, - full = 8, - binary = 16, - ownerFunds = 32, - dumpQueue = 64 - }; + enum Options { dumpTxrp = 1, dumpState = 2, expand = 4, full = 8, binary = 16, ownerFunds = 32, dumpQueue = 64 }; ReadView const& ledger; int options; @@ -56,5 +43,3 @@ void copyFrom(Json::Value& to, Json::Value const& from); } // namespace xrpl - -#endif diff --git a/src/xrpld/app/ledger/LocalTxs.h b/src/xrpld/app/ledger/LocalTxs.h index d02e1027a0..34dfede40f 100644 --- a/src/xrpld/app/ledger/LocalTxs.h +++ b/src/xrpld/app/ledger/LocalTxs.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_LEDGER_LOCALTXS_H_INCLUDED -#define XRPL_APP_LEDGER_LOCALTXS_H_INCLUDED +#pragma once #include @@ -43,5 +42,3 @@ std::unique_ptr make_LocalTxs(); } // namespace xrpl - -#endif diff --git a/src/xrpld/app/ledger/OpenLedger.h b/src/xrpld/app/ledger/OpenLedger.h index 45a3517168..187086862c 100644 --- a/src/xrpld/app/ledger/OpenLedger.h +++ b/src/xrpld/app/ledger/OpenLedger.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_LEDGER_OPENLEDGER_H_INCLUDED -#define XRPL_APP_LEDGER_OPENLEDGER_H_INCLUDED +#pragma once #include #include @@ -61,10 +60,7 @@ public: @param ledger A closed ledger */ - explicit OpenLedger( - std::shared_ptr const& ledger, - CachedSLEs& cache, - beast::Journal journal); + explicit OpenLedger(std::shared_ptr const& ledger, CachedSLEs& cache, beast::Journal journal); /** Returns `true` if there are no transactions. @@ -213,8 +209,7 @@ OpenLedger::apply( } catch (std::exception const& e) { - JLOG(j.error()) - << "OpenLedger::apply: Caught exception: " << e.what(); + JLOG(j.error()) << "OpenLedger::apply: Caught exception: " << e.what(); } } bool retry = true; @@ -246,8 +241,7 @@ OpenLedger::apply( // If there are any transactions left, we must have // tried them in at least one final pass - XRPL_ASSERT( - retries.empty() || !retry, "xrpl::OpenLedger::apply : valid retries"); + XRPL_ASSERT(retries.empty() || !retry, "xrpl::OpenLedger::apply : valid retries"); } //------------------------------------------------------------------------------ @@ -267,5 +261,3 @@ std::string debugTostr(std::shared_ptr const& view); } // namespace xrpl - -#endif diff --git a/src/xrpld/app/ledger/OrderBookDB.h b/src/xrpld/app/ledger/OrderBookDB.h deleted file mode 100644 index 68bdf294a9..0000000000 --- a/src/xrpld/app/ledger/OrderBookDB.h +++ /dev/null @@ -1,86 +0,0 @@ -#ifndef XRPL_APP_LEDGER_ORDERBOOKDB_H_INCLUDED -#define XRPL_APP_LEDGER_ORDERBOOKDB_H_INCLUDED - -#include -#include -#include - -#include -#include - -#include -#include - -namespace xrpl { - -class OrderBookDB -{ -public: - explicit OrderBookDB(Application& app); - - void - setup(std::shared_ptr const& ledger); - void - update(std::shared_ptr const& ledger); - - void - addOrderBook(Book const&); - - /** @return a list of all orderbooks that want this issuerID and currencyID. - */ - std::vector - getBooksByTakerPays( - Issue const&, - std::optional const& domain = std::nullopt); - - /** @return a count of all orderbooks that want this issuerID and - currencyID. */ - int - getBookSize( - Issue const&, - std::optional const& domain = std::nullopt); - - bool - isBookToXRP(Issue const&, std::optional domain = std::nullopt); - - BookListeners::pointer - getBookListeners(Book const&); - BookListeners::pointer - makeBookListeners(Book const&); - - // see if this txn effects any orderbook - void - processTxn( - std::shared_ptr const& ledger, - AcceptedLedgerTx const& alTx, - MultiApiJson const& jvObj); - -private: - Application& app_; - - // Maps order books by "issue in" to "issue out": - hardened_hash_map> allBooks_; - - hardened_hash_map, hardened_hash_set> - domainBooks_; - - // does an order book to XRP exist - hash_set xrpBooks_; - - // does an order book to XRP exist - hash_set> xrpDomainBooks_; - - std::recursive_mutex mLock; - - using BookToListenersMap = hash_map; - - BookToListenersMap mListeners; - - std::atomic seq_; - - beast::Journal const j_; -}; - -} // namespace xrpl - -#endif diff --git a/src/xrpld/app/ledger/OrderBookDB.cpp b/src/xrpld/app/ledger/OrderBookDBImpl.cpp similarity index 77% rename from src/xrpld/app/ledger/OrderBookDB.cpp rename to src/xrpld/app/ledger/OrderBookDBImpl.cpp index 47b04f3d2c..62c03fb7ca 100644 --- a/src/xrpld/app/ledger/OrderBookDB.cpp +++ b/src/xrpld/app/ledger/OrderBookDBImpl.cpp @@ -1,25 +1,34 @@ #include -#include -#include +#include #include -#include #include #include #include #include +#include namespace xrpl { -OrderBookDB::OrderBookDB(Application& app) - : app_(app), seq_(0), j_(app.journal("OrderBookDB")) +OrderBookDBImpl::OrderBookDBImpl(ServiceRegistry& registry, OrderBookDBConfig const& config) + : registry_(registry) + , pathSearchMax_(config.pathSearchMax) + , standalone_(config.standalone) + , seq_(0) + , j_(registry.journal("OrderBookDB")) { } -void -OrderBookDB::setup(std::shared_ptr const& ledger) +std::unique_ptr +make_OrderBookDB(ServiceRegistry& registry, OrderBookDBConfig const& config) { - if (!app_.config().standalone() && app_.getOPs().isNeedNetworkLedger()) + return std::make_unique(registry, config); +} + +void +OrderBookDBImpl::setup(std::shared_ptr const& ledger) +{ + if (!standalone_ && registry_.getOPs().isNeedNetworkLedger()) { JLOG(j_.warn()) << "Eliding full order book update: no ledger"; return; @@ -39,32 +48,28 @@ OrderBookDB::setup(std::shared_ptr const& ledger) if (seq_.exchange(ledger->seq()) != seq) return; - JLOG(j_.debug()) << "Full order book update: " << seq << " to " - << ledger->seq(); + JLOG(j_.debug()) << "Full order book update: " << seq << " to " << ledger->seq(); - if (app_.config().PATH_SEARCH_MAX != 0) + if (pathSearchMax_ != 0) { - if (app_.config().standalone()) + if (standalone_) update(ledger); else - app_.getJobQueue().addJob( - jtUPDATE_PF, - "OrderBookDB::update: " + std::to_string(ledger->seq()), - [this, ledger]() { update(ledger); }); + registry_.getJobQueue().addJob( + jtUPDATE_PF, "OrderBookUpd" + std::to_string(ledger->seq()), [this, ledger]() { update(ledger); }); } } void -OrderBookDB::update(std::shared_ptr const& ledger) +OrderBookDBImpl::update(std::shared_ptr const& ledger) { - if (app_.config().PATH_SEARCH_MAX == 0) + if (pathSearchMax_ == 0) return; // pathfinding has been disabled // A newer full update job is pending if (auto const seq = seq_.load(); seq > ledger->seq()) { - JLOG(j_.debug()) << "Eliding update for " << ledger->seq() - << " because of pending update to later " << seq; + JLOG(j_.debug()) << "Eliding update for " << ledger->seq() << " because of pending update to later " << seq; return; } @@ -85,16 +90,14 @@ OrderBookDB::update(std::shared_ptr const& ledger) { for (auto& sle : ledger->sles) { - if (app_.isStopping()) + if (registry_.isStopping()) { - JLOG(j_.info()) - << "Update halted because the process is stopping"; + JLOG(j_.info()) << "Update halted because the process is stopping"; seq_.store(0); return; } - if (sle->getType() == ltDIR_NODE && - sle->isFieldPresent(sfExchangeRate) && + if (sle->getType() == ltDIR_NODE && sle->isFieldPresent(sfExchangeRate) && sle->getFieldH256(sfRootIndex) == sle->key()) { Book book; @@ -136,14 +139,12 @@ OrderBookDB::update(std::shared_ptr const& ledger) } catch (SHAMapMissingNode const& mn) { - JLOG(j_.info()) << "Missing node in " << ledger->seq() - << " during update: " << mn.what(); + JLOG(j_.info()) << "Missing node in " << ledger->seq() << " during update: " << mn.what(); seq_.store(0); return; } - JLOG(j_.debug()) << "Update completed (" << ledger->seq() << "): " << cnt - << " books found"; + JLOG(j_.debug()) << "Update completed (" << ledger->seq() << "): " << cnt << " books found"; { std::lock_guard sl(mLock); @@ -153,11 +154,11 @@ OrderBookDB::update(std::shared_ptr const& ledger) xrpDomainBooks_.swap(xrpDomainBooks); } - app_.getLedgerMaster().newOrderBookDB(); + registry_.getLedgerMaster().newOrderBookDB(); } void -OrderBookDB::addOrderBook(Book const& book) +OrderBookDBImpl::addOrderBook(Book const& book) { bool toXRP = isXRP(book.out); @@ -176,9 +177,7 @@ OrderBookDB::addOrderBook(Book const& book) // return list of all orderbooks that want this issuerID and currencyID std::vector -OrderBookDB::getBooksByTakerPays( - Issue const& issue, - std::optional const& domain) +OrderBookDBImpl::getBooksByTakerPays(Issue const& issue, std::optional const& domain) { std::vector ret; @@ -206,9 +205,7 @@ OrderBookDB::getBooksByTakerPays( } int -OrderBookDB::getBookSize( - Issue const& issue, - std::optional const& domain) +OrderBookDBImpl::getBookSize(Issue const& issue, std::optional const& domain) { std::lock_guard sl(mLock); @@ -219,8 +216,7 @@ OrderBookDB::getBookSize( } else { - if (auto it = domainBooks_.find({issue, *domain}); - it != domainBooks_.end()) + if (auto it = domainBooks_.find({issue, *domain}); it != domainBooks_.end()) return static_cast(it->second.size()); } @@ -228,7 +224,7 @@ OrderBookDB::getBookSize( } bool -OrderBookDB::isBookToXRP(Issue const& issue, std::optional domain) +OrderBookDBImpl::isBookToXRP(Issue const& issue, std::optional domain) { std::lock_guard sl(mLock); if (domain) @@ -237,7 +233,7 @@ OrderBookDB::isBookToXRP(Issue const& issue, std::optional domain) } BookListeners::pointer -OrderBookDB::makeBookListeners(Book const& book) +OrderBookDBImpl::makeBookListeners(Book const& book) { std::lock_guard sl(mLock); auto ret = getBookListeners(book); @@ -257,7 +253,7 @@ OrderBookDB::makeBookListeners(Book const& book) } BookListeners::pointer -OrderBookDB::getBookListeners(Book const& book) +OrderBookDBImpl::getBookListeners(Book const& book) { BookListeners::pointer ret; std::lock_guard sl(mLock); @@ -272,7 +268,7 @@ OrderBookDB::getBookListeners(Book const& book) // Based on the meta, send the meta to the streams that are listening. // We need to determine which streams a given meta effects. void -OrderBookDB::processTxn( +OrderBookDBImpl::processTxn( std::shared_ptr const& ledger, AcceptedLedgerTx const& alTx, MultiApiJson const& jvObj) @@ -293,10 +289,8 @@ OrderBookDB::processTxn( if (node.getFieldU16(sfLedgerEntryType) == ltOFFER) { auto process = [&, this](SField const& field) { - if (auto data = dynamic_cast( - node.peekAtPField(field)); - data && data->isFieldPresent(sfTakerPays) && - data->isFieldPresent(sfTakerGets)) + if (auto data = dynamic_cast(node.peekAtPField(field)); + data && data->isFieldPresent(sfTakerPays) && data->isFieldPresent(sfTakerGets)) { auto listeners = getBookListeners( {data->getFieldAmount(sfTakerGets).issue(), @@ -319,8 +313,7 @@ OrderBookDB::processTxn( } catch (std::exception const& ex) { - JLOG(j_.info()) - << "processTxn: field not found (" << ex.what() << ")"; + JLOG(j_.info()) << "processTxn: field not found (" << ex.what() << ")"; } } } diff --git a/src/xrpld/app/ledger/OrderBookDBImpl.h b/src/xrpld/app/ledger/OrderBookDBImpl.h new file mode 100644 index 0000000000..69739451c4 --- /dev/null +++ b/src/xrpld/app/ledger/OrderBookDBImpl.h @@ -0,0 +1,93 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace xrpl { + +/** Configuration for OrderBookDB */ +struct OrderBookDBConfig +{ + int pathSearchMax; + bool standalone; +}; + +/** Create an OrderBookDB instance. + + @param registry Service registry for accessing other services + @param config Configuration parameters + @return A new OrderBookDB instance +*/ +std::unique_ptr +make_OrderBookDB(ServiceRegistry& registry, OrderBookDBConfig const& config); + +class OrderBookDBImpl final : public OrderBookDB +{ +public: + OrderBookDBImpl(ServiceRegistry& registry, OrderBookDBConfig const& config); + + // OrderBookDB interface implementation + void + setup(std::shared_ptr const& ledger) override; + + void + addOrderBook(Book const& book) override; + + std::vector + getBooksByTakerPays(Issue const& issue, std::optional const& domain = std::nullopt) override; + + int + getBookSize(Issue const& issue, std::optional const& domain = std::nullopt) override; + + bool + isBookToXRP(Issue const& issue, std::optional domain = std::nullopt) override; + + // OrderBookDBImpl-specific methods + void + update(std::shared_ptr const& ledger); + + // see if this txn effects any orderbook + void + processTxn(std::shared_ptr const& ledger, AcceptedLedgerTx const& alTx, MultiApiJson const& jvObj) + override; + + BookListeners::pointer + getBookListeners(Book const&) override; + BookListeners::pointer + makeBookListeners(Book const&) override; + +private: + ServiceRegistry& registry_; + int const pathSearchMax_; + bool const standalone_; + + // Maps order books by "issue in" to "issue out": + hardened_hash_map> allBooks_; + + hardened_hash_map, hardened_hash_set> domainBooks_; + + // does an order book to XRP exist + hash_set xrpBooks_; + + // does an order book to XRP exist + hash_set> xrpDomainBooks_; + + std::recursive_mutex mLock; + + using BookToListenersMap = hash_map; + + BookToListenersMap mListeners; + + std::atomic seq_; + + beast::Journal const j_; +}; + +} // namespace xrpl diff --git a/src/xrpld/app/ledger/PendingSaves.h b/src/xrpld/app/ledger/PendingSaves.h index 24eb50e568..76958fc78a 100644 --- a/src/xrpld/app/ledger/PendingSaves.h +++ b/src/xrpld/app/ledger/PendingSaves.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_PENDINGSAVES_H_INCLUDED -#define XRPL_APP_PENDINGSAVES_H_INCLUDED +#pragma once #include @@ -125,5 +124,3 @@ public: }; } // namespace xrpl - -#endif diff --git a/src/xrpld/app/ledger/TransactionMaster.h b/src/xrpld/app/ledger/TransactionMaster.h index a9bf05065d..039ff5cb99 100644 --- a/src/xrpld/app/ledger/TransactionMaster.h +++ b/src/xrpld/app/ledger/TransactionMaster.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_LEDGER_TRANSACTIONMASTER_H_INCLUDED -#define XRPL_APP_LEDGER_TRANSACTIONMASTER_H_INCLUDED +#pragma once #include @@ -27,9 +26,7 @@ public: std::shared_ptr fetch_from_cache(uint256 const&); - std::variant< - std::pair, std::shared_ptr>, - TxSearched> + std::variant, std::shared_ptr>, TxSearched> fetch(uint256 const&, error_code_i& ec); /** @@ -41,27 +38,15 @@ public: * the all ledgers in the provided range were present in * the database while the search was conducted. */ - std::variant< - std::pair, std::shared_ptr>, - TxSearched> - fetch( - uint256 const&, - ClosedInterval const& range, - error_code_i& ec); + std::variant, std::shared_ptr>, TxSearched> + fetch(uint256 const&, ClosedInterval const& range, error_code_i& ec); std::shared_ptr - fetch( - boost::intrusive_ptr const& item, - SHAMapNodeType type, - std::uint32_t uCommitLedger); + fetch(boost::intrusive_ptr const& item, SHAMapNodeType type, std::uint32_t uCommitLedger); // return value: true = we had the transaction already bool - inLedger( - uint256 const& hash, - std::uint32_t ledger, - std::optional tseq, - std::optional netID); + inLedger(uint256 const& hash, std::uint32_t ledger, std::optional tseq, std::optional netID); void canonicalize(std::shared_ptr* pTransaction); @@ -78,5 +63,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/src/xrpld/app/ledger/TransactionStateSF.cpp b/src/xrpld/app/ledger/TransactionStateSF.cpp index af7dd8640a..ee2febbd83 100644 --- a/src/xrpld/app/ledger/TransactionStateSF.cpp +++ b/src/xrpld/app/ledger/TransactionStateSF.cpp @@ -11,14 +11,8 @@ TransactionStateSF::gotNode( SHAMapNodeType type) const { - XRPL_ASSERT( - type != SHAMapNodeType::tnTRANSACTION_NM, - "xrpl::TransactionStateSF::gotNode : valid input"); - db_.store( - hotTRANSACTION_NODE, - std::move(nodeData), - nodeHash.as_uint256(), - ledgerSeq); + XRPL_ASSERT(type != SHAMapNodeType::tnTRANSACTION_NM, "xrpl::TransactionStateSF::gotNode : valid input"); + db_.store(hotTRANSACTION_NODE, std::move(nodeData), nodeHash.as_uint256(), ledgerSeq); } std::optional diff --git a/src/xrpld/app/ledger/TransactionStateSF.h b/src/xrpld/app/ledger/TransactionStateSF.h index 9950134e4b..2851884cfd 100644 --- a/src/xrpld/app/ledger/TransactionStateSF.h +++ b/src/xrpld/app/ledger/TransactionStateSF.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_LEDGER_TRANSACTIONSTATESF_H_INCLUDED -#define XRPL_APP_LEDGER_TRANSACTIONSTATESF_H_INCLUDED +#pragma once #include @@ -13,18 +12,13 @@ namespace xrpl { class TransactionStateSF : public SHAMapSyncFilter { public: - TransactionStateSF(NodeStore::Database& db, AbstractFetchPackContainer& fp) - : db_(db), fp_(fp) + TransactionStateSF(NodeStore::Database& db, AbstractFetchPackContainer& fp) : db_(db), fp_(fp) { } void - gotNode( - bool fromFilter, - SHAMapHash const& nodeHash, - std::uint32_t ledgerSeq, - Blob&& nodeData, - SHAMapNodeType type) const override; + gotNode(bool fromFilter, SHAMapHash const& nodeHash, std::uint32_t ledgerSeq, Blob&& nodeData, SHAMapNodeType type) + const override; std::optional getNode(SHAMapHash const& nodeHash) const override; @@ -35,5 +29,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/src/xrpld/app/ledger/detail/BuildLedger.cpp b/src/xrpld/app/ledger/detail/BuildLedger.cpp index a716375f6b..1414441b35 100644 --- a/src/xrpld/app/ledger/detail/BuildLedger.cpp +++ b/src/xrpld/app/ledger/detail/BuildLedger.cpp @@ -38,8 +38,7 @@ buildLedgerImpl( { OpenView accum(&*built); - XRPL_ASSERT( - !accum.open(), "xrpl::buildLedgerImpl : valid ledger state"); + XRPL_ASSERT(!accum.open(), "xrpl::buildLedgerImpl : valid ledger state"); applyTxs(accum, built); accum.apply(*built); } @@ -51,15 +50,13 @@ buildLedgerImpl( int const asf = built->stateMap().flushDirty(hotACCOUNT_NODE); int const tmf = built->txMap().flushDirty(hotTRANSACTION_NODE); - JLOG(j.debug()) << "Flushed " << asf << " accounts and " << tmf - << " transaction nodes"; + JLOG(j.debug()) << "Flushed " << asf << " accounts and " << tmf << " transaction nodes"; } built->unshare(); // Accept ledger XRPL_ASSERT( - built->header().seq < XRP_LEDGER_EARLIEST_FEES || - built->read(keylet::fees()), + built->header().seq < XRP_LEDGER_EARLIEST_FEES || built->read(keylet::fees()), "xrpl::buildLedgerImpl : valid ledger fees"); built->setAccepted(closeTime, closeResolution, closeTimeCorrect); @@ -91,8 +88,8 @@ applyTransactions( // Attempt to apply all of the retriable transactions for (int pass = 0; pass < LEDGER_TOTAL_PASSES; ++pass) { - JLOG(j.debug()) << (certainRetry ? "Pass: " : "Final pass: ") << pass - << " begins (" << txns.size() << " transactions)"; + JLOG(j.debug()) << (certainRetry ? "Pass: " : "Final pass: ") << pass << " begins (" << txns.size() + << " transactions)"; int changes = 0; auto it = txns.begin(); @@ -109,8 +106,7 @@ applyTransactions( continue; } - switch (applyTransaction( - app, view, *it->second, certainRetry, tapNONE, j)) + switch (applyTransaction(app, view, *it->second, certainRetry, tapNONE, j)) { case ApplyTransactionResult::Success: it = txns.erase(it); @@ -128,15 +124,14 @@ applyTransactions( } catch (std::exception const& ex) { - JLOG(j.warn()) - << "Transaction " << txid << " throws: " << ex.what(); + JLOG(j.warn()) << "Transaction " << txid << " throws: " << ex.what(); failed.insert(txid); it = txns.erase(it); } } - JLOG(j.debug()) << (certainRetry ? "Pass: " : "Final pass: ") << pass - << " completed (" << changes << " changes)"; + JLOG(j.debug()) << (certainRetry ? "Pass: " : "Final pass: ") << pass << " completed (" << changes + << " changes)"; // Accumulate changes. count += changes; @@ -152,9 +147,7 @@ applyTransactions( // If there are any transactions left, we must have // tried them in at least one final pass - XRPL_ASSERT( - txns.empty() || !certainRetry, - "xrpl::applyTransactions : retry transactions"); + XRPL_ASSERT(txns.empty() || !certainRetry, "xrpl::applyTransactions : retry transactions"); return count; } @@ -170,8 +163,7 @@ buildLedger( std::set& failedTxns, beast::Journal j) { - JLOG(j.debug()) << "Report: Transaction Set = " << txns.key() << ", close " - << closeTime.time_since_epoch().count() + JLOG(j.debug()) << "Report: Transaction Set = " << txns.key() << ", close " << closeTime.time_since_epoch().count() << (closeTimeCorrect ? "" : " (incorrect)"); return buildLedgerImpl( @@ -182,34 +174,23 @@ buildLedger( app, j, [&](OpenView& accum, std::shared_ptr const& built) { - JLOG(j.debug()) - << "Attempting to apply " << txns.size() << " transactions"; + JLOG(j.debug()) << "Attempting to apply " << txns.size() << " transactions"; - auto const applied = - applyTransactions(app, built, txns, failedTxns, accum, j); + auto const applied = applyTransactions(app, built, txns, failedTxns, accum, j); if (!txns.empty() || !failedTxns.empty()) - JLOG(j.debug()) - << "Applied " << applied << " transactions; " - << failedTxns.size() << " failed and " << txns.size() - << " will be retried. " - << "Total transactions in ledger (including Inner Batch): " - << accum.txCount(); + JLOG(j.debug()) << "Applied " << applied << " transactions; " << failedTxns.size() << " failed and " + << txns.size() << " will be retried. " + << "Total transactions in ledger (including Inner Batch): " << accum.txCount(); else - JLOG(j.debug()) - << "Applied " << applied << " transactions. " - << "Total transactions in ledger (including Inner Batch): " - << accum.txCount(); + JLOG(j.debug()) << "Applied " << applied << " transactions. " + << "Total transactions in ledger (including Inner Batch): " << accum.txCount(); }); } // Build a ledger by replaying std::shared_ptr -buildLedger( - LedgerReplay const& replayData, - ApplyFlags applyFlags, - Application& app, - beast::Journal j) +buildLedger(LedgerReplay const& replayData, ApplyFlags applyFlags, Application& app, beast::Journal j) { auto const& replayLedger = replayData.replay(); diff --git a/src/xrpld/app/ledger/detail/InboundLedger.cpp b/src/xrpld/app/ledger/detail/InboundLedger.cpp index 1f5e5cc7b6..3c8f61a915 100644 --- a/src/xrpld/app/ledger/detail/InboundLedger.cpp +++ b/src/xrpld/app/ledger/detail/InboundLedger.cpp @@ -61,12 +61,7 @@ InboundLedger::InboundLedger( Reason reason, clock_type& clock, std::unique_ptr peerSet) - : TimeoutCounter( - app, - hash, - ledgerAcquireTimeout, - {jtLEDGER_DATA, "InboundLedger", 5}, - app.journal("InboundLedger")) + : TimeoutCounter(app, hash, ledgerAcquireTimeout, {jtLEDGER_DATA, "InboundLedger", 5}, app.journal("InboundLedger")) , m_clock(clock) , mHaveHeader(false) , mHaveState(false) @@ -102,8 +97,7 @@ InboundLedger::init(ScopedLockType& collectionLock) JLOG(journal_.debug()) << "Acquiring ledger we already have in " << " local store. " << hash_; XRPL_ASSERT( - mLedger->header().seq < XRP_LEDGER_EARLIEST_FEES || - mLedger->read(keylet::fees()), + mLedger->header().seq < XRP_LEDGER_EARLIEST_FEES || mLedger->read(keylet::fees()), "xrpl::InboundLedger::init : valid ledger fees"); mLedger->setImmutable(); @@ -121,9 +115,8 @@ std::size_t InboundLedger::getPeerCount() const { auto const& peerIds = mPeerSet->getPeerIds(); - return std::count_if(peerIds.begin(), peerIds.end(), [this](auto id) { - return (app_.overlay().findPeerByShortID(id) != nullptr); - }); + return std::count_if( + peerIds.begin(), peerIds.end(), [this](auto id) { return (app_.overlay().findPeerByShortID(id) != nullptr); }); } void @@ -169,21 +162,15 @@ InboundLedger::~InboundLedger() } if (!isDone()) { - JLOG(journal_.debug()) - << "Acquire " << hash_ << " abort " - << ((timeouts_ == 0) ? std::string() - : (std::string("timeouts:") + - std::to_string(timeouts_) + " ")) - << mStats.get(); + JLOG(journal_.debug()) << "Acquire " << hash_ << " abort " + << ((timeouts_ == 0) ? std::string() + : (std::string("timeouts:") + std::to_string(timeouts_) + " ")) + << mStats.get(); } } static std::vector -neededHashes( - uint256 const& root, - SHAMap& map, - int max, - SHAMapSyncFilter* filter) +neededHashes(uint256 const& root, SHAMap& map, int max, SHAMapSyncFilter* filter) { std::vector ret; @@ -206,15 +193,13 @@ neededHashes( std::vector InboundLedger::neededTxHashes(int max, SHAMapSyncFilter* filter) const { - return neededHashes( - mLedger->header().txHash, mLedger->txMap(), max, filter); + return neededHashes(mLedger->header().txHash, mLedger->txMap(), max, filter); } std::vector InboundLedger::neededStateHashes(int max, SHAMapSyncFilter* filter) const { - return neededHashes( - mLedger->header().accountHash, mLedger->stateMap(), max, filter); + return neededHashes(mLedger->header().accountHash, mLedger->stateMap(), max, filter); } // See how much of the ledger data is stored locally @@ -227,16 +212,11 @@ InboundLedger::tryDB(NodeStore::Database& srcDB) auto makeLedger = [&, this](Blob const& data) { JLOG(journal_.trace()) << "Ledger header found in fetch pack"; mLedger = std::make_shared( - deserializePrefixedHeader(makeSlice(data)), - app_.config(), - app_.getNodeFamily()); - if (mLedger->header().hash != hash_ || - (mSeq != 0 && mSeq != mLedger->header().seq)) + deserializePrefixedHeader(makeSlice(data)), app_.config(), app_.getNodeFamily()); + if (mLedger->header().hash != hash_ || (mSeq != 0 && mSeq != mLedger->header().seq)) { // We know for a fact the ledger can never be acquired - JLOG(journal_.warn()) - << "hash " << hash_ << " seq " << std::to_string(mSeq) - << " cannot be a ledger"; + JLOG(journal_.warn()) << "hash " << hash_ << " seq " << std::to_string(mSeq) << " cannot be a ledger"; mLedger.reset(); failed_ = true; } @@ -256,8 +236,7 @@ InboundLedger::tryDB(NodeStore::Database& srcDB) if (std::addressof(dstDB) != std::addressof(srcDB)) { Blob blob{nodeObject->getData()}; - dstDB.store( - hotLEDGER, std::move(blob), hash_, mLedger->header().seq); + dstDB.store(hotLEDGER, std::move(blob), hash_, mLedger->header().seq); } } else @@ -274,8 +253,7 @@ InboundLedger::tryDB(NodeStore::Database& srcDB) return; // Store the ledger header in the ledger's database - mLedger->stateMap().family().db().store( - hotLEDGER, std::move(*data), hash_, mLedger->header().seq); + mLedger->stateMap().family().db().store(hotLEDGER, std::move(*data), hash_, mLedger->header().seq); } if (mSeq == 0) @@ -294,10 +272,8 @@ InboundLedger::tryDB(NodeStore::Database& srcDB) } else { - TransactionStateSF filter( - mLedger->txMap().family().db(), app_.getLedgerMaster()); - if (mLedger->txMap().fetchRoot( - SHAMapHash{mLedger->header().txHash}, &filter)) + TransactionStateSF filter(mLedger->txMap().family().db(), app_.getLedgerMaster()); + if (mLedger->txMap().fetchRoot(SHAMapHash{mLedger->header().txHash}, &filter)) { if (neededTxHashes(1, &filter).empty()) { @@ -312,15 +288,12 @@ InboundLedger::tryDB(NodeStore::Database& srcDB) { if (mLedger->header().accountHash.isZero()) { - JLOG(journal_.fatal()) - << "We are acquiring a ledger with a zero account hash"; + JLOG(journal_.fatal()) << "We are acquiring a ledger with a zero account hash"; failed_ = true; return; } - AccountStateSF filter( - mLedger->stateMap().family().db(), app_.getLedgerMaster()); - if (mLedger->stateMap().fetchRoot( - SHAMapHash{mLedger->header().accountHash}, &filter)) + AccountStateSF filter(mLedger->stateMap().family().db(), app_.getLedgerMaster()); + if (mLedger->stateMap().fetchRoot(SHAMapHash{mLedger->header().accountHash}, &filter)) { if (neededStateHashes(1, &filter).empty()) { @@ -335,8 +308,7 @@ InboundLedger::tryDB(NodeStore::Database& srcDB) JLOG(journal_.debug()) << "Had everything locally"; complete_ = true; XRPL_ASSERT( - mLedger->header().seq < XRP_LEDGER_EARLIEST_FEES || - mLedger->read(keylet::fees()), + mLedger->header().seq < XRP_LEDGER_EARLIEST_FEES || mLedger->read(keylet::fees()), "xrpl::InboundLedger::tryDB : valid ledger fees"); mLedger->setImmutable(); } @@ -359,13 +331,11 @@ InboundLedger::onTimer(bool wasProgress, ScopedLockType&) { if (mSeq != 0) { - JLOG(journal_.warn()) - << timeouts_ << " timeouts for ledger " << mSeq; + JLOG(journal_.warn()) << timeouts_ << " timeouts for ledger " << mSeq; } else { - JLOG(journal_.warn()) - << timeouts_ << " timeouts for ledger " << hash_; + JLOG(journal_.warn()) << timeouts_ << " timeouts for ledger " << hash_; } failed_ = true; done(); @@ -379,8 +349,7 @@ InboundLedger::onTimer(bool wasProgress, ScopedLockType&) mByHash = true; std::size_t pc = getPeerCount(); - JLOG(journal_.debug()) - << "No progress(" << pc << ") for ledger " << hash_; + JLOG(journal_.debug()) << "No progress(" << pc << ") for ledger " << hash_; // addPeers triggers if the reason is not HISTORY // So if the reason IS HISTORY, need to trigger after we add @@ -425,20 +394,16 @@ InboundLedger::done() touch(); JLOG(journal_.debug()) << "Acquire " << hash_ << (failed_ ? " fail " : " ") - << ((timeouts_ == 0) - ? std::string() - : (std::string("timeouts:") + - std::to_string(timeouts_) + " ")) + << ((timeouts_ == 0) ? std::string() + : (std::string("timeouts:") + std::to_string(timeouts_) + " ")) << mStats.get(); - XRPL_ASSERT( - complete_ || failed_, "xrpl::InboundLedger::done : complete or failed"); + XRPL_ASSERT(complete_ || failed_, "xrpl::InboundLedger::done : complete or failed"); if (complete_ && !failed_ && mLedger) { XRPL_ASSERT( - mLedger->header().seq < XRP_LEDGER_EARLIEST_FEES || - mLedger->read(keylet::fees()), + mLedger->header().seq < XRP_LEDGER_EARLIEST_FEES || mLedger->read(keylet::fees()), "xrpl::InboundLedger::done : valid ledger fees"); mLedger->setImmutable(); switch (mReason) @@ -453,17 +418,15 @@ InboundLedger::done() } // We hold the PeerSet lock, so must dispatch - app_.getJobQueue().addJob( - jtLEDGER_DATA, "AcquisitionDone", [self = shared_from_this()]() { - if (self->complete_ && !self->failed_) - { - self->app_.getLedgerMaster().checkAccept(self->getLedger()); - self->app_.getLedgerMaster().tryAdvance(); - } - else - self->app_.getInboundLedgers().logFailure( - self->hash_, self->mSeq); - }); + app_.getJobQueue().addJob(jtLEDGER_DATA, "AcqDone", [self = shared_from_this()]() { + if (self->complete_ && !self->failed_) + { + self->app_.getLedgerMaster().checkAccept(self->getLedger()); + self->app_.getLedgerMaster().tryAdvance(); + } + else + self->app_.getInboundLedgers().logFailure(self->hash_, self->mSeq); + }); } /** Request more nodes, perhaps from a specific peer @@ -475,9 +438,8 @@ InboundLedger::trigger(std::shared_ptr const& peer, TriggerReason reason) if (isDone()) { - JLOG(journal_.debug()) - << "Trigger on ledger: " << hash_ << (complete_ ? " completed" : "") - << (failed_ ? " failed" : ""); + JLOG(journal_.debug()) << "Trigger on ledger: " << hash_ << (complete_ ? " completed" : "") + << (failed_ ? " failed" : ""); return; } @@ -491,8 +453,7 @@ InboundLedger::trigger(std::shared_ptr const& peer, TriggerReason reason) if (complete_ || failed_) ss << " complete=" << complete_ << " failed=" << failed_; else - ss << " header=" << mHaveHeader << " tx=" << mHaveTransactions - << " as=" << mHaveState; + ss << " header=" << mHaveHeader << " tx=" << mHaveTransactions << " as=" << mHaveState; stream << ss.str(); } @@ -514,8 +475,7 @@ InboundLedger::trigger(std::shared_ptr const& peer, TriggerReason reason) // Be more aggressive if we've timed out at least once tmGL.set_querytype(protocol::qtINDIRECT); - if (!progress_ && !failed_ && mByHash && - (timeouts_ > ledgerBecomeAggressiveThreshold)) + if (!progress_ && !failed_ && mByHash && (timeouts_ > ledgerBecomeAggressiveThreshold)) { auto need = getNeededHashes(); @@ -544,22 +504,19 @@ InboundLedger::trigger(std::shared_ptr const& peer, TriggerReason reason) } } - auto packet = - std::make_shared(tmBH, protocol::mtGET_OBJECTS); + auto packet = std::make_shared(tmBH, protocol::mtGET_OBJECTS); auto const& peerIds = mPeerSet->getPeerIds(); - std::for_each( - peerIds.begin(), peerIds.end(), [this, &packet](auto id) { - if (auto p = app_.overlay().findPeerByShortID(id)) - { - mByHash = false; - p->send(packet); - } - }); + std::for_each(peerIds.begin(), peerIds.end(), [this, &packet](auto id) { + if (auto p = app_.overlay().findPeerByShortID(id)) + { + mByHash = false; + p->send(packet); + } + }); } else { - JLOG(journal_.info()) - << "getNeededHashes says acquire is complete"; + JLOG(journal_.info()) << "getNeededHashes says acquire is complete"; mHaveHeader = true; mHaveTransactions = true; mHaveState = true; @@ -575,8 +532,7 @@ InboundLedger::trigger(std::shared_ptr const& peer, TriggerReason reason) tmGL.set_itype(protocol::liBASE); if (mSeq != 0) tmGL.set_ledgerseq(mSeq); - JLOG(journal_.trace()) << "Sending header request to " - << (peer ? "selected peer" : "all peers"); + JLOG(journal_.trace()) << "Sending header request to " << (peer ? "selected peer" : "all peers"); mPeerSet->sendRequest(tmGL, peer); return; } @@ -615,20 +571,17 @@ InboundLedger::trigger(std::shared_ptr const& peer, TriggerReason reason) // we need the root node tmGL.set_itype(protocol::liAS_NODE); *tmGL.add_nodeids() = SHAMapNodeID().getRawString(); - JLOG(journal_.trace()) << "Sending AS root request to " - << (peer ? "selected peer" : "all peers"); + JLOG(journal_.trace()) << "Sending AS root request to " << (peer ? "selected peer" : "all peers"); mPeerSet->sendRequest(tmGL, peer); return; } else { - AccountStateSF filter( - mLedger->stateMap().family().db(), app_.getLedgerMaster()); + AccountStateSF filter(mLedger->stateMap().family().db(), app_.getLedgerMaster()); // Release the lock while we process the large state map sl.unlock(); - auto nodes = - mLedger->stateMap().getMissingNodes(missingNodesFind, &filter); + auto nodes = mLedger->stateMap().getMissingNodes(missingNodesFind, &filter); sl.lock(); // Make sure nothing happened while we released the lock @@ -658,10 +611,8 @@ InboundLedger::trigger(std::shared_ptr const& peer, TriggerReason reason) *(tmGL.add_nodeids()) = id.first.getRawString(); } - JLOG(journal_.trace()) - << "Sending AS node request (" << nodes.size() - << ") to " - << (peer ? "selected peer" : "all peers"); + JLOG(journal_.trace()) << "Sending AS node request (" << nodes.size() << ") to " + << (peer ? "selected peer" : "all peers"); mPeerSet->sendRequest(tmGL, peer); return; } @@ -690,18 +641,15 @@ InboundLedger::trigger(std::shared_ptr const& peer, TriggerReason reason) // we need the root node tmGL.set_itype(protocol::liTX_NODE); *(tmGL.add_nodeids()) = SHAMapNodeID().getRawString(); - JLOG(journal_.trace()) << "Sending TX root request to " - << (peer ? "selected peer" : "all peers"); + JLOG(journal_.trace()) << "Sending TX root request to " << (peer ? "selected peer" : "all peers"); mPeerSet->sendRequest(tmGL, peer); return; } else { - TransactionStateSF filter( - mLedger->txMap().family().db(), app_.getLedgerMaster()); + TransactionStateSF filter(mLedger->txMap().family().db(), app_.getLedgerMaster()); - auto nodes = - mLedger->txMap().getMissingNodes(missingNodesFind, &filter); + auto nodes = mLedger->txMap().getMissingNodes(missingNodesFind, &filter); if (nodes.empty()) { @@ -726,9 +674,8 @@ InboundLedger::trigger(std::shared_ptr const& peer, TriggerReason reason) { *(tmGL.add_nodeids()) = n.first.getRawString(); } - JLOG(journal_.trace()) - << "Sending TX node request (" << nodes.size() - << ") to " << (peer ? "selected peer" : "all peers"); + JLOG(journal_.trace()) << "Sending TX node request (" << nodes.size() << ") to " + << (peer ? "selected peer" : "all peers"); mPeerSet->sendRequest(tmGL, peer); return; } @@ -742,25 +689,20 @@ InboundLedger::trigger(std::shared_ptr const& peer, TriggerReason reason) if (complete_ || failed_) { - JLOG(journal_.debug()) - << "Done:" << (complete_ ? " complete" : "") - << (failed_ ? " failed " : " ") << mLedger->header().seq; + JLOG(journal_.debug()) << "Done:" << (complete_ ? " complete" : "") << (failed_ ? " failed " : " ") + << mLedger->header().seq; sl.unlock(); done(); } } void -InboundLedger::filterNodes( - std::vector>& nodes, - TriggerReason reason) +InboundLedger::filterNodes(std::vector>& nodes, TriggerReason reason) { // Sort nodes so that the ones we haven't recently // requested come before the ones we have. auto dup = std::stable_partition( - nodes.begin(), nodes.end(), [this](auto const& item) { - return mRecentNodes.count(item.second) == 0; - }); + nodes.begin(), nodes.end(), [this](auto const& item) { return mRecentNodes.count(item.second) == 0; }); // If everything is a duplicate we don't want to send // any query at all except on a timeout where we need @@ -782,8 +724,7 @@ InboundLedger::filterNodes( nodes.erase(dup, nodes.end()); } - std::size_t const limit = - (reason == TriggerReason::reply) ? reqNodesReply : reqNodes; + std::size_t const limit = (reason == TriggerReason::reply) ? reqNodesReply : reqNodes; if (nodes.size() > limit) nodes.resize(limit); @@ -806,14 +747,10 @@ InboundLedger::takeHeader(std::string const& data) return true; auto* f = &app_.getNodeFamily(); - mLedger = std::make_shared( - deserializeHeader(makeSlice(data)), app_.config(), *f); - if (mLedger->header().hash != hash_ || - (mSeq != 0 && mSeq != mLedger->header().seq)) + mLedger = std::make_shared(deserializeHeader(makeSlice(data)), app_.config(), *f); + if (mLedger->header().hash != hash_ || (mSeq != 0 && mSeq != mLedger->header().seq)) { - JLOG(journal_.warn()) - << "Acquire hash mismatch: " << mLedger->header().hash - << "!=" << hash_; + JLOG(journal_.warn()) << "Acquire hash mismatch: " << mLedger->header().hash << "!=" << hash_; mLedger.reset(); return false; } @@ -866,19 +803,16 @@ InboundLedger::receiveNode(protocol::TMLedgerData& packet, SHAMapAddNode& san) return; } - auto [map, rootHash, filter] = [&]() - -> std::tuple> { + auto [map, rootHash, filter] = [&]() -> std::tuple> { if (packet.type() == protocol::liTX_NODE) return { mLedger->txMap(), SHAMapHash{mLedger->header().txHash}, - std::make_unique( - mLedger->txMap().family().db(), app_.getLedgerMaster())}; + std::make_unique(mLedger->txMap().family().db(), app_.getLedgerMaster())}; return { mLedger->stateMap(), SHAMapHash{mLedger->header().accountHash}, - std::make_unique( - mLedger->stateMap().family().db(), app_.getLedgerMaster())}; + std::make_unique(mLedger->stateMap().family().db(), app_.getLedgerMaster())}; }(); try @@ -950,10 +884,8 @@ InboundLedger::takeAsRootNode(Slice const& data, SHAMapAddNode& san) // LCOV_EXCL_STOP } - AccountStateSF filter( - mLedger->stateMap().family().db(), app_.getLedgerMaster()); - san += mLedger->stateMap().addRootNode( - SHAMapHash{mLedger->header().accountHash}, data, &filter); + AccountStateSF filter(mLedger->stateMap().family().db(), app_.getLedgerMaster()); + san += mLedger->stateMap().addRootNode(SHAMapHash{mLedger->header().accountHash}, data, &filter); return san.isGood(); } @@ -977,10 +909,8 @@ InboundLedger::takeTxRootNode(Slice const& data, SHAMapAddNode& san) // LCOV_EXCL_STOP } - TransactionStateSF filter( - mLedger->txMap().family().db(), app_.getLedgerMaster()); - san += mLedger->txMap().addRootNode( - SHAMapHash{mLedger->header().txHash}, data, &filter); + TransactionStateSF filter(mLedger->txMap().family().db(), app_.getLedgerMaster()); + san += mLedger->txMap().addRootNode(SHAMapHash{mLedger->header().txHash}, data, &filter); return san.isGood(); } @@ -991,30 +921,25 @@ InboundLedger::getNeededHashes() if (!mHaveHeader) { - ret.push_back( - std::make_pair(protocol::TMGetObjectByHash::otLEDGER, hash_)); + ret.push_back(std::make_pair(protocol::TMGetObjectByHash::otLEDGER, hash_)); return ret; } if (!mHaveState) { - AccountStateSF filter( - mLedger->stateMap().family().db(), app_.getLedgerMaster()); + AccountStateSF filter(mLedger->stateMap().family().db(), app_.getLedgerMaster()); for (auto const& h : neededStateHashes(4, &filter)) { - ret.push_back( - std::make_pair(protocol::TMGetObjectByHash::otSTATE_NODE, h)); + ret.push_back(std::make_pair(protocol::TMGetObjectByHash::otSTATE_NODE, h)); } } if (!mHaveTransactions) { - TransactionStateSF filter( - mLedger->txMap().family().db(), app_.getLedgerMaster()); + TransactionStateSF filter(mLedger->txMap().family().db(), app_.getLedgerMaster()); for (auto const& h : neededTxHashes(4, &filter)) { - ret.push_back(std::make_pair( - protocol::TMGetObjectByHash::otTRANSACTION_NODE, h)); + ret.push_back(std::make_pair(protocol::TMGetObjectByHash::otTRANSACTION_NODE, h)); } } @@ -1025,9 +950,7 @@ InboundLedger::getNeededHashes() Returns 'true' if we need to dispatch */ bool -InboundLedger::gotData( - std::weak_ptr peer, - std::shared_ptr const& data) +InboundLedger::gotData(std::weak_ptr peer, std::shared_ptr const& data) { std::lock_guard sl(mReceivedDataLock); @@ -1052,17 +975,14 @@ InboundLedger::gotData( // TODO Change peer to Consumer // int -InboundLedger::processData( - std::shared_ptr peer, - protocol::TMLedgerData& packet) +InboundLedger::processData(std::shared_ptr peer, protocol::TMLedgerData& packet) { if (packet.type() == protocol::liBASE) { if (packet.nodes().empty()) { JLOG(journal_.warn()) << peer->id() << ": empty header data"; - peer->charge( - Resource::feeMalformedRequest, "ledger_data empty header"); + peer->charge(Resource::feeMalformedRequest, "ledger_data empty header"); return -1; } @@ -1077,9 +997,7 @@ InboundLedger::processData( if (!takeHeader(packet.nodes(0).nodedata())) { JLOG(journal_.warn()) << "Got invalid header data"; - peer->charge( - Resource::feeMalformedRequest, - "ledger_data invalid header"); + peer->charge(Resource::feeMalformedRequest, "ledger_data invalid header"); return -1; } @@ -1100,8 +1018,7 @@ InboundLedger::processData( } catch (std::exception const& ex) { - JLOG(journal_.warn()) - << "Included AS/TX root invalid: " << ex.what(); + JLOG(journal_.warn()) << "Included AS/TX root invalid: " << ex.what(); using namespace std::string_literals; peer->charge(Resource::feeInvalidData, "ledger_data "s + ex.what()); return -1; @@ -1114,11 +1031,9 @@ InboundLedger::processData( return san.getGood(); } - if ((packet.type() == protocol::liTX_NODE) || - (packet.type() == protocol::liAS_NODE)) + if ((packet.type() == protocol::liTX_NODE) || (packet.type() == protocol::liAS_NODE)) { - std::string type = packet.type() == protocol::liTX_NODE ? "liTX_NODE: " - : "liAS_NODE: "; + std::string type = packet.type() == protocol::liTX_NODE ? "liTX_NODE: " : "liAS_NODE: "; if (packet.nodes().empty()) { @@ -1135,8 +1050,7 @@ InboundLedger::processData( if (!node.has_nodeid() || !node.has_nodedata()) { JLOG(journal_.warn()) << "Got bad node"; - peer->charge( - Resource::feeMalformedRequest, "ledger_data bad node"); + peer->charge(Resource::feeMalformedRequest, "ledger_data bad node"); return -1; } } @@ -1144,10 +1058,8 @@ InboundLedger::processData( SHAMapAddNode san; receiveNode(packet, san); - JLOG(journal_.debug()) - << "Ledger " - << ((packet.type() == protocol::liTX_NODE) ? "TX" : "AS") - << " node stats: " << san.get(); + JLOG(journal_.debug()) << "Ledger " << ((packet.type() == protocol::liTX_NODE) ? "TX" : "AS") + << " node stats: " << san.get(); if (san.isUseful()) progress_ = true; @@ -1215,19 +1127,13 @@ struct PeerDataCounts #if _MSC_VER std::vector, int>> s; s.reserve(n); - std::sample( - counts.begin(), counts.end(), std::back_inserter(s), n, rng); + std::sample(counts.begin(), counts.end(), std::back_inserter(s), n, rng); for (auto& v : s) { outFunc(v); } #else - std::sample( - counts.begin(), - counts.end(), - boost::make_function_output_iterator(outFunc), - n, - rng); + std::sample(counts.begin(), counts.end(), boost::make_function_output_iterator(outFunc), n, rng); #endif } }; @@ -1278,9 +1184,7 @@ InboundLedger::runData() // Select a random sample of the peers that gives us the most nodes that are // useful dataCounts.prune(); - dataCounts.sampleN(maxUsefulPeers, [&](std::shared_ptr const& peer) { - trigger(peer, TriggerReason::reply); - }); + dataCounts.sampleN(maxUsefulPeers, [&](std::shared_ptr const& peer) { trigger(peer, TriggerReason::reply); }); } Json::Value diff --git a/src/xrpld/app/ledger/detail/InboundLedgers.cpp b/src/xrpld/app/ledger/detail/InboundLedgers.cpp index 445786eb63..5441e2dc95 100644 --- a/src/xrpld/app/ledger/detail/InboundLedgers.cpp +++ b/src/xrpld/app/ledger/detail/InboundLedgers.cpp @@ -1,7 +1,6 @@ #include #include #include -#include #include #include @@ -10,6 +9,7 @@ #include #include #include +#include #include #include @@ -48,19 +48,13 @@ public: /** @callgraph */ std::shared_ptr - acquire( - uint256 const& hash, - std::uint32_t seq, - InboundLedger::Reason reason) override + acquire(uint256 const& hash, std::uint32_t seq, InboundLedger::Reason reason) override { auto doAcquire = [&, seq, reason]() -> std::shared_ptr { - XRPL_ASSERT( - hash.isNonZero(), - "xrpl::InboundLedgersImp::acquire::doAcquire : nonzero hash"); + XRPL_ASSERT(hash.isNonZero(), "xrpl::InboundLedgersImp::acquire::doAcquire : nonzero hash"); // probably not the right rule - if (app_.getOPs().isNeedNetworkLedger() && - (reason != InboundLedger::Reason::GENERIC) && + if (app_.getOPs().isNeedNetworkLedger() && (reason != InboundLedger::Reason::GENERIC) && (reason != InboundLedger::Reason::CONSENSUS)) return {}; @@ -82,12 +76,7 @@ public: else { inbound = std::make_shared( - app_, - hash, - seq, - reason, - std::ref(m_clock), - mPeerSetBuilder->build()); + app_, hash, seq, reason, std::ref(m_clock), mPeerSetBuilder->build()); mLedgers.emplace(hash, inbound); inbound->init(sl); ++mCounter; @@ -106,17 +95,14 @@ public: return inbound->getLedger(); }; using namespace std::chrono_literals; - std::shared_ptr ledger = perf::measureDurationAndLog( - doAcquire, "InboundLedgersImp::acquire", 500ms, j_); + std::shared_ptr ledger = + perf::measureDurationAndLog(doAcquire, "InboundLedgersImp::acquire", 500ms, j_); return ledger; } void - acquireAsync( - uint256 const& hash, - std::uint32_t seq, - InboundLedger::Reason reason) override + acquireAsync(uint256 const& hash, std::uint32_t seq, InboundLedger::Reason reason) override { std::unique_lock lock(acquiresMutex_); try @@ -129,15 +115,11 @@ public: } catch (std::exception const& e) { - JLOG(j_.warn()) - << "Exception thrown for acquiring new inbound ledger " << hash - << ": " << e.what(); + JLOG(j_.warn()) << "Exception thrown for acquiring new inbound ledger " << hash << ": " << e.what(); } catch (...) { - JLOG(j_.warn()) - << "Unknown exception thrown for acquiring new inbound ledger " - << hash; + JLOG(j_.warn()) << "Unknown exception thrown for acquiring new inbound ledger " << hash; } pendingAcquires_.erase(hash); } @@ -145,8 +127,7 @@ public: std::shared_ptr find(uint256 const& hash) override { - XRPL_ASSERT( - hash.isNonZero(), "xrpl::InboundLedgersImp::find : nonzero input"); + XRPL_ASSERT(hash.isNonZero(), "xrpl::InboundLedgersImp::find : nonzero input"); std::shared_ptr ret; @@ -178,38 +159,28 @@ public: /** We received a TMLedgerData from a peer. */ bool - gotLedgerData( - LedgerHash const& hash, - std::shared_ptr peer, - std::shared_ptr packet) override + gotLedgerData(LedgerHash const& hash, std::shared_ptr peer, std::shared_ptr packet) + override { if (auto ledger = find(hash)) { - JLOG(j_.trace()) << "Got data (" << packet->nodes().size() - << ") for acquiring ledger: " << hash; + JLOG(j_.trace()) << "Got data (" << packet->nodes().size() << ") for acquiring ledger: " << hash; // Stash the data for later processing and see if we need to // dispatch if (ledger->gotData(std::weak_ptr(peer), packet)) - app_.getJobQueue().addJob( - jtLEDGER_DATA, "processLedgerData", [ledger]() { - ledger->runData(); - }); + app_.getJobQueue().addJob(jtLEDGER_DATA, "ProcessLData", [ledger]() { ledger->runData(); }); return true; } - JLOG(j_.trace()) << "Got data for ledger " << hash - << " which we're no longer acquiring"; + JLOG(j_.trace()) << "Got data for ledger " << hash << " which we're no longer acquiring"; // If it's state node data, stash it because it still might be // useful. if (packet->type() == protocol::liAS_NODE) { - app_.getJobQueue().addJob( - jtLEDGER_DATA, "gotStaleData", [this, packet]() { - gotStaleData(packet); - }); + app_.getJobQueue().addJob(jtLEDGER_DATA, "GotStaleData", [this, packet]() { gotStaleData(packet); }); } return false; @@ -251,8 +222,7 @@ public: if (!node.has_nodeid() || !node.has_nodedata()) return; - auto newNode = - SHAMapTreeNode::makeFromWire(makeSlice(node.nodedata())); + auto newNode = SHAMapTreeNode::makeFromWire(makeSlice(node.nodedata())); if (!newNode) return; @@ -261,8 +231,7 @@ public: newNode->serializeWithPrefix(s); app_.getLedgerMaster().addFetchPack( - newNode->getHash().as_uint256(), - std::make_shared(s.begin(), s.end())); + newNode->getHash().as_uint256(), std::make_shared(s.begin(), s.end())); } } catch (std::exception const&) @@ -308,9 +277,7 @@ public: acqs.reserve(mLedgers.size()); for (auto const& it : mLedgers) { - XRPL_ASSERT( - it.second, - "xrpl::InboundLedgersImp::getInfo : non-null ledger"); + XRPL_ASSERT(it.second, "xrpl::InboundLedgersImp::getInfo : non-null ledger"); acqs.push_back(it); } for (auto const& it : mRecentFailures) @@ -400,13 +367,9 @@ public: beast::expire(mRecentFailures, kReacquireInterval); } - JLOG(j_.debug()) - << "Swept " << stuffToSweep.size() << " out of " << total - << " inbound ledgers. Duration: " - << std::chrono::duration_cast( - m_clock.now() - start) - .count() - << "ms"; + JLOG(j_.debug()) << "Swept " << stuffToSweep.size() << " out of " << total << " inbound ledgers. Duration: " + << std::chrono::duration_cast(m_clock.now() - start).count() + << "ms"; } void @@ -453,8 +416,7 @@ make_InboundLedgers( InboundLedgers::clock_type& clock, beast::insight::Collector::ptr const& collector) { - return std::make_unique( - app, clock, collector, make_PeerSetBuilder(app)); + return std::make_unique(app, clock, collector, make_PeerSetBuilder(app)); } } // namespace xrpl diff --git a/src/xrpld/app/ledger/detail/InboundTransactions.cpp b/src/xrpld/app/ledger/detail/InboundTransactions.cpp index 80906c45e7..9e877465a5 100644 --- a/src/xrpld/app/ledger/detail/InboundTransactions.cpp +++ b/src/xrpld/app/ledger/detail/InboundTransactions.cpp @@ -2,12 +2,12 @@ #include #include #include -#include #include #include #include #include +#include #include #include @@ -30,8 +30,7 @@ public: TransactionAcquire::pointer mAcquire; std::shared_ptr mSet; - InboundTransactionSet(std::uint32_t seq, std::shared_ptr const& set) - : mSeq(seq), mSet(set) + InboundTransactionSet(std::uint32_t seq, std::shared_ptr const& set) : mSeq(seq), mSet(set) { ; } @@ -56,8 +55,7 @@ public: , m_peerSetBuilder(std::move(peerSetBuilder)) , j_(app_.journal("InboundTransactions")) { - m_zeroSet.mSet = std::make_shared( - SHAMapType::TRANSACTION, uint256(), app_.getNodeFamily()); + m_zeroSet.mSet = std::make_shared(SHAMapType::TRANSACTION, uint256(), app_.getNodeFamily()); m_zeroSet.mSet->setUnbacked(); } @@ -99,8 +97,7 @@ public: if (!acquire || stopping_) return std::shared_ptr(); - ta = std::make_shared( - app_, hash, m_peerSetBuilder->build()); + ta = std::make_shared(app_, hash, m_peerSetBuilder->build()); auto& obj = m_map[hash]; obj.mAcquire = ta; @@ -115,15 +112,12 @@ public: /** We received a TMLedgerData from a peer. */ void - gotData( - LedgerHash const& hash, - std::shared_ptr peer, - std::shared_ptr packet_ptr) override + gotData(LedgerHash const& hash, std::shared_ptr peer, std::shared_ptr packet_ptr) + override { protocol::TMLedgerData& packet = *packet_ptr; - JLOG(j_.trace()) << "Got data (" << packet.nodes().size() - << ") for acquiring ledger: " << hash; + JLOG(j_.trace()) << "Got data (" << packet.nodes().size() << ") for acquiring ledger: " << hash; TransactionAcquire::pointer ta = getAcquire(hash); @@ -160,10 +154,7 @@ public: } void - giveSet( - uint256 const& hash, - std::shared_ptr const& set, - bool fromAcquire) override + giveSet(uint256 const& hash, std::shared_ptr const& set, bool fromAcquire) override { bool isNew = true; @@ -201,8 +192,7 @@ public: auto it = m_map.begin(); - std::uint32_t const minSeq = - (seq < setKeepRounds) ? 0 : (seq - setKeepRounds); + std::uint32_t const minSeq = (seq < setKeepRounds) ? 0 : (seq - setKeepRounds); std::uint32_t maxSeq = seq + setKeepRounds; while (it != m_map.end()) @@ -254,8 +244,7 @@ make_InboundTransactions( beast::insight::Collector::ptr const& collector, std::function const&, bool)> gotSet) { - return std::make_unique( - app, collector, std::move(gotSet), make_PeerSetBuilder(app)); + return std::make_unique(app, collector, std::move(gotSet), make_PeerSetBuilder(app)); } } // namespace xrpl diff --git a/src/xrpld/app/ledger/detail/LedgerCleaner.cpp b/src/xrpld/app/ledger/detail/LedgerCleaner.cpp index 1eec2efc80..f54c79f9c0 100644 --- a/src/xrpld/app/ledger/detail/LedgerCleaner.cpp +++ b/src/xrpld/app/ledger/detail/LedgerCleaner.cpp @@ -53,8 +53,7 @@ class LedgerCleanerImp : public LedgerCleaner //-------------------------------------------------------------------------- public: - LedgerCleanerImp(Application& app, beast::Journal journal) - : app_(app), j_(journal) + LedgerCleanerImp(Application& app, beast::Journal journal) : app_(app), j_(journal) { } @@ -208,14 +207,10 @@ private: { std::unique_lock lock(mutex_); state_ = State::notCleaning; - wakeup_.wait(lock, [this]() { - return (shouldExit_ || state_ == State::cleaning); - }); + wakeup_.wait(lock, [this]() { return (shouldExit_ || state_ == State::cleaning); }); if (shouldExit_) break; - XRPL_ASSERT( - state_ == State::cleaning, - "xrpl::LedgerCleanerImp::run : is cleaning"); + XRPL_ASSERT(state_ == State::cleaning, "xrpl::LedgerCleanerImp::run : is cleaning"); } doLedgerCleaner(); } @@ -232,12 +227,9 @@ private: } catch (SHAMapMissingNode const& mn) { - JLOG(j_.warn()) - << "Ledger #" << ledger->header().seq << ": " << mn.what(); + JLOG(j_.warn()) << "Ledger #" << ledger->header().seq << ": " << mn.what(); app_.getInboundLedgers().acquire( - ledger->header().hash, - ledger->header().seq, - InboundLedger::Reason::GENERIC); + ledger->header().hash, ledger->header().seq, InboundLedger::Reason::GENERIC); } return hash ? *hash : beast::zero; // kludge } @@ -250,20 +242,14 @@ private: @return `true` if the ledger was cleaned. */ bool - doLedger( - LedgerIndex const& ledgerIndex, - LedgerHash const& ledgerHash, - bool doNodes, - bool doTxns) + doLedger(LedgerIndex const& ledgerIndex, LedgerHash const& ledgerHash, bool doNodes, bool doTxns) { - auto nodeLedger = app_.getInboundLedgers().acquire( - ledgerHash, ledgerIndex, InboundLedger::Reason::GENERIC); + auto nodeLedger = app_.getInboundLedgers().acquire(ledgerHash, ledgerIndex, InboundLedger::Reason::GENERIC); if (!nodeLedger) { JLOG(j_.debug()) << "Ledger " << ledgerIndex << " not available"; app_.getLedgerMaster().clearLedger(ledgerIndex); - app_.getInboundLedgers().acquire( - ledgerHash, ledgerIndex, InboundLedger::Reason::GENERIC); + app_.getInboundLedgers().acquire(ledgerHash, ledgerIndex, InboundLedger::Reason::GENERIC); return false; } @@ -272,15 +258,13 @@ private: (dbLedger->header().parentHash != nodeLedger->header().parentHash)) { // Ideally we'd also check for more than one ledger with that index - JLOG(j_.debug()) - << "Ledger " << ledgerIndex << " mismatches SQL DB"; + JLOG(j_.debug()) << "Ledger " << ledgerIndex << " mismatches SQL DB"; doTxns = true; } if (!app_.getLedgerMaster().fixIndex(ledgerIndex, ledgerHash)) { - JLOG(j_.debug()) - << "ledger " << ledgerIndex << " had wrong entry in history"; + JLOG(j_.debug()) << "ledger " << ledgerIndex << " had wrong entry in history"; doTxns = true; } @@ -288,8 +272,7 @@ private: { JLOG(j_.debug()) << "Ledger " << ledgerIndex << " is missing nodes"; app_.getLedgerMaster().clearLedger(ledgerIndex); - app_.getInboundLedgers().acquire( - ledgerHash, ledgerIndex, InboundLedger::Reason::GENERIC); + app_.getInboundLedgers().acquire(ledgerHash, ledgerIndex, InboundLedger::Reason::GENERIC); return false; } @@ -308,9 +291,7 @@ private: @return The hash of the ledger. This will be all-bits-zero if not found. */ LedgerHash - getHash( - LedgerIndex const& ledgerIndex, - std::shared_ptr& referenceLedger) + getHash(LedgerIndex const& ledgerIndex, std::shared_ptr& referenceLedger) { LedgerHash ledgerHash; @@ -337,17 +318,15 @@ private: LedgerHash refHash = getLedgerHash(referenceLedger, refIndex); bool const nonzero(refHash.isNonZero()); - XRPL_ASSERT( - nonzero, "xrpl::LedgerCleanerImp::getHash : nonzero hash"); + XRPL_ASSERT(nonzero, "xrpl::LedgerCleanerImp::getHash : nonzero hash"); if (nonzero) { // We found the hash and sequence of a better reference // ledger. - referenceLedger = app_.getInboundLedgers().acquire( - refHash, refIndex, InboundLedger::Reason::GENERIC); + referenceLedger = + app_.getInboundLedgers().acquire(refHash, refIndex, InboundLedger::Reason::GENERIC); if (referenceLedger) - ledgerHash = - getLedgerHash(referenceLedger, ledgerIndex); + ledgerHash = getLedgerHash(referenceLedger, ledgerIndex); } } } @@ -384,8 +363,7 @@ private: { std::lock_guard lock(mutex_); - if ((minRange_ > maxRange_) || (maxRange_ == 0) || - (minRange_ == 0)) + if ((minRange_ > maxRange_) || (maxRange_ == 0) || (minRange_ == 0)) { minRange_ = maxRange_ = 0; return; @@ -400,8 +378,7 @@ private: bool fail = false; if (ledgerHash.isZero()) { - JLOG(j_.info()) - << "Unable to get hash for ledger " << ledgerIndex; + JLOG(j_.info()) << "Unable to get hash for ledger " << ledgerIndex; fail = true; } else if (!doLedger(ledgerIndex, ledgerHash, doNodes, doTxns)) diff --git a/src/xrpld/app/ledger/detail/LedgerDeltaAcquire.cpp b/src/xrpld/app/ledger/detail/LedgerDeltaAcquire.cpp index 5b642ba3db..f06beda768 100644 --- a/src/xrpld/app/ledger/detail/LedgerDeltaAcquire.cpp +++ b/src/xrpld/app/ledger/detail/LedgerDeltaAcquire.cpp @@ -20,9 +20,7 @@ LedgerDeltaAcquire::LedgerDeltaAcquire( app, ledgerHash, LedgerReplayParameters::SUB_TASK_TIMEOUT, - {jtREPLAY_TASK, - "LedgerReplayDelta", - LedgerReplayParameters::MAX_QUEUED_TASKS}, + {jtREPLAY_TASK, "LedReplDelta", LedgerReplayParameters::MAX_QUEUED_TASKS}, app.journal("LedgerReplayDelta")) , inboundLedgers_(inboundLedgers) , ledgerSeq_(ledgerSeq) @@ -64,26 +62,22 @@ LedgerDeltaAcquire::trigger(std::size_t limit, ScopedLockType& sl) peerSet_->addPeers( limit, [this](auto peer) { - return peer->supportsFeature(ProtocolFeature::LedgerReplay) && - peer->hasLedger(hash_, ledgerSeq_); + return peer->supportsFeature(ProtocolFeature::LedgerReplay) && peer->hasLedger(hash_, ledgerSeq_); }, [this](auto peer) { if (peer->supportsFeature(ProtocolFeature::LedgerReplay)) { - JLOG(journal_.trace()) - << "Add a peer " << peer->id() << " for " << hash_; + JLOG(journal_.trace()) << "Add a peer " << peer->id() << " for " << hash_; protocol::TMReplayDeltaRequest request; request.set_ledgerhash(hash_.data(), hash_.size()); peerSet_->sendRequest(request, peer); } else { - if (++noFeaturePeerCount >= - LedgerReplayParameters::MAX_NO_FEATURE_PEER_COUNT) + if (++noFeaturePeerCount >= LedgerReplayParameters::MAX_NO_FEATURE_PEER_COUNT) { JLOG(journal_.debug()) << "Fall back for " << hash_; - timerInterval_ = - LedgerReplayParameters::SUB_TASK_FALLBACK_TIMEOUT; + timerInterval_ = LedgerReplayParameters::SUB_TASK_FALLBACK_TIMEOUT; fallBack_ = true; } } @@ -91,8 +85,7 @@ LedgerDeltaAcquire::trigger(std::size_t limit, ScopedLockType& sl) } if (fallBack_) - inboundLedgers_.acquire( - hash_, ledgerSeq_, InboundLedger::Reason::GENERIC); + inboundLedgers_.acquire(hash_, ledgerSeq_, InboundLedger::Reason::GENERIC); } void @@ -130,8 +123,7 @@ LedgerDeltaAcquire::processData( if (info.seq == ledgerSeq_) { // create a temporary ledger for building a LedgerReplay object later - replayTemp_ = - std::make_shared(info, app_.config(), app_.getNodeFamily()); + replayTemp_ = std::make_shared(info, app_.config(), app_.getNodeFamily()); if (replayTemp_) { complete_ = true; @@ -143,15 +135,12 @@ LedgerDeltaAcquire::processData( } failed_ = true; - JLOG(journal_.error()) - << "failed to create a (info only) ledger from verified data " << hash_; + JLOG(journal_.error()) << "failed to create a (info only) ledger from verified data " << hash_; notify(sl); } void -LedgerDeltaAcquire::addDataCallback( - InboundLedger::Reason reason, - OnDeltaDataCB&& cb) +LedgerDeltaAcquire::addDataCallback(InboundLedger::Reason reason, OnDeltaDataCB&& cb) { ScopedLockType sl(mtx_); dataReadyCallbacks_.emplace_back(std::move(cb)); @@ -164,8 +153,7 @@ LedgerDeltaAcquire::addDataCallback( if (isDone()) { - JLOG(journal_.debug()) - << "task added to a finished LedgerDeltaAcquire " << hash_; + JLOG(journal_.debug()) << "task added to a finished LedgerDeltaAcquire " << hash_; notify(sl); } } @@ -181,9 +169,7 @@ LedgerDeltaAcquire::tryBuild(std::shared_ptr const& parent) if (failed_ || !complete_ || !replayTemp_) return {}; - XRPL_ASSERT( - parent->seq() + 1 == replayTemp_->seq(), - "xrpl::LedgerDeltaAcquire::tryBuild : parent sequence match"); + XRPL_ASSERT(parent->seq() + 1 == replayTemp_->seq(), "xrpl::LedgerDeltaAcquire::tryBuild : parent sequence match"); XRPL_ASSERT( parent->header().hash == replayTemp_->header().parentHash, "xrpl::LedgerDeltaAcquire::tryBuild : parent hash match"); @@ -200,22 +186,17 @@ LedgerDeltaAcquire::tryBuild(std::shared_ptr const& parent) { failed_ = true; complete_ = false; - JLOG(journal_.error()) << "tryBuild failed " << hash_ << " with parent " - << parent->header().hash; + JLOG(journal_.error()) << "tryBuild failed " << hash_ << " with parent " << parent->header().hash; Throw("Cannot replay ledger"); } } void -LedgerDeltaAcquire::onLedgerBuilt( - ScopedLockType& sl, - std::optional reason) +LedgerDeltaAcquire::onLedgerBuilt(ScopedLockType& sl, std::optional reason) { - JLOG(journal_.debug()) << "onLedgerBuilt " << hash_ - << (reason ? " for a new reason" : ""); + JLOG(journal_.debug()) << "onLedgerBuilt " << hash_ << (reason ? " for a new reason" : ""); - std::vector reasons( - reasons_.begin(), reasons_.end()); + std::vector reasons(reasons_.begin(), reasons_.end()); bool firstTime = true; if (reason) // small chance { @@ -223,26 +204,23 @@ LedgerDeltaAcquire::onLedgerBuilt( reasons.push_back(*reason); firstTime = false; } - app_.getJobQueue().addJob( - jtREPLAY_TASK, - "onLedgerBuilt", - [=, ledger = this->fullLedger_, &app = this->app_]() { - for (auto reason : reasons) + app_.getJobQueue().addJob(jtREPLAY_TASK, "OnLedBuilt", [=, ledger = this->fullLedger_, &app = this->app_]() { + for (auto reason : reasons) + { + switch (reason) { - switch (reason) - { - case InboundLedger::Reason::GENERIC: - app.getLedgerMaster().storeLedger(ledger); - break; - default: - // TODO for other use cases - break; - } + case InboundLedger::Reason::GENERIC: + app.getLedgerMaster().storeLedger(ledger); + break; + default: + // TODO for other use cases + break; } + } - if (firstTime) - app.getLedgerMaster().tryAdvance(); - }); + if (firstTime) + app.getLedgerMaster().tryAdvance(); + }); } void diff --git a/src/xrpld/app/ledger/detail/LedgerDeltaAcquire.h b/src/xrpld/app/ledger/detail/LedgerDeltaAcquire.h index 779bbfa85e..66b8f27b85 100644 --- a/src/xrpld/app/ledger/detail/LedgerDeltaAcquire.h +++ b/src/xrpld/app/ledger/detail/LedgerDeltaAcquire.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_LEDGER_LEDGERDELTAACQUIRE_H_INCLUDED -#define XRPL_APP_LEDGER_LEDGERDELTAACQUIRE_H_INCLUDED +#pragma once #include #include @@ -22,10 +21,9 @@ class LedgerReplayClient; * from the network. Before asking peers, always check if the local * node has the ledger. */ -class LedgerDeltaAcquire final - : public TimeoutCounter, - public std::enable_shared_from_this, - public CountedObject +class LedgerDeltaAcquire final : public TimeoutCounter, + public std::enable_shared_from_this, + public CountedObject { public: /** @@ -33,8 +31,7 @@ public: * @param successful if the ledger delta data was acquired successfully * @param hash hash of the ledger to build */ - using OnDeltaDataCB = - std::function; + using OnDeltaDataCB = std::function; /** * Constructor @@ -68,9 +65,7 @@ public: * @note info and Txns must have been verified against the ledger hash */ void - processData( - LedgerHeader const& info, - std::map>&& orderedTxns); + processData(LedgerHeader const& info, std::map>&& orderedTxns); /** * Try to build the ledger if not already @@ -116,9 +111,7 @@ private: * is added. */ void - onLedgerBuilt( - ScopedLockType& sl, - std::optional reason = {}); + onLedgerBuilt(ScopedLockType& sl, std::optional reason = {}); /** * Call the OnDeltaDataCB callbacks @@ -143,5 +136,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/src/xrpld/app/ledger/detail/LedgerMaster.cpp b/src/xrpld/app/ledger/detail/LedgerMaster.cpp index d176e85645..5538ebcb96 100644 --- a/src/xrpld/app/ledger/detail/LedgerMaster.cpp +++ b/src/xrpld/app/ledger/detail/LedgerMaster.cpp @@ -3,18 +3,15 @@ #include #include #include -#include #include #include #include #include -#include #include #include #include #include #include -#include #include #include #include @@ -26,10 +23,13 @@ #include #include #include +#include #include #include #include +#include #include +#include #include #include @@ -72,8 +72,7 @@ shouldAcquire( return minimumOnline.has_value() && candidateLedger >= *minimumOnline; }(); - JLOG(j.trace()) << "Missing ledger " << candidateLedger - << (ret ? " should" : " should NOT") << " be acquired"; + JLOG(j.trace()) << "Missing ledger " << candidateLedger << (ret ? " should" : " should NOT") << " be acquired"; return ret; } @@ -86,16 +85,10 @@ LedgerMaster::LedgerMaster( , m_journal(journal) , mLedgerHistory(collector, app) , standalone_(app_.config().standalone()) - , fetch_depth_( - app_.getSHAMapStore().clampFetchDepth(app_.config().FETCH_DEPTH)) + , fetch_depth_(app_.getSHAMapStore().clampFetchDepth(app_.config().FETCH_DEPTH)) , ledger_history_(app_.config().LEDGER_HISTORY) , ledger_fetch_size_(app_.config().getValueFor(SizedItem::ledgerFetch)) - , fetch_packs_( - "FetchPack", - 65536, - std::chrono::seconds{45}, - stopwatch, - app_.journal("TaggedCache")) + , fetch_packs_("FetchPack", 65536, std::chrono::seconds{45}, stopwatch, app_.journal("TaggedCache")) , m_stats(std::bind(&LedgerMaster::collect_metrics, this), collector) { } @@ -113,10 +106,7 @@ LedgerMaster::getValidLedgerIndex() } bool -LedgerMaster::isCompatible( - ReadView const& view, - beast::Journal::Stream s, - char const* reason) +LedgerMaster::isCompatible(ReadView const& view, beast::Journal::Stream s, char const* reason) { auto validLedger = getValidatedLedger(); @@ -129,12 +119,7 @@ LedgerMaster::isCompatible( std::lock_guard sl(m_mutex); if ((mLastValidLedger.second != 0) && - !areCompatible( - mLastValidLedger.first, - mLastValidLedger.second, - view, - s, - reason)) + !areCompatible(mLastValidLedger.first, mLastValidLedger.second, view, s, reason)) { return false; } @@ -226,8 +211,7 @@ LedgerMaster::setValidLedger(std::shared_ptr const& l) if (!standalone_) { auto validations = app_.validators().negativeUNLFilter( - app_.getValidations().getTrustedForLedger( - l->header().hash, l->header().seq)); + app_.getValidations().getTrustedForLedger(l->header().hash, l->header().seq)); times.reserve(validations.size()); for (auto const& val : validations) times.push_back(val->getSignTime()); @@ -255,8 +239,7 @@ LedgerMaster::setValidLedger(std::shared_ptr const& l) mValidLedgerSign = signTime.time_since_epoch().count(); XRPL_ASSERT( mValidLedgerSeq || !app_.getMaxDisallowedLedger() || - l->header().seq + max_ledger_difference_ > - app_.getMaxDisallowedLedger(), + l->header().seq + max_ledger_difference_ > app_.getMaxDisallowedLedger(), "xrpl::LedgerMaster::setValidLedger : valid ledger sequence"); (void)max_ledger_difference_; mValidLedgerSeq = l->header().seq; @@ -284,8 +267,7 @@ LedgerMaster::setValidLedger(std::shared_ptr const& l) // this message may be logged more than once per session, because // the node will otherwise function normally, and this gives // operators an opportunity to see and resolve the warning. - if (auto const first = - app_.getAmendmentTable().firstUnsupportedExpected()) + if (auto const first = app_.getAmendmentTable().firstUnsupportedExpected()) { JLOG(m_journal.error()) << "One or more unsupported amendments " "reached majority. Upgrade before " @@ -309,8 +291,7 @@ LedgerMaster::setPubLedger(std::shared_ptr const& l) } void -LedgerMaster::addHeldTransaction( - std::shared_ptr const& transaction) +LedgerMaster::addHeldTransaction(std::shared_ptr const& transaction) { std::lock_guard ml(m_mutex); mHeldTransactions.insert(transaction->getSTransaction()); @@ -330,9 +311,8 @@ LedgerMaster::canBeCurrent(std::shared_ptr const& ledger) auto validLedger = getValidatedLedger(); if (validLedger && (ledger->header().seq < validLedger->header().seq)) { - JLOG(m_journal.trace()) - << "Candidate for current ledger has low seq " - << ledger->header().seq << " < " << validLedger->header().seq; + JLOG(m_journal.trace()) << "Candidate for current ledger has low seq " << ledger->header().seq << " < " + << validLedger->header().seq; return false; } @@ -346,13 +326,10 @@ LedgerMaster::canBeCurrent(std::shared_ptr const& ledger) using namespace std::chrono_literals; if ((validLedger || (ledger->header().seq > 10)) && - ((std::max(closeTime, ledgerClose) - std::min(closeTime, ledgerClose)) > - 5min)) + ((std::max(closeTime, ledgerClose) - std::min(closeTime, ledgerClose)) > 5min)) { - JLOG(m_journal.warn()) - << "Candidate for current ledger has close time " - << to_string(ledgerClose) << " at network time " - << to_string(closeTime) << " seq " << ledger->header().seq; + JLOG(m_journal.warn()) << "Candidate for current ledger has close time " << to_string(ledgerClose) + << " at network time " << to_string(closeTime) << " seq " << ledger->header().seq; return false; } @@ -366,22 +343,20 @@ LedgerMaster::canBeCurrent(std::shared_ptr const& ledger) LedgerIndex maxSeq = validLedger->header().seq + 10; if (closeTime > validLedger->header().parentCloseTime) - maxSeq += std::chrono::duration_cast( - closeTime - validLedger->header().parentCloseTime) - .count() / + maxSeq += + std::chrono::duration_cast(closeTime - validLedger->header().parentCloseTime) + .count() / 2; if (ledger->header().seq > maxSeq) { - JLOG(m_journal.warn()) - << "Candidate for current ledger has high seq " - << ledger->header().seq << " > " << maxSeq; + JLOG(m_journal.warn()) << "Candidate for current ledger has high seq " << ledger->header().seq << " > " + << maxSeq; return false; } - JLOG(m_journal.trace()) - << "Acceptable seq range: " << validLedger->header().seq - << " <= " << ledger->header().seq << " <= " << maxSeq; + JLOG(m_journal.trace()) << "Acceptable seq range: " << validLedger->header().seq + << " <= " << ledger->header().seq << " <= " << maxSeq; } return true; @@ -498,11 +473,8 @@ LedgerMaster::isValidated(ReadView const& ledger) // This ledger's hash is not the hash of the validated ledger if (hash) { - XRPL_ASSERT( - hash->isNonZero(), - "xrpl::LedgerMaster::isValidated : nonzero hash"); - uint256 valHash = - app_.getRelationalDatabase().getHashByIndex(seq); + XRPL_ASSERT(hash->isNonZero(), "xrpl::LedgerMaster::isValidated : nonzero hash"); + uint256 valHash = app_.getRelationalDatabase().getHashByIndex(seq); if (valHash == ledger.header().hash) { // SQL database doesn't match ledger chain @@ -525,9 +497,7 @@ LedgerMaster::isValidated(ReadView const& ledger) // returns Ledgers we have all the nodes for bool -LedgerMaster::getFullValidatedRange( - std::uint32_t& minVal, - std::uint32_t& maxVal) +LedgerMaster::getFullValidatedRange(std::uint32_t& minVal, std::uint32_t& maxVal) { // Validated ledger is likely not stored in the DB yet so we use the // published ledger which is. @@ -641,20 +611,16 @@ LedgerMaster::tryFill(std::shared_ptr ledger) mCompleteLedgers.insert(range(minHas, maxHas)); } maxHas = minHas; - ledgerHashes = app_.getRelationalDatabase().getHashesByIndex( - (seq < 500) ? 0 : (seq - 499), seq); + ledgerHashes = app_.getRelationalDatabase().getHashesByIndex((seq < 500) ? 0 : (seq - 499), seq); it = ledgerHashes.find(seq); if (it == ledgerHashes.end()) break; - if (!nodeStore.fetchNodeObject( - ledgerHashes.begin()->second.ledgerHash, - ledgerHashes.begin()->first)) + if (!nodeStore.fetchNodeObject(ledgerHashes.begin()->second.ledgerHash, ledgerHashes.begin()->first)) { // The ledger is not backed by the node store - JLOG(m_journal.warn()) << "SQL DB ledger sequence " << seq - << " mismatches node store"; + JLOG(m_journal.warn()) << "SQL DB ledger sequence " << seq << " mismatches node store"; break; } } @@ -686,8 +652,7 @@ LedgerMaster::getFetchPack(LedgerIndex missing, InboundLedger::Reason reason) auto const haveHash{getLedgerHashForHistory(ledgerIndex, reason)}; if (!haveHash || haveHash->isZero()) { - JLOG(m_journal.error()) - << "No hash for fetch pack. Missing Index " << missing; + JLOG(m_journal.error()) << "No hash for fetch pack. Missing Index " << missing; return; } @@ -742,9 +707,7 @@ LedgerMaster::fixMismatch(ReadView const& ledger) } catch (std::exception const& ex) { - JLOG(m_journal.warn()) - << "fixMismatch encounters partial ledger. Exception: " - << ex.what(); + JLOG(m_journal.warn()) << "fixMismatch encounters partial ledger. Exception: " << ex.what(); clearLedger(lSeq); return; } @@ -760,8 +723,7 @@ LedgerMaster::fixMismatch(ReadView const& ledger) if (invalidate != 0) { JLOG(m_journal.warn()) - << "Match at " << lSeq << ", " << invalidate - << " prior ledgers invalidated"; + << "Match at " << lSeq << ", " << invalidate << " prior ledgers invalidated"; } return; @@ -776,23 +738,17 @@ LedgerMaster::fixMismatch(ReadView const& ledger) // all prior ledgers invalidated if (invalidate != 0) { - JLOG(m_journal.warn()) - << "All " << invalidate << " prior ledgers invalidated"; + JLOG(m_journal.warn()) << "All " << invalidate << " prior ledgers invalidated"; } } void -LedgerMaster::setFullLedger( - std::shared_ptr const& ledger, - bool isSynchronous, - bool isCurrent) +LedgerMaster::setFullLedger(std::shared_ptr const& ledger, bool isSynchronous, bool isCurrent) { // A new ledger has been accepted as part of the trusted chain - JLOG(m_journal.debug()) << "Ledger " << ledger->header().seq - << " accepted :" << ledger->header().hash; + JLOG(m_journal.debug()) << "Ledger " << ledger->header().seq << " accepted :" << ledger->header().hash; XRPL_ASSERT( - ledger->stateMap().getHash().isNonZero(), - "xrpl::LedgerMaster::setFullLedger : nonzero ledger state hash"); + ledger->stateMap().getHash().isNonZero(), "xrpl::LedgerMaster::setFullLedger : nonzero ledger state hash"); ledger->setValidated(); ledger->setFull(); @@ -803,8 +759,7 @@ LedgerMaster::setFullLedger( { // Check the SQL database's entry for the sequence before this // ledger, if it's not this ledger's parent, invalidate it - uint256 prevHash = app_.getRelationalDatabase().getHashByIndex( - ledger->header().seq - 1); + uint256 prevHash = app_.getRelationalDatabase().getHashByIndex(ledger->header().seq - 1); if (prevHash.isNonZero() && prevHash != ledger->header().parentHash) clearLedger(ledger->header().seq - 1); } @@ -832,12 +787,10 @@ LedgerMaster::setFullLedger( // we think we have the previous ledger, double check auto prevLedger = getLedgerBySeq(ledger->header().seq - 1); - if (!prevLedger || - (prevLedger->header().hash != ledger->header().parentHash)) + if (!prevLedger || (prevLedger->header().hash != ledger->header().parentHash)) { - JLOG(m_journal.warn()) - << "Acquired ledger invalidates previous ledger: " - << (prevLedger ? "hashMismatch" : "missingLedger"); + JLOG(m_journal.warn()) << "Acquired ledger invalidates previous ledger: " + << (prevLedger ? "hashMismatch" : "missingLedger"); fixMismatch(*ledger); } } @@ -864,8 +817,7 @@ LedgerMaster::checkAccept(uint256 const& hash, std::uint32_t seq) if (seq < mValidLedgerSeq) return; - auto validations = app_.validators().negativeUNLFilter( - app_.getValidations().getTrustedForLedger(hash, seq)); + auto validations = app_.validators().negativeUNLFilter(app_.getValidations().getTrustedForLedger(hash, seq)); valCount = validations.size(); if (valCount >= app_.validators().quorum()) { @@ -895,8 +847,7 @@ LedgerMaster::checkAccept(uint256 const& hash, std::uint32_t seq) // FIXME: We may not want to fetch a ledger with just one // trusted validation - ledger = app_.getInboundLedgers().acquire( - hash, seq, InboundLedger::Reason::GENERIC); + ledger = app_.getInboundLedgers().acquire(hash, seq, InboundLedger::Reason::GENERIC); } if (ledger) @@ -931,18 +882,15 @@ LedgerMaster::checkAccept(std::shared_ptr const& ledger) auto const minVal = getNeededValidations(); auto validations = app_.validators().negativeUNLFilter( - app_.getValidations().getTrustedForLedger( - ledger->header().hash, ledger->header().seq)); + app_.getValidations().getTrustedForLedger(ledger->header().hash, ledger->header().seq)); auto const tvc = validations.size(); if (tvc < minVal) // nothing we can do { - JLOG(m_journal.trace()) - << "Only " << tvc << " validations for " << ledger->header().hash; + JLOG(m_journal.trace()) << "Only " << tvc << " validations for " << ledger->header().hash; return; } - JLOG(m_journal.info()) << "Advancing accepted ledger to " - << ledger->header().seq << " with >= " << minVal + JLOG(m_journal.info()) << "Advancing accepted ledger to " << ledger->header().seq << " with >= " << minVal << " validations"; ledger->setValidated(); @@ -958,8 +906,7 @@ LedgerMaster::checkAccept(std::shared_ptr const& ledger) std::uint32_t const base = app_.getFeeTrack().getLoadBase(); auto fees = app_.getValidations().fees(ledger->header().hash, base); { - auto fees2 = - app_.getValidations().fees(ledger->header().parentHash, base); + auto fees2 = app_.getValidations().fees(ledger->header().parentHash, base); fees.reserve(fees.size() + fees2.size()); std::copy(fees2.begin(), fees2.end(), std::back_inserter(fees)); } @@ -1006,8 +953,8 @@ LedgerMaster::checkAccept(std::shared_ptr const& ledger) if (upgradeWarningPrevTime_ == TimeKeeper::time_point()) { // Have not printed the warning before, check if need to print. - auto const vals = app_.getValidations().getTrustedForLedger( - ledger->header().parentHash, ledger->header().seq - 1); + auto const vals = + app_.getValidations().getTrustedForLedger(ledger->header().parentHash, ledger->header().seq - 1); std::size_t higherVersionCount = 0; std::size_t rippledCount = 0; for (auto const& v : vals) @@ -1015,10 +962,8 @@ LedgerMaster::checkAccept(std::shared_ptr const& ledger) if (v->isFieldPresent(sfServerVersion)) { auto version = v->getFieldU64(sfServerVersion); - higherVersionCount += - BuildInfo::isNewerVersion(version) ? 1 : 0; - rippledCount += - BuildInfo::isRippledVersion(version) ? 1 : 0; + higherVersionCount += BuildInfo::isNewerVersion(version) ? 1 : 0; + rippledCount += BuildInfo::isRippledVersion(version) ? 1 : 0; } } // We report only if (1) we have accumulated validation messages @@ -1029,13 +974,9 @@ LedgerMaster::checkAccept(std::shared_ptr const& ledger) { constexpr std::size_t reportingPercent = 90; constexpr std::size_t cutoffPercent = 60; - auto const unlSize{ - app_.validators().getQuorumKeys().second.size()}; - needPrint = unlSize > 0 && - calculatePercent(vals.size(), unlSize) >= - reportingPercent && - calculatePercent(higherVersionCount, rippledCount) >= - cutoffPercent; + auto const unlSize{app_.validators().getQuorumKeys().second.size()}; + needPrint = unlSize > 0 && calculatePercent(vals.size(), unlSize) >= reportingPercent && + calculatePercent(higherVersionCount, rippledCount) >= cutoffPercent; } } // To throttle the warning messages, instead of printing a warning @@ -1080,8 +1021,7 @@ LedgerMaster::consensusBuilt( if (ledger->header().seq <= mValidLedgerSeq) { auto stream = app_.journal("LedgerConsensus").info(); - JLOG(stream) << "Consensus built old ledger: " << ledger->header().seq - << " <= " << mValidLedgerSeq; + JLOG(stream) << "Consensus built old ledger: " << ledger->header().seq << " <= " << mValidLedgerSeq; return; } @@ -1098,8 +1038,7 @@ LedgerMaster::consensusBuilt( // This ledger cannot be the new fully-validated ledger, but // maybe we saved up validations for some other ledger that can be - auto validations = app_.validators().negativeUNLFilter( - app_.getValidations().currentTrusted()); + auto validations = app_.validators().negativeUNLFilter(app_.getValidations().currentTrusted()); // Track validation counts with sequence numbers class valSeq @@ -1164,9 +1103,7 @@ LedgerMaster::consensusBuilt( } std::optional -LedgerMaster::getLedgerHashForHistory( - LedgerIndex index, - InboundLedger::Reason reason) +LedgerMaster::getLedgerHashForHistory(LedgerIndex index, InboundLedger::Reason reason) { // Try to get the hash of a ledger we need to fetch for history std::optional ret; @@ -1186,8 +1123,7 @@ LedgerMaster::getLedgerHashForHistory( } std::vector> -LedgerMaster::findNewLedgersToPublish( - std::unique_lock& sl) +LedgerMaster::findNewLedgersToPublish(std::unique_lock& sl) { std::vector> ret; @@ -1202,15 +1138,13 @@ LedgerMaster::findNewLedgersToPublish( if (!mPubLedger) { - JLOG(m_journal.info()) - << "First published ledger will be " << mValidLedgerSeq; + JLOG(m_journal.info()) << "First published ledger will be " << mValidLedgerSeq; return {mValidLedger.get()}; } if (mValidLedgerSeq > (mPubLedgerSeq + MAX_LEDGER_GAP)) { - JLOG(m_journal.warn()) << "Gap in validated ledger stream " - << mPubLedgerSeq << " - " << mValidLedgerSeq - 1; + JLOG(m_journal.warn()) << "Gap in validated ledger stream " << mPubLedgerSeq << " - " << mValidLedgerSeq - 1; auto valLedger = mValidLedger.get(); ret.push_back(valLedger); @@ -1237,8 +1171,7 @@ LedgerMaster::findNewLedgersToPublish( { for (std::uint32_t seq = pubSeq; seq <= valSeq; ++seq) { - JLOG(m_journal.trace()) - << "Trying to fetch/publish valid ledger " << seq; + JLOG(m_journal.trace()) << "Trying to fetch/publish valid ledger " << seq; std::shared_ptr ledger; // This can throw @@ -1255,8 +1188,7 @@ LedgerMaster::findNewLedgersToPublish( else if (hash->isZero()) { // LCOV_EXCL_START - JLOG(m_journal.fatal()) << "Ledger: " << valSeq - << " does not have hash for " << seq; + JLOG(m_journal.fatal()) << "Ledger: " << valSeq << " does not have hash for " << seq; UNREACHABLE( "xrpl::LedgerMaster::findNewLedgersToPublish : ledger " "not found"); @@ -1271,8 +1203,7 @@ LedgerMaster::findNewLedgersToPublish( { // Can we try to acquire the ledger we need? if (!ledger && (++acqCount < ledger_fetch_size_)) - ledger = app_.getInboundLedgers().acquire( - *hash, seq, InboundLedger::Reason::GENERIC); + ledger = app_.getInboundLedgers().acquire(*hash, seq, InboundLedger::Reason::GENERIC); } // Did we acquire the next ledger we need to publish? @@ -1284,14 +1215,11 @@ LedgerMaster::findNewLedgersToPublish( } } - JLOG(m_journal.trace()) - << "ready to publish " << ret.size() << " ledgers."; + JLOG(m_journal.trace()) << "ready to publish " << ret.size() << " ledgers."; } catch (std::exception const& ex) { - JLOG(m_journal.error()) - << "Exception while trying to find ledgers to publish: " - << ex.what(); + JLOG(m_journal.error()) << "Exception while trying to find ledgers to publish: " << ex.what(); } if (app_.config().LEDGER_REPLAY) @@ -1306,26 +1234,19 @@ LedgerMaster::findNewLedgersToPublish( auto finishLedger = valLedger; while (startLedger->seq() + 1 < finishLedger->seq()) { - if (auto const parent = mLedgerHistory.getLedgerByHash( - finishLedger->header().parentHash); - parent) + if (auto const parent = mLedgerHistory.getLedgerByHash(finishLedger->header().parentHash); parent) { finishLedger = parent; } else { - auto numberLedgers = - finishLedger->seq() - startLedger->seq() + 1; - JLOG(m_journal.debug()) - << "Publish LedgerReplays " << numberLedgers - << " ledgers, from seq=" << startLedger->header().seq - << ", " << startLedger->header().hash - << " to seq=" << finishLedger->header().seq << ", " - << finishLedger->header().hash; + auto numberLedgers = finishLedger->seq() - startLedger->seq() + 1; + JLOG(m_journal.debug()) << "Publish LedgerReplays " << numberLedgers + << " ledgers, from seq=" << startLedger->header().seq << ", " + << startLedger->header().hash << " to seq=" << finishLedger->header().seq + << ", " << finishLedger->header().hash; app_.getLedgerReplayer().replay( - InboundLedger::Reason::GENERIC, - finishLedger->header().hash, - numberLedgers); + InboundLedger::Reason::GENERIC, finishLedger->header().hash, numberLedgers); break; } } @@ -1344,12 +1265,10 @@ LedgerMaster::tryAdvance() if (!mAdvanceThread && !mValidLedger.empty()) { mAdvanceThread = true; - app_.getJobQueue().addJob(jtADVANCE, "advanceLedger", [this]() { + app_.getJobQueue().addJob(jtADVANCE, "AdvanceLedger", [this]() { std::unique_lock sl(m_mutex); - XRPL_ASSERT( - !mValidLedger.empty() && mAdvanceThread, - "xrpl::LedgerMaster::tryAdvance : has valid ledger"); + XRPL_ASSERT(!mValidLedger.empty() && mAdvanceThread, "xrpl::LedgerMaster::tryAdvance : has valid ledger"); JLOG(m_journal.trace()) << "advanceThread<"; @@ -1389,9 +1308,7 @@ LedgerMaster::updatePaths() { std::lock_guard ml(m_mutex); - if (!mValidLedger.empty() && - (!mPathLedger || - (mPathLedger->header().seq != mValidLedgerSeq))) + if (!mValidLedger.empty() && (!mPathLedger || (mPathLedger->header().seq != mValidLedgerSeq))) { // We have a new valid ledger since the last full pathfinding mPathLedger = mValidLedger.get(); lastLedger = mPathLedger; @@ -1412,12 +1329,10 @@ LedgerMaster::updatePaths() if (!standalone_) { // don't pathfind with a ledger that's more than 60 seconds old using namespace std::chrono; - auto age = time_point_cast(app_.timeKeeper().closeTime()) - - lastLedger->header().closeTime; + auto age = time_point_cast(app_.timeKeeper().closeTime()) - lastLedger->header().closeTime; if (age > 1min) { - JLOG(m_journal.debug()) - << "Published ledger too old for updating paths"; + JLOG(m_journal.debug()) << "Published ledger too old for updating paths"; std::lock_guard ml(m_mutex); --mPathFindThread; mPathLedger.reset(); @@ -1434,10 +1349,9 @@ LedgerMaster::updatePaths() { --mPathFindThread; mPathLedger.reset(); - JLOG(m_journal.debug()) - << "No path requests found. Nothing to do for updating " - "paths. " - << mPathFindThread << " jobs remaining"; + JLOG(m_journal.debug()) << "No path requests found. Nothing to do for updating " + "paths. " + << mPathFindThread << " jobs remaining"; return; } } @@ -1447,9 +1361,8 @@ LedgerMaster::updatePaths() std::lock_guard ml(m_mutex); if (!pathRequests.requestsPending()) { - JLOG(m_journal.debug()) - << "No path requests left. No need for further updating " - "paths"; + JLOG(m_journal.debug()) << "No path requests left. No need for further updating " + "paths"; --mPathFindThread; mPathLedger.reset(); return; @@ -1462,17 +1375,13 @@ LedgerMaster::updatePaths() { // our parent is the problem app_.getInboundLedgers().acquire( - lastLedger->header().parentHash, - lastLedger->header().seq - 1, - InboundLedger::Reason::GENERIC); + lastLedger->header().parentHash, lastLedger->header().seq - 1, InboundLedger::Reason::GENERIC); } else { // this ledger is the problem app_.getInboundLedgers().acquire( - lastLedger->header().hash, - lastLedger->header().seq, - InboundLedger::Reason::GENERIC); + lastLedger->header().hash, lastLedger->header().seq, InboundLedger::Reason::GENERIC); } } } @@ -1482,7 +1391,7 @@ bool LedgerMaster::newPathRequest() { std::unique_lock ml(m_mutex); - mPathFindNewRequest = newPFWork("pf:newRequest", ml); + mPathFindNewRequest = newPFWork("PthFindNewReq", ml); return mPathFindNewRequest; } @@ -1503,24 +1412,18 @@ LedgerMaster::newOrderBookDB() std::unique_lock ml(m_mutex); mPathLedger.reset(); - return newPFWork("pf:newOBDB", ml); + return newPFWork("PthFindOBDB", ml); } /** A thread needs to be dispatched to handle pathfinding work of some kind. */ bool -LedgerMaster::newPFWork( - char const* name, - std::unique_lock&) +LedgerMaster::newPFWork(char const* name, std::unique_lock&) { - if (!app_.isStopping() && mPathFindThread < 2 && - app_.getPathRequests().requestsPending()) + if (!app_.isStopping() && mPathFindThread < 2 && app_.getPathRequests().requestsPending()) { - JLOG(m_journal.debug()) - << "newPFWork: Creating job. path find threads: " - << mPathFindThread; - if (app_.getJobQueue().addJob( - jtUPDATE_PF, name, [this]() { updatePaths(); })) + JLOG(m_journal.debug()) << "newPFWork: Creating job. path find threads: " << mPathFindThread; + if (app_.getJobQueue().addJob(jtUPDATE_PF, name, [this]() { updatePaths(); })) { ++mPathFindThread; } @@ -1582,20 +1485,16 @@ std::optional LedgerMaster::getCloseTimeBySeq(LedgerIndex ledgerIndex) { uint256 hash = getHashBySeq(ledgerIndex); - return hash.isNonZero() ? getCloseTimeByHash(hash, ledgerIndex) - : std::nullopt; + return hash.isNonZero() ? getCloseTimeByHash(hash, ledgerIndex) : std::nullopt; } std::optional -LedgerMaster::getCloseTimeByHash( - LedgerHash const& ledgerHash, - std::uint32_t index) +LedgerMaster::getCloseTimeByHash(LedgerHash const& ledgerHash, std::uint32_t index) { auto nodeObject = app_.getNodeStore().fetchNodeObject(ledgerHash, index); if (nodeObject && (nodeObject->getData().size() >= 120)) { - SerialIter it( - nodeObject->getData().data(), nodeObject->getData().size()); + SerialIter it(nodeObject->getData().data(), nodeObject->getData().size()); if (safe_cast(it.get32()) == HashPrefix::ledgerMaster) { it.skip( @@ -1672,8 +1571,7 @@ LedgerMaster::walkHashBySeq( // Try to acquire the complete ledger if (!ledger) { - if (auto const l = app_.getInboundLedgers().acquire( - *refHash, refIndex, reason)) + if (auto const l = app_.getInboundLedgers().acquire(*refHash, refIndex, reason)) { ledgerHash = hashOfSeq(*l, index, m_journal); XRPL_ASSERT( @@ -1791,38 +1689,29 @@ LedgerMaster::fetchForHistory( scope_unlock sul{sl}; if (auto hash = getLedgerHashForHistory(missing, reason)) { - XRPL_ASSERT( - hash->isNonZero(), - "xrpl::LedgerMaster::fetchForHistory : found ledger"); + XRPL_ASSERT(hash->isNonZero(), "xrpl::LedgerMaster::fetchForHistory : found ledger"); auto ledger = getLedgerByHash(*hash); if (!ledger) { if (!app_.getInboundLedgers().isFailure(*hash)) { - ledger = - app_.getInboundLedgers().acquire(*hash, missing, reason); - if (!ledger && missing != fetch_seq_ && - missing > app_.getNodeStore().earliestLedgerSeq()) + ledger = app_.getInboundLedgers().acquire(*hash, missing, reason); + if (!ledger && missing != fetch_seq_ && missing > app_.getNodeStore().earliestLedgerSeq()) { - JLOG(m_journal.trace()) - << "fetchForHistory want fetch pack " << missing; + JLOG(m_journal.trace()) << "fetchForHistory want fetch pack " << missing; fetch_seq_ = missing; getFetchPack(missing, reason); } else - JLOG(m_journal.trace()) - << "fetchForHistory no fetch pack for " << missing; + JLOG(m_journal.trace()) << "fetchForHistory no fetch pack for " << missing; } else - JLOG(m_journal.debug()) - << "fetchForHistory found failed acquire"; + JLOG(m_journal.debug()) << "fetchForHistory found failed acquire"; } if (ledger) { auto seq = ledger->header().seq; - XRPL_ASSERT( - seq == missing, - "xrpl::LedgerMaster::fetchForHistory : sequence match"); + XRPL_ASSERT(seq == missing, "xrpl::LedgerMaster::fetchForHistory : sequence match"); JLOG(m_journal.trace()) << "fetchForHistory acquired " << seq; setFullLedger(ledger, false, false); int fillInProgress; @@ -1832,18 +1721,14 @@ LedgerMaster::fetchForHistory( fillInProgress = mFillInProgress; } if (fillInProgress == 0 && - app_.getRelationalDatabase().getHashByIndex(seq - 1) == - ledger->header().parentHash) + app_.getRelationalDatabase().getHashByIndex(seq - 1) == ledger->header().parentHash) { { // Previous ledger is in DB std::lock_guard lock(m_mutex); mFillInProgress = seq; } - app_.getJobQueue().addJob( - jtADVANCE, "tryFill", [this, ledger]() { - tryFill(ledger); - }); + app_.getJobQueue().addJob(jtADVANCE, "TryFill", [this, ledger]() { tryFill(ledger); }); } progress = true; } @@ -1853,9 +1738,7 @@ LedgerMaster::fetchForHistory( // Do not fetch ledger sequences lower // than the earliest ledger sequence fetchSz = app_.getNodeStore().earliestLedgerSeq(); - fetchSz = missing >= fetchSz - ? std::min(ledger_fetch_size_, (missing - fetchSz) + 1) - : 0; + fetchSz = missing >= fetchSz ? std::min(ledger_fetch_size_, (missing - fetchSz) + 1) : 0; try { for (std::uint32_t i = 0; i < fetchSz; ++i) @@ -1873,23 +1756,17 @@ LedgerMaster::fetchForHistory( } catch (std::exception const& ex) { - JLOG(m_journal.warn()) - << "Threw while prefetching: " << ex.what(); + JLOG(m_journal.warn()) << "Threw while prefetching: " << ex.what(); } } } else { - JLOG(m_journal.fatal()) - << "Can't find ledger following prevMissing " << missing; - JLOG(m_journal.fatal()) - << "Pub:" << mPubLedgerSeq << " Val:" << mValidLedgerSeq; - JLOG(m_journal.fatal()) - << "Ledgers: " << app_.getLedgerMaster().getCompleteLedgers(); - JLOG(m_journal.fatal()) - << "Acquire reason: " - << (reason == InboundLedger::Reason::HISTORY ? "HISTORY" - : "NOT HISTORY"); + JLOG(m_journal.fatal()) << "Can't find ledger following prevMissing " << missing; + JLOG(m_journal.fatal()) << "Pub:" << mPubLedgerSeq << " Val:" << mValidLedgerSeq; + JLOG(m_journal.fatal()) << "Ledgers: " << app_.getLedgerMaster().getCompleteLedgers(); + JLOG(m_journal.fatal()) << "Acquire reason: " + << (reason == InboundLedger::Reason::HISTORY ? "HISTORY" : "NOT HISTORY"); clearLedger(missing + 1); progress = true; } @@ -1908,8 +1785,7 @@ LedgerMaster::doAdvance(std::unique_lock& sl) if (pubLedgers.empty()) { if (!standalone_ && !app_.getFeeTrack().isLoadedLocal() && - (app_.getJobQueue().getJobCount(jtPUBOLDLEDGER) < 10) && - (mValidLedgerSeq == mPubLedgerSeq) && + (app_.getJobQueue().getJobCount(jtPUBOLDLEDGER) < 10) && (mValidLedgerSeq == mPubLedgerSeq) && (getValidatedLedgerAge() < MAX_LEDGER_AGE_ACQUIRE) && (app_.getNodeStore().getWriteLoad() < MAX_WRITE_LOAD_ACQUIRE)) { @@ -1919,14 +1795,11 @@ LedgerMaster::doAdvance(std::unique_lock& sl) { std::lock_guard sll(mCompleteLock); missing = prevMissing( - mCompleteLedgers, - mPubLedger->header().seq, - app_.getNodeStore().earliestLedgerSeq()); + mCompleteLedgers, mPubLedger->header().seq, app_.getNodeStore().earliestLedgerSeq()); } if (missing) { - JLOG(m_journal.trace()) - << "tryAdvance discovered missing " << *missing; + JLOG(m_journal.trace()) << "tryAdvance discovered missing " << *missing; if ((mFillInProgress == 0 || *missing > mFillInProgress) && shouldAcquire( mValidLedgerSeq, @@ -1935,8 +1808,7 @@ LedgerMaster::doAdvance(std::unique_lock& sl) *missing, m_journal)) { - JLOG(m_journal.trace()) - << "advanceThread should acquire"; + JLOG(m_journal.trace()) << "advanceThread should acquire"; } else missing = std::nullopt; @@ -1946,8 +1818,7 @@ LedgerMaster::doAdvance(std::unique_lock& sl) fetchForHistory(*missing, progress, reason, sl); if (mValidLedgerSeq != mPubLedgerSeq) { - JLOG(m_journal.debug()) - << "tryAdvance found last valid changed"; + JLOG(m_journal.debug()) << "tryAdvance found last valid changed"; progress = true; } } @@ -1960,14 +1831,12 @@ LedgerMaster::doAdvance(std::unique_lock& sl) } else { - JLOG(m_journal.trace()) << "tryAdvance found " << pubLedgers.size() - << " ledgers to publish"; + JLOG(m_journal.trace()) << "tryAdvance found " << pubLedgers.size() << " ledgers to publish"; for (auto const& ledger : pubLedgers) { { scope_unlock sul{sl}; - JLOG(m_journal.debug()) - << "tryAdvance publishing seq " << ledger->header().seq; + JLOG(m_journal.debug()) << "tryAdvance publishing seq " << ledger->header().seq; setFullLedger(ledger, true, true); } @@ -1980,7 +1849,7 @@ LedgerMaster::doAdvance(std::unique_lock& sl) } app_.getOPs().clearNeedNetworkLedger(); - progress = newPFWork("pf:newLedger", sl); + progress = newPFWork("PthFindNewLed", sl); } if (progress) mAdvanceWork = true; @@ -2011,7 +1880,7 @@ LedgerMaster::gotFetchPack(bool progress, std::uint32_t seq) { if (!mGotFetchPackThread.test_and_set(std::memory_order_acquire)) { - app_.getJobQueue().addJob(jtLEDGER_DATA, "gotFetchPack", [&]() { + app_.getJobQueue().addJob(jtLEDGER_DATA, "GotFetchPack", [&]() { app_.getInboundLedgers().gotFetchPack(); mGotFetchPackThread.clear(std::memory_order_release); }); @@ -2056,24 +1925,22 @@ populateFetchPack( Serializer s(1024); - want.visitDifferences( - have, - [&s, withLeaves, &cnt, into, seq](SHAMapTreeNode const& n) -> bool { - if (!withLeaves && n.isLeaf()) - return true; + want.visitDifferences(have, [&s, withLeaves, &cnt, into, seq](SHAMapTreeNode const& n) -> bool { + if (!withLeaves && n.isLeaf()) + return true; - s.erase(); - n.serializeWithPrefix(s); + s.erase(); + n.serializeWithPrefix(s); - auto const& hash = n.getHash().as_uint256(); + auto const& hash = n.getHash().as_uint256(); - protocol::TMIndexedObject* obj = into->add_objects(); - obj->set_ledgerseq(seq); - obj->set_hash(hash.data(), hash.size()); - obj->set_data(s.getDataPtr(), s.getLength()); + protocol::TMIndexedObject* obj = into->add_objects(); + obj->set_ledgerseq(seq); + obj->set_hash(hash.data(), hash.size()); + obj->set_data(s.getDataPtr(), s.getLength()); - return --cnt != 0; - }); + return --cnt != 0; + }); } void @@ -2105,16 +1972,14 @@ LedgerMaster::makeFetchPack( if (!have) { - JLOG(m_journal.info()) - << "Peer requests fetch pack for ledger we don't have: " << have; + JLOG(m_journal.info()) << "Peer requests fetch pack for ledger we don't have: " << have; peer->charge(Resource::feeRequestNoReply, "get_object ledger"); return; } if (have->open()) { - JLOG(m_journal.warn()) - << "Peer requests fetch pack from open ledger: " << have; + JLOG(m_journal.warn()) << "Peer requests fetch pack from open ledger: " << have; peer->charge(Resource::feeMalformedRequest, "get_object ledger open"); return; } @@ -2130,11 +1995,9 @@ LedgerMaster::makeFetchPack( if (!want) { - JLOG(m_journal.info()) - << "Peer requests fetch pack for ledger whose predecessor we " - << "don't have: " << have; - peer->charge( - Resource::feeRequestNoReply, "get_object ledger no parent"); + JLOG(m_journal.info()) << "Peer requests fetch pack for ledger whose predecessor we " + << "don't have: " << have; + peer->charge(Resource::feeRequestNoReply, "get_object ledger no parent"); return; } @@ -2172,14 +2035,12 @@ LedgerMaster::makeFetchPack( // Add the data protocol::TMIndexedObject* obj = reply.add_objects(); - obj->set_hash( - want->header().hash.data(), want->header().hash.size()); + obj->set_hash(want->header().hash.data(), want->header().hash.size()); obj->set_data(hdr.getDataPtr(), hdr.getLength()); obj->set_ledgerseq(lSeq); } - populateFetchPack( - want->stateMap(), &have->stateMap(), 16384, &reply, lSeq); + populateFetchPack(want->stateMap(), &have->stateMap(), 16384, &reply, lSeq); // We use nullptr here because transaction maps are per ledger // and so the requestor is unlikely to already have it. @@ -2195,16 +2056,14 @@ LedgerMaster::makeFetchPack( auto msg = std::make_shared(reply, protocol::mtGET_OBJECTS); - JLOG(m_journal.info()) - << "Built fetch pack with " << reply.objects().size() << " nodes (" - << msg->getBufferSize() << " bytes)"; + JLOG(m_journal.info()) << "Built fetch pack with " << reply.objects().size() << " nodes (" + << msg->getBufferSize() << " bytes)"; peer->send(msg); } catch (std::exception const& ex) { - JLOG(m_journal.warn()) - << "Exception building fetch pack. Exception: " << ex.what(); + JLOG(m_journal.warn()) << "Exception building fetch pack. Exception: " << ex.what(); } } @@ -2234,8 +2093,7 @@ LedgerMaster::txnIdFromIndex(uint32_t ledgerSeq, uint32_t txnIndex) return {}; for (auto it = lgr->txs.begin(); it != lgr->txs.end(); ++it) - if (it->first && it->second && - it->second->isFieldPresent(sfTransactionIndex) && + if (it->first && it->second && it->second->isFieldPresent(sfTransactionIndex) && it->second->getFieldU32(sfTransactionIndex) == txnIndex) return it->first->getTransactionID(); diff --git a/src/xrpld/app/ledger/detail/LedgerReplay.cpp b/src/xrpld/app/ledger/detail/LedgerReplay.cpp index 5d7ce0e69f..e77adc9700 100644 --- a/src/xrpld/app/ledger/detail/LedgerReplay.cpp +++ b/src/xrpld/app/ledger/detail/LedgerReplay.cpp @@ -3,9 +3,7 @@ namespace xrpl { -LedgerReplay::LedgerReplay( - std::shared_ptr parent, - std::shared_ptr replay) +LedgerReplay::LedgerReplay(std::shared_ptr parent, std::shared_ptr replay) : parent_{std::move(parent)}, replay_{std::move(replay)} { for (auto const& item : replay_->txMap()) @@ -20,9 +18,7 @@ LedgerReplay::LedgerReplay( std::shared_ptr parent, std::shared_ptr replay, std::map>&& orderedTxns) - : parent_{std::move(parent)} - , replay_{std::move(replay)} - , orderedTxns_{std::move(orderedTxns)} + : parent_{std::move(parent)}, replay_{std::move(replay)}, orderedTxns_{std::move(orderedTxns)} { } diff --git a/src/xrpld/app/ledger/detail/LedgerReplayMsgHandler.cpp b/src/xrpld/app/ledger/detail/LedgerReplayMsgHandler.cpp index 9356f17af0..4fcb924c27 100644 --- a/src/xrpld/app/ledger/detail/LedgerReplayMsgHandler.cpp +++ b/src/xrpld/app/ledger/detail/LedgerReplayMsgHandler.cpp @@ -8,25 +8,19 @@ #include namespace xrpl { -LedgerReplayMsgHandler::LedgerReplayMsgHandler( - Application& app, - LedgerReplayer& replayer) - : app_(app) - , replayer_(replayer) - , journal_(app.journal("LedgerReplayMsgHandler")) +LedgerReplayMsgHandler::LedgerReplayMsgHandler(Application& app, LedgerReplayer& replayer) + : app_(app), replayer_(replayer), journal_(app.journal("LedgerReplayMsgHandler")) { } protocol::TMProofPathResponse -LedgerReplayMsgHandler::processProofPathRequest( - std::shared_ptr const& msg) +LedgerReplayMsgHandler::processProofPathRequest(std::shared_ptr const& msg) { protocol::TMProofPathRequest& packet = *msg; protocol::TMProofPathResponse reply; if (!packet.has_key() || !packet.has_ledgerhash() || !packet.has_type() || - packet.ledgerhash().size() != uint256::size() || - packet.key().size() != uint256::size() || + packet.ledgerhash().size() != uint256::size() || packet.key().size() != uint256::size() || !protocol::TMLedgerMapType_IsValid(packet.type())) { JLOG(journal_.debug()) << "getProofPath: Invalid request"; @@ -42,8 +36,7 @@ LedgerReplayMsgHandler::processProofPathRequest( auto ledger = app_.getLedgerMaster().getLedgerByHash(ledgerHash); if (!ledger) { - JLOG(journal_.debug()) - << "getProofPath: Don't have ledger " << ledgerHash; + JLOG(journal_.debug()) << "getProofPath: Don't have ledger " << ledgerHash; reply.set_error(protocol::TMReplyError::reNO_LEDGER); return reply; } @@ -64,8 +57,7 @@ LedgerReplayMsgHandler::processProofPathRequest( if (!path) { - JLOG(journal_.debug()) << "getProofPath: Don't have the node " << key - << " of ledger " << ledgerHash; + JLOG(journal_.debug()) << "getProofPath: Don't have the node " << key << " of ledger " << ledgerHash; reply.set_error(protocol::TMReplyError::reNO_NODE); return reply; } @@ -78,20 +70,17 @@ LedgerReplayMsgHandler::processProofPathRequest( for (auto const& b : *path) reply.add_path(b.data(), b.size()); - JLOG(journal_.debug()) << "getProofPath for the node " << key - << " of ledger " << ledgerHash << " path length " + JLOG(journal_.debug()) << "getProofPath for the node " << key << " of ledger " << ledgerHash << " path length " << path->size(); return reply; } bool -LedgerReplayMsgHandler::processProofPathResponse( - std::shared_ptr const& msg) +LedgerReplayMsgHandler::processProofPathResponse(std::shared_ptr const& msg) { protocol::TMProofPathResponse& reply = *msg; - if (reply.has_error() || !reply.has_key() || !reply.has_ledgerhash() || - !reply.has_type() || !reply.has_ledgerheader() || - reply.path_size() == 0) + if (reply.has_error() || !reply.has_key() || !reply.has_ledgerhash() || !reply.has_type() || + !reply.has_ledgerheader() || reply.path_size() == 0) { JLOG(journal_.debug()) << "Bad message: Error reply"; return false; @@ -99,14 +88,12 @@ LedgerReplayMsgHandler::processProofPathResponse( if (reply.type() != protocol::lmACCOUNT_STATE) { - JLOG(journal_.debug()) - << "Bad message: we only support the state ShaMap for now"; + JLOG(journal_.debug()) << "Bad message: we only support the state ShaMap for now"; return false; } // deserialize the header - auto info = deserializeHeader( - {reply.ledgerheader().data(), reply.ledgerheader().size()}); + auto info = deserializeHeader({reply.ledgerheader().data(), reply.ledgerheader().size()}); uint256 replyHash(reply.ledgerhash()); if (calculateLedgerHash(info) != replyHash) { @@ -118,10 +105,9 @@ LedgerReplayMsgHandler::processProofPathResponse( uint256 key(reply.key()); if (key != keylet::skip().key) { - JLOG(journal_.debug()) - << "Bad message: we only support the short skip list for now. " - "Key in reply " - << key; + JLOG(journal_.debug()) << "Bad message: we only support the short skip list for now. " + "Key in reply " + << key; return false; } @@ -158,14 +144,12 @@ LedgerReplayMsgHandler::processProofPathResponse( } protocol::TMReplayDeltaResponse -LedgerReplayMsgHandler::processReplayDeltaRequest( - std::shared_ptr const& msg) +LedgerReplayMsgHandler::processReplayDeltaRequest(std::shared_ptr const& msg) { protocol::TMReplayDeltaRequest& packet = *msg; protocol::TMReplayDeltaResponse reply; - if (!packet.has_ledgerhash() || - packet.ledgerhash().size() != uint256::size()) + if (!packet.has_ledgerhash() || packet.ledgerhash().size() != uint256::size()) { JLOG(journal_.debug()) << "getReplayDelta: Invalid request"; reply.set_error(protocol::TMReplyError::reBAD_REQUEST); @@ -177,8 +161,7 @@ LedgerReplayMsgHandler::processReplayDeltaRequest( auto ledger = app_.getLedgerMaster().getLedgerByHash(ledgerHash); if (!ledger || !ledger->isImmutable()) { - JLOG(journal_.debug()) - << "getReplayDelta: Don't have ledger " << ledgerHash; + JLOG(journal_.debug()) << "getReplayDelta: Don't have ledger " << ledgerHash; reply.set_error(protocol::TMReplyError::reNO_LEDGER); return reply; } @@ -189,19 +172,17 @@ LedgerReplayMsgHandler::processReplayDeltaRequest( reply.set_ledgerheader(nData.getDataPtr(), nData.getLength()); // pack transactions auto const& txMap = ledger->txMap(); - txMap.visitLeaves( - [&](boost::intrusive_ptr const& txNode) { - reply.add_transaction(txNode->data(), txNode->size()); - }); + txMap.visitLeaves([&](boost::intrusive_ptr const& txNode) { + reply.add_transaction(txNode->data(), txNode->size()); + }); - JLOG(journal_.debug()) << "getReplayDelta for ledger " << ledgerHash - << " txMap hash " << txMap.getHash().as_uint256(); + JLOG(journal_.debug()) << "getReplayDelta for ledger " << ledgerHash << " txMap hash " + << txMap.getHash().as_uint256(); return reply; } bool -LedgerReplayMsgHandler::processReplayDeltaResponse( - std::shared_ptr const& msg) +LedgerReplayMsgHandler::processReplayDeltaResponse(std::shared_ptr const& msg) { protocol::TMReplayDeltaResponse& reply = *msg; if (reply.has_error() || !reply.has_ledgerheader()) @@ -210,8 +191,7 @@ LedgerReplayMsgHandler::processReplayDeltaResponse( return false; } - auto info = deserializeHeader( - {reply.ledgerheader().data(), reply.ledgerheader().size()}); + auto info = deserializeHeader({reply.ledgerheader().data(), reply.ledgerheader().size()}); uint256 replyHash(reply.ledgerhash()); if (calculateLedgerHash(info) != replyHash) { @@ -231,8 +211,7 @@ LedgerReplayMsgHandler::processReplayDeltaResponse( // -- TxShaMapItem for building a ShaMap for verification // -- Tx // -- TxMetaData for Tx ordering - Serializer shaMapItemData( - reply.transaction(i).data(), reply.transaction(i).size()); + Serializer shaMapItemData(reply.transaction(i).data(), reply.transaction(i).size()); SerialIter txMetaSit(makeSlice(reply.transaction(i))); SerialIter txSit(txMetaSit.getSlice(txMetaSit.getVLDataLength())); @@ -248,9 +227,7 @@ LedgerReplayMsgHandler::processReplayDeltaResponse( STObject meta(metaSit, sfMetadata); orderedTxns.emplace(meta[sfTransactionIndex], std::move(tx)); - if (!txMap.addGiveItem( - SHAMapNodeType::tnTRANSACTION_MD, - make_shamapitem(tid, shaMapItemData.slice()))) + if (!txMap.addGiveItem(SHAMapNodeType::tnTRANSACTION_MD, make_shamapitem(tid, shaMapItemData.slice()))) { JLOG(journal_.debug()) << "Bad message: Cannot deserialize"; return false; diff --git a/src/xrpld/app/ledger/detail/LedgerReplayMsgHandler.h b/src/xrpld/app/ledger/detail/LedgerReplayMsgHandler.h index fff3e75460..260f1ff753 100644 --- a/src/xrpld/app/ledger/detail/LedgerReplayMsgHandler.h +++ b/src/xrpld/app/ledger/detail/LedgerReplayMsgHandler.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_LEDGER_LEDGERREPLAYMSGHANDLER_H_INCLUDED -#define XRPL_APP_LEDGER_LEDGERREPLAYMSGHANDLER_H_INCLUDED +#pragma once #include #include @@ -19,8 +18,7 @@ public: * @note check has_error() and error() of the response for error */ protocol::TMProofPathResponse - processProofPathRequest( - std::shared_ptr const& msg); + processProofPathRequest(std::shared_ptr const& msg); /** * Process TMProofPathResponse @@ -28,16 +26,14 @@ public: * true otherwise */ bool - processProofPathResponse( - std::shared_ptr const& msg); + processProofPathResponse(std::shared_ptr const& msg); /** * Process TMReplayDeltaRequest and return TMReplayDeltaResponse * @note check has_error() and error() of the response for error */ protocol::TMReplayDeltaResponse - processReplayDeltaRequest( - std::shared_ptr const& msg); + processReplayDeltaRequest(std::shared_ptr const& msg); /** * Process TMReplayDeltaResponse @@ -45,8 +41,7 @@ public: * true otherwise */ bool - processReplayDeltaResponse( - std::shared_ptr const& msg); + processReplayDeltaResponse(std::shared_ptr const& msg); private: Application& app_; @@ -55,5 +50,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/src/xrpld/app/ledger/detail/LedgerReplayTask.cpp b/src/xrpld/app/ledger/detail/LedgerReplayTask.cpp index cd174b098f..b7d788e15a 100644 --- a/src/xrpld/app/ledger/detail/LedgerReplayTask.cpp +++ b/src/xrpld/app/ledger/detail/LedgerReplayTask.cpp @@ -19,10 +19,7 @@ LedgerReplayTask::TaskParameter::TaskParameter( } bool -LedgerReplayTask::TaskParameter::update( - uint256 const& hash, - std::uint32_t seq, - std::vector const& sList) +LedgerReplayTask::TaskParameter::update(uint256 const& hash, std::uint32_t seq, std::vector const& sList) { if (finishHash_ != hash || sList.size() + 1 < totalLedgers_ || full_) return false; @@ -31,22 +28,18 @@ LedgerReplayTask::TaskParameter::update( skipList_ = sList; skipList_.emplace_back(finishHash_); startHash_ = skipList_[skipList_.size() - totalLedgers_]; - XRPL_ASSERT( - startHash_.isNonZero(), - "xrpl::LedgerReplayTask::TaskParameter::update : nonzero start hash"); + XRPL_ASSERT(startHash_.isNonZero(), "xrpl::LedgerReplayTask::TaskParameter::update : nonzero start hash"); startSeq_ = finishSeq_ - totalLedgers_ + 1; full_ = true; return true; } bool -LedgerReplayTask::TaskParameter::canMergeInto( - TaskParameter const& existingTask) const +LedgerReplayTask::TaskParameter::canMergeInto(TaskParameter const& existingTask) const { if (reason_ == existingTask.reason_) { - if (finishHash_ == existingTask.finishHash_ && - totalLedgers_ <= existingTask.totalLedgers_) + if (finishHash_ == existingTask.finishHash_ && totalLedgers_ <= existingTask.totalLedgers_) { return true; } @@ -54,11 +47,9 @@ LedgerReplayTask::TaskParameter::canMergeInto( if (existingTask.full_) { auto const& exList = existingTask.skipList_; - if (auto i = std::find(exList.begin(), exList.end(), finishHash_); - i != exList.end()) + if (auto i = std::find(exList.begin(), exList.end(), finishHash_); i != exList.end()) { - return existingTask.totalLedgers_ >= - totalLedgers_ + (exList.end() - i) - 1; + return existingTask.totalLedgers_ >= totalLedgers_ + (exList.end() - i) - 1; } } } @@ -76,17 +67,14 @@ LedgerReplayTask::LedgerReplayTask( app, parameter.finishHash_, LedgerReplayParameters::TASK_TIMEOUT, - {jtREPLAY_TASK, - "LedgerReplayTask", - LedgerReplayParameters::MAX_QUEUED_TASKS}, + {jtREPLAY_TASK, "LedReplTask", LedgerReplayParameters::MAX_QUEUED_TASKS}, app.journal("LedgerReplayTask")) , inboundLedgers_(inboundLedgers) , replayer_(replayer) , parameter_(parameter) , maxTimeouts_(std::max( LedgerReplayParameters::TASK_MAX_TIMEOUTS_MINIMUM, - parameter.totalLedgers_ * - LedgerReplayParameters::TASK_MAX_TIMEOUTS_MULTIPLIER)) + parameter.totalLedgers_ * LedgerReplayParameters::TASK_MAX_TIMEOUTS_MULTIPLIER)) , skipListAcquirer_(skipListAcquirer) { JLOG(journal_.trace()) << "Create " << hash_; @@ -113,8 +101,7 @@ LedgerReplayTask::init() else { auto const skipListData = sptr->skipListAcquirer_->getData(); - sptr->updateSkipList( - hash, skipListData->ledgerSeq, skipListData->skipList); + sptr->updateSkipList(hash, skipListData->ledgerSeq, skipListData->skipList); } } }); @@ -139,16 +126,12 @@ LedgerReplayTask::trigger(ScopedLockType& sl) parent_ = app_.getLedgerMaster().getLedgerByHash(parameter_.startHash_); if (!parent_) { - parent_ = inboundLedgers_.acquire( - parameter_.startHash_, - parameter_.startSeq_, - InboundLedger::Reason::GENERIC); + parent_ = + inboundLedgers_.acquire(parameter_.startHash_, parameter_.startSeq_, InboundLedger::Reason::GENERIC); } if (parent_) { - JLOG(journal_.trace()) - << "Got start ledger " << parameter_.startHash_ << " for task " - << hash_; + JLOG(journal_.trace()) << "Got start ledger " << parameter_.startHash_ << " for task " << hash_; } } @@ -158,8 +141,7 @@ LedgerReplayTask::trigger(ScopedLockType& sl) void LedgerReplayTask::deltaReady(uint256 const& deltaHash) { - JLOG(journal_.trace()) << "Delta " << deltaHash << " ready for task " - << hash_; + JLOG(journal_.trace()) << "Delta " << deltaHash << " ready for task " << hash_; ScopedLockType sl(mtx_); if (!isDone()) tryAdvance(sl); @@ -169,14 +151,11 @@ void LedgerReplayTask::tryAdvance(ScopedLockType& sl) { JLOG(journal_.trace()) << "tryAdvance task " << hash_ - << (parameter_.full_ ? ", full parameter" - : ", waiting to fill parameter") - << ", deltaIndex=" << deltaToBuild_ - << ", totalDeltas=" << deltas_.size() << ", parent " + << (parameter_.full_ ? ", full parameter" : ", waiting to fill parameter") + << ", deltaIndex=" << deltaToBuild_ << ", totalDeltas=" << deltas_.size() << ", parent " << (parent_ ? parent_->header().hash : uint256()); - bool shouldTry = parent_ && parameter_.full_ && - parameter_.totalLedgers_ - 1 == deltas_.size(); + bool shouldTry = parent_ && parameter_.full_ && parameter_.totalLedgers_ - 1 == deltas_.size(); if (!shouldTry) return; @@ -186,14 +165,11 @@ LedgerReplayTask::tryAdvance(ScopedLockType& sl) { auto& delta = deltas_[deltaToBuild_]; XRPL_ASSERT( - parent_->seq() + 1 == delta->ledgerSeq_, - "xrpl::LedgerReplayTask::tryAdvance : consecutive sequence"); + parent_->seq() + 1 == delta->ledgerSeq_, "xrpl::LedgerReplayTask::tryAdvance : consecutive sequence"); if (auto l = delta->tryBuild(parent_); l) { - JLOG(journal_.debug()) - << "Task " << hash_ << " got ledger " << l->header().hash - << " deltaIndex=" << deltaToBuild_ - << " totalDeltas=" << deltas_.size(); + JLOG(journal_.debug()) << "Task " << hash_ << " got ledger " << l->header().hash + << " deltaIndex=" << deltaToBuild_ << " totalDeltas=" << deltas_.size(); parent_ = l; } else @@ -210,10 +186,7 @@ LedgerReplayTask::tryAdvance(ScopedLockType& sl) } void -LedgerReplayTask::updateSkipList( - uint256 const& hash, - std::uint32_t seq, - std::vector const& sList) +LedgerReplayTask::updateSkipList(uint256 const& hash, std::uint32_t seq, std::vector const& sList) { { ScopedLockType sl(mtx_); @@ -240,8 +213,7 @@ LedgerReplayTask::onTimer(bool progress, ScopedLockType& sl) if (timeouts_ > maxTimeouts_) { failed_ = true; - JLOG(journal_.debug()) - << "LedgerReplayTask Failed, too many timeouts " << hash_; + JLOG(journal_.debug()) << "LedgerReplayTask Failed, too many timeouts " << hash_; } else { @@ -259,26 +231,23 @@ void LedgerReplayTask::addDelta(std::shared_ptr const& delta) { std::weak_ptr wptr = shared_from_this(); - delta->addDataCallback( - parameter_.reason_, [wptr](bool good, uint256 const& hash) { - if (auto sptr = wptr.lock(); sptr) - { - if (!good) - sptr->cancel(); - else - sptr->deltaReady(hash); - } - }); + delta->addDataCallback(parameter_.reason_, [wptr](bool good, uint256 const& hash) { + if (auto sptr = wptr.lock(); sptr) + { + if (!good) + sptr->cancel(); + else + sptr->deltaReady(hash); + } + }); ScopedLockType sl(mtx_); if (!isDone()) { - JLOG(journal_.trace()) - << "addDelta task " << hash_ << " deltaIndex=" << deltaToBuild_ - << " totalDeltas=" << deltas_.size(); + JLOG(journal_.trace()) << "addDelta task " << hash_ << " deltaIndex=" << deltaToBuild_ + << " totalDeltas=" << deltas_.size(); XRPL_ASSERT( - deltas_.empty() || - deltas_.back()->ledgerSeq_ + 1 == delta->ledgerSeq_, + deltas_.empty() || deltas_.back()->ledgerSeq_ + 1 == delta->ledgerSeq_, "xrpl::LedgerReplayTask::addDelta : no deltas or consecutive " "sequence"); deltas_.push_back(delta); diff --git a/src/xrpld/app/ledger/detail/LedgerReplayer.cpp b/src/xrpld/app/ledger/detail/LedgerReplayer.cpp index 1d1cdf3ec2..b52abc5624 100644 --- a/src/xrpld/app/ledger/detail/LedgerReplayer.cpp +++ b/src/xrpld/app/ledger/detail/LedgerReplayer.cpp @@ -22,18 +22,13 @@ LedgerReplayer::~LedgerReplayer() } void -LedgerReplayer::replay( - InboundLedger::Reason r, - uint256 const& finishLedgerHash, - std::uint32_t totalNumLedgers) +LedgerReplayer::replay(InboundLedger::Reason r, uint256 const& finishLedgerHash, std::uint32_t totalNumLedgers) { XRPL_ASSERT( - finishLedgerHash.isNonZero() && totalNumLedgers > 0 && - totalNumLedgers <= LedgerReplayParameters::MAX_TASK_SIZE, + finishLedgerHash.isNonZero() && totalNumLedgers > 0 && totalNumLedgers <= LedgerReplayParameters::MAX_TASK_SIZE, "xrpl::LedgerReplayer::replay : valid inputs"); - LedgerReplayTask::TaskParameter parameter( - r, finishLedgerHash, totalNumLedgers); + LedgerReplayTask::TaskParameter parameter(r, finishLedgerHash, totalNumLedgers); std::shared_ptr task; std::shared_ptr skipList; @@ -44,8 +39,7 @@ LedgerReplayer::replay( return; if (tasks_.size() >= LedgerReplayParameters::MAX_TASKS) { - JLOG(j_.info()) << "Too many replay tasks, dropping new task " - << parameter.finishHash_; + JLOG(j_.info()) << "Too many replay tasks, dropping new task " << parameter.finishHash_; return; } @@ -53,15 +47,12 @@ LedgerReplayer::replay( { if (parameter.canMergeInto(t->getTaskParameter())) { - JLOG(j_.info()) << "Task " << parameter.finishHash_ << " with " - << totalNumLedgers + JLOG(j_.info()) << "Task " << parameter.finishHash_ << " with " << totalNumLedgers << " ledgers merged into an existing task."; return; } } - JLOG(j_.info()) << "Replay " << totalNumLedgers - << " ledgers. Finish ledger hash " - << parameter.finishHash_; + JLOG(j_.info()) << "Replay " << totalNumLedgers << " ledgers. Finish ledger hash " << parameter.finishHash_; auto i = skipLists_.find(parameter.finishHash_); if (i != skipLists_.end()) @@ -70,16 +61,12 @@ LedgerReplayer::replay( if (!skipList) // cannot find, or found but cannot lock { skipList = std::make_shared( - app_, - inboundLedgers_, - parameter.finishHash_, - peerSetBuilder_->build()); + app_, inboundLedgers_, parameter.finishHash_, peerSetBuilder_->build()); skipLists_[parameter.finishHash_] = skipList; newSkipList = true; } - task = std::make_shared( - app_, inboundLedgers_, *this, skipList, std::move(parameter)); + task = std::make_shared(app_, inboundLedgers_, *this, skipList, std::move(parameter)); tasks_.push_back(task); } @@ -103,21 +90,15 @@ LedgerReplayer::createDeltas(std::shared_ptr task) JLOG(j_.trace()) << "Creating " << parameter.totalLedgers_ - 1 << " deltas"; if (parameter.totalLedgers_ > 1) { - auto skipListItem = std::find( - parameter.skipList_.begin(), - parameter.skipList_.end(), - parameter.startHash_); - if (skipListItem == parameter.skipList_.end() || - ++skipListItem == parameter.skipList_.end()) + auto skipListItem = std::find(parameter.skipList_.begin(), parameter.skipList_.end(), parameter.startHash_); + if (skipListItem == parameter.skipList_.end() || ++skipListItem == parameter.skipList_.end()) { - JLOG(j_.error()) << "Task parameter error when creating deltas " - << parameter.finishHash_; + JLOG(j_.error()) << "Task parameter error when creating deltas " << parameter.finishHash_; return; } for (std::uint32_t seq = parameter.startSeq_ + 1; - seq <= parameter.finishSeq_ && - skipListItem != parameter.skipList_.end(); + seq <= parameter.finishSeq_ && skipListItem != parameter.skipList_.end(); ++seq, ++skipListItem) { std::shared_ptr delta; @@ -133,11 +114,7 @@ LedgerReplayer::createDeltas(std::shared_ptr task) if (!delta) // cannot find, or found but cannot lock { delta = std::make_shared( - app_, - inboundLedgers_, - *skipListItem, - seq, - peerSetBuilder_->build()); + app_, inboundLedgers_, *skipListItem, seq, peerSetBuilder_->build()); deltas_[*skipListItem] = delta; newDelta = true; } @@ -151,9 +128,7 @@ LedgerReplayer::createDeltas(std::shared_ptr task) } void -LedgerReplayer::gotSkipList( - LedgerHeader const& info, - boost::intrusive_ptr const& item) +LedgerReplayer::gotSkipList(LedgerHeader const& info, boost::intrusive_ptr const& item) { std::shared_ptr skipList = {}; { @@ -174,9 +149,7 @@ LedgerReplayer::gotSkipList( } void -LedgerReplayer::gotReplayDelta( - LedgerHeader const& info, - std::map>&& txns) +LedgerReplayer::gotReplayDelta(LedgerHeader const& info, std::map>&& txns) { std::shared_ptr delta = {}; { @@ -202,8 +175,7 @@ LedgerReplayer::sweep() auto const start = std::chrono::steady_clock::now(); { std::lock_guard lock(mtx_); - JLOG(j_.debug()) << "Sweeping, LedgerReplayer has " << tasks_.size() - << " tasks, " << skipLists_.size() + JLOG(j_.debug()) << "Sweeping, LedgerReplayer has " << tasks_.size() << " tasks, " << skipLists_.size() << " skipLists, and " << deltas_.size() << " deltas."; tasks_.erase( @@ -213,8 +185,7 @@ LedgerReplayer::sweep() [this](auto const& t) -> bool { if (t->finished()) { - JLOG(j_.debug()) << "Sweep task " - << t->getTaskParameter().finishHash_; + JLOG(j_.debug()) << "Sweep task " << t->getTaskParameter().finishHash_; return true; } return false; @@ -235,11 +206,10 @@ LedgerReplayer::sweep() removeCannotLocked(skipLists_); removeCannotLocked(deltas_); } - JLOG(j_.debug()) << " LedgerReplayer sweep lock duration " - << std::chrono::duration_cast( - std::chrono::steady_clock::now() - start) - .count() - << "ms"; + JLOG(j_.debug()) + << " LedgerReplayer sweep lock duration " + << std::chrono::duration_cast(std::chrono::steady_clock::now() - start).count() + << "ms"; } void @@ -248,8 +218,7 @@ LedgerReplayer::stop() JLOG(j_.info()) << "Stopping..."; { std::lock_guard lock(mtx_); - std::for_each( - tasks_.begin(), tasks_.end(), [](auto& i) { i->cancel(); }); + std::for_each(tasks_.begin(), tasks_.end(), [](auto& i) { i->cancel(); }); tasks_.clear(); auto lockAndCancel = [](auto& i) { if (auto sptr = i.second.lock(); sptr) diff --git a/src/xrpld/app/ledger/detail/LedgerToJson.cpp b/src/xrpld/app/ledger/detail/LedgerToJson.cpp index b1f6d6b297..a675550537 100644 --- a/src/xrpld/app/ledger/detail/LedgerToJson.cpp +++ b/src/xrpld/app/ledger/detail/LedgerToJson.cpp @@ -33,17 +33,10 @@ isBinary(LedgerFill const& fill) } void -fillJson( - Json::Value& json, - bool closed, - LedgerHeader const& info, - bool bFull, - unsigned apiVersion) +fillJson(Json::Value& json, bool closed, LedgerHeader const& info, bool bFull, unsigned apiVersion) { json[jss::parent_hash] = to_string(info.parentHash); - json[jss::ledger_index] = (apiVersion > 1) - ? Json::Value(info.seq) - : Json::Value(std::to_string(info.seq)); + json[jss::ledger_index] = (apiVersion > 1) ? Json::Value(info.seq) : Json::Value(std::to_string(info.seq)); if (closed) { @@ -63,8 +56,7 @@ fillJson( json[jss::close_flags] = info.closeFlags; // Always show fields that contribute to the ledger hash - json[jss::parent_close_time] = - info.parentCloseTime.time_since_epoch().count(); + json[jss::parent_close_time] = info.parentCloseTime.time_since_epoch().count(); json[jss::close_time] = info.closeTime.time_since_epoch().count(); json[jss::close_time_resolution] = info.closeTimeResolution.count(); @@ -111,19 +103,15 @@ fillJsonTx( if (fill.context->apiVersion > 1) txJson[jss::hash] = to_string(txn->getTransactionID()); - auto const json_meta = - (fill.context->apiVersion > 1 ? jss::meta_blob : jss::meta); + auto const json_meta = (fill.context->apiVersion > 1 ? jss::meta_blob : jss::meta); if (stMeta) txJson[json_meta] = serializeHex(*stMeta); } else if (fill.context->apiVersion > 1) { - copyFrom( - txJson[jss::tx_json], - txn->getJson(JsonOptions::disable_API_prior_V2, false)); + copyFrom(txJson[jss::tx_json], txn->getJson(JsonOptions::disable_API_prior_V2, false)); txJson[jss::hash] = to_string(txn->getTransactionID()); - RPC::insertDeliverMax( - txJson[jss::tx_json], txnType, fill.context->apiVersion); + RPC::insertDeliverMax(txJson[jss::tx_json], txnType, fill.context->apiVersion); if (stMeta) { @@ -132,23 +120,16 @@ fillJsonTx( // If applicable, insert delivered amount if (txnType == ttPAYMENT || txnType == ttCHECK_CASH) RPC::insertDeliveredAmount( - txJson[jss::meta], - fill.ledger, - txn, - {txn->getTransactionID(), fill.ledger.seq(), *stMeta}); + txJson[jss::meta], fill.ledger, txn, {txn->getTransactionID(), fill.ledger.seq(), *stMeta}); // If applicable, insert mpt issuance id - RPC::insertMPTokenIssuanceID( - txJson[jss::meta], - txn, - {txn->getTransactionID(), fill.ledger.seq(), *stMeta}); + RPC::insertMPTokenIssuanceID(txJson[jss::meta], txn, {txn->getTransactionID(), fill.ledger.seq(), *stMeta}); } if (!fill.ledger.open()) txJson[jss::ledger_hash] = to_string(fill.ledger.header().hash); - bool const validated = - fill.context->ledgerMaster.isValidated(fill.ledger); + bool const validated = fill.context->ledgerMaster.isValidated(fill.ledger); txJson[jss::validated] = validated; if (validated) { @@ -169,21 +150,15 @@ fillJsonTx( // If applicable, insert delivered amount if (txnType == ttPAYMENT || txnType == ttCHECK_CASH) RPC::insertDeliveredAmount( - txJson[jss::metaData], - fill.ledger, - txn, - {txn->getTransactionID(), fill.ledger.seq(), *stMeta}); + txJson[jss::metaData], fill.ledger, txn, {txn->getTransactionID(), fill.ledger.seq(), *stMeta}); // If applicable, insert mpt issuance id RPC::insertMPTokenIssuanceID( - txJson[jss::metaData], - txn, - {txn->getTransactionID(), fill.ledger.seq(), *stMeta}); + txJson[jss::metaData], txn, {txn->getTransactionID(), fill.ledger.seq(), *stMeta}); } } - if ((fill.options & LedgerFill::ownerFunds) && - txn->getTxnType() == ttOFFER_CREATE) + if ((fill.options & LedgerFill::ownerFunds) && txn->getTxnType() == ttOFFER_CREATE) { auto const account = txn->getAccountID(sfAccount); auto const amount = txn->getFieldAmount(sfTakerGets); @@ -193,11 +168,7 @@ fillJsonTx( if (account != amount.getIssuer()) { auto const ownerFunds = accountFunds( - fill.ledger, - account, - amount, - fhIGNORE_FREEZE, - beast::Journal{beast::Journal::getNullSink()}); + fill.ledger, account, amount, fhIGNORE_FREEZE, beast::Journal{beast::Journal::getNullSink()}); txJson[jss::owner_funds] = ownerFunds.getText(); } } @@ -217,8 +188,7 @@ fillJsonTx(Json::Value& json, LedgerFill const& fill) auto appendAll = [&](auto const& txs) { for (auto& i : txs) { - txns.append( - fillJsonTx(fill, bBinary, bExpanded, i.first, i.second)); + txns.append(fillJsonTx(fill, bBinary, bExpanded, i.first, i.second)); } }; @@ -229,8 +199,7 @@ fillJsonTx(Json::Value& json, LedgerFill const& fill) // Nothing the user can do about this. if (fill.context) { - JLOG(fill.context->j.error()) - << "Exception in " << __func__ << ": " << ex.what(); + JLOG(fill.context->j.error()) << "Exception in " << __func__ << ": " << ex.what(); } } } @@ -273,8 +242,7 @@ fillJsonQueue(Json::Value& json, LedgerFill const& fill) txJson[jss::LastLedgerSequence] = *tx.lastValid; txJson[jss::fee] = to_string(tx.consequences.fee()); - auto const spend = - tx.consequences.potentialSpend() + tx.consequences.fee(); + auto const spend = tx.consequences.potentialSpend() + tx.consequences.fee(); txJson[jss::max_spend_drops] = to_string(spend); txJson[jss::auth_change] = tx.consequences.isBlocker(); @@ -306,8 +274,7 @@ fillJson(Json::Value& json, LedgerFill const& fill) !fill.ledger.open(), fill.ledger.header(), bFull, - (fill.context ? fill.context->apiVersion - : RPC::apiMaximumSupportedVersion)); + (fill.context ? fill.context->apiVersion : RPC::apiMaximumSupportedVersion)); if (bFull || fill.options & LedgerFill::dumpTxrp) fillJsonTx(json, fill); diff --git a/src/xrpld/app/ledger/detail/LocalTxs.cpp b/src/xrpld/app/ledger/detail/LocalTxs.cpp index 1e9cfe0b9b..48bd80fbf2 100644 --- a/src/xrpld/app/ledger/detail/LocalTxs.cpp +++ b/src/xrpld/app/ledger/detail/LocalTxs.cpp @@ -42,8 +42,7 @@ public: , m_seqProxy(txn->getSeqProxy()) { if (txn->isFieldPresent(sfLastLedgerSequence)) - m_expire = - std::min(m_expire, txn->getFieldU32(sfLastLedgerSequence) + 1); + m_expire = std::min(m_expire, txn->getFieldU32(sfLastLedgerSequence) + 1); } uint256 const& @@ -93,8 +92,7 @@ public: // Add a new transaction to the set of local transactions void - push_back(LedgerIndex index, std::shared_ptr const& txn) - override + push_back(LedgerIndex index, std::shared_ptr const& txn) override { std::lock_guard lock(m_lock); @@ -137,8 +135,7 @@ public: if (!sleAcct) return false; - SeqProxy const acctSeq = - SeqProxy::sequence(sleAcct->getFieldU32(sfSequence)); + SeqProxy const acctSeq = SeqProxy::sequence(sleAcct->getFieldU32(sfSequence)); SeqProxy const seqProx = txn.getSeqProxy(); if (seqProx.isSeq()) diff --git a/src/xrpld/app/ledger/detail/OpenLedger.cpp b/src/xrpld/app/ledger/detail/OpenLedger.cpp index 35f4b75157..d621285619 100644 --- a/src/xrpld/app/ledger/detail/OpenLedger.cpp +++ b/src/xrpld/app/ledger/detail/OpenLedger.cpp @@ -1,11 +1,11 @@ #include #include -#include #include #include #include #include +#include #include #include @@ -13,10 +13,7 @@ namespace xrpl { -OpenLedger::OpenLedger( - std::shared_ptr const& ledger, - CachedSLEs& cache, - beast::Journal journal) +OpenLedger::OpenLedger(std::shared_ptr const& ledger, CachedSLEs& cache, beast::Journal journal) : j_(journal), cache_(cache), current_(create(ledger->rules(), ledger)) { } @@ -82,9 +79,7 @@ OpenLedger::accept( *ledger, boost::adaptors::transform( current_->txs, - [](std::pair< - std::shared_ptr, - std::shared_ptr> const& p) { + [](std::pair, std::shared_ptr> const& p) { return p.first; }), retries, @@ -127,8 +122,7 @@ OpenLedger::accept( tx->add(s); msg.set_rawtransaction(s.data(), s.size()); msg.set_status(protocol::tsNEW); - msg.set_receivetimestamp( - app.timeKeeper().now().time_since_epoch().count()); + msg.set_receivetimestamp(app.timeKeeper().now().time_since_epoch().count()); app.overlay().relay(txId, msg, *toSkip); } } @@ -141,14 +135,9 @@ OpenLedger::accept( //------------------------------------------------------------------------------ std::shared_ptr -OpenLedger::create( - Rules const& rules, - std::shared_ptr const& ledger) +OpenLedger::create(Rules const& rules, std::shared_ptr const& ledger) { - return std::make_shared( - open_ledger, - rules, - std::make_shared(ledger, cache_)); + return std::make_shared(open_ledger, rules, std::make_shared(ledger, cache_)); } auto @@ -166,8 +155,7 @@ OpenLedger::apply_one( auto const result = xrpl::apply(app, view, *tx, flags, j); if (result.applied || result.ter == terQUEUED) return Result::success; - if (isTefFailure(result.ter) || isTemMalformed(result.ter) || - isTelLocal(result.ter)) + if (isTefFailure(result.ter) || isTemMalformed(result.ter) || isTelLocal(result.ter)) return Result::failure; return Result::retry; } diff --git a/src/xrpld/app/ledger/detail/SkipListAcquire.cpp b/src/xrpld/app/ledger/detail/SkipListAcquire.cpp index 5f4b0dc339..353b4fdbc8 100644 --- a/src/xrpld/app/ledger/detail/SkipListAcquire.cpp +++ b/src/xrpld/app/ledger/detail/SkipListAcquire.cpp @@ -15,9 +15,7 @@ SkipListAcquire::SkipListAcquire( app, ledgerHash, LedgerReplayParameters::SUB_TASK_TIMEOUT, - {jtREPLAY_TASK, - "SkipListAcquire", - LedgerReplayParameters::MAX_QUEUED_TASKS}, + {jtREPLAY_TASK, "SkipListAcq", LedgerReplayParameters::MAX_QUEUED_TASKS}, app.journal("LedgerReplaySkipList")) , inboundLedgers_(inboundLedgers) , peerSet_(std::move(peerSet)) @@ -56,32 +54,25 @@ SkipListAcquire::trigger(std::size_t limit, ScopedLockType& sl) peerSet_->addPeers( limit, [this](auto peer) { - return peer->supportsFeature(ProtocolFeature::LedgerReplay) && - peer->hasLedger(hash_, 0); + return peer->supportsFeature(ProtocolFeature::LedgerReplay) && peer->hasLedger(hash_, 0); }, [this](auto peer) { if (peer->supportsFeature(ProtocolFeature::LedgerReplay)) { - JLOG(journal_.trace()) - << "Add a peer " << peer->id() << " for " << hash_; + JLOG(journal_.trace()) << "Add a peer " << peer->id() << " for " << hash_; protocol::TMProofPathRequest request; request.set_ledgerhash(hash_.data(), hash_.size()); - request.set_key( - keylet::skip().key.data(), keylet::skip().key.size()); - request.set_type( - protocol::TMLedgerMapType::lmACCOUNT_STATE); + request.set_key(keylet::skip().key.data(), keylet::skip().key.size()); + request.set_type(protocol::TMLedgerMapType::lmACCOUNT_STATE); peerSet_->sendRequest(request, peer); } else { - JLOG(journal_.trace()) << "Add a no feature peer " - << peer->id() << " for " << hash_; - if (++noFeaturePeerCount_ >= - LedgerReplayParameters::MAX_NO_FEATURE_PEER_COUNT) + JLOG(journal_.trace()) << "Add a no feature peer " << peer->id() << " for " << hash_; + if (++noFeaturePeerCount_ >= LedgerReplayParameters::MAX_NO_FEATURE_PEER_COUNT) { JLOG(journal_.debug()) << "Fall back for " << hash_; - timerInterval_ = - LedgerReplayParameters::SUB_TASK_FALLBACK_TIMEOUT; + timerInterval_ = LedgerReplayParameters::SUB_TASK_FALLBACK_TIMEOUT; fallBack_ = true; } } @@ -115,13 +106,9 @@ SkipListAcquire::pmDowncast() } void -SkipListAcquire::processData( - std::uint32_t ledgerSeq, - boost::intrusive_ptr const& item) +SkipListAcquire::processData(std::uint32_t ledgerSeq, boost::intrusive_ptr const& item) { - XRPL_ASSERT( - ledgerSeq != 0 && item, - "xrpl::SkipListAcquire::processData : valid inputs"); + XRPL_ASSERT(ledgerSeq != 0 && item, "xrpl::SkipListAcquire::processData : valid inputs"); ScopedLockType sl(mtx_); if (isDone()) return; @@ -129,12 +116,9 @@ SkipListAcquire::processData( JLOG(journal_.trace()) << "got data for " << hash_; try { - if (auto sle = - std::make_shared(SerialIter{item->slice()}, item->key()); - sle) + if (auto sle = std::make_shared(SerialIter{item->slice()}, item->key()); sle) { - if (auto const& skipList = sle->getFieldV256(sfHashes).value(); - !skipList.empty()) + if (auto const& skipList = sle->getFieldV256(sfHashes).value(); !skipList.empty()) onSkipListAcquired(skipList, ledgerSeq, sl); return; } @@ -144,8 +128,7 @@ SkipListAcquire::processData( } failed_ = true; - JLOG(journal_.error()) << "failed to retrieve Skip list from verified data " - << hash_; + JLOG(journal_.error()) << "failed to retrieve Skip list from verified data " << hash_; notify(sl); } @@ -156,8 +139,7 @@ SkipListAcquire::addDataCallback(OnSkipListDataCB&& cb) dataReadyCallbacks_.emplace_back(std::move(cb)); if (isDone()) { - JLOG(journal_.debug()) - << "task added to a finished SkipListAcquire " << hash_; + JLOG(journal_.debug()) << "task added to a finished SkipListAcquire " << hash_; notify(sl); } } @@ -170,12 +152,9 @@ SkipListAcquire::getData() const } void -SkipListAcquire::retrieveSkipList( - std::shared_ptr const& ledger, - ScopedLockType& sl) +SkipListAcquire::retrieveSkipList(std::shared_ptr const& ledger, ScopedLockType& sl) { - if (auto const hashIndex = ledger->read(keylet::skip()); - hashIndex && hashIndex->isFieldPresent(sfHashes)) + if (auto const hashIndex = ledger->read(keylet::skip()); hashIndex && hashIndex->isFieldPresent(sfHashes)) { auto const& slist = hashIndex->getFieldV256(sfHashes).value(); if (!slist.empty()) @@ -186,16 +165,12 @@ SkipListAcquire::retrieveSkipList( } failed_ = true; - JLOG(journal_.error()) << "failed to retrieve Skip list from a ledger " - << hash_; + JLOG(journal_.error()) << "failed to retrieve Skip list from a ledger " << hash_; notify(sl); } void -SkipListAcquire::onSkipListAcquired( - std::vector const& skipList, - std::uint32_t ledgerSeq, - ScopedLockType& sl) +SkipListAcquire::onSkipListAcquired(std::vector const& skipList, std::uint32_t ledgerSeq, ScopedLockType& sl) { complete_ = true; data_ = std::make_shared(ledgerSeq, skipList); diff --git a/src/xrpld/app/ledger/detail/SkipListAcquire.h b/src/xrpld/app/ledger/detail/SkipListAcquire.h index 15c420a5cd..f3bfb60bee 100644 --- a/src/xrpld/app/ledger/detail/SkipListAcquire.h +++ b/src/xrpld/app/ledger/detail/SkipListAcquire.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_LEDGER_SKIPLISTACQUIRE_H_INCLUDED -#define XRPL_APP_LEDGER_SKIPLISTACQUIRE_H_INCLUDED +#pragma once #include #include @@ -19,10 +18,9 @@ class LedgerReplayClient; * Manage the retrieval of a skip list in a ledger from the network. * Before asking peers, always check if the local node has the ledger. */ -class SkipListAcquire final - : public TimeoutCounter, - public std::enable_shared_from_this, - public CountedObject +class SkipListAcquire final : public TimeoutCounter, + public std::enable_shared_from_this, + public CountedObject { public: /** @@ -30,17 +28,14 @@ public: * @param successful if the skipList data was acquired successfully * @param hash hash of the ledger that has the skipList */ - using OnSkipListDataCB = - std::function; + using OnSkipListDataCB = std::function; struct SkipListData { std::uint32_t const ledgerSeq; std::vector const skipList; - SkipListData( - std::uint32_t const ledgerSeq, - std::vector const& skipList) + SkipListData(std::uint32_t const ledgerSeq, std::vector const& skipList) : ledgerSeq(ledgerSeq), skipList(skipList) { } @@ -75,9 +70,7 @@ public: * @note ledgerSeq and item must have been verified against the ledger hash */ void - processData( - std::uint32_t ledgerSeq, - boost::intrusive_ptr const& item); + processData(std::uint32_t ledgerSeq, boost::intrusive_ptr const& item); /** * Add a callback that will be called when the skipList is ready or failed. @@ -111,9 +104,7 @@ private: * @param sl lock. this function must be called with the lock */ void - retrieveSkipList( - std::shared_ptr const& ledger, - ScopedLockType& sl); + retrieveSkipList(std::shared_ptr const& ledger, ScopedLockType& sl); /** * Process the skip list @@ -122,10 +113,7 @@ private: * @param sl lock. this function must be called with the lock */ void - onSkipListAcquired( - std::vector const& skipList, - std::uint32_t ledgerSeq, - ScopedLockType& sl); + onSkipListAcquired(std::vector const& skipList, std::uint32_t ledgerSeq, ScopedLockType& sl); /** * Call the OnSkipListDataCB callbacks @@ -145,5 +133,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/src/xrpld/app/ledger/detail/TimeoutCounter.cpp b/src/xrpld/app/ledger/detail/TimeoutCounter.cpp index 3482725148..0ce6de0d34 100644 --- a/src/xrpld/app/ledger/detail/TimeoutCounter.cpp +++ b/src/xrpld/app/ledger/detail/TimeoutCounter.cpp @@ -34,17 +34,16 @@ TimeoutCounter::setTimer(ScopedLockType& sl) if (isDone()) return; timer_.expires_after(timerInterval_); - timer_.async_wait( - [wptr = pmDowncast()](boost::system::error_code const& ec) { - if (ec == boost::asio::error::operation_aborted) - return; + timer_.async_wait([wptr = pmDowncast()](boost::system::error_code const& ec) { + if (ec == boost::asio::error::operation_aborted) + return; - if (auto ptr = wptr.lock()) - { - ScopedLockType sl(ptr->mtx_); - ptr->queueJob(sl); - } - }); + if (auto ptr = wptr.lock()) + { + ScopedLockType sl(ptr->mtx_); + ptr->queueJob(sl); + } + }); } void @@ -53,22 +52,17 @@ TimeoutCounter::queueJob(ScopedLockType& sl) if (isDone()) return; if (queueJobParameter_.jobLimit && - app_.getJobQueue().getJobCountTotal(queueJobParameter_.jobType) >= - queueJobParameter_.jobLimit) + app_.getJobQueue().getJobCountTotal(queueJobParameter_.jobType) >= queueJobParameter_.jobLimit) { - JLOG(journal_.debug()) << "Deferring " << queueJobParameter_.jobName - << " timer due to load"; + JLOG(journal_.debug()) << "Deferring " << queueJobParameter_.jobName << " timer due to load"; setTimer(sl); return; } - app_.getJobQueue().addJob( - queueJobParameter_.jobType, - queueJobParameter_.jobName, - [wptr = pmDowncast()]() { - if (auto sptr = wptr.lock(); sptr) - sptr->invokeOnTimer(); - }); + app_.getJobQueue().addJob(queueJobParameter_.jobType, queueJobParameter_.jobName, [wptr = pmDowncast()]() { + if (auto sptr = wptr.lock(); sptr) + sptr->invokeOnTimer(); + }); } void diff --git a/src/xrpld/app/ledger/detail/TimeoutCounter.h b/src/xrpld/app/ledger/detail/TimeoutCounter.h index c228d50aac..5f5ccb2f43 100644 --- a/src/xrpld/app/ledger/detail/TimeoutCounter.h +++ b/src/xrpld/app/ledger/detail/TimeoutCounter.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_LEDGER_TIMEOUTCOUNTER_H_INCLUDED -#define XRPL_APP_LEDGER_TIMEOUTCOUNTER_H_INCLUDED +#pragma once #include @@ -131,5 +130,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/src/xrpld/app/ledger/detail/TransactionAcquire.cpp b/src/xrpld/app/ledger/detail/TransactionAcquire.cpp index 3cd0e84ef0..06cd6a2696 100644 --- a/src/xrpld/app/ledger/detail/TransactionAcquire.cpp +++ b/src/xrpld/app/ledger/detail/TransactionAcquire.cpp @@ -3,7 +3,8 @@ #include #include #include -#include + +#include #include @@ -19,21 +20,12 @@ enum { MAX_TIMEOUTS = 20, }; -TransactionAcquire::TransactionAcquire( - Application& app, - uint256 const& hash, - std::unique_ptr peerSet) - : TimeoutCounter( - app, - hash, - TX_ACQUIRE_TIMEOUT, - {jtTXN_DATA, "TransactionAcquire", {}}, - app.journal("TransactionAcquire")) +TransactionAcquire::TransactionAcquire(Application& app, uint256 const& hash, std::unique_ptr peerSet) + : TimeoutCounter(app, hash, TX_ACQUIRE_TIMEOUT, {jtTXN_DATA, "TxAcq", {}}, app.journal("TransactionAcquire")) , mHaveRoot(false) , mPeerSet(std::move(peerSet)) { - mMap = std::make_shared( - SHAMapType::TRANSACTION, hash, app_.getNodeFamily()); + mMap = std::make_shared(SHAMapType::TRANSACTION, hash, app_.getNodeFamily()); mMap->setUnbacked(); } @@ -60,9 +52,7 @@ TransactionAcquire::done() // just updates the consensus and related structures when we acquire // a transaction set. No need to update them if we're shutting down. app_.getJobQueue().addJob( - jtTXN_DATA, "completeAcquire", [pap, hash, map]() { - pap->getInboundTransactions().giveSet(hash, map, true); - }); + jtTXN_DATA, "ComplAcquire", [pap, hash, map]() { pap->getInboundTransactions().giveSet(hash, map, true); }); } } @@ -104,8 +94,7 @@ TransactionAcquire::trigger(std::shared_ptr const& peer) if (!mHaveRoot) { - JLOG(journal_.trace()) << "TransactionAcquire::trigger " - << (peer ? "havePeer" : "noPeer") << " no root"; + JLOG(journal_.trace()) << "TransactionAcquire::trigger " << (peer ? "havePeer" : "noPeer") << " no root"; protocol::TMGetLedger tmGL; tmGL.set_ledgerhash(hash_.begin(), hash_.size()); tmGL.set_itype(protocol::liTS_CANDIDATE); @@ -184,11 +173,8 @@ TransactionAcquire::takeNodes( if (d.first.isRoot()) { if (mHaveRoot) - JLOG(journal_.debug()) - << "Got root TXS node, already have it"; - else if (!mMap->addRootNode( - SHAMapHash{hash_}, d.second, nullptr) - .isGood()) + JLOG(journal_.debug()) << "Got root TXS node, already have it"; + else if (!mMap->addRootNode(SHAMapHash{hash_}, d.second, nullptr).isGood()) { JLOG(journal_.warn()) << "TX acquire got bad root node"; } @@ -208,9 +194,7 @@ TransactionAcquire::takeNodes( } catch (std::exception const& ex) { - JLOG(journal_.error()) - << "Peer " << peer->id() - << " sent us junky transaction node data: " << ex.what(); + JLOG(journal_.error()) << "Peer " << peer->id() << " sent us junky transaction node data: " << ex.what(); return SHAMapAddNode::invalid(); } } @@ -219,9 +203,7 @@ void TransactionAcquire::addPeers(std::size_t limit) { mPeerSet->addPeers( - limit, - [this](auto peer) { return peer->hasTxSet(hash_); }, - [this](auto peer) { trigger(peer); }); + limit, [this](auto peer) { return peer->hasTxSet(hash_); }, [this](auto peer) { trigger(peer); }); } void diff --git a/src/xrpld/app/ledger/detail/TransactionAcquire.h b/src/xrpld/app/ledger/detail/TransactionAcquire.h index 83f9b62f83..4345c74fc6 100644 --- a/src/xrpld/app/ledger/detail/TransactionAcquire.h +++ b/src/xrpld/app/ledger/detail/TransactionAcquire.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_LEDGER_TRANSACTIONACQUIRE_H_INCLUDED -#define XRPL_APP_LEDGER_TRANSACTIONACQUIRE_H_INCLUDED +#pragma once #include @@ -9,24 +8,18 @@ namespace xrpl { // VFALCO TODO rename to PeerTxRequest // A transaction set we are trying to acquire -class TransactionAcquire final - : public TimeoutCounter, - public std::enable_shared_from_this, - public CountedObject +class TransactionAcquire final : public TimeoutCounter, + public std::enable_shared_from_this, + public CountedObject { public: using pointer = std::shared_ptr; - TransactionAcquire( - Application& app, - uint256 const& hash, - std::unique_ptr peerSet); + TransactionAcquire(Application& app, uint256 const& hash, std::unique_ptr peerSet); ~TransactionAcquire() = default; SHAMapAddNode - takeNodes( - std::vector> const& data, - std::shared_ptr const&); + takeNodes(std::vector> const& data, std::shared_ptr const&); void init(int startPeers); @@ -55,5 +48,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/src/xrpld/app/ledger/detail/TransactionMaster.cpp b/src/xrpld/app/ledger/detail/TransactionMaster.cpp index e8580bcfc6..834234dd4e 100644 --- a/src/xrpld/app/ledger/detail/TransactionMaster.cpp +++ b/src/xrpld/app/ledger/detail/TransactionMaster.cpp @@ -9,13 +9,7 @@ namespace xrpl { TransactionMaster::TransactionMaster(Application& app) - : mApp(app) - , mCache( - "TransactionCache", - 65536, - std::chrono::minutes{30}, - stopwatch(), - mApp.journal("TaggedCache")) + : mApp(app), mCache("TransactionCache", 65536, std::chrono::minutes{30}, stopwatch(), mApp.journal("TaggedCache")) { } @@ -41,13 +35,10 @@ TransactionMaster::fetch_from_cache(uint256 const& txnID) return mCache.fetch(txnID); } -std::variant< - std::pair, std::shared_ptr>, - TxSearched> +std::variant, std::shared_ptr>, TxSearched> TransactionMaster::fetch(uint256 const& txnID, error_code_i& ec) { - using TxPair = - std::pair, std::shared_ptr>; + using TxPair = std::pair, std::shared_ptr>; if (auto txn = fetch_from_cache(txnID); txn && !txn->isValidated()) return std::pair{std::move(txn), nullptr}; @@ -65,16 +56,10 @@ TransactionMaster::fetch(uint256 const& txnID, error_code_i& ec) return std::pair{std::move(txn), std::move(txnMeta)}; } -std::variant< - std::pair, std::shared_ptr>, - TxSearched> -TransactionMaster::fetch( - uint256 const& txnID, - ClosedInterval const& range, - error_code_i& ec) +std::variant, std::shared_ptr>, TxSearched> +TransactionMaster::fetch(uint256 const& txnID, ClosedInterval const& range, error_code_i& ec) { - using TxPair = - std::pair, std::shared_ptr>; + using TxPair = std::pair, std::shared_ptr>; if (auto txn = fetch_from_cache(txnID); txn && !txn->isValidated()) return std::pair{std::move(txn), nullptr}; @@ -93,10 +78,7 @@ TransactionMaster::fetch( } std::shared_ptr -TransactionMaster::fetch( - boost::intrusive_ptr const& item, - SHAMapNodeType type, - std::uint32_t uCommitLedger) +TransactionMaster::fetch(boost::intrusive_ptr const& item, SHAMapNodeType type, std::uint32_t uCommitLedger) { std::shared_ptr txn; auto iTx = fetch_from_cache(item->key()); @@ -111,8 +93,7 @@ TransactionMaster::fetch( else if (type == SHAMapNodeType::tnTRANSACTION_MD) { auto blob = SerialIter{item->slice()}.getVL(); - txn = std::make_shared( - SerialIter{blob.data(), blob.size()}); + txn = std::make_shared(SerialIter{blob.data(), blob.size()}); } } else diff --git a/src/xrpld/app/main/Application.cpp b/src/xrpld/app/main/Application.cpp index 15abff9b14..4612479b78 100644 --- a/src/xrpld/app/main/Application.cpp +++ b/src/xrpld/app/main/Application.cpp @@ -6,31 +6,27 @@ #include #include #include -#include +#include #include #include #include #include -#include #include #include #include #include #include -#include #include -#include #include #include #include #include +#include +#include #include -#include -#include +#include #include -#include #include -#include #include #include #include @@ -40,6 +36,8 @@ #include #include #include +#include +#include #include #include #include @@ -49,7 +47,9 @@ #include #include #include +#include #include +#include #include #include @@ -89,10 +89,7 @@ private: beast::Journal journal, std::chrono::milliseconds interval, boost::asio::io_context& ios) - : m_event(ev) - , m_journal(journal) - , m_probe(interval, ios) - , lastSample_{} + : m_event(ev), m_journal(journal), m_probe(interval, ios), lastSample_{} { } @@ -115,8 +112,7 @@ private: m_event.notify(lastSample); if (lastSample >= 500ms) { - JLOG(m_journal.warn()) - << "io_context latency = " << lastSample.count(); + JLOG(m_journal.warn()) << "io_context latency = " << lastSample.count(); } } @@ -169,8 +165,7 @@ public: std::unique_ptr m_nodeStore; NodeFamily nodeFamily_; - // VFALCO TODO Make OrderBookDB abstract - OrderBookDB m_orderBookDB; + std::unique_ptr m_orderBookDB; std::unique_ptr m_pathRequests; std::unique_ptr m_ledgerMaster; std::unique_ptr ledgerCleaner_; @@ -196,18 +191,14 @@ public: boost::asio::steady_timer sweepTimer_; boost::asio::steady_timer entropyTimer_; - std::unique_ptr mRelationalDatabase; + std::optional relationalDatabase_; std::unique_ptr mWalletDB; std::unique_ptr overlay_; std::optional trapTxID_; boost::asio::signal_set m_signals; - // Once we get C++20, we could use `std::atomic_flag` for `isTimeToStop` - // and eliminate the need for the condition variable and the mutex. - std::condition_variable stoppingCondition_; - mutable std::mutex stoppingMutex_; - std::atomic isTimeToStop = false; + std::atomic_flag isTimeToStop; std::atomic checkSigs_; @@ -243,35 +234,24 @@ public: //-------------------------------------------------------------------------- - ApplicationImp( - std::unique_ptr config, - std::unique_ptr logs, - std::unique_ptr timeKeeper) + ApplicationImp(std::unique_ptr config, std::unique_ptr logs, std::unique_ptr timeKeeper) : BasicApp(numberOfThreads(*config)) , config_(std::move(config)) , logs_(std::move(logs)) , timeKeeper_(std::move(timeKeeper)) - , instanceCookie_( - 1 + - rand_int( - crypto_prng(), - std::numeric_limits::max() - 1)) + , instanceCookie_(1 + rand_int(crypto_prng(), std::numeric_limits::max() - 1)) , m_journal(logs_->journal("Application")) // PerfLog must be started before any other threads are launched. , perfLog_(perf::make_PerfLog( - perf::setup_PerfLog( - config_->section("perf"), - config_->CONFIG_DIR), + perf::setup_PerfLog(config_->section("perf"), config_->CONFIG_DIR), *this, logs_->journal("PerfLog"), [this] { signalStop("PerfLog"); })) , m_txMaster(*this) - , m_collectorManager(make_CollectorManager( - config_->section(SECTION_INSIGHT), - logs_->journal("Collector"))) + , m_collectorManager(make_CollectorManager(config_->section(SECTION_INSIGHT), logs_->journal("Collector"))) , m_jobQueue(std::make_unique( [](std::unique_ptr const& config) { @@ -281,8 +261,7 @@ public: if (config->WORKERS) return config->WORKERS; - auto count = - static_cast(std::thread::hardware_concurrency()); + auto count = static_cast(std::thread::hardware_concurrency()); // Be more aggressive about the number of threads to use // for the job queue if the server is configured as @@ -303,42 +282,24 @@ public: , m_nodeStoreScheduler(*m_jobQueue) - , m_shaMapStore(make_SHAMapStore( - *this, - m_nodeStoreScheduler, - logs_->journal("SHAMapStore"))) + , m_shaMapStore(make_SHAMapStore(*this, m_nodeStoreScheduler, logs_->journal("SHAMapStore"))) - , m_tempNodeCache( - "NodeCache", - 16384, - std::chrono::seconds{90}, - stopwatch(), - logs_->journal("TaggedCache")) + , m_tempNodeCache("NodeCache", 16384, std::chrono::seconds{90}, stopwatch(), logs_->journal("TaggedCache")) - , cachedSLEs_( - "Cached SLEs", - 0, - std::chrono::minutes(1), - stopwatch(), - logs_->journal("CachedSLEs")) + , cachedSLEs_("Cached SLEs", 0, std::chrono::minutes(1), stopwatch(), logs_->journal("CachedSLEs")) , validatorKeys_(*config_, m_journal) - , m_resourceManager(Resource::make_Manager( - m_collectorManager->collector(), - logs_->journal("Resource"))) + , m_resourceManager(Resource::make_Manager(m_collectorManager->collector(), logs_->journal("Resource"))) - , m_nodeStore(m_shaMapStore->makeNodeStore( - config_->PREFETCH_WORKERS > 0 ? config_->PREFETCH_WORKERS : 4)) + , m_nodeStore(m_shaMapStore->makeNodeStore(config_->PREFETCH_WORKERS > 0 ? config_->PREFETCH_WORKERS : 4)) , nodeFamily_(*this, *m_collectorManager) - , m_orderBookDB(*this) + , m_orderBookDB(make_OrderBookDB(*this, {config_->PATH_SEARCH_MAX, config_->standalone()})) - , m_pathRequests(std::make_unique( - *this, - logs_->journal("PathRequest"), - m_collectorManager->collector())) + , m_pathRequests( + std::make_unique(*this, logs_->journal("PathRequest"), m_collectorManager->collector())) , m_ledgerMaster(std::make_unique( *this, @@ -346,28 +307,19 @@ public: m_collectorManager->collector(), logs_->journal("LedgerMaster"))) - , ledgerCleaner_( - make_LedgerCleaner(*this, logs_->journal("LedgerCleaner"))) + , ledgerCleaner_(make_LedgerCleaner(*this, logs_->journal("LedgerCleaner"))) // VFALCO NOTE must come before NetworkOPs to prevent a crash due // to dependencies in the destructor. // - , m_inboundLedgers(make_InboundLedgers( - *this, - stopwatch(), - m_collectorManager->collector())) + , m_inboundLedgers(make_InboundLedgers(*this, stopwatch(), m_collectorManager->collector())) , m_inboundTransactions(make_InboundTransactions( *this, m_collectorManager->collector(), - [this](std::shared_ptr const& set, bool fromAcquire) { - gotTXSet(set, fromAcquire); - })) + [this](std::shared_ptr const& set, bool fromAcquire) { gotTXSet(set, fromAcquire); })) - , m_ledgerReplayer(std::make_unique( - *this, - *m_inboundLedgers, - make_PeerSetBuilder(*this))) + , m_ledgerReplayer(std::make_unique(*this, *m_inboundLedgers, make_PeerSetBuilder(*this))) , m_acceptedLedgerCache( "AcceptedLedger", @@ -391,14 +343,11 @@ public: , cluster_(std::make_unique(logs_->journal("Overlay"))) - , peerReservations_(std::make_unique( - logs_->journal("PeerReservationTable"))) + , peerReservations_(std::make_unique(logs_->journal("PeerReservationTable"))) - , validatorManifests_( - std::make_unique(logs_->journal("ManifestCache"))) + , validatorManifests_(std::make_unique(logs_->journal("ManifestCache"))) - , publisherManifests_( - std::make_unique(logs_->journal("ManifestCache"))) + , publisherManifests_(std::make_unique(logs_->journal("ManifestCache"))) , validators_(std::make_unique( *validatorManifests_, @@ -418,23 +367,15 @@ public: *m_resourceManager, *m_collectorManager)) - , mFeeTrack( - std::make_unique(logs_->journal("LoadManager"))) + , mFeeTrack(std::make_unique(logs_->journal("LoadManager"))) - , hashRouter_(std::make_unique( - setup_HashRouter(*config_), - stopwatch())) + , hashRouter_(std::make_unique(setup_HashRouter(*config_), stopwatch())) - , mValidations( - ValidationParms(), - stopwatch(), - *this, - logs_->journal("Validations")) + , mValidations(ValidationParms(), stopwatch(), *this, logs_->journal("Validations")) , m_loadManager(make_LoadManager(*this, logs_->journal("LoadManager"))) - , txQ_( - std::make_unique(setup_TxQ(*config_), logs_->journal("TxQ"))) + , txQ_(std::make_unique(setup_TxQ(*config_), logs_->journal("TxQ"))) , sweepTimer_(get_io_context()) @@ -444,8 +385,7 @@ public: , checkSigs_(true) - , m_resolver( - ResolverAsio::New(get_io_context(), logs_->journal("Resolver"))) + , m_resolver(ResolverAsio::New(get_io_context(), logs_->journal("Resolver"))) , m_io_latency_sampler( m_collectorManager->collector()->make_event("ios_latency"), @@ -545,8 +485,7 @@ public: if (nodeIdentity_) return *nodeIdentity_; - LogicError( - "Accessing Application::nodeIdentity() before it is initialized."); + LogicError("Accessing Application::nodeIdentity() before it is initialized."); } std::optional @@ -674,7 +613,7 @@ public: OrderBookDB& getOrderBookDB() override { - return m_orderBookDB; + return *m_orderBookDB; } PathRequests& @@ -776,16 +715,14 @@ public: Overlay& overlay() override { - XRPL_ASSERT( - overlay_, "xrpl::ApplicationImp::overlay : non-null overlay"); + XRPL_ASSERT(overlay_, "xrpl::ApplicationImp::overlay : non-null overlay"); return *overlay_; } TxQ& getTxQ() override { - XRPL_ASSERT( - txQ_, "xrpl::ApplicationImp::getTxQ : non-null transaction queue"); + XRPL_ASSERT(txQ_, "xrpl::ApplicationImp::getTxQ : non-null transaction queue"); return *txQ_; } @@ -793,18 +730,16 @@ public: getRelationalDatabase() override { XRPL_ASSERT( - mRelationalDatabase, + relationalDatabase_, "xrpl::ApplicationImp::getRelationalDatabase : non-null " "relational database"); - return *mRelationalDatabase; + return *relationalDatabase_; } DatabaseCon& getWalletDB() override { - XRPL_ASSERT( - mWalletDB, - "xrpl::ApplicationImp::getWalletDB : non-null wallet database"); + XRPL_ASSERT(mWalletDB, "xrpl::ApplicationImp::getWalletDB : non-null wallet database"); return *mWalletDB; } @@ -826,8 +761,7 @@ public: try { - mRelationalDatabase = - RelationalDatabase::init(*this, *config_, *m_jobQueue); + relationalDatabase_.emplace(setup_RelationalDatabase(*this, *config_, *m_jobQueue)); // wallet database auto setup = setup_DatabaseCon(*config_, m_journal); @@ -837,8 +771,7 @@ public: } catch (std::exception const& e) { - JLOG(m_journal.fatal()) - << "Failed to initialize SQL databases: " << e.what(); + JLOG(m_journal.fatal()) << "Failed to initialize SQL databases: " << e.what(); return false; } @@ -852,27 +785,23 @@ public: { auto j = logs_->journal("NodeObject"); NodeStore::DummyScheduler dummyScheduler; - std::unique_ptr source = - NodeStore::Manager::instance().make_Database( - megabytes(config_->getValueFor( - SizedItem::burstSize, std::nullopt)), - dummyScheduler, - 0, - config_->section(ConfigSection::importNodeDatabase()), - j); + std::unique_ptr source = NodeStore::Manager::instance().make_Database( + megabytes(config_->getValueFor(SizedItem::burstSize, std::nullopt)), + dummyScheduler, + 0, + config_->section(ConfigSection::importNodeDatabase()), + j); - JLOG(j.warn()) << "Starting node import from '" << source->getName() - << "' to '" << m_nodeStore->getName() << "'."; + JLOG(j.warn()) << "Starting node import from '" << source->getName() << "' to '" << m_nodeStore->getName() + << "'."; using namespace std::chrono; auto const start = steady_clock::now(); m_nodeStore->importDatabase(*source); - auto const elapsed = - duration_cast(steady_clock::now() - start); - JLOG(j.warn()) << "Node import from '" << source->getName() - << "' took " << elapsed.count() << " seconds."; + auto const elapsed = duration_cast(steady_clock::now() - start); + JLOG(j.warn()) << "Node import from '" << source->getName() << "' took " << elapsed.count() << " seconds."; } return true; @@ -894,28 +823,23 @@ public: setSweepTimer() { // Only start the timer if waitHandlerCounter_ is not yet joined. - if (auto optionalCountedHandler = waitHandlerCounter_.wrap( - [this](boost::system::error_code const& e) { - if (e.value() == boost::system::errc::success) - { - m_jobQueue->addJob( - jtSWEEP, "sweep", [this]() { doSweep(); }); - } - // Recover as best we can if an unexpected error occurs. - if (e.value() != boost::system::errc::success && - e.value() != boost::asio::error::operation_aborted) - { - // Try again later and hope for the best. - JLOG(m_journal.error()) - << "Sweep timer got error '" << e.message() - << "'. Restarting timer."; - setSweepTimer(); - } - })) + if (auto optionalCountedHandler = waitHandlerCounter_.wrap([this](boost::system::error_code const& e) { + if (e.value() == boost::system::errc::success) + { + m_jobQueue->addJob(jtSWEEP, "sweep", [this]() { doSweep(); }); + } + // Recover as best we can if an unexpected error occurs. + if (e.value() != boost::system::errc::success && e.value() != boost::asio::error::operation_aborted) + { + // Try again later and hope for the best. + JLOG(m_journal.error()) << "Sweep timer got error '" << e.message() << "'. Restarting timer."; + setSweepTimer(); + } + })) { using namespace std::chrono; - sweepTimer_.expires_after(seconds{config_->SWEEP_INTERVAL.value_or( - config_->getValueFor(SizedItem::sweepInterval))}); + sweepTimer_.expires_after( + seconds{config_->SWEEP_INTERVAL.value_or(config_->getValueFor(SizedItem::sweepInterval))}); sweepTimer_.async_wait(std::move(*optionalCountedHandler)); } } @@ -924,24 +848,20 @@ public: setEntropyTimer() { // Only start the timer if waitHandlerCounter_ is not yet joined. - if (auto optionalCountedHandler = waitHandlerCounter_.wrap( - [this](boost::system::error_code const& e) { - if (e.value() == boost::system::errc::success) - { - crypto_prng().mix_entropy(); - setEntropyTimer(); - } - // Recover as best we can if an unexpected error occurs. - if (e.value() != boost::system::errc::success && - e.value() != boost::asio::error::operation_aborted) - { - // Try again later and hope for the best. - JLOG(m_journal.error()) - << "Entropy timer got error '" << e.message() - << "'. Restarting timer."; - setEntropyTimer(); - } - })) + if (auto optionalCountedHandler = waitHandlerCounter_.wrap([this](boost::system::error_code const& e) { + if (e.value() == boost::system::errc::success) + { + crypto_prng().mix_entropy(); + setEntropyTimer(); + } + // Recover as best we can if an unexpected error occurs. + if (e.value() != boost::system::errc::success && e.value() != boost::asio::error::operation_aborted) + { + // Try again later and hope for the best. + JLOG(m_journal.error()) << "Entropy timer got error '" << e.message() << "'. Restarting timer."; + setEntropyTimer(); + } + })) { using namespace std::chrono_literals; entropyTimer_.expires_after(5min); @@ -952,8 +872,8 @@ public: void doSweep() { - if (!config_->standalone() && - !getRelationalDatabase().transactionDbHasSpace(*config_)) + XRPL_ASSERT(relationalDatabase_, "xrpl::ApplicationImp::doSweep : non-null relational database"); + if (!config_->standalone() && !relationalDatabase_->transactionDbHasSpace(*config_)) { signalStop("Out of transaction DB space"); } @@ -963,52 +883,38 @@ public: // have listeners register for "onSweep ()" notification. { - std::shared_ptr const fullBelowCache = - nodeFamily_.getFullBelowCache(); + std::shared_ptr const fullBelowCache = nodeFamily_.getFullBelowCache(); - std::shared_ptr const treeNodeCache = - nodeFamily_.getTreeNodeCache(); + std::shared_ptr const treeNodeCache = nodeFamily_.getTreeNodeCache(); std::size_t const oldFullBelowSize = fullBelowCache->size(); std::size_t const oldTreeNodeSize = treeNodeCache->size(); nodeFamily_.sweep(); - JLOG(m_journal.debug()) - << "NodeFamily::FullBelowCache sweep. Size before: " - << oldFullBelowSize - << "; size after: " << fullBelowCache->size(); + JLOG(m_journal.debug()) << "NodeFamily::FullBelowCache sweep. Size before: " << oldFullBelowSize + << "; size after: " << fullBelowCache->size(); - JLOG(m_journal.debug()) - << "NodeFamily::TreeNodeCache sweep. Size before: " - << oldTreeNodeSize << "; size after: " << treeNodeCache->size(); + JLOG(m_journal.debug()) << "NodeFamily::TreeNodeCache sweep. Size before: " << oldTreeNodeSize + << "; size after: " << treeNodeCache->size(); } { - TaggedCache const& masterTxCache = - getMasterTransaction().getCache(); + TaggedCache const& masterTxCache = getMasterTransaction().getCache(); std::size_t const oldMasterTxSize = masterTxCache.size(); getMasterTransaction().sweep(); - JLOG(m_journal.debug()) - << "MasterTransaction sweep. Size before: " << oldMasterTxSize - << "; size after: " << masterTxCache.size(); + JLOG(m_journal.debug()) << "MasterTransaction sweep. Size before: " << oldMasterTxSize + << "; size after: " << masterTxCache.size(); } { - // Does not appear to have an associated cache. - getNodeStore().sweep(); - } - { - std::size_t const oldLedgerMasterCacheSize = - getLedgerMaster().getFetchPackCacheSize(); + std::size_t const oldLedgerMasterCacheSize = getLedgerMaster().getFetchPackCacheSize(); getLedgerMaster().sweep(); - JLOG(m_journal.debug()) - << "LedgerMaster sweep. Size before: " - << oldLedgerMasterCacheSize << "; size after: " - << getLedgerMaster().getFetchPackCacheSize(); + JLOG(m_journal.debug()) << "LedgerMaster sweep. Size before: " << oldLedgerMasterCacheSize + << "; size after: " << getLedgerMaster().getFetchPackCacheSize(); } { // NodeCache == TaggedCache @@ -1016,52 +922,36 @@ public: getTempNodeCache().sweep(); - JLOG(m_journal.debug()) - << "TempNodeCache sweep. Size before: " << oldTempNodeCacheSize - << "; size after: " << getTempNodeCache().size(); + JLOG(m_journal.debug()) << "TempNodeCache sweep. Size before: " << oldTempNodeCacheSize + << "; size after: " << getTempNodeCache().size(); } { - std::size_t const oldCurrentCacheSize = - getValidations().sizeOfCurrentCache(); - std::size_t const oldSizeSeqEnforcesSize = - getValidations().sizeOfSeqEnforcersCache(); - std::size_t const oldByLedgerSize = - getValidations().sizeOfByLedgerCache(); - std::size_t const oldBySequenceSize = - getValidations().sizeOfBySequenceCache(); + std::size_t const oldCurrentCacheSize = getValidations().sizeOfCurrentCache(); + std::size_t const oldSizeSeqEnforcesSize = getValidations().sizeOfSeqEnforcersCache(); + std::size_t const oldByLedgerSize = getValidations().sizeOfByLedgerCache(); + std::size_t const oldBySequenceSize = getValidations().sizeOfBySequenceCache(); getValidations().expire(m_journal); - JLOG(m_journal.debug()) - << "Validations Current expire. Size before: " - << oldCurrentCacheSize - << "; size after: " << getValidations().sizeOfCurrentCache(); + JLOG(m_journal.debug()) << "Validations Current expire. Size before: " << oldCurrentCacheSize + << "; size after: " << getValidations().sizeOfCurrentCache(); - JLOG(m_journal.debug()) - << "Validations SeqEnforcer expire. Size before: " - << oldSizeSeqEnforcesSize << "; size after: " - << getValidations().sizeOfSeqEnforcersCache(); + JLOG(m_journal.debug()) << "Validations SeqEnforcer expire. Size before: " << oldSizeSeqEnforcesSize + << "; size after: " << getValidations().sizeOfSeqEnforcersCache(); - JLOG(m_journal.debug()) - << "Validations ByLedger expire. Size before: " - << oldByLedgerSize - << "; size after: " << getValidations().sizeOfByLedgerCache(); + JLOG(m_journal.debug()) << "Validations ByLedger expire. Size before: " << oldByLedgerSize + << "; size after: " << getValidations().sizeOfByLedgerCache(); - JLOG(m_journal.debug()) - << "Validations BySequence expire. Size before: " - << oldBySequenceSize - << "; size after: " << getValidations().sizeOfBySequenceCache(); + JLOG(m_journal.debug()) << "Validations BySequence expire. Size before: " << oldBySequenceSize + << "; size after: " << getValidations().sizeOfBySequenceCache(); } { - std::size_t const oldInboundLedgersSize = - getInboundLedgers().cacheSize(); + std::size_t const oldInboundLedgersSize = getInboundLedgers().cacheSize(); getInboundLedgers().sweep(); - JLOG(m_journal.debug()) - << "InboundLedgers sweep. Size before: " - << oldInboundLedgersSize - << "; size after: " << getInboundLedgers().cacheSize(); + JLOG(m_journal.debug()) << "InboundLedgers sweep. Size before: " << oldInboundLedgersSize + << "; size after: " << getInboundLedgers().cacheSize(); } { size_t const oldTasksSize = getLedgerReplayer().tasksSize(); @@ -1070,39 +960,30 @@ public: getLedgerReplayer().sweep(); - JLOG(m_journal.debug()) - << "LedgerReplayer tasks sweep. Size before: " << oldTasksSize - << "; size after: " << getLedgerReplayer().tasksSize(); + JLOG(m_journal.debug()) << "LedgerReplayer tasks sweep. Size before: " << oldTasksSize + << "; size after: " << getLedgerReplayer().tasksSize(); - JLOG(m_journal.debug()) - << "LedgerReplayer deltas sweep. Size before: " - << oldDeltasSize - << "; size after: " << getLedgerReplayer().deltasSize(); + JLOG(m_journal.debug()) << "LedgerReplayer deltas sweep. Size before: " << oldDeltasSize + << "; size after: " << getLedgerReplayer().deltasSize(); - JLOG(m_journal.debug()) - << "LedgerReplayer skipLists sweep. Size before: " - << oldSkipListsSize - << "; size after: " << getLedgerReplayer().skipListsSize(); + JLOG(m_journal.debug()) << "LedgerReplayer skipLists sweep. Size before: " << oldSkipListsSize + << "; size after: " << getLedgerReplayer().skipListsSize(); } { - std::size_t const oldAcceptedLedgerSize = - m_acceptedLedgerCache.size(); + std::size_t const oldAcceptedLedgerSize = m_acceptedLedgerCache.size(); m_acceptedLedgerCache.sweep(); - JLOG(m_journal.debug()) - << "AcceptedLedgerCache sweep. Size before: " - << oldAcceptedLedgerSize - << "; size after: " << m_acceptedLedgerCache.size(); + JLOG(m_journal.debug()) << "AcceptedLedgerCache sweep. Size before: " << oldAcceptedLedgerSize + << "; size after: " << m_acceptedLedgerCache.size(); } { std::size_t const oldCachedSLEsSize = cachedSLEs_.size(); cachedSLEs_.sweep(); - JLOG(m_journal.debug()) - << "CachedSLEs sweep. Size before: " << oldCachedSLEsSize - << "; size after: " << cachedSLEs_.size(); + JLOG(m_journal.debug()) << "CachedSLEs sweep. Size before: " << oldCachedSLEsSize + << "; size after: " << cachedSLEs_.size(); } // Set timer to do another sweep later. @@ -1136,14 +1017,16 @@ private: loadLedgerFromFile(std::string const& ledgerID); bool - loadOldLedger( - std::string const& ledgerID, - bool replay, - bool isFilename, - std::optional trapTxID); + loadOldLedger(std::string const& ledgerID, bool replay, bool isFilename, std::optional trapTxID); void setMaxDisallowedLedger(); + + Application& + app() override + { + return *this; + } }; //------------------------------------------------------------------------------ @@ -1162,17 +1045,16 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) // to async_wait). m_signals.add(SIGINT); m_signals.add(SIGTERM); - m_signals.async_wait( - [this](boost::system::error_code const& ec, int signum) { - // Indicates the signal handler has been aborted; do nothing - if (ec == boost::asio::error::operation_aborted) - return; + m_signals.async_wait([this](boost::system::error_code const& ec, int signum) { + // Indicates the signal handler has been aborted; do nothing + if (ec == boost::asio::error::operation_aborted) + return; - JLOG(m_journal.info()) << "Received signal " << signum; + JLOG(m_journal.info()) << "Received signal " << signum; - if (signum == SIGTERM || signum == SIGINT) - signalStop("Signal: " + to_string(signum)); - }); + if (signum == SIGTERM || signum == SIGINT) + signalStop("Signal: " + to_string(signum)); + }); auto debug_log = config_->getDebugLogFile(); @@ -1189,8 +1071,7 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) logs_->threshold(kDebug); } - JLOG(m_journal.info()) << "Process starting: " - << BuildInfo::getFullVersionString() + JLOG(m_journal.info()) << "Process starting: " << BuildInfo::getFullVersionString() << ", Instance Cookie: " << instanceCookie_; if (numberOfThreads(*config_) < 2) @@ -1223,8 +1104,7 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) for (auto const& [a, vote] : amendments) { auto const f = xrpl::getRegisteredFeature(a); - XRPL_ASSERT( - f, "xrpl::ApplicationImp::setup : registered feature"); + XRPL_ASSERT(f, "xrpl::ApplicationImp::setup : registered feature"); if (f) supported.emplace_back(a, *f, vote); } @@ -1235,38 +1115,30 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) Section const& upVoted = config_->section(SECTION_AMENDMENTS); m_amendmentTable = make_AmendmentTable( - *this, - config().AMENDMENT_MAJORITY_TIME, - supported, - upVoted, - downVoted, - logs_->journal("Amendments")); + *this, config().AMENDMENT_MAJORITY_TIME, supported, upVoted, downVoted, logs_->journal("Amendments")); } Pathfinder::initPathTable(); auto const startUp = config_->START_UP; JLOG(m_journal.debug()) << "startUp: " << startUp; - if (startUp == Config::FRESH) + if (startUp == StartUpType::FRESH) { JLOG(m_journal.info()) << "Starting new Ledger"; startGenesisLedger(); } - else if ( - startUp == Config::LOAD || startUp == Config::LOAD_FILE || - startUp == Config::REPLAY) + else if (startUp == StartUpType::LOAD || startUp == StartUpType::LOAD_FILE || startUp == StartUpType::REPLAY) { JLOG(m_journal.info()) << "Loading specified Ledger"; if (!loadOldLedger( config_->START_LEDGER, - startUp == Config::REPLAY, - startUp == Config::LOAD_FILE, + startUp == StartUpType::REPLAY, + startUp == StartUpType::LOAD_FILE, config_->TRAP_TX_HASH)) { - JLOG(m_journal.error()) - << "The specified ledger could not be loaded."; + JLOG(m_journal.error()) << "The specified ledger could not be loaded."; if (config_->FAST_LOAD) { // Fall back to syncing from the network, such as @@ -1279,7 +1151,7 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) } } } - else if (startUp == Config::NETWORK) + else if (startUp == StartUpType::NETWORK) { // This should probably become the default once we have a stable // network. @@ -1295,11 +1167,10 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) if (auto const& forcedRange = config().FORCED_LEDGER_RANGE_PRESENT) { - m_ledgerMaster->setLedgerRangePresent( - forcedRange->first, forcedRange->second); + m_ledgerMaster->setLedgerRangePresent(forcedRange->first, forcedRange->second); } - m_orderBookDB.setup(getLedgerMaster().getCurrentLedger()); + m_orderBookDB->setup(getLedgerMaster().getCurrentLedger()); nodeIdentity_ = getNodeIdentity(*this, cmdline); @@ -1342,17 +1213,14 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) config().section(SECTION_VALIDATOR_LIST_KEYS).values(), config().VALIDATOR_LIST_THRESHOLD)) { - JLOG(m_journal.fatal()) - << "Invalid entry in validator configuration."; + JLOG(m_journal.fatal()) << "Invalid entry in validator configuration."; return false; } } - if (!validatorSites_->load( - config().section(SECTION_VALIDATOR_LIST_SITES).values())) + if (!validatorSites_->load(config().section(SECTION_VALIDATOR_LIST_SITES).values())) { - JLOG(m_journal.fatal()) - << "Invalid entry in [" << SECTION_VALIDATOR_LIST_SITES << "]"; + JLOG(m_journal.fatal()) << "Invalid entry in [" << SECTION_VALIDATOR_LIST_SITES << "]"; return false; } @@ -1382,8 +1250,7 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) add(*overlay_); // add to PropertyStream // start first consensus round - if (!m_networkOPs->beginConsensus( - m_ledgerMaster->getClosedLedger()->header().hash, {})) + if (!m_networkOPs->beginConsensus(m_ledgerMaster->getClosedLedger()->header().hash, {})) { JLOG(m_journal.fatal()) << "Unable to start consensus"; return false; @@ -1392,8 +1259,7 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) { try { - auto setup = setup_ServerHandler( - *config_, beast::logstream{m_journal.error()}); + auto setup = setup_ServerHandler(*config_, beast::logstream{m_journal.error()}); setup.makeContexts(); serverHandler_->setup(setup, m_journal); fixConfigPorts(*config_, serverHandler_->endpoints()); @@ -1417,8 +1283,7 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) // of message, if displayed, should be displayed from PeerFinder. if (config_->PEER_PRIVATE && config_->IPS_FIXED.empty()) { - JLOG(m_journal.warn()) - << "No outbound peer connections will be made"; + JLOG(m_journal.warn()) << "No outbound peer connections will be made"; } // VFALCO NOTE the state timer resets the deadlock detector. @@ -1443,12 +1308,10 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) JLOG(m_journal.warn()) << "*** rippled."; JLOG(m_journal.warn()) << "*** If you do not use them to sign " "transactions please edit your"; - JLOG(m_journal.warn()) - << "*** configuration file and remove the [enable_signing] stanza."; + JLOG(m_journal.warn()) << "*** configuration file and remove the [enable_signing] stanza."; JLOG(m_journal.warn()) << "*** If you do use them to sign transactions " "please migrate to a"; - JLOG(m_journal.warn()) - << "*** standalone signing solution as soon as possible."; + JLOG(m_journal.warn()) << "*** standalone signing solution as soon as possible."; } // @@ -1461,14 +1324,12 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) if (!jrReader.parse(cmd, jvCommand)) { - JLOG(m_journal.fatal()) << "Couldn't parse entry in [" - << SECTION_RPC_STARTUP << "]: '" << cmd; + JLOG(m_journal.fatal()) << "Couldn't parse entry in [" << SECTION_RPC_STARTUP << "]: '" << cmd; } if (!config_->quiet()) { - JLOG(m_journal.fatal()) - << "Startup RPC: " << jvCommand << std::endl; + JLOG(m_journal.fatal()) << "Startup RPC: " << jvCommand << std::endl; } Resource::Charge loadType = Resource::feeReferenceRPC; @@ -1503,8 +1364,7 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) void ApplicationImp::start(bool withTimers) { - JLOG(m_journal.info()) << "Application starting. Version is " - << BuildInfo::getVersionString(); + JLOG(m_journal.info()) << "Application starting. Version is " << BuildInfo::getVersionString(); if (withTimers) { @@ -1520,8 +1380,7 @@ ApplicationImp::start(bool withTimers) overlay_->start(); if (grpcServer_->start()) - fixConfigPorts( - *config_, {{SECTION_PORT_GRPC, grpcServer_->getEndpoint()}}); + fixConfigPorts(*config_, {{SECTION_PORT_GRPC, grpcServer_->getEndpoint()}}); ledgerCleaner_->start(); perfLog_->start(); @@ -1539,10 +1398,7 @@ ApplicationImp::run() getLoadManager().activateStallDetector(); } - { - std::unique_lock lk{stoppingMutex_}; - stoppingCondition_.wait(lk, [this] { return isTimeToStop.load(); }); - } + isTimeToStop.wait(false, std::memory_order_relaxed); JLOG(m_journal.debug()) << "Application stopping"; @@ -1570,8 +1426,7 @@ ApplicationImp::run() } catch (boost::system::system_error const& e) { - JLOG(m_journal.error()) - << "Application: sweepTimer cancel error: " << e.what(); + JLOG(m_journal.error()) << "Application: sweepTimer cancel error: " << e.what(); } try @@ -1580,8 +1435,7 @@ ApplicationImp::run() } catch (boost::system::system_error const& e) { - JLOG(m_journal.error()) - << "Application: entropyTimer cancel error: " << e.what(); + JLOG(m_journal.error()) << "Application: entropyTimer cancel error: " << e.what(); } } @@ -1597,14 +1451,11 @@ ApplicationImp::run() // TODO Store manifests in manifests.sqlite instead of wallet.db validatorManifests_->save( - getWalletDB(), "ValidatorManifests", [this](PublicKey const& pubKey) { - return validators().listed(pubKey); - }); + getWalletDB(), "ValidatorManifests", [this](PublicKey const& pubKey) { return validators().listed(pubKey); }); - publisherManifests_->save( - getWalletDB(), "PublisherManifests", [this](PublicKey const& pubKey) { - return validators().trustedPublisher(pubKey); - }); + publisherManifests_->save(getWalletDB(), "PublisherManifests", [this](PublicKey const& pubKey) { + return validators().trustedPublisher(pubKey); + }); // The order of these stop calls is delicate. // Re-ordering them risks undefined behavior. @@ -1629,14 +1480,14 @@ ApplicationImp::run() void ApplicationImp::signalStop(std::string msg) { - if (!isTimeToStop.exchange(true)) + if (!isTimeToStop.test_and_set(std::memory_order_acquire)) { if (msg.empty()) JLOG(m_journal.warn()) << "Server stopping"; else JLOG(m_journal.warn()) << "Server stopping: " << msg; - stoppingCondition_.notify_all(); + isTimeToStop.notify_all(); } } @@ -1655,7 +1506,7 @@ ApplicationImp::checkSigs(bool check) bool ApplicationImp::isStopping() const { - return isTimeToStop.load(); + return isTimeToStop.test(std::memory_order_relaxed); } int @@ -1687,19 +1538,16 @@ void ApplicationImp::startGenesisLedger() { std::vector const initialAmendments = - (config_->START_UP == Config::FRESH) ? m_amendmentTable->getDesired() - : std::vector{}; + (config_->START_UP == StartUpType::FRESH) ? m_amendmentTable->getDesired() : std::vector{}; - std::shared_ptr const genesis = std::make_shared( - create_genesis, *config_, initialAmendments, nodeFamily_); + std::shared_ptr const genesis = + std::make_shared(create_genesis, *config_, initialAmendments, nodeFamily_); m_ledgerMaster->storeLedger(genesis); - auto const next = - std::make_shared(*genesis, timeKeeper().closeTime()); + auto const next = std::make_shared(*genesis, timeKeeper().closeTime()); next->updateSkipList(); XRPL_ASSERT( - next->header().seq < XRP_LEDGER_EARLIEST_FEES || - next->read(keylet::fees()), + next->header().seq < XRP_LEDGER_EARLIEST_FEES || next->read(keylet::fees()), "xrpl::ApplicationImp::startGenesisLedger : valid ledger fees"); next->setImmutable(); openLedger_.emplace(next, cachedSLEs_, logs_->journal("OpenLedger")); @@ -1720,8 +1568,7 @@ ApplicationImp::getLastFullLedger() return ledger; XRPL_ASSERT( - ledger->header().seq < XRP_LEDGER_EARLIEST_FEES || - ledger->read(keylet::fees()), + ledger->header().seq < XRP_LEDGER_EARLIEST_FEES || ledger->read(keylet::fees()), "xrpl::ApplicationImp::getLastFullLedger : valid ledger fees"); ledger->setImmutable(); @@ -1805,18 +1652,15 @@ ApplicationImp::loadLedgerFromFile(std::string const& name) if (ledger.get().isMember("close_time_resolution")) { using namespace std::chrono; - closeTimeResolution = - seconds{ledger.get()["close_time_resolution"].asUInt()}; + closeTimeResolution = seconds{ledger.get()["close_time_resolution"].asUInt()}; } if (ledger.get().isMember("close_time_estimated")) { - closeTimeEstimated = - ledger.get()["close_time_estimated"].asBool(); + closeTimeEstimated = ledger.get()["close_time_estimated"].asBool(); } if (ledger.get().isMember("total_coins")) { - totalDrops = beast::lexicalCastThrow( - ledger.get()["total_coins"].asString()); + totalDrops = beast::lexicalCastThrow(ledger.get()["total_coins"].asString()); } ledger = ledger.get()["accountState"]; @@ -1828,8 +1672,7 @@ ApplicationImp::loadLedgerFromFile(std::string const& name) return nullptr; } - auto loadLedger = - std::make_shared(seq, closeTime, *config_, nodeFamily_); + auto loadLedger = std::make_shared(seq, closeTime, *config_, nodeFamily_); loadLedger->setTotalDrops(totalDrops); for (Json::UInt index = 0; index < ledger.get().size(); ++index) @@ -1866,8 +1709,7 @@ ApplicationImp::loadLedgerFromFile(std::string const& name) if (!loadLedger->addSLE(sle)) { - JLOG(m_journal.fatal()) - << "Couldn't add serialized ledger: " << uIndex; + JLOG(m_journal.fatal()) << "Couldn't add serialized ledger: " << uIndex; return nullptr; } } @@ -1875,11 +1717,9 @@ ApplicationImp::loadLedgerFromFile(std::string const& name) loadLedger->stateMap().flushDirty(hotACCOUNT_NODE); XRPL_ASSERT( - loadLedger->header().seq < XRP_LEDGER_EARLIEST_FEES || - loadLedger->read(keylet::fees()), + loadLedger->header().seq < XRP_LEDGER_EARLIEST_FEES || loadLedger->read(keylet::fees()), "xrpl::ApplicationImp::loadLedgerFromFile : valid ledger fees"); - loadLedger->setAccepted( - closeTime, closeTimeResolution, !closeTimeEstimated); + loadLedger->setAccepted(closeTime, closeTimeResolution, !closeTimeEstimated); return loadLedger; } @@ -1918,12 +1758,7 @@ ApplicationImp::loadOldLedger( { // Try to build the ledger from the back end auto il = std::make_shared( - *this, - hash, - 0, - InboundLedger::Reason::GENERIC, - stopwatch(), - make_DummyPeerSet(*this)); + *this, hash, 0, InboundLedger::Reason::GENERIC, stopwatch(), make_DummyPeerSet(*this)); if (il->checkLocal()) loadLedger = il->getLedger(); } @@ -1957,8 +1792,7 @@ ApplicationImp::loadOldLedger( loadLedger = loadByHash(replayLedger->header().parentHash, *this); if (!loadLedger) { - JLOG(m_journal.info()) - << "Loading parent ledger from node store"; + JLOG(m_journal.info()) << "Loading parent ledger from node store"; // Try to build the ledger from the back end auto il = std::make_shared( @@ -1990,27 +1824,24 @@ ApplicationImp::loadOldLedger( sys_days{January / 1 / 2018} - sys_days{January / 1 / 2000}}; if (loadLedger->header().closeTime < ledgerWarnTimePoint) { - JLOG(m_journal.fatal()) - << "\n\n*** WARNING ***\n" - "You are replaying a ledger from before " - << to_string(ledgerWarnTimePoint) - << " UTC.\n" - "This replay will not handle your ledger as it was " - "originally " - "handled.\nConsider running an earlier version of rippled " - "to " - "get the older rules.\n*** CONTINUING ***\n"; + JLOG(m_journal.fatal()) << "\n\n*** WARNING ***\n" + "You are replaying a ledger from before " + << to_string(ledgerWarnTimePoint) + << " UTC.\n" + "This replay will not handle your ledger as it was " + "originally " + "handled.\nConsider running an earlier version of rippled " + "to " + "get the older rules.\n*** CONTINUING ***\n"; } - JLOG(m_journal.info()) << "Loading ledger " << loadLedger->header().hash - << " seq:" << loadLedger->header().seq; + JLOG(m_journal.info()) << "Loading ledger " << loadLedger->header().hash << " seq:" << loadLedger->header().seq; if (loadLedger->header().accountHash.isZero()) { // LCOV_EXCL_START JLOG(m_journal.fatal()) << "Ledger is empty."; - UNREACHABLE( - "xrpl::ApplicationImp::loadOldLedger : ledger is empty"); + UNREACHABLE("xrpl::ApplicationImp::loadOldLedger : ledger is empty"); return false; // LCOV_EXCL_STOP } @@ -2037,21 +1868,18 @@ ApplicationImp::loadOldLedger( // LCOV_EXCL_STOP } - m_ledgerMaster->setLedgerRangePresent( - loadLedger->header().seq, loadLedger->header().seq); + m_ledgerMaster->setLedgerRangePresent(loadLedger->header().seq, loadLedger->header().seq); m_ledgerMaster->switchLCL(loadLedger); loadLedger->setValidated(); m_ledgerMaster->setFullLedger(loadLedger, true, false); - openLedger_.emplace( - loadLedger, cachedSLEs_, logs_->journal("OpenLedger")); + openLedger_.emplace(loadLedger, cachedSLEs_, logs_->journal("OpenLedger")); if (replay) { // inject transaction(s) from the replayLedger into our open ledger // and build replay structure - auto replayData = - std::make_unique(loadLedger, replayLedger); + auto replayData = std::make_unique(loadLedger, replayLedger); for (auto const& [_, tx] : replayData->orderedTxns()) { @@ -2068,34 +1896,30 @@ ApplicationImp::loadOldLedger( forceValidity(getHashRouter(), txID, Validity::SigGoodOnly); - openLedger_->modify( - [&txID, &s](OpenView& view, beast::Journal j) { - view.rawTxInsert(txID, std::move(s), nullptr); - return true; - }); + openLedger_->modify([&txID, &s](OpenView& view, beast::Journal j) { + view.rawTxInsert(txID, std::move(s), nullptr); + return true; + }); } m_ledgerMaster->takeReplay(std::move(replayData)); if (trapTxID && !trapTxID_) { - JLOG(m_journal.fatal()) - << "Ledger " << replayLedger->header().seq - << " does not contain the transaction hash " << *trapTxID; + JLOG(m_journal.fatal()) << "Ledger " << replayLedger->header().seq + << " does not contain the transaction hash " << *trapTxID; return false; } } } catch (SHAMapMissingNode const& mn) { - JLOG(m_journal.fatal()) - << "While loading specified ledger: " << mn.what(); + JLOG(m_journal.fatal()) << "While loading specified ledger: " << mn.what(); return false; } catch (boost::bad_lexical_cast&) { - JLOG(m_journal.fatal()) - << "Ledger specified '" << ledgerID << "' is not valid"; + JLOG(m_journal.fatal()) << "Ledger specified '" << ledgerID << "' is not valid"; return false; } @@ -2163,8 +1987,7 @@ ApplicationImp::setMaxDisallowedLedger() if (seq) maxDisallowedLedger_ = *seq; - JLOG(m_journal.trace()) - << "Max persisted ledger is " << maxDisallowedLedger_; + JLOG(m_journal.trace()) << "Max persisted ledger is " << maxDisallowedLedger_; } //------------------------------------------------------------------------------ @@ -2176,13 +1999,9 @@ Application::Application() : beast::PropertyStream::Source("app") //------------------------------------------------------------------------------ std::unique_ptr -make_Application( - std::unique_ptr config, - std::unique_ptr logs, - std::unique_ptr timeKeeper) +make_Application(std::unique_ptr config, std::unique_ptr logs, std::unique_ptr timeKeeper) { - return std::make_unique( - std::move(config), std::move(logs), std::move(timeKeeper)); + return std::make_unique(std::move(config), std::move(logs), std::move(timeKeeper)); } void @@ -2197,8 +2016,7 @@ fixConfigPorts(Config& config, Endpoints const& endpoints) auto const optPort = section.get("port"); if (optPort) { - std::uint16_t const port = - beast::lexicalCast(*optPort); + std::uint16_t const port = beast::lexicalCast(*optPort); if (!port) section.set("port", std::to_string(ep.port())); } diff --git a/src/xrpld/app/main/Application.h b/src/xrpld/app/main/Application.h index ffb3cd9983..a0fea69171 100644 --- a/src/xrpld/app/main/Application.h +++ b/src/xrpld/app/main/Application.h @@ -1,11 +1,11 @@ -#ifndef XRPL_APP_MAIN_APPLICATION_H_INCLUDED -#define XRPL_APP_MAIN_APPLICATION_H_INCLUDED +#pragma once #include -#include #include #include +#include +#include #include #include @@ -91,7 +91,7 @@ class Validations; class RCLValidationsAdaptor; using RCLValidations = Validations; -class Application : public beast::PropertyStream::Source +class Application : public ServiceRegistry, public beast::PropertyStream::Source { public: /* VFALCO NOTE @@ -112,8 +112,6 @@ public: public: Application(); - virtual ~Application() = default; - virtual bool setup(boost::program_options::variables_map const& options) = 0; @@ -127,8 +125,6 @@ public: checkSigs() const = 0; virtual void checkSigs(bool) = 0; - virtual bool - isStopping() const = 0; // // --- @@ -138,132 +134,32 @@ public: virtual std::uint64_t instanceID() const = 0; - virtual Logs& - logs() = 0; virtual Config& config() = 0; - virtual boost::asio::io_context& - getIOContext() = 0; - - virtual CollectorManager& - getCollectorManager() = 0; - virtual Family& - getNodeFamily() = 0; - virtual TimeKeeper& - timeKeeper() = 0; - virtual JobQueue& - getJobQueue() = 0; - virtual NodeCache& - getTempNodeCache() = 0; - virtual CachedSLEs& - cachedSLEs() = 0; - virtual AmendmentTable& - getAmendmentTable() = 0; - virtual HashRouter& - getHashRouter() = 0; - virtual LoadFeeTrack& - getFeeTrack() = 0; - virtual LoadManager& - getLoadManager() = 0; - virtual Overlay& - overlay() = 0; - virtual TxQ& - getTxQ() = 0; - virtual ValidatorList& - validators() = 0; - virtual ValidatorSite& - validatorSites() = 0; - virtual ManifestCache& - validatorManifests() = 0; - virtual ManifestCache& - publisherManifests() = 0; - virtual Cluster& - cluster() = 0; - virtual PeerReservationTable& - peerReservations() = 0; - virtual RCLValidations& - getValidations() = 0; - virtual NodeStore::Database& - getNodeStore() = 0; - virtual InboundLedgers& - getInboundLedgers() = 0; - virtual InboundTransactions& - getInboundTransactions() = 0; - - virtual TaggedCache& - getAcceptedLedgerCache() = 0; - - virtual LedgerMaster& - getLedgerMaster() = 0; - virtual LedgerCleaner& - getLedgerCleaner() = 0; - virtual LedgerReplayer& - getLedgerReplayer() = 0; - virtual NetworkOPs& - getOPs() = 0; - virtual OrderBookDB& - getOrderBookDB() = 0; - virtual ServerHandler& - getServerHandler() = 0; - virtual TransactionMaster& - getMasterTransaction() = 0; - virtual perf::PerfLog& - getPerfLog() = 0; - virtual std::pair const& nodeIdentity() = 0; virtual std::optional getValidationPublicKey() const = 0; - virtual Resource::Manager& - getResourceManager() = 0; - virtual PathRequests& - getPathRequests() = 0; - virtual SHAMapStore& - getSHAMapStore() = 0; - virtual PendingSaves& - pendingSaves() = 0; - virtual OpenLedger& - openLedger() = 0; - virtual OpenLedger const& - openLedger() const = 0; - virtual RelationalDatabase& - getRelationalDatabase() = 0; - virtual std::chrono::milliseconds getIOLatency() = 0; virtual bool serverOkay(std::string& reason) = 0; - virtual beast::Journal - journal(std::string const& name) = 0; - /* Returns the number of file descriptors the application needs */ virtual int fdRequired() const = 0; - /** Retrieve the "wallet database" */ - virtual DatabaseCon& - getWalletDB() = 0; - /** Ensure that a newly-started validator does not sign proposals older * than the last ledger it persisted. */ virtual LedgerIndex getMaxDisallowedLedger() = 0; - - virtual std::optional const& - trapTxID() const = 0; }; std::unique_ptr -make_Application( - std::unique_ptr config, - std::unique_ptr logs, - std::unique_ptr timeKeeper); +make_Application(std::unique_ptr config, std::unique_ptr logs, std::unique_ptr timeKeeper); } // namespace xrpl - -#endif diff --git a/src/xrpld/app/main/BasicApp.cpp b/src/xrpld/app/main/BasicApp.cpp index 95cdf890cc..be0c158b85 100644 --- a/src/xrpld/app/main/BasicApp.cpp +++ b/src/xrpld/app/main/BasicApp.cpp @@ -12,8 +12,7 @@ BasicApp::BasicApp(std::size_t numberOfThreads) while (numberOfThreads--) { threads_.emplace_back([this, numberOfThreads]() { - beast::setCurrentThreadName( - "io svc #" + std::to_string(numberOfThreads)); + beast::setCurrentThreadName("io svc #" + std::to_string(numberOfThreads)); this->io_context_.run(); }); } diff --git a/src/xrpld/app/main/BasicApp.h b/src/xrpld/app/main/BasicApp.h index 75c4c1890c..278c255af3 100644 --- a/src/xrpld/app/main/BasicApp.h +++ b/src/xrpld/app/main/BasicApp.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_BASICAPP_H_INCLUDED -#define XRPL_APP_BASICAPP_H_INCLUDED +#pragma once #include @@ -11,9 +10,7 @@ class BasicApp { private: - std::optional> - work_; + std::optional> work_; std::vector threads_; boost::asio::io_context io_context_; @@ -27,5 +24,3 @@ public: return io_context_; } }; - -#endif diff --git a/src/xrpld/app/main/CollectorManager.cpp b/src/xrpld/app/main/CollectorManager.cpp index 110ea564d8..7a3306b60b 100644 --- a/src/xrpld/app/main/CollectorManager.cpp +++ b/src/xrpld/app/main/CollectorManager.cpp @@ -11,19 +11,16 @@ public: beast::insight::Collector::ptr m_collector; std::unique_ptr m_groups; - CollectorManagerImp(Section const& params, beast::Journal journal) - : m_journal(journal) + CollectorManagerImp(Section const& params, beast::Journal journal) : m_journal(journal) { std::string const& server = get(params, "server"); if (server == "statsd") { - beast::IP::Endpoint const address( - beast::IP::Endpoint::from_string(get(params, "address"))); + beast::IP::Endpoint const address(beast::IP::Endpoint::from_string(get(params, "address"))); std::string const& prefix(get(params, "prefix")); - m_collector = - beast::insight::StatsDCollector::New(address, prefix, journal); + m_collector = beast::insight::StatsDCollector::New(address, prefix, journal); } else { diff --git a/src/xrpld/app/main/CollectorManager.h b/src/xrpld/app/main/CollectorManager.h index d0d202625c..15785ec292 100644 --- a/src/xrpld/app/main/CollectorManager.h +++ b/src/xrpld/app/main/CollectorManager.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_MAIN_COLLECTORMANAGER_H_INCLUDED -#define XRPL_APP_MAIN_COLLECTORMANAGER_H_INCLUDED +#pragma once #include #include @@ -23,5 +22,3 @@ std::unique_ptr make_CollectorManager(Section const& params, beast::Journal journal); } // namespace xrpl - -#endif diff --git a/src/xrpld/app/main/GRPCServer.cpp b/src/xrpld/app/main/GRPCServer.cpp index 6ed902ec1e..9b07728eb8 100644 --- a/src/xrpld/app/main/GRPCServer.cpp +++ b/src/xrpld/app/main/GRPCServer.cpp @@ -24,8 +24,7 @@ getEndpoint(std::string const& peer) peerClean = peer.substr(first + 1); } - std::optional endpoint = - beast::IP::Endpoint::from_string_checked(peerClean); + std::optional endpoint = beast::IP::Endpoint::from_string_checked(peerClean); if (endpoint) return beast::IP::to_asio_endpoint(endpoint.value()); } @@ -70,15 +69,7 @@ std::shared_ptr GRPCServerImpl::CallData::clone() { return std::make_shared>( - service_, - cq_, - app_, - bindListener_, - handler_, - forward_, - requiredCondition_, - loadType_, - secureGatewayIPs_); + service_, cq_, app_, bindListener_, handler_, forward_, requiredCondition_, loadType_, secureGatewayIPs_); } template @@ -88,8 +79,7 @@ GRPCServerImpl::CallData::process() // sanity check BOOST_ASSERT(!finished_); - std::shared_ptr> thisShared = - this->shared_from_this(); + std::shared_ptr> thisShared = this->shared_from_this(); // Need to set finished to true before processing the response, // because as soon as the response is posted to the completion @@ -100,26 +90,22 @@ GRPCServerImpl::CallData::process() // ensures that finished is always true when this CallData object // is returned as a tag in handleRpcs(), after sending the response finished_ = true; - auto coro = app_.getJobQueue().postCoro( - JobType::jtRPC, - "gRPC-Client", - [thisShared](std::shared_ptr coro) { + auto coro = + app_.getJobQueue().postCoro(JobType::jtRPC, "gRPC-Client", [thisShared](std::shared_ptr coro) { thisShared->process(coro); }); // If coro is null, then the JobQueue has already been shutdown if (!coro) { - grpc::Status status{ - grpc::StatusCode::INTERNAL, "Job Queue is already stopped"}; + grpc::Status status{grpc::StatusCode::INTERNAL, "Job Queue is already stopped"}; responder_.FinishWithError(status, this); } } template void -GRPCServerImpl::CallData::process( - std::shared_ptr coro) +GRPCServerImpl::CallData::process(std::shared_ptr coro) { try { @@ -127,9 +113,7 @@ GRPCServerImpl::CallData::process( bool isUnlimited = clientIsUnlimited(); if (!isUnlimited && usage.disconnect(app_.journal("gRPCServer"))) { - grpc::Status status{ - grpc::StatusCode::RESOURCE_EXHAUSTED, - "usage balance exceeds threshold"}; + grpc::Status status{grpc::StatusCode::RESOURCE_EXHAUSTED, "usage balance exceeds threshold"}; responder_.FinishWithError(status, this); } else @@ -151,8 +135,7 @@ GRPCServerImpl::CallData::process( toLog << user.value(); toLog << " isUnlimited = " << isUnlimited; - JLOG(app_.journal("GRPCServer::Calldata").debug()) - << toLog.str(); + JLOG(app_.journal("GRPCServer::Calldata").debug()) << toLog.str(); } RPC::GRPCContext context{ @@ -169,15 +152,12 @@ GRPCServerImpl::CallData::process( request_}; // Make sure we can currently handle the rpc - error_code_i conditionMetRes = - RPC::conditionMet(requiredCondition_, context); + error_code_i conditionMetRes = RPC::conditionMet(requiredCondition_, context); if (conditionMetRes != rpcSUCCESS) { RPC::ErrorInfo errorInfo = RPC::get_error_info(conditionMetRes); - grpc::Status status{ - grpc::StatusCode::FAILED_PRECONDITION, - errorInfo.message.c_str()}; + grpc::Status status{grpc::StatusCode::FAILED_PRECONDITION, errorInfo.message.c_str()}; responder_.FinishWithError(status, this); } else @@ -225,8 +205,7 @@ GRPCServerImpl::CallData::getUser() { if (auto descriptor = Request::GetDescriptor()->FindFieldByName("user")) { - std::string user = - Request::GetReflection()->GetString(request_, descriptor); + std::string user = Request::GetReflection()->GetString(request_, descriptor); if (!user.empty()) { return user; @@ -272,14 +251,11 @@ GRPCServerImpl::CallData::clientIsUnlimited() template void -GRPCServerImpl::CallData::setIsUnlimited( - Response& response, - bool isUnlimited) +GRPCServerImpl::CallData::setIsUnlimited(Response& response, bool isUnlimited) { if (isUnlimited) { - if (auto descriptor = - Response::GetDescriptor()->FindFieldByName("is_unlimited")) + if (auto descriptor = Response::GetDescriptor()->FindFieldByName("is_unlimited")) { Response::GetReflection()->SetBool(&response, descriptor, true); } @@ -292,13 +268,11 @@ GRPCServerImpl::CallData::getUsage() { auto endpoint = getClientEndpoint(); if (endpoint) - return app_.getResourceManager().newInboundEndpoint( - beast::IP::from_asio(endpoint.value())); + return app_.getResourceManager().newInboundEndpoint(beast::IP::from_asio(endpoint.value())); Throw("Failed to get client endpoint"); } -GRPCServerImpl::GRPCServerImpl(Application& app) - : app_(app), journal_(app_.journal("gRPC Server")) +GRPCServerImpl::GRPCServerImpl(Application& app) : app_(app), journal_(app_.journal("gRPC Server")) { // if present, get endpoint from config if (app_.config().exists(SECTION_PORT_GRPC)) @@ -314,8 +288,7 @@ GRPCServerImpl::GRPCServerImpl(Application& app) return; try { - boost::asio::ip::tcp::endpoint endpoint( - boost::asio::ip::make_address(*optIp), std::stoi(*optPort)); + boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::make_address(*optIp), std::stoi(*optPort)); std::stringstream ss; ss << endpoint; @@ -341,11 +314,9 @@ GRPCServerImpl::GRPCServerImpl(Application& app) if (addr.is_unspecified()) { - JLOG(journal_.error()) - << "Can't pass unspecified IP in " - << "secure_gateway section of port_grpc"; - Throw( - "Unspecified IP in secure_gateway section"); + JLOG(journal_.error()) << "Can't pass unspecified IP in " + << "secure_gateway section of port_grpc"; + Throw("Unspecified IP in secure_gateway section"); } secureGatewayIPs_.emplace_back(addr); @@ -353,10 +324,8 @@ GRPCServerImpl::GRPCServerImpl(Application& app) } catch (std::exception const&) { - JLOG(journal_.error()) - << "Error parsing secure gateway IPs for grpc server"; - Throw( - "Error parsing secure_gateway section"); + JLOG(journal_.error()) << "Error parsing secure gateway IPs for grpc server"; + Throw("Error parsing secure_gateway section"); } } } @@ -394,11 +363,7 @@ GRPCServerImpl::handleRpcs() auto erase = [&requests](Processor* ptr) { auto it = std::find_if( - requests.begin(), - requests.end(), - [ptr](std::shared_ptr& sPtr) { - return sPtr.get() == ptr; - }); + requests.begin(), requests.end(), [ptr](std::shared_ptr& sPtr) { return sPtr.get() == ptr; }); BOOST_ASSERT(it != requests.end()); it->swap(requests.back()); requests.pop_back(); @@ -460,21 +425,16 @@ GRPCServerImpl::setupListeners() { std::vector> requests; - auto addToRequests = [&requests](auto callData) { - requests.push_back(std::move(callData)); - }; + auto addToRequests = [&requests](auto callData) { requests.push_back(std::move(callData)); }; { - using cd = CallData< - org::xrpl::rpc::v1::GetLedgerRequest, - org::xrpl::rpc::v1::GetLedgerResponse>; + using cd = CallData; addToRequests(std::make_shared( service_, *cq_, app_, - &org::xrpl::rpc::v1::XRPLedgerAPIService::AsyncService:: - RequestGetLedger, + &org::xrpl::rpc::v1::XRPLedgerAPIService::AsyncService::RequestGetLedger, doLedgerGrpc, &org::xrpl::rpc::v1::XRPLedgerAPIService::Stub::GetLedger, RPC::NO_CONDITION, @@ -482,16 +442,13 @@ GRPCServerImpl::setupListeners() secureGatewayIPs_)); } { - using cd = CallData< - org::xrpl::rpc::v1::GetLedgerDataRequest, - org::xrpl::rpc::v1::GetLedgerDataResponse>; + using cd = CallData; addToRequests(std::make_shared( service_, *cq_, app_, - &org::xrpl::rpc::v1::XRPLedgerAPIService::AsyncService:: - RequestGetLedgerData, + &org::xrpl::rpc::v1::XRPLedgerAPIService::AsyncService::RequestGetLedgerData, doLedgerDataGrpc, &org::xrpl::rpc::v1::XRPLedgerAPIService::Stub::GetLedgerData, RPC::NO_CONDITION, @@ -499,16 +456,13 @@ GRPCServerImpl::setupListeners() secureGatewayIPs_)); } { - using cd = CallData< - org::xrpl::rpc::v1::GetLedgerDiffRequest, - org::xrpl::rpc::v1::GetLedgerDiffResponse>; + using cd = CallData; addToRequests(std::make_shared( service_, *cq_, app_, - &org::xrpl::rpc::v1::XRPLedgerAPIService::AsyncService:: - RequestGetLedgerDiff, + &org::xrpl::rpc::v1::XRPLedgerAPIService::AsyncService::RequestGetLedgerDiff, doLedgerDiffGrpc, &org::xrpl::rpc::v1::XRPLedgerAPIService::Stub::GetLedgerDiff, RPC::NO_CONDITION, @@ -516,16 +470,13 @@ GRPCServerImpl::setupListeners() secureGatewayIPs_)); } { - using cd = CallData< - org::xrpl::rpc::v1::GetLedgerEntryRequest, - org::xrpl::rpc::v1::GetLedgerEntryResponse>; + using cd = CallData; addToRequests(std::make_shared( service_, *cq_, app_, - &org::xrpl::rpc::v1::XRPLedgerAPIService::AsyncService:: - RequestGetLedgerEntry, + &org::xrpl::rpc::v1::XRPLedgerAPIService::AsyncService::RequestGetLedgerEntry, doLedgerEntryGrpc, &org::xrpl::rpc::v1::XRPLedgerAPIService::Stub::GetLedgerEntry, RPC::NO_CONDITION, @@ -549,8 +500,7 @@ GRPCServerImpl::start() // Listen on the given address without any authentication mechanism. // Actually binded port will be returned into "port" variable. int port = 0; - builder.AddListeningPort( - serverAddress_, grpc::InsecureServerCredentials(), &port); + builder.AddListeningPort(serverAddress_, grpc::InsecureServerCredentials(), &port); // Register "service_" as the instance through which we'll communicate with // clients. In this case it corresponds to an *asynchronous* service. builder.RegisterService(&service_); @@ -567,10 +517,8 @@ GRPCServerImpl::start() boost::asio::ip::tcp::endpoint GRPCServerImpl::getEndpoint() const { - std::string const addr = - serverAddress_.substr(0, serverAddress_.find_last_of(':')); - return boost::asio::ip::tcp::endpoint( - boost::asio::ip::make_address(addr), serverPort_); + std::string const addr = serverAddress_.substr(0, serverAddress_.find_last_of(':')); + return boost::asio::ip::tcp::endpoint(boost::asio::ip::make_address(addr), serverPort_); } bool diff --git a/src/xrpld/app/main/GRPCServer.h b/src/xrpld/app/main/GRPCServer.h index c2697e26c6..1b41722fff 100644 --- a/src/xrpld/app/main/GRPCServer.h +++ b/src/xrpld/app/main/GRPCServer.h @@ -1,16 +1,15 @@ -#ifndef XRPL_CORE_GRPCSERVER_H_INCLUDED -#define XRPL_CORE_GRPCSERVER_H_INCLUDED +#pragma once #include #include #include -#include #include #include #include #include #include +#include #include @@ -85,17 +84,13 @@ private: // typedef for actual handler (that populates a response) // handlers are defined in rpc/GRPCHandlers.h template - using Handler = std::function( - RPC::GRPCContext&)>; + using Handler = std::function(RPC::GRPCContext&)>; // This implementation is currently limited to v1 of the API static unsigned constexpr apiVersion = 1; template - using Forward = std::function; + using Forward = std::function< + grpc::Status(org::xrpl::rpc::v1::XRPLedgerAPIService::Stub*, grpc::ClientContext*, Request, Response*)>; public: explicit GRPCServerImpl(Application& app); @@ -128,9 +123,7 @@ public: private: // Class encompassing the state and logic needed to serve a request. template - class CallData - : public Processor, - public std::enable_shared_from_this> + class CallData : public Processor, public std::enable_shared_from_this> { private: // The means of communication with the gRPC runtime for an asynchronous @@ -306,4 +299,3 @@ private: bool running_ = false; }; } // namespace xrpl -#endif diff --git a/src/xrpld/app/main/LoadManager.cpp b/src/xrpld/app/main/LoadManager.cpp index 91afb67eb7..5e3b572e1d 100644 --- a/src/xrpld/app/main/LoadManager.cpp +++ b/src/xrpld/app/main/LoadManager.cpp @@ -1,10 +1,10 @@ #include #include #include -#include #include #include +#include #include #include @@ -26,8 +26,7 @@ LoadManager::~LoadManager() catch (std::exception const& ex) { // Swallow the exception in a destructor. - JLOG(journal_.warn()) - << "std::exception in ~LoadManager. " << ex.what(); + JLOG(journal_.warn()) << "std::exception in ~LoadManager. " << ex.what(); } } @@ -55,8 +54,7 @@ void LoadManager::start() { JLOG(journal_.debug()) << "Starting"; - XRPL_ASSERT( - !thread_.joinable(), "xrpl::LoadManager::start : thread not joinable"); + XRPL_ASSERT(!thread_.joinable(), "xrpl::LoadManager::start : thread not joinable"); thread_ = std::thread{&LoadManager::run, this}; } @@ -104,8 +102,7 @@ LoadManager::run() // Measure the amount of time we have been stalled, in seconds. using namespace std::chrono; - auto const timeSpentStalled = - duration_cast(steady_clock::now() - lastHeartbeat); + auto const timeSpentStalled = duration_cast(steady_clock::now() - lastHeartbeat); constexpr auto reportingIntervalSeconds = 10s; constexpr auto stallFatalLogMessageTimeLimit = 90s; @@ -118,23 +115,17 @@ LoadManager::run() { if (timeSpentStalled < stallFatalLogMessageTimeLimit) { - JLOG(journal_.warn()) - << "Server stalled for " << timeSpentStalled.count() - << " seconds."; + JLOG(journal_.warn()) << "Server stalled for " << timeSpentStalled.count() << " seconds."; if (app_.getJobQueue().isOverloaded()) { - JLOG(journal_.warn()) - << "JobQueue: " << app_.getJobQueue().getJson(0); + JLOG(journal_.warn()) << "JobQueue: " << app_.getJobQueue().getJson(0); } } else { - JLOG(journal_.fatal()) - << "Server stalled for " << timeSpentStalled.count() - << " seconds."; - JLOG(journal_.fatal()) - << "JobQueue: " << app_.getJobQueue().getJson(0); + JLOG(journal_.fatal()) << "Server stalled for " << timeSpentStalled.count() << " seconds."; + JLOG(journal_.fatal()) << "JobQueue: " << app_.getJobQueue().getJson(0); } } @@ -143,11 +134,9 @@ LoadManager::run() // as a LogicError if (timeSpentStalled >= stallLogicErrorTimeLimit) { - JLOG(journal_.fatal()) - << "LogicError: Fatal server stall detected. Stalled time: " - << timeSpentStalled.count() << "s"; - JLOG(journal_.fatal()) - << "JobQueue: " << app_.getJobQueue().getJson(0); + JLOG(journal_.fatal()) << "LogicError: Fatal server stall detected. Stalled time: " + << timeSpentStalled.count() << "s"; + JLOG(journal_.fatal()) << "JobQueue: " << app_.getJobQueue().getJson(0); LogicError("Fatal server stall detected"); } } @@ -156,8 +145,7 @@ LoadManager::run() bool change = false; if (app_.getJobQueue().isOverloaded()) { - JLOG(journal_.info()) << "Raising local fee (JQ overload): " - << app_.getJobQueue().getJson(0); + JLOG(journal_.info()) << "Raising local fee (JQ overload): " << app_.getJobQueue().getJson(0); change = app_.getFeeTrack().raiseLocalFee(); } else diff --git a/src/xrpld/app/main/LoadManager.h b/src/xrpld/app/main/LoadManager.h index 15caa9b0f0..c36afb1804 100644 --- a/src/xrpld/app/main/LoadManager.h +++ b/src/xrpld/app/main/LoadManager.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_MAIN_LOADMANAGER_H_INCLUDED -#define XRPL_APP_MAIN_LOADMANAGER_H_INCLUDED +#pragma once #include @@ -95,5 +94,3 @@ std::unique_ptr make_LoadManager(Application& app, beast::Journal journal); } // namespace xrpl - -#endif diff --git a/src/xrpld/app/main/Main.cpp b/src/xrpld/app/main/Main.cpp index 7c138168e4..7bdccd12a7 100644 --- a/src/xrpld/app/main/Main.cpp +++ b/src/xrpld/app/main/Main.cpp @@ -1,5 +1,4 @@ #include -#include #include #include #include @@ -8,6 +7,7 @@ #include #include #include +#include #include #include @@ -86,11 +86,10 @@ adjustDescriptorLimit(int needed, beast::Journal j) if (needed > available) { - j.fatal() << "Insufficient number of file descriptors: " << needed - << " are needed, but only " << available << " are available."; + j.fatal() << "Insufficient number of file descriptors: " << needed << " are needed, but only " << available + << " are available."; - std::cerr << "Insufficient number of file descriptors: " << needed - << " are needed, but only " << available + std::cerr << "Insufficient number of file descriptors: " << needed << " are needed, but only " << available << " are available.\n"; return false; @@ -103,69 +102,68 @@ adjustDescriptorLimit(int needed, beast::Journal j) void printHelp(po::options_description const& desc) { - std::cerr - << systemName() << "d [options] \n" - << desc << std::endl - << "Commands: \n" - " account_currencies []\n" - " account_info | []\n" - " account_lines |\"\" []\n" - " account_channels |\"\" []\n" - " account_objects []\n" - " account_offers | []\n" - " account_tx accountID [ledger_index_min [ledger_index_max " - "[limit " - "]]] [binary]\n" - " book_changes []\n" - " book_offers [ " - "[ [ []]]]]\n" - " can_delete [||now|always|never]\n" - " channel_authorize \n" - " channel_verify \n" - " connect []\n" - " consensus_info\n" - " deposit_authorized " - "[ [, ...]]\n" - " feature [ [accept|reject]]\n" - " fetch_info [clear]\n" - " gateway_balances [] [ [ " - " ]]\n" - " get_counts\n" - " json \n" - " ledger [|current|closed|validated] [full]\n" - " ledger_accept\n" - " ledger_cleaner\n" - " ledger_closed\n" - " ledger_current\n" - " ledger_request \n" - " log_level [[] ]\n" - " logrotate\n" - " manifest \n" - " peers\n" - " ping\n" - " random\n" - " peer_reservations_add []\n" - " peer_reservations_del \n" - " peer_reservations_list\n" - " ripple ...\n" - " ripple_path_find []\n" - " server_definitions []\n" - " server_info [counters]\n" - " server_state [counters]\n" - " sign [offline]\n" - " sign_for " - "[offline] []\n" - " stop\n" - " simulate [|] []\n" - " submit |[ ]\n" - " submit_multisigned \n" - " tx \n" - " validation_create [||]\n" - " validator_info\n" - " validators\n" - " validator_list_sites\n" - " version\n" - " wallet_propose []\n"; + std::cerr << systemName() << "d [options] \n" + << desc << std::endl + << "Commands: \n" + " account_currencies []\n" + " account_info | []\n" + " account_lines |\"\" []\n" + " account_channels |\"\" []\n" + " account_objects []\n" + " account_offers | []\n" + " account_tx accountID [ledger_index_min [ledger_index_max " + "[limit " + "]]] [binary]\n" + " book_changes []\n" + " book_offers [ " + "[ [ []]]]]\n" + " can_delete [||now|always|never]\n" + " channel_authorize \n" + " channel_verify \n" + " connect []\n" + " consensus_info\n" + " deposit_authorized " + "[ [, ...]]\n" + " feature [ [accept|reject]]\n" + " fetch_info [clear]\n" + " gateway_balances [] [ [ " + " ]]\n" + " get_counts\n" + " json \n" + " ledger [|current|closed|validated] [full]\n" + " ledger_accept\n" + " ledger_cleaner\n" + " ledger_closed\n" + " ledger_current\n" + " ledger_request \n" + " log_level [[] ]\n" + " logrotate\n" + " manifest \n" + " peers\n" + " ping\n" + " random\n" + " peer_reservations_add []\n" + " peer_reservations_del \n" + " peer_reservations_list\n" + " ripple ...\n" + " ripple_path_find []\n" + " server_definitions []\n" + " server_info [counters]\n" + " server_state [counters]\n" + " sign [offline]\n" + " sign_for " + "[offline] []\n" + " stop\n" + " simulate [|] []\n" + " submit |[ ]\n" + " submit_multisigned \n" + " tx \n" + " validation_create [||]\n" + " validator_info\n" + " validators\n" + " validator_list_sites\n" + " version\n" + " wallet_propose []\n"; } //------------------------------------------------------------------------------ @@ -188,8 +186,7 @@ public: std::for_each(v.begin(), v.end(), [this](std::string s) { boost::trim(s); if (selectors_.empty() || !s.empty()) - selectors_.emplace_back( - beast::unit_test::selector::automatch, s); + selectors_.emplace_back(beast::unit_test::selector::automatch, s); }); } @@ -227,9 +224,7 @@ anyMissing(Runner& runner, multi_selector const& pred) { auto const missing = pred.size() - runner.suites(); runner.add_failures(missing); - std::cout << "Failed: " << missing - << " filters did not match any existing test suites" - << std::endl; + std::cout << "Failed: " << missing << " filters did not match any existing test suites" << std::endl; return true; } return false; @@ -259,8 +254,7 @@ runUnitTests( multi_runner_child child_runner{num_jobs, quiet, log}; child_runner.arg(argument); multi_selector pred(pattern); - auto const any_failed = - child_runner.run_multi(pred) || anyMissing(child_runner, pred); + auto const any_failed = child_runner.run_multi(pred) || anyMissing(child_runner, pred); if (any_failed) return EXIT_FAILURE; @@ -281,9 +275,7 @@ runUnitTests( } for (std::size_t i = 0; i < num_jobs; ++i) - children.emplace_back( - boost::process::v1::exe = exe_name, - boost::process::v1::args = args); + children.emplace_back(boost::process::v1::exe = exe_name, boost::process::v1::args = args); int bad_child_exits = 0; int terminated_child_exits = 0; @@ -331,8 +323,7 @@ run(int argc, char** argv) { using namespace std; - beast::setCurrentThreadName( - "rippled: main " + BuildInfo::getVersionString()); + beast::setCurrentThreadName("xrpld-main"); po::variables_map vm; @@ -349,42 +340,27 @@ run(int argc, char** argv) // Set up option parsing. // po::options_description gen("General Options"); - gen.add_options()( - "conf", po::value(), "Specify the configuration file.")( - "debug", "Enable normally suppressed debug logging")( - "help,h", "Display this message.")( + gen.add_options()("conf", po::value(), "Specify the configuration file.")( + "debug", "Enable normally suppressed debug logging")("help,h", "Display this message.")( "newnodeid", "Generate a new node identity for this server.")( - "nodeid", - po::value(), - "Specify the node identity for this server.")( - "quorum", - po::value(), - "Override the minimum validation quorum.")( - "silent", "No output to the console after startup.")( - "standalone,a", "Run with no peers.")("verbose,v", "Verbose logging.") + "nodeid", po::value(), "Specify the node identity for this server.")( + "quorum", po::value(), "Override the minimum validation quorum.")( + "silent", "No output to the console after startup.")("standalone,a", "Run with no peers.")( + "verbose,v", "Verbose logging.") ("force_ledger_present_range", po::value(), "Specify the range of present ledgers for testing purposes. Min and " - "max values are comma separated.")( - "version", "Display the build version."); + "max values are comma separated.")("version", "Display the build version."); po::options_description data("Ledger/Data Options"); data.add_options()("import", importText.c_str())( - "ledger", - po::value(), - "Load the specified ledger and start from the value given.")( - "ledgerfile", - po::value(), - "Load the specified ledger file.")( - "load", "Load the current ledger from the local DB.")( - "net", "Get the initial ledger from the network.")( + "ledger", po::value(), "Load the specified ledger and start from the value given.")( + "ledgerfile", po::value(), "Load the specified ledger file.")( + "load", "Load the current ledger from the local DB.")("net", "Get the initial ledger from the network.")( "replay", "Replay a ledger close.")( - "trap_tx_hash", - po::value(), - "Trap a specific transaction during replay.")( - "start", "Start from a fresh Ledger.")( - "vacuum", "VACUUM the transaction db.")( + "trap_tx_hash", po::value(), "Trap a specific transaction during replay.")( + "start", "Start from a fresh Ledger.")("vacuum", "VACUUM the transaction db.")( "valid", "Consider the initial ledger a valid network ledger."); po::options_description rpc("RPC Client Options"); @@ -419,16 +395,12 @@ run(int argc, char** argv) "is made available to each suite that runs. Interpretation of the " "argument is handled individually by any suite that accesses it -- " "as such, it typically only make sense to provide this when running " - "a single suite.")( - "unittest-ipv6", - "Use IPv6 localhost when running unittests (default is IPv4).")( + "a single suite.")("unittest-ipv6", "Use IPv6 localhost when running unittests (default is IPv4).")( "unittest-log", "Force unit test log message output. Only useful in combination with " "--quiet, in which case log messages will print but suite/case names " "will not.")( - "unittest-jobs", - po::value(), - "Number of unittest jobs to run in parallel (child processes)."); + "unittest-jobs", po::value(), "Number of unittest jobs to run in parallel (child processes)."); #endif // ENABLE_TESTS // These are hidden options, not intended to be shown in the usage/help @@ -442,11 +414,9 @@ run(int argc, char** argv) "purpose, " "so this option is not needed for users") #ifdef ENABLE_TESTS - ("unittest-child", - "For internal use only when spawning child unit test processes.") + ("unittest-child", "For internal use only when spawning child unit test processes.") #else - ("unittest", "Disabled in this build.")( - "unittest-child", "Disabled in this build.") + ("unittest", "Disabled in this build.")("unittest-child", "Disabled in this build.") #endif // ENABLE_TESTS ("fg", "Deprecated: server always in foreground mode."); @@ -498,8 +468,7 @@ run(int argc, char** argv) if (vm.count("version")) { - std::cout << "rippled version " << BuildInfo::getVersionString() - << std::endl; + std::cout << "rippled version " << BuildInfo::getVersionString() << std::endl; #ifdef GIT_COMMIT_HASH std::cout << "Git commit hash: " << GIT_COMMIT_HASH << std::endl; #endif @@ -561,15 +530,10 @@ run(int argc, char** argv) auto config = std::make_unique(); - auto configFile = - vm.count("conf") ? vm["conf"].as() : std::string(); + auto configFile = vm.count("conf") ? vm["conf"].as() : std::string(); // config file, quiet flag. - config->setup( - configFile, - bool(vm.count("quiet")), - bool(vm.count("silent")), - bool(vm.count("standalone"))); + config->setup(configFile, bool(vm.count("quiet")), bool(vm.count("silent")), bool(vm.count("standalone"))); if (vm.count("vacuum")) { @@ -587,8 +551,7 @@ run(int argc, char** argv) } catch (std::exception const& e) { - std::cerr << "exception " << e.what() << " in function " << __func__ - << std::endl; + std::cerr << "exception " << e.what() << " in function " << __func__ << std::endl; return -1; } @@ -602,9 +565,7 @@ run(int argc, char** argv) auto const r = [&vm]() -> std::vector { std::vector strVec; boost::split( - strVec, - vm["force_ledger_present_range"].as(), - boost::algorithm::is_any_of(",")); + strVec, vm["force_ledger_present_range"].as(), boost::algorithm::is_any_of(",")); std::vector result; for (auto& s : strVec) { @@ -619,15 +580,13 @@ run(int argc, char** argv) { if (r[0] > r[1]) { - throw std::runtime_error( - "Invalid force_ledger_present_range parameter"); + throw std::runtime_error("Invalid force_ledger_present_range parameter"); } config->FORCED_LEDGER_RANGE_PRESENT.emplace(r[0], r[1]); } else { - throw std::runtime_error( - "Invalid force_ledger_present_range parameter"); + throw std::runtime_error("Invalid force_ledger_present_range parameter"); } } catch (std::exception const& e) @@ -642,7 +601,7 @@ run(int argc, char** argv) if (vm.count("start")) { - config->START_UP = Config::FRESH; + config->START_UP = StartUpType::FRESH; } if (vm.count("import")) @@ -653,7 +612,7 @@ run(int argc, char** argv) config->START_LEDGER = vm["ledger"].as(); if (vm.count("replay")) { - config->START_UP = Config::REPLAY; + config->START_UP = StartUpType::REPLAY; if (vm.count("trap_tx_hash")) { uint256 tmp = {}; @@ -672,36 +631,33 @@ run(int argc, char** argv) } } else - config->START_UP = Config::LOAD; + config->START_UP = StartUpType::LOAD; } else if (vm.count("ledgerfile")) { config->START_LEDGER = vm["ledgerfile"].as(); - config->START_UP = Config::LOAD_FILE; + config->START_UP = StartUpType::LOAD_FILE; } else if (vm.count("load") || config->FAST_LOAD) { - config->START_UP = Config::LOAD; + config->START_UP = StartUpType::LOAD; } if (vm.count("trap_tx_hash") && vm.count("replay") == 0) { - std::cerr << "Cannot use trap option without replay option" - << std::endl; + std::cerr << "Cannot use trap option without replay option" << std::endl; return -1; } if (vm.count("net") && !config->FAST_LOAD) { - if ((config->START_UP == Config::LOAD) || - (config->START_UP == Config::REPLAY)) + if ((config->START_UP == StartUpType::LOAD) || (config->START_UP == StartUpType::REPLAY)) { - std::cerr << "Net and load/replay options are incompatible" - << std::endl; + std::cerr << "Net and load/replay options are incompatible" << std::endl; return -1; } - config->START_UP = Config::NETWORK; + config->START_UP = StartUpType::NETWORK; } if (vm.count("valid")) @@ -713,12 +669,10 @@ run(int argc, char** argv) // happen after the config file is loaded. if (vm.count("rpc_ip")) { - auto endpoint = beast::IP::Endpoint::from_string_checked( - vm["rpc_ip"].as()); + auto endpoint = beast::IP::Endpoint::from_string_checked(vm["rpc_ip"].as()); if (!endpoint) { - std::cerr << "Invalid rpc_ip = " << vm["rpc_ip"].as() - << "\n"; + std::cerr << "Invalid rpc_ip = " << vm["rpc_ip"].as() << "\n"; return -1; } @@ -730,8 +684,7 @@ run(int argc, char** argv) std::cerr << "WARNING: using deprecated rpc_port param.\n"; try { - endpoint = - endpoint->at_port(vm["rpc_port"].as()); + endpoint = endpoint->at_port(vm["rpc_port"].as()); if (endpoint->port() == 0) throw std::domain_error("0"); } @@ -760,8 +713,7 @@ run(int argc, char** argv) } catch (std::exception const& e) { - std::cerr << "Invalid value specified for --quorum (" << e.what() - << ")\n"; + std::cerr << "Invalid value specified for --quorum (" << e.what() << ")\n"; return -1; } } @@ -784,13 +736,12 @@ run(int argc, char** argv) // say 1.7 or higher if (config->had_trailing_comments()) { - JLOG(logs->journal("Application").warn()) - << "Trailing comments were seen in your config file. " - << "The treatment of inline/trailing comments has changed " - "recently. " - << "Any `#` characters NOT intended to delimit comments should " - "be " - << "preceded by a \\"; + JLOG(logs->journal("Application").warn()) << "Trailing comments were seen in your config file. " + << "The treatment of inline/trailing comments has changed " + "recently. " + << "Any `#` characters NOT intended to delimit comments should " + "be " + << "preceded by a \\"; } // We want at least 1024 file descriptors. We'll @@ -801,16 +752,14 @@ run(int argc, char** argv) if (vm.count("debug")) setDebugLogSink(logs->makeSink("Debug", beast::severities::kTrace)); - auto app = make_Application( - std::move(config), std::move(logs), std::make_unique()); + auto app = make_Application(std::move(config), std::move(logs), std::make_unique()); if (!app->setup(vm)) return -1; // With our configuration parsed, ensure we have // enough file descriptors available: - if (!adjustDescriptorLimit( - app->fdRequired(), app->logs().journal("Application"))) + if (!adjustDescriptorLimit(app->fdRequired(), app->logs().journal("Application"))) return -1; // Start the server @@ -824,8 +773,7 @@ run(int argc, char** argv) // We have an RPC command to process: beast::setCurrentThreadName("rippled: rpc"); - return RPCCall::fromCommandLine( - *config, vm["parameters"].as>(), *logs); + return RPCCall::fromCommandLine(*config, vm["parameters"].as>(), *logs); // LCOV_EXCL_STOP } diff --git a/src/xrpld/app/main/NodeIdentity.cpp b/src/xrpld/app/main/NodeIdentity.cpp index 73ef3f0152..3019caeb31 100644 --- a/src/xrpld/app/main/NodeIdentity.cpp +++ b/src/xrpld/app/main/NodeIdentity.cpp @@ -1,15 +1,14 @@ #include #include -#include #include #include +#include + namespace xrpl { std::pair -getNodeIdentity( - Application& app, - boost::program_options::variables_map const& cmdline) +getNodeIdentity(Application& app, boost::program_options::variables_map const& cmdline) { std::optional seed; @@ -22,12 +21,10 @@ getNodeIdentity( } else if (app.config().exists(SECTION_NODE_SEED)) { - seed = parseBase58( - app.config().section(SECTION_NODE_SEED).lines().front()); + seed = parseBase58(app.config().section(SECTION_NODE_SEED).lines().front()); if (!seed) - Throw("Invalid [" SECTION_NODE_SEED - "] in configuration file"); + Throw("Invalid [" SECTION_NODE_SEED "] in configuration file"); } if (seed) diff --git a/src/xrpld/app/main/NodeIdentity.h b/src/xrpld/app/main/NodeIdentity.h index 7fdb748033..bebd5c261d 100644 --- a/src/xrpld/app/main/NodeIdentity.h +++ b/src/xrpld/app/main/NodeIdentity.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_MAIN_NODEIDENTITY_H_INCLUDED -#define XRPL_APP_MAIN_NODEIDENTITY_H_INCLUDED +#pragma once #include @@ -16,10 +15,6 @@ namespace xrpl { @param cmdline The command line parameters passed into the application. */ std::pair -getNodeIdentity( - Application& app, - boost::program_options::variables_map const& cmdline); +getNodeIdentity(Application& app, boost::program_options::variables_map const& cmdline); } // namespace xrpl - -#endif diff --git a/src/xrpld/app/main/NodeStoreScheduler.cpp b/src/xrpld/app/main/NodeStoreScheduler.cpp index 221c1f098e..1b3ff4ab03 100644 --- a/src/xrpld/app/main/NodeStoreScheduler.cpp +++ b/src/xrpld/app/main/NodeStoreScheduler.cpp @@ -12,9 +12,7 @@ NodeStoreScheduler::scheduleTask(NodeStore::Task& task) if (jobQueue_.isStopped()) return; - if (!jobQueue_.addJob(jtWRITE, "NodeObject::store", [&task]() { - task.performScheduledTask(); - })) + if (!jobQueue_.addJob(jtWRITE, "NObjStore", [&task]() { task.performScheduledTask(); })) { // Job not added, presumably because we're shutting down. // Recover by executing the task synchronously. @@ -29,10 +27,7 @@ NodeStoreScheduler::onFetch(NodeStore::FetchReport const& report) return; jobQueue_.addLoadEvents( - report.fetchType == NodeStore::FetchType::async ? jtNS_ASYNC_READ - : jtNS_SYNC_READ, - 1, - report.elapsed); + report.fetchType == NodeStore::FetchType::async ? jtNS_ASYNC_READ : jtNS_SYNC_READ, 1, report.elapsed); } void diff --git a/src/xrpld/app/main/NodeStoreScheduler.h b/src/xrpld/app/main/NodeStoreScheduler.h index 0214b76660..19e8d9d212 100644 --- a/src/xrpld/app/main/NodeStoreScheduler.h +++ b/src/xrpld/app/main/NodeStoreScheduler.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_MAIN_NODESTORESCHEDULER_H_INCLUDED -#define XRPL_APP_MAIN_NODESTORESCHEDULER_H_INCLUDED +#pragma once #include #include @@ -24,5 +23,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/src/xrpld/app/main/Tuning.h b/src/xrpld/app/main/Tuning.h index 25cc2ef75d..0f612b1b1c 100644 --- a/src/xrpld/app/main/Tuning.h +++ b/src/xrpld/app/main/Tuning.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_MAIN_TUNING_H_INCLUDED -#define XRPL_APP_MAIN_TUNING_H_INCLUDED +#pragma once #include @@ -11,5 +10,3 @@ constexpr std::chrono::seconds fullBelowExpiration = std::chrono::minutes{10}; constexpr std::size_t maxPoppedTransactions = 10; } // namespace xrpl - -#endif diff --git a/src/xrpld/app/misc/AMMHelpers.h b/src/xrpld/app/misc/AMMHelpers.h index 3a33f49ee4..cde485f5dc 100644 --- a/src/xrpld/app/misc/AMMHelpers.h +++ b/src/xrpld/app/misc/AMMHelpers.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_MISC_AMMHELPERS_H_INCLUDED -#define XRPL_APP_MISC_AMMHELPERS_H_INCLUDED +#pragma once #include #include @@ -37,10 +36,7 @@ enum class IsDeposit : bool { No = false, Yes = true }; * @return LP Tokens as IOU */ STAmount -ammLPTokens( - STAmount const& asset1, - STAmount const& asset2, - Issue const& lptIssue); +ammLPTokens(STAmount const& asset1, STAmount const& asset2, Issue const& lptIssue); /** Calculate LP Tokens given asset's deposit amount. * @param asset1Balance current AMM asset1 balance @@ -64,11 +60,7 @@ lpTokensOut( * @return */ STAmount -ammAssetIn( - STAmount const& asset1Balance, - STAmount const& lptAMMBalance, - STAmount const& lpTokens, - std::uint16_t tfee); +ammAssetIn(STAmount const& asset1Balance, STAmount const& lptAMMBalance, STAmount const& lpTokens, std::uint16_t tfee); /** Calculate LP Tokens given asset's withdraw amount. Return 0 * if can't calculate. @@ -93,11 +85,7 @@ lpTokensIn( * @return calculated asset amount */ STAmount -ammAssetOut( - STAmount const& assetBalance, - STAmount const& lptAMMBalance, - STAmount const& lpTokens, - std::uint16_t tfee); +ammAssetOut(STAmount const& assetBalance, STAmount const& lptAMMBalance, STAmount const& lpTokens, std::uint16_t tfee); /** Check if the relative distance between the qualities * is within the requested distance. @@ -107,10 +95,7 @@ ammAssetOut( * @return true if within dist, false otherwise */ inline bool -withinRelativeDistance( - Quality const& calcQuality, - Quality const& reqQuality, - Number const& dist) +withinRelativeDistance(Quality const& calcQuality, Quality const& reqQuality, Number const& dist) { if (calcQuality == reqQuality) return true; @@ -174,10 +159,7 @@ solveQuadraticEqSmallest(Number const& a, Number const& b, Number const& c); */ template std::optional> -getAMMOfferStartWithTakerGets( - TAmounts const& pool, - Quality const& targetQuality, - std::uint16_t const& tfee) +getAMMOfferStartWithTakerGets(TAmounts const& pool, Quality const& targetQuality, std::uint16_t const& tfee) { if (targetQuality.rate() == beast::zero) return std::nullopt; @@ -186,15 +168,13 @@ getAMMOfferStartWithTakerGets( auto const f = feeMult(tfee); auto const a = 1; auto const b = pool.in * (1 - 1 / f) / targetQuality.rate() - 2 * pool.out; - auto const c = - pool.out * pool.out - (pool.in * pool.out) / targetQuality.rate(); + auto const c = pool.out * pool.out - (pool.in * pool.out) / targetQuality.rate(); auto nTakerGets = solveQuadraticEqSmallest(a, b, c); if (!nTakerGets || *nTakerGets <= 0) return std::nullopt; // LCOV_EXCL_LINE - auto const nTakerGetsConstraint = - pool.out - pool.in / (targetQuality.rate() * f); + auto const nTakerGetsConstraint = pool.out - pool.in / (targetQuality.rate() * f); if (nTakerGetsConstraint <= 0) return std::nullopt; @@ -205,16 +185,13 @@ getAMMOfferStartWithTakerGets( auto getAmounts = [&pool, &tfee](Number const& nTakerGetsProposed) { // Round downward to minimize the offer and to maximize the quality. // This has the most impact when takerGets is XRP. - auto const takerGets = toAmount( - getIssue(pool.out), nTakerGetsProposed, Number::downward); - return TAmounts{ - swapAssetOut(pool, takerGets, tfee), takerGets}; + auto const takerGets = toAmount(getIssue(pool.out), nTakerGetsProposed, Number::downward); + return TAmounts{swapAssetOut(pool, takerGets, tfee), takerGets}; }; // Try to reduce the offer size to improve the quality. // The quality might still not match the targetQuality for a tiny offer. - if (auto const amounts = getAmounts(*nTakerGets); - Quality{amounts} < targetQuality) + if (auto const amounts = getAmounts(*nTakerGets); Quality{amounts} < targetQuality) return getAmounts(detail::reduceOffer(amounts.out)); else return amounts; @@ -245,10 +222,7 @@ getAMMOfferStartWithTakerGets( */ template std::optional> -getAMMOfferStartWithTakerPays( - TAmounts const& pool, - Quality const& targetQuality, - std::uint16_t tfee) +getAMMOfferStartWithTakerPays(TAmounts const& pool, Quality const& targetQuality, std::uint16_t tfee) { if (targetQuality.rate() == beast::zero) return std::nullopt; @@ -257,15 +231,13 @@ getAMMOfferStartWithTakerPays( auto const f = feeMult(tfee); auto const& a = f; auto const b = pool.in * (1 + f); - auto const c = - pool.in * pool.in - pool.in * pool.out * targetQuality.rate(); + auto const c = pool.in * pool.in - pool.in * pool.out * targetQuality.rate(); auto nTakerPays = solveQuadraticEqSmallest(a, b, c); if (!nTakerPays || nTakerPays <= 0) return std::nullopt; // LCOV_EXCL_LINE - auto const nTakerPaysConstraint = - pool.out * targetQuality.rate() - pool.in / f; + auto const nTakerPaysConstraint = pool.out * targetQuality.rate() - pool.in / f; if (nTakerPaysConstraint <= 0) return std::nullopt; @@ -276,16 +248,13 @@ getAMMOfferStartWithTakerPays( auto getAmounts = [&pool, &tfee](Number const& nTakerPaysProposed) { // Round downward to minimize the offer and to maximize the quality. // This has the most impact when takerPays is XRP. - auto const takerPays = toAmount( - getIssue(pool.in), nTakerPaysProposed, Number::downward); - return TAmounts{ - takerPays, swapAssetIn(pool, takerPays, tfee)}; + auto const takerPays = toAmount(getIssue(pool.in), nTakerPaysProposed, Number::downward); + return TAmounts{takerPays, swapAssetIn(pool, takerPays, tfee)}; }; // Try to reduce the offer size to improve the quality. // The quality might still not match the targetQuality for a tiny offer. - if (auto const amounts = getAmounts(*nTakerPays); - Quality{amounts} < targetQuality) + if (auto const amounts = getAmounts(*nTakerPays); Quality{amounts} < targetQuality) return getAmounts(detail::reduceOffer(amounts.in)); else return amounts; @@ -327,61 +296,48 @@ changeSpotPriceQuality( auto const f = feeMult(tfee); // 1 - fee auto const& a = f; auto const b = pool.in * (1 + f); - Number const c = - pool.in * pool.in - pool.in * pool.out * quality.rate(); + Number const c = pool.in * pool.in - pool.in * pool.out * quality.rate(); if (auto const res = b * b - 4 * a * c; res < 0) return std::nullopt; // LCOV_EXCL_LINE - else if (auto const nTakerPaysPropose = (-b + root2(res)) / (2 * a); - nTakerPaysPropose > 0) + else if (auto const nTakerPaysPropose = (-b + root2(res)) / (2 * a); nTakerPaysPropose > 0) { auto const nTakerPays = [&]() { // The fee might make the AMM offer quality less than CLOB // quality. Therefore, AMM offer has to satisfy this constraint: // o / i >= q. Substituting o with swapAssetIn() gives: i <= O / // q - I / (1 - fee). - auto const nTakerPaysConstraint = - pool.out * quality.rate() - pool.in / f; + auto const nTakerPaysConstraint = pool.out * quality.rate() - pool.in / f; if (nTakerPaysPropose > nTakerPaysConstraint) return nTakerPaysConstraint; return nTakerPaysPropose; }(); if (nTakerPays <= 0) { - JLOG(j.trace()) - << "changeSpotPriceQuality calc failed: " - << to_string(pool.in) << " " << to_string(pool.out) << " " - << quality << " " << tfee; + JLOG(j.trace()) << "changeSpotPriceQuality calc failed: " << to_string(pool.in) << " " + << to_string(pool.out) << " " << quality << " " << tfee; return std::nullopt; } - auto const takerPays = - toAmount(getIssue(pool.in), nTakerPays, Number::upward); + auto const takerPays = toAmount(getIssue(pool.in), nTakerPays, Number::upward); // should not fail - if (auto const amounts = - TAmounts{ - takerPays, swapAssetIn(pool, takerPays, tfee)}; - Quality{amounts} < quality && - !withinRelativeDistance( - Quality{amounts}, quality, Number(1, -7))) + if (auto const amounts = TAmounts{takerPays, swapAssetIn(pool, takerPays, tfee)}; + Quality{amounts} < quality && !withinRelativeDistance(Quality{amounts}, quality, Number(1, -7))) { - JLOG(j.error()) - << "changeSpotPriceQuality failed: " << to_string(pool.in) - << " " << to_string(pool.out) << " " - << " " << quality << " " << tfee << " " - << to_string(amounts.in) << " " << to_string(amounts.out); + JLOG(j.error()) << "changeSpotPriceQuality failed: " << to_string(pool.in) << " " << to_string(pool.out) + << " " + << " " << quality << " " << tfee << " " << to_string(amounts.in) << " " + << to_string(amounts.out); Throw("changeSpotPriceQuality failed"); } else { - JLOG(j.trace()) - << "changeSpotPriceQuality succeeded: " - << to_string(pool.in) << " " << to_string(pool.out) << " " - << " " << quality << " " << tfee << " " - << to_string(amounts.in) << " " << to_string(amounts.out); + JLOG(j.trace()) << "changeSpotPriceQuality succeeded: " << to_string(pool.in) << " " + << to_string(pool.out) << " " + << " " << quality << " " << tfee << " " << to_string(amounts.in) << " " + << to_string(amounts.out); return amounts; } } - JLOG(j.trace()) << "changeSpotPriceQuality calc failed: " - << to_string(pool.in) << " " << to_string(pool.out) + JLOG(j.trace()) << "changeSpotPriceQuality calc failed: " << to_string(pool.in) << " " << to_string(pool.out) << " " << quality << " " << tfee; return std::nullopt; } @@ -395,26 +351,20 @@ changeSpotPriceQuality( }(); if (!amounts) { - JLOG(j.trace()) << "changeSpotPrice calc failed: " << to_string(pool.in) - << " " << to_string(pool.out) << " " << quality << " " - << tfee << std::endl; + JLOG(j.trace()) << "changeSpotPrice calc failed: " << to_string(pool.in) << " " << to_string(pool.out) << " " + << quality << " " << tfee << std::endl; return std::nullopt; } if (Quality{*amounts} < quality) { - JLOG(j.error()) << "changeSpotPriceQuality failed: " - << to_string(pool.in) << " " << to_string(pool.out) - << " " << quality << " " << tfee << " " - << to_string(amounts->in) << " " - << to_string(amounts->out); + JLOG(j.error()) << "changeSpotPriceQuality failed: " << to_string(pool.in) << " " << to_string(pool.out) << " " + << quality << " " << tfee << " " << to_string(amounts->in) << " " << to_string(amounts->out); return std::nullopt; } - JLOG(j.trace()) << "changeSpotPriceQuality succeeded: " - << to_string(pool.in) << " " << to_string(pool.out) << " " - << " " << quality << " " << tfee << " " - << to_string(amounts->in) << " " << to_string(amounts->out); + JLOG(j.trace()) << "changeSpotPriceQuality succeeded: " << to_string(pool.in) << " " << to_string(pool.out) << " " + << " " << quality << " " << tfee << " " << to_string(amounts->in) << " " << to_string(amounts->out); return amounts; } @@ -442,13 +392,9 @@ changeSpotPriceQuality( */ template TOut -swapAssetIn( - TAmounts const& pool, - TIn const& assetIn, - std::uint16_t tfee) +swapAssetIn(TAmounts const& pool, TIn const& assetIn, std::uint16_t tfee) { - if (auto const& rules = getCurrentTransactionRules(); - rules && rules->enabled(fixAMMv1_1)) + if (auto const& rules = getCurrentTransactionRules(); rules && rules->enabled(fixAMMv1_1)) { // set rounding to always favor the amm. Clip to zero. // calculate: @@ -498,8 +444,7 @@ swapAssetIn( { return toAmount( getIssue(pool.out), - pool.out - - (pool.in * pool.out) / (pool.in + assetIn * feeMult(tfee)), + pool.out - (pool.in * pool.out) / (pool.in + assetIn * feeMult(tfee)), Number::downward); } } @@ -515,13 +460,9 @@ swapAssetIn( */ template TIn -swapAssetOut( - TAmounts const& pool, - TOut const& assetOut, - std::uint16_t tfee) +swapAssetOut(TAmounts const& pool, TOut const& assetOut, std::uint16_t tfee) { - if (auto const& rules = getCurrentTransactionRules(); - rules && rules->enabled(fixAMMv1_1)) + if (auto const& rules = getCurrentTransactionRules(); rules && rules->enabled(fixAMMv1_1)) { // set rounding to always favor the amm. Clip to zero. // calculate: @@ -571,8 +512,7 @@ swapAssetOut( { return toAmount( getIssue(pool.in), - ((pool.in * pool.out) / (pool.out - assetOut) - pool.in) / - feeMult(tfee), + ((pool.in * pool.out) / (pool.out - assetOut) - pool.in) / feeMult(tfee), Number::upward); } } @@ -594,10 +534,7 @@ square(Number const& n); * @param isDeposit Yes if deposit, No if withdraw */ STAmount -adjustLPTokens( - STAmount const& lptAMMBalance, - STAmount const& lpTokens, - IsDeposit isDeposit); +adjustLPTokens(STAmount const& lptAMMBalance, STAmount const& lpTokens, IsDeposit isDeposit); /** Calls adjustLPTokens() and adjusts deposit or withdraw amounts if * the adjusted LP tokens are less than the provided LP tokens. @@ -656,11 +593,7 @@ getAssetRounding(IsDeposit isDeposit) */ template STAmount -getRoundedAsset( - Rules const& rules, - STAmount const& balance, - A const& frac, - IsDeposit isDeposit) +getRoundedAsset(Rules const& rules, STAmount const& balance, A const& frac, IsDeposit isDeposit) { if (!rules.enabled(fixAMMv1_3)) { @@ -698,11 +631,7 @@ getRoundedAsset( * digits) when adding the lptokens to the balance. */ STAmount -getRoundedLPTokens( - Rules const& rules, - STAmount const& balance, - Number const& frac, - IsDeposit isDeposit); +getRoundedLPTokens(Rules const& rules, STAmount const& balance, Number const& frac, IsDeposit isDeposit); /** Round AMM single deposit/withdrawal LPToken amount. * The lambda's are used to delay evaluation until the function is executed @@ -755,12 +684,6 @@ adjustAssetOutByTokens( * is used to adjust equal deposit/withdraw amount. */ Number -adjustFracByTokens( - Rules const& rules, - STAmount const& lptAMMBalance, - STAmount const& tokens, - Number const& frac); +adjustFracByTokens(Rules const& rules, STAmount const& lptAMMBalance, STAmount const& tokens, Number const& frac); } // namespace xrpl - -#endif // XRPL_APP_MISC_AMMHELPERS_H_INCLUDED diff --git a/src/xrpld/app/misc/AMMUtils.h b/src/xrpld/app/misc/AMMUtils.h index 266f50bb87..c97397a141 100644 --- a/src/xrpld/app/misc/AMMUtils.h +++ b/src/xrpld/app/misc/AMMUtils.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_MISC_AMMUTILS_H_INCLUDED -#define XRPL_APP_MISC_AMMUTILS_H_INCLUDED +#pragma once #include #include @@ -51,39 +50,25 @@ ammLPHolds( beast::Journal const j); STAmount -ammLPHolds( - ReadView const& view, - SLE const& ammSle, - AccountID const& lpAccount, - beast::Journal const j); +ammLPHolds(ReadView const& view, SLE const& ammSle, AccountID const& lpAccount, beast::Journal const j); /** Get AMM trading fee for the given account. The fee is discounted * if the account is the auction slot owner or one of the slot's authorized * accounts. */ std::uint16_t -getTradingFee( - ReadView const& view, - SLE const& ammSle, - AccountID const& account); +getTradingFee(ReadView const& view, SLE const& ammSle, AccountID const& account); /** Returns total amount held by AMM for the given token. */ STAmount -ammAccountHolds( - ReadView const& view, - AccountID const& ammAccountID, - Issue const& issue); +ammAccountHolds(ReadView const& view, AccountID const& ammAccountID, Issue const& issue); /** Delete trustlines to AMM. If all trustlines are deleted then * AMM object and account are deleted. Otherwise tecIMPCOMPLETE is returned. */ TER -deleteAMMAccount( - Sandbox& view, - Issue const& asset, - Issue const& asset2, - beast::Journal j); +deleteAMMAccount(Sandbox& view, Issue const& asset, Issue const& asset2, beast::Journal j); /** Initialize Auction and Voting slots and set the trading/discounted fee. */ @@ -100,10 +85,7 @@ initializeFeeAuctionVote( * for instance Liquidity Provider has more than one LPToken trustline. */ Expected -isOnlyLiquidityProvider( - ReadView const& view, - Issue const& ammIssue, - AccountID const& lpAccount); +isOnlyLiquidityProvider(ReadView const& view, Issue const& ammIssue, AccountID const& lpAccount); /** Due to rounding, the LPTokenBalance of the last LP might * not match the LP's trustline balance. If it's within the tolerance, @@ -117,5 +99,3 @@ verifyAndAdjustLPTokenBalance( AccountID const& account); } // namespace xrpl - -#endif // XRPL_APP_MISC_AMMUTILS_H_INCLUDED diff --git a/src/xrpld/app/misc/AmendmentTable.h b/src/xrpld/app/misc/AmendmentTable.h index 0265e0127f..bfef818b0a 100644 --- a/src/xrpld/app/misc/AmendmentTable.h +++ b/src/xrpld/app/misc/AmendmentTable.h @@ -1,9 +1,9 @@ -#ifndef XRPL_APP_MISC_AMENDMENTTABLE_H_INCLUDED -#define XRPL_APP_MISC_AMENDMENTTABLE_H_INCLUDED +#pragma once #include #include +#include #include #include #include @@ -22,8 +22,7 @@ public: struct FeatureInfo { FeatureInfo() = delete; - FeatureInfo(std::string const& n, uint256 const& f, VoteBehavior v) - : name(n), feature(f), vote(v) + FeatureInfo(std::string const& n, uint256 const& f, VoteBehavior v) : name(n), feature(f), vote(v) { } @@ -71,8 +70,7 @@ public: /** Called when a new fully-validated ledger is accepted. */ void - doValidatedLedger( - std::shared_ptr const& lastValidatedLedger) + doValidatedLedger(std::shared_ptr const& lastValidatedLedger) { if (needValidatedLedger(lastValidatedLedger->seq())) doValidatedLedger( @@ -143,34 +141,30 @@ public: // Inject appropriate pseudo-transactions for (auto const& it : actions) { - STTx amendTx( - ttAMENDMENT, - [&it, seq = lastClosedLedger->seq() + 1](auto& obj) { - obj.setAccountID(sfAccount, AccountID()); - obj.setFieldH256(sfAmendment, it.first); - obj.setFieldU32(sfLedgerSequence, seq); + STTx amendTx(ttAMENDMENT, [&it, seq = lastClosedLedger->seq() + 1](auto& obj) { + obj.setAccountID(sfAccount, AccountID()); + obj.setFieldH256(sfAmendment, it.first); + obj.setFieldU32(sfLedgerSequence, seq); - if (it.second != 0) - obj.setFieldU32(sfFlags, it.second); - }); + if (it.second != 0) + obj.setFieldU32(sfFlags, it.second); + }); Serializer s; amendTx.add(s); - JLOG(j.debug()) << "Amendments: Adding pseudo-transaction: " - << amendTx.getTransactionID() << ": " + JLOG(j.debug()) << "Amendments: Adding pseudo-transaction: " << amendTx.getTransactionID() << ": " << strHex(s.slice()) << ": " << amendTx; initialPosition->addGiveItem( - SHAMapNodeType::tnTRANSACTION_NM, - make_shamapitem(amendTx.getTransactionID(), s.slice())); + SHAMapNodeType::tnTRANSACTION_NM, make_shamapitem(amendTx.getTransactionID(), s.slice())); } } }; std::unique_ptr make_AmendmentTable( - Application& app, + ServiceRegistry& registry, std::chrono::seconds majorityTime, std::vector const& supported, Section const& enabled, @@ -178,5 +172,3 @@ make_AmendmentTable( beast::Journal journal); } // namespace xrpl - -#endif diff --git a/src/xrpld/app/misc/CanonicalTXSet.cpp b/src/xrpld/app/misc/CanonicalTXSet.cpp index ac1b86e62f..6e6102afe7 100644 --- a/src/xrpld/app/misc/CanonicalTXSet.cpp +++ b/src/xrpld/app/misc/CanonicalTXSet.cpp @@ -33,10 +33,7 @@ void CanonicalTXSet::insert(std::shared_ptr const& txn) { map_.insert(std::make_pair( - Key(accountKey(txn->getAccountID(sfAccount)), - txn->getSeqProxy(), - txn->getTransactionID()), - txn)); + Key(accountKey(txn->getAccountID(sfAccount)), txn->getSeqProxy(), txn->getTransactionID()), txn)); } std::shared_ptr @@ -59,10 +56,8 @@ CanonicalTXSet::popAcctTransaction(std::shared_ptr const& tx) auto const seqProxy = tx->getSeqProxy(); Key const after(effectiveAccount, seqProxy, beast::zero); auto const itrNext{map_.lower_bound(after)}; - if (itrNext != map_.end() && - itrNext->first.getAccount() == effectiveAccount && - (!itrNext->second->getSeqProxy().isSeq() || - itrNext->second->getSeqProxy().value() == seqProxy.value() + 1)) + if (itrNext != map_.end() && itrNext->first.getAccount() == effectiveAccount && + (!itrNext->second->getSeqProxy().isSeq() || itrNext->second->getSeqProxy().value() == seqProxy.value() + 1)) { result = std::move(itrNext->second); map_.erase(itrNext); diff --git a/src/xrpld/app/misc/CanonicalTXSet.h b/src/xrpld/app/misc/CanonicalTXSet.h index 8d0461a845..45f58b5701 100644 --- a/src/xrpld/app/misc/CanonicalTXSet.h +++ b/src/xrpld/app/misc/CanonicalTXSet.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_MISC_CANONICALTXSET_H_INCLUDED -#define XRPL_APP_MISC_CANONICALTXSET_H_INCLUDED +#pragma once #include #include @@ -86,8 +85,7 @@ private: accountKey(AccountID const& account); public: - using const_iterator = - std::map>::const_iterator; + using const_iterator = std::map>::const_iterator; public: explicit CanonicalTXSet(LedgerHash const& saltHash) : salt_(saltHash) @@ -157,5 +155,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/src/xrpld/app/misc/DelegateUtils.h b/src/xrpld/app/misc/DelegateUtils.h index 37d9195a82..78ccc46d0b 100644 --- a/src/xrpld/app/misc/DelegateUtils.h +++ b/src/xrpld/app/misc/DelegateUtils.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_MISC_DELEGATEUTILS_H_INCLUDED -#define XRPL_APP_MISC_DELEGATEUTILS_H_INCLUDED +#pragma once #include #include @@ -34,5 +33,3 @@ loadGranularPermission( std::unordered_set& granularPermissions); } // namespace xrpl - -#endif // XRPL_APP_MISC_DELEGATEUTILS_H_INCLUDED diff --git a/src/xrpld/app/misc/DeliverMax.h b/src/xrpld/app/misc/DeliverMax.h index e9455354f8..1b4241f091 100644 --- a/src/xrpld/app/misc/DeliverMax.h +++ b/src/xrpld/app/misc/DeliverMax.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_MISC_DELIVERMAX_H_INCLUDED -#define XRPL_APP_MISC_DELIVERMAX_H_INCLUDED +#pragma once #include @@ -27,5 +26,3 @@ insertDeliverMax(Json::Value& tx_json, TxType txnType, unsigned int apiVersion); } // namespace RPC } // namespace xrpl - -#endif diff --git a/src/xrpld/app/misc/FeeVote.h b/src/xrpld/app/misc/FeeVote.h index aed64be2c2..3ecf474867 100644 --- a/src/xrpld/app/misc/FeeVote.h +++ b/src/xrpld/app/misc/FeeVote.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_MISC_FEEVOTE_H_INCLUDED -#define XRPL_APP_MISC_FEEVOTE_H_INCLUDED +#pragma once #include #include @@ -19,10 +18,7 @@ public: @param baseValidation */ virtual void - doValidation( - Fees const& lastFees, - Rules const& rules, - STValidation& val) = 0; + doValidation(Fees const& lastFees, Rules const& rules, STValidation& val) = 0; /** Cast our local vote on the fee. @@ -45,5 +41,3 @@ std::unique_ptr make_FeeVote(FeeSetup const& setup, beast::Journal journal); } // namespace xrpl - -#endif diff --git a/src/xrpld/app/misc/FeeVoteImpl.cpp b/src/xrpld/app/misc/FeeVoteImpl.cpp index 08a9abf2db..4c38b561f6 100644 --- a/src/xrpld/app/misc/FeeVoteImpl.cpp +++ b/src/xrpld/app/misc/FeeVoteImpl.cpp @@ -18,8 +18,7 @@ private: std::map voteMap_; public: - VotableValue(value_type current, value_type target) - : current_(current), target_(target) + VotableValue(value_type current, value_type target) : current_(current), target_(target) { // Add our vote ++voteMap_[target_]; @@ -55,8 +54,7 @@ VotableValue::getVotes() const -> std::pair for (auto const& [key, val] : voteMap_) { // Take most voted value between current and target, inclusive - if ((key <= std::max(target_, current_)) && - (key >= std::min(target_, current_)) && (val > weight)) + if ((key <= std::max(target_, current_)) && (key >= std::min(target_, current_)) && (val > weight)) { ourVote = key; weight = val; @@ -80,8 +78,7 @@ public: FeeVoteImpl(FeeSetup const& setup, beast::Journal journal); void - doValidation(Fees const& lastFees, Rules const& rules, STValidation& val) - override; + doValidation(Fees const& lastFees, Rules const& rules, STValidation& val) override; void doVoting( @@ -92,55 +89,34 @@ public: //-------------------------------------------------------------------------- -FeeVoteImpl::FeeVoteImpl(FeeSetup const& setup, beast::Journal journal) - : target_(setup), journal_(journal) +FeeVoteImpl::FeeVoteImpl(FeeSetup const& setup, beast::Journal journal) : target_(setup), journal_(journal) { } void -FeeVoteImpl::doValidation( - Fees const& lastFees, - Rules const& rules, - STValidation& v) +FeeVoteImpl::doValidation(Fees const& lastFees, Rules const& rules, STValidation& v) { // Values should always be in a valid range (because the voting process // will ignore out-of-range values) but if we detect such a case, we do // not send a value. if (rules.enabled(featureXRPFees)) { - auto vote = [&v, this]( - auto const current, - XRPAmount target, - char const* name, - auto const& sfield) { + auto vote = [&v, this](auto const current, XRPAmount target, char const* name, auto const& sfield) { if (current != target) { - JLOG(journal_.info()) - << "Voting for " << name << " of " << target; + JLOG(journal_.info()) << "Voting for " << name << " of " << target; v[sfield] = target; } }; vote(lastFees.base, target_.reference_fee, "base fee", sfBaseFeeDrops); - vote( - lastFees.reserve, - target_.account_reserve, - "base reserve", - sfReserveBaseDrops); - vote( - lastFees.increment, - target_.owner_reserve, - "reserve increment", - sfReserveIncrementDrops); + vote(lastFees.reserve, target_.account_reserve, "base reserve", sfReserveBaseDrops); + vote(lastFees.increment, target_.owner_reserve, "reserve increment", sfReserveIncrementDrops); } else { - auto to32 = [](XRPAmount target) { - return target.dropsAs(); - }; - auto to64 = [](XRPAmount target) { - return target.dropsAs(); - }; + auto to32 = [](XRPAmount target) { return target.dropsAs(); }; + auto to64 = [](XRPAmount target) { return target.dropsAs(); }; auto vote = [&v, this]( auto const current, XRPAmount target, @@ -149,8 +125,7 @@ FeeVoteImpl::doValidation( auto const& sfield) { if (current != target) { - JLOG(journal_.info()) - << "Voting for " << name << " of " << target; + JLOG(journal_.info()) << "Voting for " << name << " of " << target; if (auto const f = convertCallback(target)) v[sfield] = *f; @@ -158,18 +133,8 @@ FeeVoteImpl::doValidation( }; vote(lastFees.base, target_.reference_fee, to64, "base fee", sfBaseFee); - vote( - lastFees.reserve, - target_.account_reserve, - to32, - "base reserve", - sfReserveBase); - vote( - lastFees.increment, - target_.owner_reserve, - to32, - "reserve increment", - sfReserveIncrement); + vote(lastFees.reserve, target_.account_reserve, to32, "base reserve", sfReserveBase); + vote(lastFees.increment, target_.owner_reserve, to32, "reserve increment", sfReserveIncrement); } } @@ -181,38 +146,32 @@ FeeVoteImpl::doVoting( { // LCL must be flag ledger XRPL_ASSERT( - lastClosedLedger && isFlagLedger(lastClosedLedger->seq()), - "xrpl::FeeVoteImpl::doVoting : has a flag ledger"); + lastClosedLedger && isFlagLedger(lastClosedLedger->seq()), "xrpl::FeeVoteImpl::doVoting : has a flag ledger"); - detail::VotableValue baseFeeVote( - lastClosedLedger->fees().base, target_.reference_fee); + detail::VotableValue baseFeeVote(lastClosedLedger->fees().base, target_.reference_fee); - detail::VotableValue baseReserveVote( - lastClosedLedger->fees().reserve, target_.account_reserve); + detail::VotableValue baseReserveVote(lastClosedLedger->fees().reserve, target_.account_reserve); - detail::VotableValue incReserveVote( - lastClosedLedger->fees().increment, target_.owner_reserve); + detail::VotableValue incReserveVote(lastClosedLedger->fees().increment, target_.owner_reserve); auto const& rules = lastClosedLedger->rules(); if (rules.enabled(featureXRPFees)) { - auto doVote = [](std::shared_ptr const& val, - detail::VotableValue& value, - SF_AMOUNT const& xrpField) { - if (auto const field = ~val->at(~xrpField); - field && field->native()) - { - auto const vote = field->xrp(); - if (isLegalAmountSigned(vote)) - value.addVote(vote); + auto doVote = + [](std::shared_ptr const& val, detail::VotableValue& value, SF_AMOUNT const& xrpField) { + if (auto const field = ~val->at(~xrpField); field && field->native()) + { + auto const vote = field->xrp(); + if (isLegalAmountSigned(vote)) + value.addVote(vote); + else + value.noVote(); + } else + { value.noVote(); - } - else - { - value.noVote(); - } - }; + } + }; for (auto const& val : set) { @@ -225,27 +184,26 @@ FeeVoteImpl::doVoting( } else { - auto doVote = [](std::shared_ptr const& val, - detail::VotableValue& value, - auto const& valueField) { - if (auto const field = val->at(~valueField)) - { - using XRPType = XRPAmount::value_type; - auto const vote = *field; - if (vote <= std::numeric_limits::max() && - isLegalAmountSigned(XRPAmount{unsafe_cast(vote)})) - value.addVote(XRPAmount{unsafe_cast(vote)}); + auto doVote = + [](std::shared_ptr const& val, detail::VotableValue& value, auto const& valueField) { + if (auto const field = val->at(~valueField)) + { + using XRPType = XRPAmount::value_type; + auto const vote = *field; + if (vote <= std::numeric_limits::max() && + isLegalAmountSigned(XRPAmount{unsafe_cast(vote)})) + value.addVote(XRPAmount{unsafe_cast(vote)}); + else + // Invalid amounts will be treated as if they're + // not provided. Don't throw because this value is + // provided by an external entity. + value.noVote(); + } else - // Invalid amounts will be treated as if they're - // not provided. Don't throw because this value is - // provided by an external entity. + { value.noVote(); - } - else - { - value.noVote(); - } - }; + } + }; for (auto const& val : set) { @@ -270,9 +228,8 @@ FeeVoteImpl::doVoting( // add transactions to our position if (baseFee.second || baseReserve.second || incReserve.second) { - JLOG(journal_.warn()) - << "We are voting for a fee change: " << baseFee.first << "/" - << baseReserve.first << "/" << incReserve.first; + JLOG(journal_.warn()) << "We are voting for a fee change: " << baseFee.first << "/" << baseReserve.first << "/" + << incReserve.first; STTx feeTx(ttFEE, [=, &rules](auto& obj) { obj[sfAccount] = AccountID(); @@ -287,13 +244,9 @@ FeeVoteImpl::doVoting( { // Without the featureXRPFees amendment, these fields are // required. - obj[sfBaseFee] = - baseFee.first.dropsAs(baseFeeVote.current()); - obj[sfReserveBase] = baseReserve.first.dropsAs( - baseReserveVote.current()); - obj[sfReserveIncrement] = - incReserve.first.dropsAs( - incReserveVote.current()); + obj[sfBaseFee] = baseFee.first.dropsAs(baseFeeVote.current()); + obj[sfReserveBase] = baseReserve.first.dropsAs(baseReserveVote.current()); + obj[sfReserveIncrement] = incReserve.first.dropsAs(incReserveVote.current()); obj[sfReferenceFeeUnits] = Config::FEE_UNITS_DEPRECATED; } }); @@ -305,9 +258,7 @@ FeeVoteImpl::doVoting( Serializer s; feeTx.add(s); - if (!initialPosition->addGiveItem( - SHAMapNodeType::tnTRANSACTION_NM, - make_shamapitem(txID, s.slice()))) + if (!initialPosition->addGiveItem(SHAMapNodeType::tnTRANSACTION_NM, make_shamapitem(txID, s.slice()))) { JLOG(journal_.warn()) << "Ledger already had fee change"; } diff --git a/src/xrpld/app/misc/LendingHelpers.h b/src/xrpld/app/misc/LendingHelpers.h index 79fc617569..f8297dfdf7 100644 --- a/src/xrpld/app/misc/LendingHelpers.h +++ b/src/xrpld/app/misc/LendingHelpers.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_MISC_LENDINGHELPERS_H_INCLUDED -#define XRPL_APP_MISC_LENDINGHELPERS_H_INCLUDED +#pragma once #include #include @@ -19,10 +18,7 @@ loanPeriodicRate(TenthBips32 interestRate, std::uint32_t paymentInterval); /// Ensure the periodic payment is always rounded consistently inline Number -roundPeriodicPayment( - Asset const& asset, - Number const& periodicPayment, - std::int32_t scale) +roundPeriodicPayment(Asset const& asset, Number const& periodicPayment, std::int32_t scale) { return roundToAsset(asset, periodicPayment, scale, Number::upward); } @@ -113,8 +109,7 @@ struct LoanState interestOutstanding() const { XRPL_ASSERT_PARTS( - interestDue + managementFeeDue == - valueOutstanding - principalOutstanding, + interestDue + managementFeeDue == valueOutstanding - principalOutstanding, "xrpl::LoanState::interestOutstanding", "other values add up correctly"); return interestDue + managementFeeDue; @@ -159,11 +154,7 @@ struct LoanProperties // accumulated rounding errors and leftover dust amounts. template void -adjustImpreciseNumber( - NumberProxy value, - Number const& adjustment, - Asset const& asset, - int vaultScale) +adjustImpreciseNumber(NumberProxy value, Number const& adjustment, Asset const& asset, int vaultScale) { value = roundToAsset(asset, value + adjustment, vaultScale); @@ -176,8 +167,7 @@ getAssetsTotalScale(SLE::const_ref vaultSle) { if (!vaultSle) return Number::minExponent - 1; // LCOV_EXCL_LINE - return STAmount{vaultSle->at(sfAsset), vaultSle->at(sfAssetsTotal)} - .exponent(); + return STAmount{vaultSle->at(sfAsset), vaultSle->at(sfAssetsTotal)}.exponent(); } TER @@ -209,11 +199,7 @@ LoanState constructRoundedLoanState(SLE::const_ref loan); Number -computeManagementFee( - Asset const& asset, - Number const& interest, - TenthBips32 managementFeeRate, - std::int32_t scale); +computeManagementFee(Asset const& asset, Number const& interest, TenthBips32 managementFeeRate, std::int32_t scale); Number computeFullPaymentInterest( @@ -317,15 +303,11 @@ struct ExtendedPaymentComponents : public PaymentComponents // borrower is sufficient to cover all components of the payment. Number totalDue; - ExtendedPaymentComponents( - PaymentComponents const& p, - Number fee, - Number interest = numZero) + ExtendedPaymentComponents(PaymentComponents const& p, Number fee, Number interest = numZero) : PaymentComponents(p) , untrackedManagementFee(fee) , untrackedInterest(interest) - , totalDue( - trackedValueDelta + untrackedInterest + untrackedManagementFee) + , totalDue(trackedValueDelta + untrackedInterest + untrackedManagementFee) { } }; @@ -378,9 +360,7 @@ Number computeRaisedRate(Number const& periodicRate, std::uint32_t paymentsRemaining); Number -computePaymentFactor( - Number const& periodicRate, - std::uint32_t paymentsRemaining); +computePaymentFactor(Number const& periodicRate, std::uint32_t paymentsRemaining); std::pair computeInterestAndFeeParts( @@ -390,10 +370,7 @@ computeInterestAndFeeParts( std::int32_t loanScale); Number -loanPeriodicPayment( - Number const& principalOutstanding, - Number const& periodicRate, - std::uint32_t paymentsRemaining); +loanPeriodicPayment(Number const& principalOutstanding, Number const& periodicRate, std::uint32_t paymentsRemaining); Number loanPrincipalFromPeriodicPayment( @@ -488,5 +465,3 @@ loanMakePayment( beast::Journal j); } // namespace xrpl - -#endif // XRPL_APP_MISC_LENDINGHELPERS_H_INCLUDED diff --git a/src/xrpld/app/misc/LoadFeeTrack.h b/src/xrpld/app/misc/LoadFeeTrack.h index 181fb0536e..8eb53187ce 100644 --- a/src/xrpld/app/misc/LoadFeeTrack.h +++ b/src/xrpld/app/misc/LoadFeeTrack.h @@ -1,5 +1,4 @@ -#ifndef XRPL_CORE_LOADFEETRACK_H_INCLUDED -#define XRPL_CORE_LOADFEETRACK_H_INCLUDED +#pragma once #include #include @@ -25,8 +24,7 @@ struct Fees; class LoadFeeTrack final { public: - explicit LoadFeeTrack( - beast::Journal journal = beast::Journal(beast::Journal::getNullSink())) + explicit LoadFeeTrack(beast::Journal journal = beast::Journal(beast::Journal::getNullSink())) : j_(journal) , localTxnLoadFee_(lftNormalFee) , remoteTxnLoadFee_(lftNormalFee) @@ -76,8 +74,7 @@ public: getLoadFactor() const { std::lock_guard sl(lock_); - return std::max( - {clusterTxnLoadFee_, localTxnLoadFee_, remoteTxnLoadFee_}); + return std::max({clusterTxnLoadFee_, localTxnLoadFee_, remoteTxnLoadFee_}); } std::pair @@ -86,8 +83,7 @@ public: std::lock_guard sl(lock_); return std::make_pair( - std::max(localTxnLoadFee_, remoteTxnLoadFee_), - std::max(remoteTxnLoadFee_, clusterTxnLoadFee_)); + std::max(localTxnLoadFee_, remoteTxnLoadFee_), std::max(remoteTxnLoadFee_, clusterTxnLoadFee_)); } void @@ -114,26 +110,21 @@ public: isLoadedCluster() const { std::lock_guard sl(lock_); - return (raiseCount_ != 0) || (localTxnLoadFee_ != lftNormalFee) || - (clusterTxnLoadFee_ != lftNormalFee); + return (raiseCount_ != 0) || (localTxnLoadFee_ != lftNormalFee) || (clusterTxnLoadFee_ != lftNormalFee); } private: - static std::uint32_t constexpr lftNormalFee = - 256; // 256 is the minimum/normal load factor - static std::uint32_t constexpr lftFeeIncFraction = - 4; // increase fee by 1/4 - static std::uint32_t constexpr lftFeeDecFraction = - 4; // decrease fee by 1/4 + static std::uint32_t constexpr lftNormalFee = 256; // 256 is the minimum/normal load factor + static std::uint32_t constexpr lftFeeIncFraction = 4; // increase fee by 1/4 + static std::uint32_t constexpr lftFeeDecFraction = 4; // decrease fee by 1/4 static std::uint32_t constexpr lftFeeMax = lftNormalFee * 1000000; beast::Journal const j_; std::mutex mutable lock_; - std::uint32_t localTxnLoadFee_; // Scale factor, lftNormalFee = normal fee - std::uint32_t remoteTxnLoadFee_; // Scale factor, lftNormalFee = normal fee - std::uint32_t - clusterTxnLoadFee_; // Scale factor, lftNormalFee = normal fee + std::uint32_t localTxnLoadFee_; // Scale factor, lftNormalFee = normal fee + std::uint32_t remoteTxnLoadFee_; // Scale factor, lftNormalFee = normal fee + std::uint32_t clusterTxnLoadFee_; // Scale factor, lftNormalFee = normal fee std::uint32_t raiseCount_; }; @@ -141,12 +132,6 @@ private: // Scale using load as well as base rate XRPAmount -scaleFeeLoad( - XRPAmount fee, - LoadFeeTrack const& feeTrack, - Fees const& fees, - bool bUnlimited); +scaleFeeLoad(XRPAmount fee, LoadFeeTrack const& feeTrack, Fees const& fees, bool bUnlimited); } // namespace xrpl - -#endif diff --git a/src/xrpld/app/misc/NegativeUNLVote.cpp b/src/xrpld/app/misc/NegativeUNLVote.cpp index 12467697fa..d4a64a34dd 100644 --- a/src/xrpld/app/misc/NegativeUNLVote.cpp +++ b/src/xrpld/app/misc/NegativeUNLVote.cpp @@ -6,8 +6,7 @@ namespace xrpl { -NegativeUNLVote::NegativeUNLVote(NodeID const& myId, beast::Journal j) - : myId_(myId), j_(j) +NegativeUNLVote::NegativeUNLVote(NodeID const& myId, beast::Journal j) : myId_(myId), j_(j) { } @@ -63,27 +62,20 @@ NegativeUNLVote::doVoting( purgeNewValidators(seq); // Process the table and find all candidates to disable or to re-enable - auto const candidates = - findAllCandidates(unlNodeIDs, negUnlNodeIDs, *scoreTable); + auto const candidates = findAllCandidates(unlNodeIDs, negUnlNodeIDs, *scoreTable); // Pick one to disable and one to re-enable if any, add ttUNL_MODIFY Tx if (!candidates.toDisableCandidates.empty()) { - auto n = choose( - prevLedger->header().hash, candidates.toDisableCandidates); - XRPL_ASSERT( - nidToKeyMap.contains(n), - "xrpl::NegativeUNLVote::doVoting : found node to disable"); + auto n = choose(prevLedger->header().hash, candidates.toDisableCandidates); + XRPL_ASSERT(nidToKeyMap.contains(n), "xrpl::NegativeUNLVote::doVoting : found node to disable"); addTx(seq, nidToKeyMap.at(n), ToDisable, initialSet); } if (!candidates.toReEnableCandidates.empty()) { - auto n = choose( - prevLedger->header().hash, candidates.toReEnableCandidates); - XRPL_ASSERT( - nidToKeyMap.contains(n), - "xrpl::NegativeUNLVote::doVoting : found node to enable"); + auto n = choose(prevLedger->header().hash, candidates.toReEnableCandidates); + XRPL_ASSERT(nidToKeyMap.contains(n), "xrpl::NegativeUNLVote::doVoting : found node to enable"); addTx(seq, nidToKeyMap.at(n), ToReEnable, initialSet); } } @@ -105,29 +97,22 @@ NegativeUNLVote::addTx( Serializer s; negUnlTx.add(s); if (!initialSet->addGiveItem( - SHAMapNodeType::tnTRANSACTION_NM, - make_shamapitem(negUnlTx.getTransactionID(), s.slice()))) + SHAMapNodeType::tnTRANSACTION_NM, make_shamapitem(negUnlTx.getTransactionID(), s.slice()))) { - JLOG(j_.warn()) << "N-UNL: ledger seq=" << seq - << ", add ttUNL_MODIFY tx failed"; + JLOG(j_.warn()) << "N-UNL: ledger seq=" << seq << ", add ttUNL_MODIFY tx failed"; } else { JLOG(j_.debug()) << "N-UNL: ledger seq=" << seq - << ", add a ttUNL_MODIFY Tx with txID: " - << negUnlTx.getTransactionID() << ", the validator to " - << (modify == ToDisable ? "disable: " : "re-enable: ") - << vp; + << ", add a ttUNL_MODIFY Tx with txID: " << negUnlTx.getTransactionID() + << ", the validator to " << (modify == ToDisable ? "disable: " : "re-enable: ") << vp; } } NodeID -NegativeUNLVote::choose( - uint256 const& randomPadData, - std::vector const& candidates) +NegativeUNLVote::choose(uint256 const& randomPadData, std::vector const& candidates) { - XRPL_ASSERT( - !candidates.empty(), "xrpl::NegativeUNLVote::choose : non-empty input"); + XRPL_ASSERT(!candidates.empty(), "xrpl::NegativeUNLVote::choose : non-empty input"); static_assert(NodeID::bytes <= uint256::bytes); NodeID randomPad = NodeID::fromVoid(randomPadData.data()); NodeID txNodeID = candidates[0]; @@ -167,9 +152,8 @@ NegativeUNLVote::buildScoreTable( auto const numAncestors = ledgerAncestors.size(); if (numAncestors < FLAG_LEDGER_INTERVAL) { - JLOG(j_.debug()) << "N-UNL: ledger " << seq - << " not enough history. Can trace back only " - << numAncestors << " ledgers."; + JLOG(j_.debug()) << "N-UNL: ledger " << seq << " not enough history. Can trace back only " << numAncestors + << " ledgers."; return {}; } @@ -184,8 +168,7 @@ NegativeUNLVote::buildScoreTable( // the score table. for (int i = 0; i < FLAG_LEDGER_INTERVAL; ++i) { - for (auto const& v : validations.getTrustedForLedger( - ledgerAncestors[numAncestors - 1 - i], seq - 2 - i)) + for (auto const& v : validations.getTrustedForLedger(ledgerAncestors[numAncestors - 1 - i], seq - 2 - i)) { if (scoreTable.count(v->getNodeID())) ++scoreTable[v->getNodeID()]; @@ -201,16 +184,12 @@ NegativeUNLVote::buildScoreTable( }(); if (myValidationCount < negativeUNLMinLocalValsToVote) { - JLOG(j_.debug()) << "N-UNL: ledger " << seq - << ". Local node only issued " << myValidationCount - << " validations in last " << FLAG_LEDGER_INTERVAL - << " ledgers." + JLOG(j_.debug()) << "N-UNL: ledger " << seq << ". Local node only issued " << myValidationCount + << " validations in last " << FLAG_LEDGER_INTERVAL << " ledgers." << " The reliability measurement could be wrong."; return {}; } - else if ( - myValidationCount > negativeUNLMinLocalValsToVote && - myValidationCount <= FLAG_LEDGER_INTERVAL) + else if (myValidationCount > negativeUNLMinLocalValsToVote && myValidationCount <= FLAG_LEDGER_INTERVAL) { return scoreTable; } @@ -218,9 +197,8 @@ NegativeUNLVote::buildScoreTable( { // cannot happen because validations.getTrustedForLedger does not // return multiple validations of the same ledger from a validator. - JLOG(j_.error()) << "N-UNL: ledger " << seq << ". Local node issued " - << myValidationCount << " validations in last " - << FLAG_LEDGER_INTERVAL << " ledgers. Too many!"; + JLOG(j_.error()) << "N-UNL: ledger " << seq << ". Local node issued " << myValidationCount + << " validations in last " << FLAG_LEDGER_INTERVAL << " ledgers. Too many!"; return {}; } } @@ -233,8 +211,7 @@ NegativeUNLVote::findAllCandidates( { // Compute if need to find more validators to disable auto const canAdd = [&]() -> bool { - auto const maxNegativeListed = static_cast( - std::ceil(unl.size() * negativeUNLMaxListed)); + auto const maxNegativeListed = static_cast(std::ceil(unl.size() * negativeUNLMaxListed)); std::size_t negativeListed = 0; for (auto const& n : unl) { @@ -242,11 +219,9 @@ NegativeUNLVote::findAllCandidates( ++negativeListed; } bool const result = negativeListed < maxNegativeListed; - JLOG(j_.trace()) << "N-UNL: nodeId " << myId_ << " lowWaterMark " - << negativeUNLLowWaterMark << " highWaterMark " - << negativeUNLHighWaterMark << " canAdd " << result - << " negativeListed " << negativeListed - << " maxNegativeListed " << maxNegativeListed; + JLOG(j_.trace()) << "N-UNL: nodeId " << myId_ << " lowWaterMark " << negativeUNLLowWaterMark + << " highWaterMark " << negativeUNLHighWaterMark << " canAdd " << result << " negativeListed " + << negativeListed << " maxNegativeListed " << maxNegativeListed; return result; }(); @@ -260,8 +235,7 @@ NegativeUNLVote::findAllCandidates( // (2) has less than negativeUNLLowWaterMark validations, // (3) is not in negUnl, and // (4) is not a new validator. - if (canAdd && score < negativeUNLLowWaterMark && - !negUnl.count(nodeId) && !newValidators_.count(nodeId)) + if (canAdd && score < negativeUNLLowWaterMark && !negUnl.count(nodeId) && !newValidators_.count(nodeId)) { JLOG(j_.trace()) << "N-UNL: toDisable candidate " << nodeId; candidates.toDisableCandidates.push_back(nodeId); @@ -301,17 +275,14 @@ NegativeUNLVote::findAllCandidates( } void -NegativeUNLVote::newValidators( - LedgerIndex seq, - hash_set const& nowTrusted) +NegativeUNLVote::newValidators(LedgerIndex seq, hash_set const& nowTrusted) { std::lock_guard lock(mutex_); for (auto const& n : nowTrusted) { if (newValidators_.find(n) == newValidators_.end()) { - JLOG(j_.trace()) << "N-UNL: add a new validator " << n - << " at ledger seq=" << seq; + JLOG(j_.trace()) << "N-UNL: add a new validator " << n << " at ledger seq=" << seq; newValidators_[n] = seq; } } diff --git a/src/xrpld/app/misc/NegativeUNLVote.h b/src/xrpld/app/misc/NegativeUNLVote.h index 3146294923..4019d32f13 100644 --- a/src/xrpld/app/misc/NegativeUNLVote.h +++ b/src/xrpld/app/misc/NegativeUNLVote.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_MISC_NEGATIVEUNLVOTE_H_INCLUDED -#define XRPL_APP_MISC_NEGATIVEUNLVOTE_H_INCLUDED +#pragma once #include @@ -34,20 +33,17 @@ public: * An unreliable validator is a candidate to be disabled by the NegativeUNL * protocol. */ - static constexpr size_t negativeUNLLowWaterMark = - FLAG_LEDGER_INTERVAL * 50 / 100; + static constexpr size_t negativeUNLLowWaterMark = FLAG_LEDGER_INTERVAL * 50 / 100; /** * An unreliable validator must have more than negativeUNLHighWaterMark * validations in the last flag ledger period to be re-enabled. */ - static constexpr size_t negativeUNLHighWaterMark = - FLAG_LEDGER_INTERVAL * 80 / 100; + static constexpr size_t negativeUNLHighWaterMark = FLAG_LEDGER_INTERVAL * 80 / 100; /** * The minimum number of validations of the local node for it to * participate in the voting. */ - static constexpr size_t negativeUNLMinLocalValsToVote = - FLAG_LEDGER_INTERVAL * 90 / 100; + static constexpr size_t negativeUNLMinLocalValsToVote = FLAG_LEDGER_INTERVAL * 90 / 100; /** * We don't want to disable new validators immediately after adding them. * So we skip voting for disabling them for 2 flag ledgers. @@ -129,11 +125,7 @@ private: * @param initialSet the transaction set */ void - addTx( - LedgerIndex seq, - PublicKey const& vp, - NegativeUNLModify modify, - std::shared_ptr const& initialSet); + addTx(LedgerIndex seq, PublicKey const& vp, NegativeUNLModify modify, std::shared_ptr const& initialSet); /** * Pick one candidate from a vector of candidates. @@ -195,5 +187,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/src/xrpld/app/misc/NetworkOPs.cpp b/src/xrpld/app/misc/NetworkOPs.cpp index 2422ec4ae6..8732f9610d 100644 --- a/src/xrpld/app/misc/NetworkOPs.cpp +++ b/src/xrpld/app/misc/NetworkOPs.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -6,20 +7,18 @@ #include #include #include -#include #include #include #include #include #include -#include #include -#include #include #include #include #include #include +#include #include #include #include @@ -38,9 +37,11 @@ #include #include #include +#include #include #include #include +#include #include #include #include @@ -82,11 +83,7 @@ class NetworkOPsImp final : public NetworkOPs bool applied = false; TER result; - TransactionStatus( - std::shared_ptr t, - bool a, - bool l, - FailHard f) + TransactionStatus(std::shared_ptr t, bool a, bool l, FailHard f) : transaction(t), admin(a), local(l), failType(f) { XRPL_ASSERT( @@ -134,8 +131,7 @@ class NetworkOPsImp final : public NetworkOPs OperatingMode mode_ = OperatingMode::DISCONNECTED; std::array counters_; mutable std::mutex mutex_; - std::chrono::steady_clock::time_point start_ = - std::chrono::steady_clock::now(); + std::chrono::steady_clock::time_point start_ = std::chrono::steady_clock::now(); std::chrono::steady_clock::time_point const processStart_ = start_; std::uint64_t initialSyncUs_{0}; static std::array const states_; @@ -143,8 +139,7 @@ class NetworkOPsImp final : public NetworkOPs public: explicit StateAccounting() { - counters_[static_cast(OperatingMode::DISCONNECTED)] - .transitions = 1; + counters_[static_cast(OperatingMode::DISCONNECTED)].transitions = 1; } /** @@ -185,10 +180,7 @@ class NetworkOPsImp final : public NetworkOPs { ServerFeeSummary() = default; - ServerFeeSummary( - XRPAmount fee, - TxQ::Metrics&& escalationMetrics, - LoadFeeTrack const& loadFeeTrack); + ServerFeeSummary(XRPAmount fee, TxQ::Metrics&& escalationMetrics, LoadFeeTrack const& loadFeeTrack); bool operator!=(ServerFeeSummary const& b) const; @@ -206,7 +198,7 @@ class NetworkOPsImp final : public NetworkOPs public: NetworkOPsImp( - Application& app, + ServiceRegistry& registry, NetworkOPs::clock_type& clock, bool standalone, std::size_t minPeerCount, @@ -217,7 +209,7 @@ public: boost::asio::io_context& io_svc, beast::Journal journal, beast::insight::Collector::ptr const& collector) - : app_(app) + : registry_(registry) , m_journal(journal) , m_localTX(make_LocalTxs()) , mMode(start_valid ? OperatingMode::FULL : OperatingMode::DISCONNECTED) @@ -225,22 +217,18 @@ public: , clusterTimer_(io_svc) , accountHistoryTxTimer_(io_svc) , mConsensus( - app, + registry_.app(), make_FeeVote( - setup_FeeVote(app_.config().section("voting")), - app_.logs().journal("FeeVote")), + setup_FeeVote(registry_.app().config().section("voting")), + registry_.logs().journal("FeeVote")), ledgerMaster, *m_localTX, - app.getInboundTransactions(), + registry.getInboundTransactions(), beast::get_abstract_clock(), validatorKeys, - app_.logs().journal("LedgerConsensus")) - , validatorPK_( - validatorKeys.keys ? validatorKeys.keys->publicKey - : decltype(validatorPK_){}) - , validatorMasterPK_( - validatorKeys.keys ? validatorKeys.keys->masterPublicKey - : decltype(validatorMasterPK_){}) + registry_.logs().journal("LedgerConsensus")) + , validatorPK_(validatorKeys.keys ? validatorKeys.keys->publicKey : decltype(validatorPK_){}) + , validatorMasterPK_(validatorKeys.keys ? validatorKeys.keys->masterPublicKey : decltype(validatorMasterPK_){}) , m_ledgerMaster(ledgerMaster) , m_job_queue(job_queue) , m_standalone(standalone) @@ -276,11 +264,8 @@ public: submitTransaction(std::shared_ptr const&) override; void - processTransaction( - std::shared_ptr& transaction, - bool bUnlimited, - bool bLocal, - FailHard failType) override; + processTransaction(std::shared_ptr& transaction, bool bUnlimited, bool bLocal, FailHard failType) + override; void processTransactionSet(CanonicalTXSet const& set) override; @@ -294,10 +279,7 @@ public: * @param failType fail_hard setting from transaction submission. */ void - doTransactionSync( - std::shared_ptr transaction, - bool bUnlimited, - FailHard failType); + doTransactionSync(std::shared_ptr transaction, bool bUnlimited, FailHard failType); /** * For transactions not submitted by a locally connected client, fire and @@ -309,10 +291,7 @@ public: * @param failType fail_hard setting from transaction submission. */ void - doTransactionAsync( - std::shared_ptr transaction, - bool bUnlimited, - FailHard failtype); + doTransactionAsync(std::shared_ptr transaction, bool bUnlimited, FailHard failtype); private: bool @@ -343,9 +322,7 @@ public: // Json::Value - getOwnerInfo( - std::shared_ptr lpLedger, - AccountID const& account) override; + getOwnerInfo(std::shared_ptr lpLedger, AccountID const& account) override; // // Book functions. @@ -366,9 +343,7 @@ public: processTrustedProposal(RCLCxPeerPos proposal) override; bool - recvValidation( - std::shared_ptr const& val, - std::string const& source) override; + recvValidation(std::shared_ptr const& val, std::string const& source) override; void mapComplete(std::shared_ptr const& map, bool fromAcquire) override; @@ -384,9 +359,7 @@ private: public: bool - beginConsensus( - uint256 const& networkClosed, - std::unique_ptr const& clog) override; + beginConsensus(uint256 const& networkClosed, std::unique_ptr const& clog) override; void endConsensus(std::unique_ptr const& clog) override; void @@ -440,8 +413,7 @@ public: Json::Value getLedgerFetchInfo() override; std::uint32_t - acceptLedger( - std::optional consensusDelay) override; + acceptLedger(std::optional consensusDelay) override; void reportFeeChange() override; void @@ -470,38 +442,22 @@ public: // InfoSub::Source. // void - subAccount( - InfoSub::ref ispListener, - hash_set const& vnaAccountIDs, - bool rt) override; + subAccount(InfoSub::ref ispListener, hash_set const& vnaAccountIDs, bool rt) override; void - unsubAccount( - InfoSub::ref ispListener, - hash_set const& vnaAccountIDs, - bool rt) override; + unsubAccount(InfoSub::ref ispListener, hash_set const& vnaAccountIDs, bool rt) override; // Just remove the subscription from the tracking // not from the InfoSub. Needed for InfoSub destruction void - unsubAccountInternal( - std::uint64_t seq, - hash_set const& vnaAccountIDs, - bool rt) override; + unsubAccountInternal(std::uint64_t seq, hash_set const& vnaAccountIDs, bool rt) override; error_code_i - subAccountHistory(InfoSub::ref ispListener, AccountID const& account) - override; + subAccountHistory(InfoSub::ref ispListener, AccountID const& account) override; void - unsubAccountHistory( - InfoSub::ref ispListener, - AccountID const& account, - bool historyOnly) override; + unsubAccountHistory(InfoSub::ref ispListener, AccountID const& account, bool historyOnly) override; void - unsubAccountHistoryInternal( - std::uint64_t seq, - AccountID const& account, - bool historyOnly) override; + unsubAccountHistoryInternal(std::uint64_t seq, AccountID const& account, bool historyOnly) override; bool subLedger(InfoSub::ref ispListener, Json::Value& jvResult) override; @@ -514,8 +470,7 @@ public: unsubBookChanges(std::uint64_t uListener) override; bool - subServer(InfoSub::ref ispListener, Json::Value& jvResult, bool admin) - override; + subServer(InfoSub::ref ispListener, Json::Value& jvResult, bool admin) override; bool unsubServer(std::uint64_t uListener) override; @@ -575,8 +530,7 @@ public: } catch (boost::system::system_error const& e) { - JLOG(m_journal.error()) - << "NetworkOPs: heartbeatTimer cancel error: " << e.what(); + JLOG(m_journal.error()) << "NetworkOPs: heartbeatTimer cancel error: " << e.what(); } try @@ -585,8 +539,7 @@ public: } catch (boost::system::system_error const& e) { - JLOG(m_journal.error()) - << "NetworkOPs: clusterTimer cancel error: " << e.what(); + JLOG(m_journal.error()) << "NetworkOPs: clusterTimer cancel error: " << e.what(); } try @@ -595,9 +548,7 @@ public: } catch (boost::system::system_error const& e) { - JLOG(m_journal.error()) - << "NetworkOPs: accountHistoryTxTimer cancel error: " - << e.what(); + JLOG(m_journal.error()) << "NetworkOPs: accountHistoryTxTimer cancel error: " << e.what(); } } // Make sure that any waitHandlers pending in our timers are done. @@ -705,22 +656,19 @@ private: InfoSub::wptr sinkWptr_; std::shared_ptr index_; }; - using SubAccountHistoryMapType = - hash_map>; + using SubAccountHistoryMapType = hash_map>; /** * @note called while holding mSubLock */ void - subAccountHistoryStart( - std::shared_ptr const& ledger, - SubAccountHistoryInfoWeak& subInfo); + subAccountHistoryStart(std::shared_ptr const& ledger, SubAccountHistoryInfoWeak& subInfo); void addAccountHistoryJob(SubAccountHistoryInfoWeak subInfo); void setAccountHistoryJobTimer(SubAccountHistoryInfoWeak subInfo); - Application& app_; + ServiceRegistry& registry_; beast::Journal m_journal; std::unique_ptr m_localTX; @@ -795,37 +743,18 @@ private: struct Stats { template - Stats( - Handler const& handler, - beast::insight::Collector::ptr const& collector) + Stats(Handler const& handler, beast::insight::Collector::ptr const& collector) : hook(collector->make_hook(handler)) - , disconnected_duration(collector->make_gauge( - "State_Accounting", - "Disconnected_duration")) - , connected_duration(collector->make_gauge( - "State_Accounting", - "Connected_duration")) - , syncing_duration( - collector->make_gauge("State_Accounting", "Syncing_duration")) - , tracking_duration(collector->make_gauge( - "State_Accounting", - "Tracking_duration")) - , full_duration( - collector->make_gauge("State_Accounting", "Full_duration")) - , disconnected_transitions(collector->make_gauge( - "State_Accounting", - "Disconnected_transitions")) - , connected_transitions(collector->make_gauge( - "State_Accounting", - "Connected_transitions")) - , syncing_transitions(collector->make_gauge( - "State_Accounting", - "Syncing_transitions")) - , tracking_transitions(collector->make_gauge( - "State_Accounting", - "Tracking_transitions")) - , full_transitions( - collector->make_gauge("State_Accounting", "Full_transitions")) + , disconnected_duration(collector->make_gauge("State_Accounting", "Disconnected_duration")) + , connected_duration(collector->make_gauge("State_Accounting", "Connected_duration")) + , syncing_duration(collector->make_gauge("State_Accounting", "Syncing_duration")) + , tracking_duration(collector->make_gauge("State_Accounting", "Tracking_duration")) + , full_duration(collector->make_gauge("State_Accounting", "Full_duration")) + , disconnected_transitions(collector->make_gauge("State_Accounting", "Disconnected_transitions")) + , connected_transitions(collector->make_gauge("State_Accounting", "Connected_transitions")) + , syncing_transitions(collector->make_gauge("State_Accounting", "Syncing_transitions")) + , tracking_transitions(collector->make_gauge("State_Accounting", "Tracking_transitions")) + , full_transitions(collector->make_gauge("State_Accounting", "Full_transitions")) { } @@ -853,22 +782,19 @@ private: //------------------------------------------------------------------------------ -static std::array const stateNames{ - {"disconnected", "connected", "syncing", "tracking", "full"}}; +static std::array const stateNames{{"disconnected", "connected", "syncing", "tracking", "full"}}; std::array const NetworkOPsImp::states_ = stateNames; -std::array const - NetworkOPsImp::StateAccounting::states_ = { - {Json::StaticString(stateNames[0]), - Json::StaticString(stateNames[1]), - Json::StaticString(stateNames[2]), - Json::StaticString(stateNames[3]), - Json::StaticString(stateNames[4])}}; +std::array const NetworkOPsImp::StateAccounting::states_ = { + {Json::StaticString(stateNames[0]), + Json::StaticString(stateNames[1]), + Json::StaticString(stateNames[2]), + Json::StaticString(stateNames[3]), + Json::StaticString(stateNames[4])}}; -static auto const genesisAccountId = calcAccountID( - generateKeyPair(KeyType::secp256k1, generateSeed("masterpassphrase")) - .first); +static auto const genesisAccountId = + calcAccountID(generateKeyPair(KeyType::secp256k1, generateSeed("masterpassphrase")).first); //------------------------------------------------------------------------------ inline OperatingMode @@ -924,7 +850,7 @@ NetworkOPsImp::getHostId(bool forAdmin) // For non-admin uses hash the node public key into a // single RFC1751 word: static std::string const shroudedHostId = [this]() { - auto const& id = app_.nodeIdentity(); + auto const& id = registry_.app().nodeIdentity(); return RFC1751::getWordFromBlob(id.first.data(), id.first.size()); }(); @@ -938,7 +864,7 @@ NetworkOPsImp::setStateTimer() setHeartbeatTimer(); // Only do this work if a cluster is configured - if (app_.cluster().size() != 0) + if (registry_.cluster().size() != 0) setClusterTimer(); } @@ -950,21 +876,17 @@ NetworkOPsImp::setTimer( std::function onError) { // Only start the timer if waitHandlerCounter_ is not yet joined. - if (auto optionalCountedHandler = waitHandlerCounter_.wrap( - [this, onExpire, onError](boost::system::error_code const& e) { - if ((e.value() == boost::system::errc::success) && - (!m_job_queue.isStopped())) + if (auto optionalCountedHandler = + waitHandlerCounter_.wrap([this, onExpire, onError](boost::system::error_code const& e) { + if ((e.value() == boost::system::errc::success) && (!m_job_queue.isStopped())) { onExpire(); } // Recover as best we can if an unexpected error occurs. - if (e.value() != boost::system::errc::success && - e.value() != boost::asio::error::operation_aborted) + if (e.value() != boost::system::errc::success && e.value() != boost::asio::error::operation_aborted) { // Try again later and hope for the best. - JLOG(m_journal.error()) - << "Timer got error '" << e.message() - << "'. Restarting timer."; + JLOG(m_journal.error()) << "Timer got error '" << e.message() << "'. Restarting timer."; onError(); } })) @@ -980,11 +902,7 @@ NetworkOPsImp::setHeartbeatTimer() setTimer( heartbeatTimer_, mConsensus.parms().ledgerGRANULARITY, - [this]() { - m_job_queue.addJob(jtNETOP_TIMER, "NetOPs.heartbeat", [this]() { - processHeartbeatTimer(); - }); - }, + [this]() { m_job_queue.addJob(jtNETOP_TIMER, "NetHeart", [this]() { processHeartbeatTimer(); }); }, [this]() { setHeartbeatTimer(); }); } @@ -996,19 +914,14 @@ NetworkOPsImp::setClusterTimer() setTimer( clusterTimer_, 10s, - [this]() { - m_job_queue.addJob(jtNETOP_CLUSTER, "NetOPs.cluster", [this]() { - processClusterTimer(); - }); - }, + [this]() { m_job_queue.addJob(jtNETOP_CLUSTER, "NetCluster", [this]() { processClusterTimer(); }); }, [this]() { setClusterTimer(); }); } void NetworkOPsImp::setAccountHistoryJobTimer(SubAccountHistoryInfoWeak subInfo) { - JLOG(m_journal.debug()) << "Scheduling AccountHistory job for account " - << toBase58(subInfo.index_->accountId_); + JLOG(m_journal.debug()) << "Scheduling AccountHistory job for account " << toBase58(subInfo.index_->accountId_); using namespace std::chrono_literals; setTimer( accountHistoryTxTimer_, @@ -1020,16 +933,15 @@ NetworkOPsImp::setAccountHistoryJobTimer(SubAccountHistoryInfoWeak subInfo) void NetworkOPsImp::processHeartbeatTimer() { - RclConsensusLogger clog( - "Heartbeat Timer", mConsensus.validating(), m_journal); + RclConsensusLogger clog("Heartbeat Timer", mConsensus.validating(), m_journal); { - std::unique_lock lock{app_.getMasterMutex()}; + std::unique_lock lock{registry_.app().getMasterMutex()}; // VFALCO NOTE This is for diagnosing a crash on exit - LoadManager& mgr(app_.getLoadManager()); + LoadManager& mgr(registry_.getLoadManager()); mgr.heartbeat(); - std::size_t const numPeers = app_.overlay().size(); + std::size_t const numPeers = registry_.overlay().size(); // do we have sufficient peers? If not, we are disconnected. if (numPeers < minPeerCount_) @@ -1045,9 +957,8 @@ NetworkOPsImp::processHeartbeatTimer() } else { - CLOG(clog.ss()) - << "already DISCONNECTED. too few peers (" << numPeers - << "), need at least " << minPeerCount_; + CLOG(clog.ss()) << "already DISCONNECTED. too few peers (" << numPeers << "), need at least " + << minPeerCount_; } // MasterMutex lock need not be held to call setHeartbeatTimer() @@ -1062,10 +973,8 @@ NetworkOPsImp::processHeartbeatTimer() if (mMode == OperatingMode::DISCONNECTED) { setMode(OperatingMode::CONNECTED); - JLOG(m_journal.info()) - << "Node count (" << numPeers << ") is sufficient."; - CLOG(clog.ss()) << "setting mode to CONNECTED based on " << numPeers - << " peers. "; + JLOG(m_journal.info()) << "Node count (" << numPeers << ") is sufficient."; + CLOG(clog.ss()) << "setting mode to CONNECTED based on " << numPeers << " peers. "; } // Check if the last validated ledger forces a change between these @@ -1079,13 +988,12 @@ NetworkOPsImp::processHeartbeatTimer() auto newMode = mMode.load(); if (origMode != newMode) { - CLOG(clog.ss()) - << ", changing to " << strOperatingMode(newMode, true); + CLOG(clog.ss()) << ", changing to " << strOperatingMode(newMode, true); } CLOG(clog.ss()) << ". "; } - mConsensus.timerEntry(app_.timeKeeper().closeTime(), clog.ss()); + mConsensus.timerEntry(registry_.timeKeeper().closeTime(), clog.ss()); CLOG(clog.ss()) << "consensus phase " << to_string(mLastConsensusPhase); ConsensusPhase const currPhase = mConsensus.phase(); @@ -1103,18 +1011,16 @@ NetworkOPsImp::processHeartbeatTimer() void NetworkOPsImp::processClusterTimer() { - if (app_.cluster().size() == 0) + if (registry_.cluster().size() == 0) return; using namespace std::chrono_literals; - bool const update = app_.cluster().update( - app_.nodeIdentity().first, + bool const update = registry_.cluster().update( + registry_.app().nodeIdentity().first, "", - (m_ledgerMaster.getValidatedLedgerAge() <= 4min) - ? app_.getFeeTrack().getLocalFee() - : 0, - app_.timeKeeper().now()); + (m_ledgerMaster.getValidatedLedgerAge() <= 4min) ? registry_.getFeeTrack().getLocalFee() : 0, + registry_.timeKeeper().now()); if (!update) { @@ -1124,7 +1030,7 @@ NetworkOPsImp::processClusterTimer() } protocol::TMCluster cluster; - app_.cluster().for_each([&cluster](ClusterNode const& node) { + registry_.cluster().for_each([&cluster](ClusterNode const& node) { protocol::TMClusterNode& n = *cluster.add_clusternodes(); n.set_publickey(toBase58(TokenType::NodePublic, node.identity())); n.set_reporttime(node.getReportTime().time_since_epoch().count()); @@ -1133,24 +1039,21 @@ NetworkOPsImp::processClusterTimer() n.set_nodename(node.name()); }); - Resource::Gossip gossip = app_.getResourceManager().exportConsumers(); + Resource::Gossip gossip = registry_.getResourceManager().exportConsumers(); for (auto& item : gossip.items) { protocol::TMLoadSource& node = *cluster.add_loadsources(); node.set_name(to_string(item.address)); node.set_cost(item.balance); } - app_.overlay().foreach(send_if( - std::make_shared(cluster, protocol::mtCLUSTER), - peer_in_cluster())); + registry_.overlay().foreach(send_if(std::make_shared(cluster, protocol::mtCLUSTER), peer_in_cluster())); setClusterTimer(); } //------------------------------------------------------------------------------ std::string -NetworkOPsImp::strOperatingMode(OperatingMode const mode, bool const admin) - const +NetworkOPsImp::strOperatingMode(OperatingMode const mode, bool const admin) const { if (mode == OperatingMode::FULL && admin) { @@ -1178,11 +1081,9 @@ NetworkOPsImp::submitTransaction(std::shared_ptr const& iTrans) } // Enforce Network bar for batch txn - if (iTrans->isFlag(tfInnerBatchTxn) && - m_ledgerMaster.getValidatedRules().enabled(featureBatch)) + if (iTrans->isFlag(tfInnerBatchTxn) && m_ledgerMaster.getValidatedRules().enabled(featureBatch)) { - JLOG(m_journal.error()) - << "Submitted transaction invalid: tfInnerBatchTxn flag present."; + JLOG(m_journal.error()) << "Submitted transaction invalid: tfInnerBatchTxn flag present."; return; } @@ -1190,7 +1091,7 @@ NetworkOPsImp::submitTransaction(std::shared_ptr const& iTrans) auto const trans = sterilize(*iTrans); auto const txid = trans->getTransactionID(); - auto const flags = app_.getHashRouter().getFlags(txid); + auto const flags = registry_.getHashRouter().getFlags(txid); if ((flags & HashRouterFlags::BAD) != HashRouterFlags::UNDEFINED) { @@ -1201,31 +1102,26 @@ NetworkOPsImp::submitTransaction(std::shared_ptr const& iTrans) try { auto const [validity, reason] = checkValidity( - app_.getHashRouter(), - *trans, - m_ledgerMaster.getValidatedRules(), - app_.config()); + registry_.getHashRouter(), *trans, m_ledgerMaster.getValidatedRules(), registry_.app().config()); if (validity != Validity::Valid) { - JLOG(m_journal.warn()) - << "Submitted transaction invalid: " << reason; + JLOG(m_journal.warn()) << "Submitted transaction invalid: " << reason; return; } } catch (std::exception const& ex) { - JLOG(m_journal.warn()) - << "Exception checking transaction " << txid << ": " << ex.what(); + JLOG(m_journal.warn()) << "Exception checking transaction " << txid << ": " << ex.what(); return; } std::string reason; - auto tx = std::make_shared(trans, reason, app_); + auto tx = std::make_shared(trans, reason, registry_.app()); - m_job_queue.addJob(jtTRANSACTION, "submitTxn", [this, tx]() { + m_job_queue.addJob(jtTRANSACTION, "SubmitTxn", [this, tx]() { auto t = tx; processTransaction(t, false, false, FailHard::no); }); @@ -1234,7 +1130,7 @@ NetworkOPsImp::submitTransaction(std::shared_ptr const& iTrans) bool NetworkOPsImp::preProcessTransaction(std::shared_ptr& transaction) { - auto const newFlags = app_.getHashRouter().getFlags(transaction->getID()); + auto const newFlags = registry_.getHashRouter().getFlags(transaction->getID()); if ((newFlags & HashRouterFlags::BAD) != HashRouterFlags::UNDEFINED) { @@ -1255,8 +1151,7 @@ NetworkOPsImp::preProcessTransaction(std::shared_ptr& transaction) { transaction->setStatus(INVALID); transaction->setResult(temINVALID_FLAG); - app_.getHashRouter().setFlags( - transaction->getID(), HashRouterFlags::BAD); + registry_.getHashRouter().setFlags(transaction->getID(), HashRouterFlags::BAD); return false; } @@ -1264,10 +1159,8 @@ NetworkOPsImp::preProcessTransaction(std::shared_ptr& transaction) // but I'm not 100% sure yet. // If so, only cost is looking up HashRouter flags. auto const [validity, reason] = - checkValidity(app_.getHashRouter(), sttx, view->rules(), app_.config()); - XRPL_ASSERT( - validity == Validity::Valid, - "xrpl::NetworkOPsImp::processTransaction : valid validity"); + checkValidity(registry_.getHashRouter(), sttx, view->rules(), registry_.app().config()); + XRPL_ASSERT(validity == Validity::Valid, "xrpl::NetworkOPsImp::processTransaction : valid validity"); // Not concerned with local checks at this point. if (validity == Validity::SigBad) @@ -1275,13 +1168,12 @@ NetworkOPsImp::preProcessTransaction(std::shared_ptr& transaction) JLOG(m_journal.info()) << "Transaction has bad signature: " << reason; transaction->setStatus(INVALID); transaction->setResult(temBAD_SIGNATURE); - app_.getHashRouter().setFlags( - transaction->getID(), HashRouterFlags::BAD); + registry_.getHashRouter().setFlags(transaction->getID(), HashRouterFlags::BAD); return false; } // canonicalize can change our pointer - app_.getMasterTransaction().canonicalize(&transaction); + registry_.getMasterTransaction().canonicalize(&transaction); return true; } @@ -1306,24 +1198,19 @@ NetworkOPsImp::processTransaction( } void -NetworkOPsImp::doTransactionAsync( - std::shared_ptr transaction, - bool bUnlimited, - FailHard failType) +NetworkOPsImp::doTransactionAsync(std::shared_ptr transaction, bool bUnlimited, FailHard failType) { std::lock_guard lock(mMutex); if (transaction->getApplying()) return; - mTransactions.push_back( - TransactionStatus(transaction, bUnlimited, false, failType)); + mTransactions.push_back(TransactionStatus(transaction, bUnlimited, false, failType)); transaction->setApplying(); if (mDispatchState == DispatchState::none) { - if (m_job_queue.addJob( - jtBATCH, "transactionBatch", [this]() { transactionBatch(); })) + if (m_job_queue.addJob(jtBATCH, "TxBatchAsync", [this]() { transactionBatch(); })) { mDispatchState = DispatchState::scheduled; } @@ -1331,24 +1218,18 @@ NetworkOPsImp::doTransactionAsync( } void -NetworkOPsImp::doTransactionSync( - std::shared_ptr transaction, - bool bUnlimited, - FailHard failType) +NetworkOPsImp::doTransactionSync(std::shared_ptr transaction, bool bUnlimited, FailHard failType) { std::unique_lock lock(mMutex); if (!transaction->getApplying()) { - mTransactions.push_back( - TransactionStatus(transaction, bUnlimited, true, failType)); + mTransactions.push_back(TransactionStatus(transaction, bUnlimited, true, failType)); transaction->setApplying(); } doTransactionSyncBatch( - lock, [&transaction](std::unique_lock const&) { - return transaction->getApplying(); - }); + lock, [&transaction](std::unique_lock const&) { return transaction->getApplying(); }); } void @@ -1370,9 +1251,7 @@ NetworkOPsImp::doTransactionSyncBatch( if (mTransactions.size()) { // More transactions need to be applied, but by another job. - if (m_job_queue.addJob(jtBATCH, "transactionBatch", [this]() { - transactionBatch(); - })) + if (m_job_queue.addJob(jtBATCH, "TxBatchSync", [this]() { transactionBatch(); })) { mDispatchState = DispatchState::scheduled; } @@ -1390,17 +1269,15 @@ NetworkOPsImp::processTransactionSet(CanonicalTXSet const& set) for (auto const& [_, tx] : set) { std::string reason; - auto transaction = std::make_shared(tx, reason, app_); + auto transaction = std::make_shared(tx, reason, registry_.app()); if (transaction->getStatus() == INVALID) { if (!reason.empty()) { - JLOG(m_journal.trace()) - << "Exception checking transaction: " << reason; + JLOG(m_journal.trace()) << "Exception checking transaction: " << reason; } - app_.getHashRouter().setFlags( - tx->getTransactionID(), HashRouterFlags::BAD); + registry_.getHashRouter().setFlags(tx->getTransactionID(), HashRouterFlags::BAD); continue; } @@ -1440,13 +1317,9 @@ NetworkOPsImp::processTransactionSet(CanonicalTXSet const& set) } doTransactionSyncBatch(lock, [&](std::unique_lock const&) { - XRPL_ASSERT( - lock.owns_lock(), - "xrpl::NetworkOPsImp::processTransactionSet has lock"); + XRPL_ASSERT(lock.owns_lock(), "xrpl::NetworkOPsImp::processTransactionSet has lock"); return std::any_of( - mTransactions.begin(), mTransactions.end(), [](auto const& t) { - return t.transaction->getApplying(); - }); + mTransactions.begin(), mTransactions.end(), [](auto const& t) { return t.transaction->getApplying(); }); }); } @@ -1470,26 +1343,21 @@ NetworkOPsImp::apply(std::unique_lock& batchLock) std::vector submit_held; std::vector transactions; mTransactions.swap(transactions); - XRPL_ASSERT( - !transactions.empty(), - "xrpl::NetworkOPsImp::apply : non-empty transactions"); - XRPL_ASSERT( - mDispatchState != DispatchState::running, - "xrpl::NetworkOPsImp::apply : is not running"); + XRPL_ASSERT(!transactions.empty(), "xrpl::NetworkOPsImp::apply : non-empty transactions"); + XRPL_ASSERT(mDispatchState != DispatchState::running, "xrpl::NetworkOPsImp::apply : is not running"); mDispatchState = DispatchState::running; batchLock.unlock(); { - std::unique_lock masterLock{app_.getMasterMutex(), std::defer_lock}; + std::unique_lock masterLock{registry_.app().getMasterMutex(), std::defer_lock}; bool changed = false; { - std::unique_lock ledgerLock{ - m_ledgerMaster.peekMutex(), std::defer_lock}; + std::unique_lock ledgerLock{m_ledgerMaster.peekMutex(), std::defer_lock}; std::lock(masterLock, ledgerLock); - app_.openLedger().modify([&](OpenView& view, beast::Journal j) { + registry_.openLedger().modify([&](OpenView& view, beast::Journal j) { for (TransactionStatus& e : transactions) { // we check before adding to the batch @@ -1500,8 +1368,8 @@ NetworkOPsImp::apply(std::unique_lock& batchLock) if (e.failType == FailHard::yes) flags |= tapFAIL_HARD; - auto const result = app_.getTxQ().apply( - app_, view, e.transaction->getSTransaction(), flags, j); + auto const result = + registry_.getTxQ().apply(registry_.app(), view, e.transaction->getSTransaction(), flags, j); e.result = result.ter; e.applied = result.applied; changed = changed || result.applied; @@ -1516,23 +1384,21 @@ NetworkOPsImp::apply(std::unique_lock& batchLock) if (auto const l = m_ledgerMaster.getValidatedLedger()) validatedLedgerIndex = l->header().seq; - auto newOL = app_.openLedger().current(); + auto newOL = registry_.openLedger().current(); for (TransactionStatus& e : transactions) { e.transaction->clearSubmitResult(); if (e.applied) { - pubProposedTransaction( - newOL, e.transaction->getSTransaction(), e.result); + pubProposedTransaction(newOL, e.transaction->getSTransaction(), e.result); e.transaction->setApplied(); } e.transaction->setResult(e.result); if (isTemMalformed(e.result)) - app_.getHashRouter().setFlags( - e.transaction->getID(), HashRouterFlags::BAD); + registry_.getHashRouter().setFlags(e.transaction->getID(), HashRouterFlags::BAD); #ifdef DEBUG if (e.result != tesSUCCESS) @@ -1541,8 +1407,7 @@ NetworkOPsImp::apply(std::unique_lock& batchLock) if (transResultInfo(e.result, token, human)) { - JLOG(m_journal.info()) - << "TransactionResult: " << token << ": " << human; + JLOG(m_journal.info()) << "TransactionResult: " << token << ": " << human; } } #endif @@ -1551,8 +1416,7 @@ NetworkOPsImp::apply(std::unique_lock& batchLock) if (e.result == tesSUCCESS) { - JLOG(m_journal.debug()) - << "Transaction is now included in open ledger"; + JLOG(m_journal.debug()) << "Transaction is now included in open ledger"; e.transaction->setStatus(INCLUDED); // Pop as many "reasonable" transactions for this account as @@ -1561,15 +1425,14 @@ NetworkOPsImp::apply(std::unique_lock& batchLock) auto const& txCur = e.transaction->getSTransaction(); std::size_t count = 0; - for (auto txNext = m_ledgerMaster.popAcctTransaction(txCur); - txNext && count < maxPoppedTransactions; + for (auto txNext = m_ledgerMaster.popAcctTransaction(txCur); txNext && count < maxPoppedTransactions; txNext = m_ledgerMaster.popAcctTransaction(txCur), ++count) { if (!batchLock.owns_lock()) batchLock.lock(); std::string reason; auto const trans = sterilize(*txNext); - auto t = std::make_shared(trans, reason, app_); + auto t = std::make_shared(trans, reason, registry_.app()); if (t->getApplying()) break; submit_held.emplace_back(t, false, false, FailHard::no); @@ -1586,9 +1449,8 @@ NetworkOPsImp::apply(std::unique_lock& batchLock) } else if (e.result == terQUEUED) { - JLOG(m_journal.debug()) - << "Transaction is likely to claim a" - << " fee, but is queued until fee drops"; + JLOG(m_journal.debug()) << "Transaction is likely to claim a" + << " fee, but is queued until fee drops"; e.transaction->setStatus(HELD); // Add to held transactions, because it could get @@ -1598,19 +1460,13 @@ NetworkOPsImp::apply(std::unique_lock& batchLock) e.transaction->setQueued(); e.transaction->setKept(); } - else if ( - isTerRetry(e.result) || isTelLocal(e.result) || - isTefFailure(e.result)) + else if (isTerRetry(e.result) || isTelLocal(e.result) || isTefFailure(e.result)) { if (e.failType != FailHard::yes) { - auto const lastLedgerSeq = - e.transaction->getSTransaction()->at( - ~sfLastLedgerSequence); - auto const ledgersLeft = lastLedgerSeq - ? *lastLedgerSeq - - m_ledgerMaster.getCurrentLedgerIndex() - : std::optional{}; + auto const lastLedgerSeq = e.transaction->getSTransaction()->at(~sfLastLedgerSequence); + auto const ledgersLeft = lastLedgerSeq ? *lastLedgerSeq - m_ledgerMaster.getCurrentLedgerIndex() + : std::optional{}; // If any of these conditions are met, the transaction can // be held: // 1. It was submitted locally. (Note that this flag is only @@ -1627,56 +1483,43 @@ NetworkOPsImp::apply(std::unique_lock& batchLock) // the other conditions, so don't hold it again. Time's // up!) // - if (e.local || - (ledgersLeft && ledgersLeft <= LocalTxs::holdLedgers) || - app_.getHashRouter().setFlags( - e.transaction->getID(), HashRouterFlags::HELD)) + if (e.local || (ledgersLeft && ledgersLeft <= LocalTxs::holdLedgers) || + registry_.getHashRouter().setFlags(e.transaction->getID(), HashRouterFlags::HELD)) { // transaction should be held - JLOG(m_journal.debug()) - << "Transaction should be held: " << e.result; + JLOG(m_journal.debug()) << "Transaction should be held: " << e.result; e.transaction->setStatus(HELD); m_ledgerMaster.addHeldTransaction(e.transaction); e.transaction->setKept(); } else JLOG(m_journal.debug()) - << "Not holding transaction " - << e.transaction->getID() << ": " + << "Not holding transaction " << e.transaction->getID() << ": " << (e.local ? "local" : "network") << ", " - << "result: " << e.result << " ledgers left: " - << (ledgersLeft ? to_string(*ledgersLeft) - : "unspecified"); + << "result: " << e.result + << " ledgers left: " << (ledgersLeft ? to_string(*ledgersLeft) : "unspecified"); } } else { - JLOG(m_journal.debug()) - << "Status other than success " << e.result; + JLOG(m_journal.debug()) << "Status other than success " << e.result; e.transaction->setStatus(INVALID); } - auto const enforceFailHard = - e.failType == FailHard::yes && !isTesSuccess(e.result); + auto const enforceFailHard = e.failType == FailHard::yes && !isTesSuccess(e.result); if (addLocal && !enforceFailHard) { - m_localTX->push_back( - m_ledgerMaster.getCurrentLedgerIndex(), - e.transaction->getSTransaction()); + m_localTX->push_back(m_ledgerMaster.getCurrentLedgerIndex(), e.transaction->getSTransaction()); e.transaction->setKept(); } - if ((e.applied || - ((mMode != OperatingMode::FULL) && - (e.failType != FailHard::yes) && e.local) || + if ((e.applied || ((mMode != OperatingMode::FULL) && (e.failType != FailHard::yes) && e.local) || (e.result == terQUEUED)) && !enforceFailHard) { - auto const toSkip = - app_.getHashRouter().shouldRelay(e.transaction->getID()); - if (auto const sttx = *(e.transaction->getSTransaction()); - toSkip && + auto const toSkip = registry_.getHashRouter().shouldRelay(e.transaction->getID()); + if (auto const sttx = *(e.transaction->getSTransaction()); toSkip && // Skip relaying if it's an inner batch txn. The flag should // only be set if the Batch feature is enabled. If Batch is // not enabled, the flag is always invalid, so don't relay @@ -1689,11 +1532,10 @@ NetworkOPsImp::apply(std::unique_lock& batchLock) sttx.add(s); tx.set_rawtransaction(s.data(), s.size()); tx.set_status(protocol::tsCURRENT); - tx.set_receivetimestamp( - app_.timeKeeper().now().time_since_epoch().count()); + tx.set_receivetimestamp(registry_.timeKeeper().now().time_since_epoch().count()); tx.set_deferred(e.result == terQUEUED); // FIXME: This should be when we received it - app_.overlay().relay(e.transaction->getID(), tx, *toSkip); + registry_.overlay().relay(e.transaction->getID(), tx, *toSkip); e.transaction->setBroadcast(); } } @@ -1701,10 +1543,8 @@ NetworkOPsImp::apply(std::unique_lock& batchLock) if (validatedLedgerIndex) { auto [fee, accountSeq, availableSeq] = - app_.getTxQ().getTxRequiredFeeAndSeq( - *newOL, e.transaction->getSTransaction()); - e.transaction->setCurrentLedgerState( - *validatedLedgerIndex, fee, accountSeq, availableSeq); + registry_.getTxQ().getTxRequiredFeeAndSeq(*newOL, e.transaction->getSTransaction()); + e.transaction->setCurrentLedgerState(*validatedLedgerIndex, fee, accountSeq, availableSeq); } } } @@ -1736,9 +1576,7 @@ NetworkOPsImp::apply(std::unique_lock& batchLock) // Json::Value -NetworkOPsImp::getOwnerInfo( - std::shared_ptr lpLedger, - AccountID const& account) +NetworkOPsImp::getOwnerInfo(std::shared_ptr lpLedger, AccountID const& account) { Json::Value jvObjects(Json::objectValue); auto root = keylet::ownerDir(account); @@ -1752,30 +1590,24 @@ NetworkOPsImp::getOwnerInfo( for (auto const& uDirEntry : sleNode->getFieldV256(sfIndexes)) { auto sleCur = lpLedger->read(keylet::child(uDirEntry)); - XRPL_ASSERT( - sleCur, - "xrpl::NetworkOPsImp::getOwnerInfo : non-null child SLE"); + XRPL_ASSERT(sleCur, "xrpl::NetworkOPsImp::getOwnerInfo : non-null child SLE"); switch (sleCur->getType()) { case ltOFFER: if (!jvObjects.isMember(jss::offers)) - jvObjects[jss::offers] = - Json::Value(Json::arrayValue); + jvObjects[jss::offers] = Json::Value(Json::arrayValue); - jvObjects[jss::offers].append( - sleCur->getJson(JsonOptions::none)); + jvObjects[jss::offers].append(sleCur->getJson(JsonOptions::none)); break; case ltRIPPLE_STATE: if (!jvObjects.isMember(jss::ripple_lines)) { - jvObjects[jss::ripple_lines] = - Json::Value(Json::arrayValue); + jvObjects[jss::ripple_lines] = Json::Value(Json::arrayValue); } - jvObjects[jss::ripple_lines].append( - sleCur->getJson(JsonOptions::none)); + jvObjects[jss::ripple_lines].append(sleCur->getJson(JsonOptions::none)); break; case ltACCOUNT_ROOT: @@ -1795,9 +1627,7 @@ NetworkOPsImp::getOwnerInfo( if (uNodeDir) { sleNode = lpLedger->read(keylet::page(root, uNodeDir)); - XRPL_ASSERT( - sleNode, - "xrpl::NetworkOPsImp::getOwnerInfo : read next page"); + XRPL_ASSERT(sleNode, "xrpl::NetworkOPsImp::getOwnerInfo : read next page"); } } while (uNodeDir); } @@ -1866,9 +1696,7 @@ NetworkOPsImp::clearUNLBlocked() } bool -NetworkOPsImp::checkLastClosedLedger( - Overlay::PeerSequence const& peerList, - uint256& networkClosed) +NetworkOPsImp::checkLastClosedLedger(Overlay::PeerSequence const& peerList, uint256& networkClosed) { // Returns true if there's an *abnormal* ledger issue, normal changing in // TRACKING mode should return false. Do we have sufficient validations for @@ -1890,9 +1718,8 @@ NetworkOPsImp::checkLastClosedLedger( //------------------------------------------------------------------------- // Determine preferred last closed ledger - auto& validations = app_.getValidations(); - JLOG(m_journal.debug()) - << "ValidationTrie " << Json::Compact(validations.getJsonTrie()); + auto& validations = registry_.getValidations(); + JLOG(m_journal.debug()) << "ValidationTrie " << Json::Compact(validations.getJsonTrie()); // Will rely on peer LCL if no trusted validations exist hash_map peerCounts; @@ -1936,13 +1763,11 @@ NetworkOPsImp::checkLastClosedLedger( auto consensus = m_ledgerMaster.getLedgerByHash(closedLedger); if (!consensus) - consensus = app_.getInboundLedgers().acquire( - closedLedger, 0, InboundLedger::Reason::CONSENSUS); + consensus = registry_.getInboundLedgers().acquire(closedLedger, 0, InboundLedger::Reason::CONSENSUS); if (consensus && (!m_ledgerMaster.canBeCurrent(consensus) || - !m_ledgerMaster.isCompatible( - *consensus, m_journal.debug(), "Not switching"))) + !m_ledgerMaster.isCompatible(*consensus, m_journal.debug(), "Not switching"))) { // Don't switch to a ledger not on the validated chain // or with an invalid close time or sequence @@ -1951,8 +1776,7 @@ NetworkOPsImp::checkLastClosedLedger( } JLOG(m_journal.warn()) << "We are not running on the consensus ledger"; - JLOG(m_journal.info()) << "Our LCL: " << ourClosed->header().hash - << getJson({*ourClosed, {}}); + JLOG(m_journal.info()) << "Our LCL: " << ourClosed->header().hash << getJson({*ourClosed, {}}); JLOG(m_journal.info()) << "Net LCL " << closedLedger; if ((mMode == OperatingMode::TRACKING) || (mMode == OperatingMode::FULL)) @@ -1972,17 +1796,15 @@ NetworkOPsImp::checkLastClosedLedger( } void -NetworkOPsImp::switchLastClosedLedger( - std::shared_ptr const& newLCL) +NetworkOPsImp::switchLastClosedLedger(std::shared_ptr const& newLCL) { // set the newLCL as our last closed ledger -- this is abnormal code - JLOG(m_journal.error()) - << "JUMP last closed ledger to " << newLCL->header().hash; + JLOG(m_journal.error()) << "JUMP last closed ledger to " << newLCL->header().hash; clearNeedNetworkLedger(); // Update fee computations. - app_.getTxQ().processClosedLedger(app_, *newLCL, true); + registry_.getTxQ().processClosedLedger(registry_.app(), *newLCL, true); // Caller must own master lock { @@ -1990,14 +1812,14 @@ NetworkOPsImp::switchLastClosedLedger( // open ledger. Then apply local tx. auto retries = m_localTX->getTxSet(); - auto const lastVal = app_.getLedgerMaster().getValidatedLedger(); + auto const lastVal = registry_.getLedgerMaster().getValidatedLedger(); std::optional rules; if (lastVal) - rules = makeRulesGivenLedger(*lastVal, app_.config().features); + rules = makeRulesGivenLedger(*lastVal, registry_.app().config().features); else - rules.emplace(app_.config().features); - app_.openLedger().accept( - app_, + rules.emplace(registry_.app().config().features); + registry_.openLedger().accept( + registry_.app(), *rules, newLCL, OrderedTxs({}), @@ -2007,7 +1829,7 @@ NetworkOPsImp::switchLastClosedLedger( "jump", [&](OpenView& view, beast::Journal j) { // Stuff the ledger with transactions from the queue. - return app_.getTxQ().accept(app_, view); + return registry_.getTxQ().accept(registry_.app(), view); }); } @@ -2016,30 +1838,21 @@ NetworkOPsImp::switchLastClosedLedger( protocol::TMStatusChange s; s.set_newevent(protocol::neSWITCHED_LEDGER); s.set_ledgerseq(newLCL->header().seq); - s.set_networktime(app_.timeKeeper().now().time_since_epoch().count()); - s.set_ledgerhashprevious( - newLCL->header().parentHash.begin(), - newLCL->header().parentHash.size()); - s.set_ledgerhash( - newLCL->header().hash.begin(), newLCL->header().hash.size()); + s.set_networktime(registry_.timeKeeper().now().time_since_epoch().count()); + s.set_ledgerhashprevious(newLCL->header().parentHash.begin(), newLCL->header().parentHash.size()); + s.set_ledgerhash(newLCL->header().hash.begin(), newLCL->header().hash.size()); - app_.overlay().foreach( - send_always(std::make_shared(s, protocol::mtSTATUS_CHANGE))); + registry_.overlay().foreach(send_always(std::make_shared(s, protocol::mtSTATUS_CHANGE))); } bool -NetworkOPsImp::beginConsensus( - uint256 const& networkClosed, - std::unique_ptr const& clog) +NetworkOPsImp::beginConsensus(uint256 const& networkClosed, std::unique_ptr const& clog) { - XRPL_ASSERT( - networkClosed.isNonZero(), - "xrpl::NetworkOPsImp::beginConsensus : nonzero input"); + XRPL_ASSERT(networkClosed.isNonZero(), "xrpl::NetworkOPsImp::beginConsensus : nonzero input"); auto closingInfo = m_ledgerMaster.getCurrentLedger()->header(); - JLOG(m_journal.info()) << "Consensus time for #" << closingInfo.seq - << " with LCL " << closingInfo.parentHash; + JLOG(m_journal.info()) << "Consensus time for #" << closingInfo.seq << " with LCL " << closingInfo.parentHash; auto prevLedger = m_ledgerMaster.getLedgerByHash(closingInfo.parentHash); @@ -2062,34 +1875,27 @@ NetworkOPsImp::beginConsensus( "xrpl::NetworkOPsImp::beginConsensus : prevLedger hash matches " "parent"); XRPL_ASSERT( - closingInfo.parentHash == - m_ledgerMaster.getClosedLedger()->header().hash, + closingInfo.parentHash == m_ledgerMaster.getClosedLedger()->header().hash, "xrpl::NetworkOPsImp::beginConsensus : closedLedger parent matches " "hash"); - app_.validators().setNegativeUNL(prevLedger->negativeUNL()); - TrustChanges const changes = app_.validators().updateTrusted( - app_.getValidations().getCurrentNodeIDs(), + registry_.validators().setNegativeUNL(prevLedger->negativeUNL()); + TrustChanges const changes = registry_.validators().updateTrusted( + registry_.getValidations().getCurrentNodeIDs(), closingInfo.parentCloseTime, *this, - app_.overlay(), - app_.getHashRouter()); + registry_.overlay(), + registry_.getHashRouter()); if (!changes.added.empty() || !changes.removed.empty()) { - app_.getValidations().trustChanged(changes.added, changes.removed); + registry_.getValidations().trustChanged(changes.added, changes.removed); // Update the AmendmentTable so it tracks the current validators. - app_.getAmendmentTable().trustChanged( - app_.validators().getQuorumKeys().second); + registry_.getAmendmentTable().trustChanged(registry_.validators().getQuorumKeys().second); } mConsensus.startRound( - app_.timeKeeper().closeTime(), - networkClosed, - prevLedger, - changes.removed, - changes.added, - clog); + registry_.timeKeeper().closeTime(), networkClosed, prevLedger, changes.removed, changes.added, clog); ConsensusPhase const currPhase = mConsensus.phase(); if (mLastConsensusPhase != currPhase) @@ -2117,15 +1923,14 @@ NetworkOPsImp::processTrustedProposal(RCLCxPeerPos peerPos) // // Another, innocuous explanation is unusual message routing and delays, // causing this node to receive its own messages back. - JLOG(m_journal.error()) - << "Received a proposal signed by MY KEY from a peer. This may " - "indicate a misconfiguration where another node has the same " - "validator key, or may be caused by unusual message routing and " - "delays."; + JLOG(m_journal.error()) << "Received a proposal signed by MY KEY from a peer. This may " + "indicate a misconfiguration where another node has the same " + "validator key, or may be caused by unusual message routing and " + "delays."; return false; } - return mConsensus.peerProposal(app_.timeKeeper().closeTime(), peerPos); + return mConsensus.peerProposal(registry_.timeKeeper().closeTime(), peerPos); } void @@ -2139,12 +1944,11 @@ NetworkOPsImp::mapComplete(std::shared_ptr const& map, bool fromAcquire) protocol::TMHaveTransactionSet msg; msg.set_hash(map->getHash().as_uint256().begin(), 256 / 8); msg.set_status(protocol::tsHAVE); - app_.overlay().foreach( - send_always(std::make_shared(msg, protocol::mtHAVE_SET))); + registry_.overlay().foreach(send_always(std::make_shared(msg, protocol::mtHAVE_SET))); // We acquired it because consensus asked us to if (fromAcquire) - mConsensus.gotTxSet(app_.timeKeeper().closeTime(), RCLTxSet{map}); + mConsensus.gotTxSet(registry_.timeKeeper().closeTime(), RCLTxSet{map}); } void @@ -2152,7 +1956,7 @@ NetworkOPsImp::endConsensus(std::unique_ptr const& clog) { uint256 deadLedger = m_ledgerMaster.getClosedLedger()->header().parentHash; - for (auto const& it : app_.overlay().getActivePeers()) + for (auto const& it : registry_.overlay().getActivePeers()) { if (it && (it->getClosedLedgerHash() == deadLedger)) { @@ -2162,8 +1966,7 @@ NetworkOPsImp::endConsensus(std::unique_ptr const& clog) } uint256 networkClosed; - bool ledgerChange = - checkLastClosedLedger(app_.overlay().getActivePeers(), networkClosed); + bool ledgerChange = checkLastClosedLedger(registry_.overlay().getActivePeers(), networkClosed); if (networkClosed.isZero()) { @@ -2177,9 +1980,7 @@ NetworkOPsImp::endConsensus(std::unique_ptr const& clog) // timing to make sure there shouldn't be a newer LCL. We need this // information to do the next three tests. - if (((mMode == OperatingMode::CONNECTED) || - (mMode == OperatingMode::SYNCING)) && - !ledgerChange) + if (((mMode == OperatingMode::CONNECTED) || (mMode == OperatingMode::SYNCING)) && !ledgerChange) { // Count number of peers that agree with us and UNL nodes whose // validations we have for LCL. If the ledger is good enough, go to @@ -2188,17 +1989,14 @@ NetworkOPsImp::endConsensus(std::unique_ptr const& clog) setMode(OperatingMode::TRACKING); } - if (((mMode == OperatingMode::CONNECTED) || - (mMode == OperatingMode::TRACKING)) && - !ledgerChange) + if (((mMode == OperatingMode::CONNECTED) || (mMode == OperatingMode::TRACKING)) && !ledgerChange) { // check if the ledger is good enough to go to FULL // Note: Do not go to FULL if we don't have the previous ledger // check if the ledger is bad enough to go to CONNECTED -- TODO auto current = m_ledgerMaster.getCurrentLedger(); - if (app_.timeKeeper().now() < - (current->header().parentCloseTime + - 2 * current->header().closeTimeResolution)) + if (registry_.timeKeeper().now() < + (current->header().parentCloseTime + 2 * current->header().closeTimeResolution)) { setMode(OperatingMode::FULL); } @@ -2229,8 +2027,7 @@ NetworkOPsImp::pubManifest(Manifest const& mo) jvObj[jss::type] = "manifestReceived"; jvObj[jss::master_key] = toBase58(TokenType::NodePublic, mo.masterKey); if (mo.signingKey) - jvObj[jss::signing_key] = - toBase58(TokenType::NodePublic, *mo.signingKey); + jvObj[jss::signing_key] = toBase58(TokenType::NodePublic, *mo.signingKey); jvObj[jss::seq] = Json::UInt(mo.sequence); if (auto sig = mo.getSignature()) jvObj[jss::signature] = strHex(*sig); @@ -2239,8 +2036,7 @@ NetworkOPsImp::pubManifest(Manifest const& mo) jvObj[jss::domain] = mo.domain; jvObj[jss::manifest] = strHex(mo.serialized); - for (auto i = mStreamMaps[sManifests].begin(); - i != mStreamMaps[sManifests].end();) + for (auto i = mStreamMaps[sManifests].begin(); i != mStreamMaps[sManifests].end();) { if (auto p = i->second.lock()) { @@ -2267,11 +2063,9 @@ NetworkOPsImp::ServerFeeSummary::ServerFeeSummary( } bool -NetworkOPsImp::ServerFeeSummary::operator!=( - NetworkOPsImp::ServerFeeSummary const& b) const +NetworkOPsImp::ServerFeeSummary::operator!=(NetworkOPsImp::ServerFeeSummary const& b) const { - if (loadFactorServer != b.loadFactorServer || - loadBaseServer != b.loadBaseServer || baseFee != b.baseFee || + if (loadFactorServer != b.loadFactorServer || loadBaseServer != b.loadBaseServer || baseFee != b.baseFee || em.has_value() != b.em.has_value()) return true; @@ -2279,8 +2073,7 @@ NetworkOPsImp::ServerFeeSummary::operator!=( { return ( em->minProcessingFeeLevel != b.em->minProcessingFeeLevel || - em->openLedgerFeeLevel != b.em->openLedgerFeeLevel || - em->referenceFeeLevel != b.em->referenceFeeLevel); + em->openLedgerFeeLevel != b.em->openLedgerFeeLevel || em->referenceFeeLevel != b.em->referenceFeeLevel); } return false; @@ -2309,9 +2102,9 @@ NetworkOPsImp::pubServer() Json::Value jvObj(Json::objectValue); ServerFeeSummary f{ - app_.openLedger().current()->fees().base, - app_.getTxQ().getMetrics(*app_.openLedger().current()), - app_.getFeeTrack()}; + registry_.openLedger().current()->fees().base, + registry_.getTxQ().getMetrics(*registry_.openLedger().current()), + registry_.getFeeTrack()}; jvObj[jss::type] = "serverStatus"; jvObj[jss::server_status] = strOperatingMode(); @@ -2323,27 +2116,19 @@ NetworkOPsImp::pubServer() { auto const loadFactor = std::max( safe_cast(f.loadFactorServer), - mulDiv( - f.em->openLedgerFeeLevel, - f.loadBaseServer, - f.em->referenceFeeLevel) - .value_or(xrpl::muldiv_max)); + mulDiv(f.em->openLedgerFeeLevel, f.loadBaseServer, f.em->referenceFeeLevel).value_or(xrpl::muldiv_max)); jvObj[jss::load_factor] = trunc32(loadFactor); - jvObj[jss::load_factor_fee_escalation] = - f.em->openLedgerFeeLevel.jsonClipped(); - jvObj[jss::load_factor_fee_queue] = - f.em->minProcessingFeeLevel.jsonClipped(); - jvObj[jss::load_factor_fee_reference] = - f.em->referenceFeeLevel.jsonClipped(); + jvObj[jss::load_factor_fee_escalation] = f.em->openLedgerFeeLevel.jsonClipped(); + jvObj[jss::load_factor_fee_queue] = f.em->minProcessingFeeLevel.jsonClipped(); + jvObj[jss::load_factor_fee_reference] = f.em->referenceFeeLevel.jsonClipped(); } else jvObj[jss::load_factor] = f.loadFactorServer; mLastFeeSummary = f; - for (auto i = mStreamMaps[sServer].begin(); - i != mStreamMaps[sServer].end();) + for (auto i = mStreamMaps[sServer].begin(); i != mStreamMaps[sServer].end();) { InfoSub::pointer p = i->second.lock(); @@ -2403,15 +2188,14 @@ NetworkOPsImp::pubValidation(std::shared_ptr const& val) auto const signerPublic = val->getSignerPublic(); jvObj[jss::type] = "validationReceived"; - jvObj[jss::validation_public_key] = - toBase58(TokenType::NodePublic, signerPublic); + jvObj[jss::validation_public_key] = toBase58(TokenType::NodePublic, signerPublic); jvObj[jss::ledger_hash] = to_string(val->getLedgerHash()); jvObj[jss::signature] = strHex(val->getSignature()); jvObj[jss::full] = val->isFull(); jvObj[jss::flags] = val->getFlags(); jvObj[jss::signing_time] = *(*val)[~sfSigningTime]; jvObj[jss::data] = strHex(val->getSerializer().slice()); - jvObj[jss::network_id] = app_.config().NETWORK_ID; + jvObj[jss::network_id] = registry_.app().config().NETWORK_ID; if (auto version = (*val)[~sfServerVersion]) jvObj[jss::server_version] = std::to_string(*version); @@ -2422,8 +2206,7 @@ NetworkOPsImp::pubValidation(std::shared_ptr const& val) if (auto hash = (*val)[~sfValidatedHash]) jvObj[jss::validated_hash] = strHex(*hash); - auto const masterKey = - app_.validatorManifests().getMasterKey(signerPublic); + auto const masterKey = registry_.validatorManifests().getMasterKey(signerPublic); if (masterKey != signerPublic) jvObj[jss::master_key] = toBase58(TokenType::NodePublic, masterKey); @@ -2457,16 +2240,13 @@ NetworkOPsImp::pubValidation(std::shared_ptr const& val) // (The ~ operator converts the Proxy to a std::optional, which // simplifies later operations) - if (auto const baseFeeXRP = ~val->at(~sfBaseFeeDrops); - baseFeeXRP && baseFeeXRP->native()) + if (auto const baseFeeXRP = ~val->at(~sfBaseFeeDrops); baseFeeXRP && baseFeeXRP->native()) jvObj[jss::base_fee] = baseFeeXRP->xrp().jsonClipped(); - if (auto const reserveBaseXRP = ~val->at(~sfReserveBaseDrops); - reserveBaseXRP && reserveBaseXRP->native()) + if (auto const reserveBaseXRP = ~val->at(~sfReserveBaseDrops); reserveBaseXRP && reserveBaseXRP->native()) jvObj[jss::reserve_base] = reserveBaseXRP->xrp().jsonClipped(); - if (auto const reserveIncXRP = ~val->at(~sfReserveIncrementDrops); - reserveIncXRP && reserveIncXRP->native()) + if (auto const reserveIncXRP = ~val->at(~sfReserveIncrementDrops); reserveIncXRP && reserveIncXRP->native()) jvObj[jss::reserve_inc] = reserveIncXRP->xrp().jsonClipped(); // NOTE Use MultiApiJson to publish two slightly different JSON objects @@ -2478,13 +2258,11 @@ NetworkOPsImp::pubValidation(std::shared_ptr const& val) // Type conversion for older API versions to string if (jvTx.isMember(jss::ledger_index)) { - jvTx[jss::ledger_index] = - std::to_string(jvTx[jss::ledger_index].asUInt()); + jvTx[jss::ledger_index] = std::to_string(jvTx[jss::ledger_index].asUInt()); } }); - for (auto i = mStreamMaps[sValidations].begin(); - i != mStreamMaps[sValidations].end();) + for (auto i = mStreamMaps[sValidations].begin(); i != mStreamMaps[sValidations].end();) { if (auto p = i->second.lock()) { @@ -2512,8 +2290,7 @@ NetworkOPsImp::pubPeerStatus(std::function const& func) jvObj[jss::type] = "peerStatusChange"; - for (auto i = mStreamMaps[sPeerStatus].begin(); - i != mStreamMaps[sPeerStatus].end();) + for (auto i = mStreamMaps[sPeerStatus].begin(); i != mStreamMaps[sPeerStatus].end();) { InfoSub::pointer p = i->second.lock(); @@ -2536,12 +2313,12 @@ NetworkOPsImp::setMode(OperatingMode om) using namespace std::chrono_literals; if (om == OperatingMode::CONNECTED) { - if (app_.getLedgerMaster().getValidatedLedgerAge() < 1min) + if (registry_.getLedgerMaster().getValidatedLedgerAge() < 1min) om = OperatingMode::SYNCING; } else if (om == OperatingMode::SYNCING) { - if (app_.getLedgerMaster().getValidatedLedgerAge() >= 1min) + if (registry_.getLedgerMaster().getValidatedLedgerAge() >= 1min) om = OperatingMode::CONNECTED; } @@ -2560,12 +2337,9 @@ NetworkOPsImp::setMode(OperatingMode om) } bool -NetworkOPsImp::recvValidation( - std::shared_ptr const& val, - std::string const& source) +NetworkOPsImp::recvValidation(std::shared_ptr const& val, std::string const& source) { - JLOG(m_journal.trace()) - << "recvValidation " << val->getLedgerHash() << " from " << source; + JLOG(m_journal.trace()) << "recvValidation " << val->getLedgerHash() << " from " << source; std::unique_lock lock(validationsMutex_); BypassAccept bypassAccept = BypassAccept::no; @@ -2576,19 +2350,16 @@ NetworkOPsImp::recvValidation( else pendingValidations_.insert(val->getLedgerHash()); scope_unlock unlock(lock); - handleNewValidation(app_, val, source, bypassAccept, m_journal); + handleNewValidation(registry_.app(), val, source, bypassAccept, m_journal); } catch (std::exception const& e) { - JLOG(m_journal.warn()) - << "Exception thrown for handling new validation " - << val->getLedgerHash() << ": " << e.what(); + JLOG(m_journal.warn()) << "Exception thrown for handling new validation " << val->getLedgerHash() << ": " + << e.what(); } catch (...) { - JLOG(m_journal.warn()) - << "Unknown exception thrown for handling new validation " - << val->getLedgerHash(); + JLOG(m_journal.warn()) << "Unknown exception thrown for handling new validation " << val->getLedgerHash(); } if (bypassAccept == BypassAccept::no) { @@ -2601,7 +2372,7 @@ NetworkOPsImp::recvValidation( JLOG(m_journal.debug()) << [this, &val]() -> auto { std::stringstream ss; ss << "VALIDATION: " << val->render() << " master_key: "; - auto master = app_.validators().getTrustedKey(val->getSignerPublic()); + auto master = registry_.validators().getTrustedKey(val->getSignerPublic()); if (master) { ss << toBase58(TokenType::NodePublic, *master); @@ -2615,7 +2386,7 @@ NetworkOPsImp::recvValidation( // We will always relay trusted validations; if configured, we will // also relay all untrusted validations. - return app_.config().RELAY_UNTRUSTED_VALIDATIONS == 1 || val->isTrusted(); + return registry_.app().config().RELAY_UNTRUSTED_VALIDATIONS == 1 || val->isTrusted(); } Json::Value @@ -2657,8 +2428,7 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) "One or more unsupported amendments have reached majority. " "Upgrade to the latest version before they are activated " "to avoid being amendment blocked."; - if (auto const expected = - app_.getAmendmentTable().firstUnsupportedExpected()) + if (auto const expected = registry_.getAmendmentTable().firstUnsupportedExpected()) { auto& d = w[jss::details] = Json::objectValue; d[jss::expected_date] = expected->time_since_epoch().count(); @@ -2675,25 +2445,23 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) info[jss::hostid] = getHostId(admin); // domain: if configured with a domain, report it: - if (!app_.config().SERVER_DOMAIN.empty()) - info[jss::server_domain] = app_.config().SERVER_DOMAIN; + if (!registry_.app().config().SERVER_DOMAIN.empty()) + info[jss::server_domain] = registry_.app().config().SERVER_DOMAIN; info[jss::build_version] = BuildInfo::getVersionString(); info[jss::server_state] = strOperatingMode(admin); - info[jss::time] = to_string(std::chrono::floor( - std::chrono::system_clock::now())); + info[jss::time] = to_string(std::chrono::floor(std::chrono::system_clock::now())); if (needNetworkLedger_) info[jss::network_ledger] = "waiting"; - info[jss::validation_quorum] = - static_cast(app_.validators().quorum()); + info[jss::validation_quorum] = static_cast(registry_.validators().quorum()); if (admin) { - switch (app_.config().NODE_SIZE) + switch (registry_.app().config().NODE_SIZE) { case 0: info[jss::node_size] = "tiny"; @@ -2712,13 +2480,12 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) break; } - auto when = app_.validators().expires(); + auto when = registry_.validators().expires(); if (!human) { if (when) - info[jss::validator_list_expires] = - safe_cast(when->time_since_epoch().count()); + info[jss::validator_list_expires] = safe_cast(when->time_since_epoch().count()); else info[jss::validator_list_expires] = 0; } @@ -2726,7 +2493,7 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) { auto& x = (info[jss::validator_list] = Json::objectValue); - x[jss::count] = static_cast(app_.validators().count()); + x[jss::count] = static_cast(registry_.validators().count()); if (when) { @@ -2739,7 +2506,7 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) { x[jss::expiration] = to_string(*when); - if (*when > app_.timeKeeper().now()) + if (*when > registry_.timeKeeper().now()) x[jss::status] = "active"; else x[jss::status] = "expired"; @@ -2764,16 +2531,14 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) } #endif } - info[jss::io_latency_ms] = - static_cast(app_.getIOLatency().count()); + info[jss::io_latency_ms] = static_cast(registry_.app().getIOLatency().count()); if (admin) { - if (auto const localPubKey = app_.validators().localPublicKey(); - localPubKey && app_.getValidationPublicKey()) + if (auto const localPubKey = registry_.validators().localPublicKey(); + localPubKey && registry_.app().getValidationPublicKey()) { - info[jss::pubkey_validator] = - toBase58(TokenType::NodePublic, localPubKey.value()); + info[jss::pubkey_validator] = toBase58(TokenType::NodePublic, localPubKey.value()); } else { @@ -2783,18 +2548,17 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) if (counters) { - info[jss::counters] = app_.getPerfLog().countersJson(); + info[jss::counters] = registry_.getPerfLog().countersJson(); Json::Value nodestore(Json::objectValue); - app_.getNodeStore().getCountsJson(nodestore); + registry_.getNodeStore().getCountsJson(nodestore); info[jss::counters][jss::nodestore] = nodestore; - info[jss::current_activities] = app_.getPerfLog().currentJson(); + info[jss::current_activities] = registry_.getPerfLog().currentJson(); } - info[jss::pubkey_node] = - toBase58(TokenType::NodePublic, app_.nodeIdentity().first); + info[jss::pubkey_node] = toBase58(TokenType::NodePublic, registry_.app().nodeIdentity().first); - info[jss::complete_ledgers] = app_.getLedgerMaster().getCompleteLedgers(); + info[jss::complete_ledgers] = registry_.getLedgerMaster().getCompleteLedgers(); if (amendmentBlocked_) info[jss::amendment_blocked] = true; @@ -2804,20 +2568,18 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) if (fp != 0) info[jss::fetch_pack] = Json::UInt(fp); - info[jss::peers] = Json::UInt(app_.overlay().size()); + info[jss::peers] = Json::UInt(registry_.overlay().size()); Json::Value lastClose = Json::objectValue; lastClose[jss::proposers] = Json::UInt(mConsensus.prevProposers()); if (human) { - lastClose[jss::converge_time_s] = - std::chrono::duration{mConsensus.prevRoundTime()}.count(); + lastClose[jss::converge_time_s] = std::chrono::duration{mConsensus.prevRoundTime()}.count(); } else { - lastClose[jss::converge_time] = - Json::Int(mConsensus.prevRoundTime().count()); + lastClose[jss::converge_time] = Json::Int(mConsensus.prevRoundTime().count()); } info[jss::last_close] = lastClose; @@ -2827,26 +2589,21 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) if (admin) info[jss::load] = m_job_queue.getJson(); - if (auto const netid = app_.overlay().networkID()) + if (auto const netid = registry_.overlay().networkID()) info[jss::network_id] = static_cast(*netid); - auto const escalationMetrics = - app_.getTxQ().getMetrics(*app_.openLedger().current()); + auto const escalationMetrics = registry_.getTxQ().getMetrics(*registry_.openLedger().current()); - auto const loadFactorServer = app_.getFeeTrack().getLoadFactor(); - auto const loadBaseServer = app_.getFeeTrack().getLoadBase(); + auto const loadFactorServer = registry_.getFeeTrack().getLoadFactor(); + auto const loadBaseServer = registry_.getFeeTrack().getLoadBase(); /* Scale the escalated fee level to unitless "load factor". In practice, this just strips the units, but it will continue to work correctly if either base value ever changes. */ auto const loadFactorFeeEscalation = - mulDiv( - escalationMetrics.openLedgerFeeLevel, - loadBaseServer, - escalationMetrics.referenceFeeLevel) + mulDiv(escalationMetrics.openLedgerFeeLevel, loadBaseServer, escalationMetrics.referenceFeeLevel) .value_or(xrpl::muldiv_max); - auto const loadFactor = std::max( - safe_cast(loadFactorServer), loadFactorFeeEscalation); + auto const loadFactor = std::max(safe_cast(loadFactorServer), loadFactorFeeEscalation); if (!human) { @@ -2859,48 +2616,36 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) probably isn't enough extant XRP to drive the factor that high. */ - info[jss::load_factor_fee_escalation] = - escalationMetrics.openLedgerFeeLevel.jsonClipped(); - info[jss::load_factor_fee_queue] = - escalationMetrics.minProcessingFeeLevel.jsonClipped(); - info[jss::load_factor_fee_reference] = - escalationMetrics.referenceFeeLevel.jsonClipped(); + info[jss::load_factor_fee_escalation] = escalationMetrics.openLedgerFeeLevel.jsonClipped(); + info[jss::load_factor_fee_queue] = escalationMetrics.minProcessingFeeLevel.jsonClipped(); + info[jss::load_factor_fee_reference] = escalationMetrics.referenceFeeLevel.jsonClipped(); } else { - info[jss::load_factor] = - static_cast(loadFactor) / loadBaseServer; + info[jss::load_factor] = static_cast(loadFactor) / loadBaseServer; if (loadFactorServer != loadFactor) - info[jss::load_factor_server] = - static_cast(loadFactorServer) / loadBaseServer; + info[jss::load_factor_server] = static_cast(loadFactorServer) / loadBaseServer; if (admin) { - std::uint32_t fee = app_.getFeeTrack().getLocalFee(); + std::uint32_t fee = registry_.getFeeTrack().getLocalFee(); if (fee != loadBaseServer) - info[jss::load_factor_local] = - static_cast(fee) / loadBaseServer; - fee = app_.getFeeTrack().getRemoteFee(); + info[jss::load_factor_local] = static_cast(fee) / loadBaseServer; + fee = registry_.getFeeTrack().getRemoteFee(); if (fee != loadBaseServer) - info[jss::load_factor_net] = - static_cast(fee) / loadBaseServer; - fee = app_.getFeeTrack().getClusterFee(); + info[jss::load_factor_net] = static_cast(fee) / loadBaseServer; + fee = registry_.getFeeTrack().getClusterFee(); if (fee != loadBaseServer) - info[jss::load_factor_cluster] = - static_cast(fee) / loadBaseServer; + info[jss::load_factor_cluster] = static_cast(fee) / loadBaseServer; } - if (escalationMetrics.openLedgerFeeLevel != - escalationMetrics.referenceFeeLevel && + if (escalationMetrics.openLedgerFeeLevel != escalationMetrics.referenceFeeLevel && (admin || loadFactorFeeEscalation != loadFactor)) info[jss::load_factor_fee_escalation] = - escalationMetrics.openLedgerFeeLevel.decimalFromReference( - escalationMetrics.referenceFeeLevel); - if (escalationMetrics.minProcessingFeeLevel != - escalationMetrics.referenceFeeLevel) + escalationMetrics.openLedgerFeeLevel.decimalFromReference(escalationMetrics.referenceFeeLevel); + if (escalationMetrics.minProcessingFeeLevel != escalationMetrics.referenceFeeLevel) info[jss::load_factor_fee_queue] = - escalationMetrics.minProcessingFeeLevel.decimalFromReference( - escalationMetrics.referenceFeeLevel); + escalationMetrics.minProcessingFeeLevel.decimalFromReference(escalationMetrics.referenceFeeLevel); } bool valid = false; @@ -2923,8 +2668,7 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) l[jss::base_fee] = baseFee.jsonClipped(); l[jss::reserve_base] = lpClosed->fees().reserve.jsonClipped(); l[jss::reserve_inc] = lpClosed->fees().increment.jsonClipped(); - l[jss::close_time] = Json::Value::UInt( - lpClosed->header().closeTime.time_since_epoch().count()); + l[jss::close_time] = Json::Value::UInt(lpClosed->header().closeTime.time_since_epoch().count()); } else { @@ -2932,28 +2676,24 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) l[jss::reserve_base_xrp] = lpClosed->fees().reserve.decimalXRP(); l[jss::reserve_inc_xrp] = lpClosed->fees().increment.decimalXRP(); - if (auto const closeOffset = app_.timeKeeper().closeOffset(); - std::abs(closeOffset.count()) >= 60) - l[jss::close_time_offset] = - static_cast(closeOffset.count()); + if (auto const closeOffset = registry_.timeKeeper().closeOffset(); std::abs(closeOffset.count()) >= 60) + l[jss::close_time_offset] = static_cast(closeOffset.count()); constexpr std::chrono::seconds highAgeThreshold{1000000}; if (m_ledgerMaster.haveValidated()) { auto const age = m_ledgerMaster.getValidatedLedgerAge(); - l[jss::age] = - Json::UInt(age < highAgeThreshold ? age.count() : 0); + l[jss::age] = Json::UInt(age < highAgeThreshold ? age.count() : 0); } else { auto lCloseTime = lpClosed->header().closeTime; - auto closeTime = app_.timeKeeper().closeTime(); + auto closeTime = registry_.timeKeeper().closeTime(); if (lCloseTime <= closeTime) { using namespace std::chrono_literals; auto age = closeTime - lCloseTime; - l[jss::age] = - Json::UInt(age < highAgeThreshold ? age.count() : 0); + l[jss::age] = Json::UInt(age < highAgeThreshold ? age.count() : 0); } } } @@ -2972,25 +2712,21 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) accounting_.json(info); info[jss::uptime] = UptimeClock::now().time_since_epoch().count(); - info[jss::jq_trans_overflow] = - std::to_string(app_.overlay().getJqTransOverflow()); - info[jss::peer_disconnects] = - std::to_string(app_.overlay().getPeerDisconnect()); - info[jss::peer_disconnects_resources] = - std::to_string(app_.overlay().getPeerDisconnectCharges()); + info[jss::jq_trans_overflow] = std::to_string(registry_.overlay().getJqTransOverflow()); + info[jss::peer_disconnects] = std::to_string(registry_.overlay().getPeerDisconnect()); + info[jss::peer_disconnects_resources] = std::to_string(registry_.overlay().getPeerDisconnectCharges()); // This array must be sorted in increasing order. - static constexpr std::array protocols{ - "http", "https", "peer", "ws", "ws2", "wss", "wss2"}; + static constexpr std::array protocols{"http", "https", "peer", "ws", "ws2", "wss", "wss2"}; static_assert(std::is_sorted(std::begin(protocols), std::end(protocols))); { Json::Value ports{Json::arrayValue}; - for (auto const& port : app_.getServerHandler().setup().ports) + for (auto const& port : registry_.getServerHandler().setup().ports) { // Don't publish admin ports for non-admin users if (!admin && - !(port.admin_nets_v4.empty() && port.admin_nets_v6.empty() && - port.admin_user.empty() && port.admin_password.empty())) + !(port.admin_nets_v4.empty() && port.admin_nets_v6.empty() && port.admin_user.empty() && + port.admin_password.empty())) continue; std::vector proto; std::set_intersection( @@ -3009,9 +2745,9 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) } } - if (app_.config().exists(SECTION_PORT_GRPC)) + if (registry_.app().config().exists(SECTION_PORT_GRPC)) { - auto const& grpcSection = app_.config().section(SECTION_PORT_GRPC); + auto const& grpcSection = registry_.app().config().section(SECTION_PORT_GRPC); auto const optPort = grpcSection.get("port"); if (optPort && grpcSection.get("ip")) { @@ -3030,13 +2766,13 @@ NetworkOPsImp::getServerInfo(bool human, bool admin, bool counters) void NetworkOPsImp::clearLedgerFetch() { - app_.getInboundLedgers().clearFailures(); + registry_.getInboundLedgers().clearFailures(); } Json::Value NetworkOPsImp::getLedgerFetchInfo() { - return app_.getInboundLedgers().getInfo(); + return registry_.getInboundLedgers().getInfo(); } void @@ -3052,8 +2788,7 @@ NetworkOPsImp::pubProposedTransaction( if (transaction->isFlag(tfInnerBatchTxn)) return; - MultiApiJson jvObj = - transJson(transaction, result, false, ledger, std::nullopt); + MultiApiJson jvObj = transJson(transaction, result, false, ledger, std::nullopt); { std::lock_guard sl(mSubLock); @@ -3086,23 +2821,17 @@ NetworkOPsImp::pubLedger(std::shared_ptr const& lpAccepted) // Ledgers are published only when they acquire sufficient validations // Holes are filled across connection loss or other catastrophe - std::shared_ptr alpAccepted = - app_.getAcceptedLedgerCache().fetch(lpAccepted->header().hash); + std::shared_ptr alpAccepted = registry_.getAcceptedLedgerCache().fetch(lpAccepted->header().hash); if (!alpAccepted) { - alpAccepted = std::make_shared(lpAccepted, app_); - app_.getAcceptedLedgerCache().canonicalize_replace_client( - lpAccepted->header().hash, alpAccepted); + alpAccepted = std::make_shared(lpAccepted); + registry_.getAcceptedLedgerCache().canonicalize_replace_client(lpAccepted->header().hash, alpAccepted); } - XRPL_ASSERT( - alpAccepted->getLedger().get() == lpAccepted.get(), - "xrpl::NetworkOPsImp::pubLedger : accepted input"); + XRPL_ASSERT(alpAccepted->getLedger().get() == lpAccepted.get(), "xrpl::NetworkOPsImp::pubLedger : accepted input"); { - JLOG(m_journal.debug()) - << "Publishing ledger " << lpAccepted->header().seq << " " - << lpAccepted->header().hash; + JLOG(m_journal.debug()) << "Publishing ledger " << lpAccepted->header().seq << " " << lpAccepted->header().hash; std::lock_guard sl(mSubLock); @@ -3113,24 +2842,21 @@ NetworkOPsImp::pubLedger(std::shared_ptr const& lpAccepted) jvObj[jss::type] = "ledgerClosed"; jvObj[jss::ledger_index] = lpAccepted->header().seq; jvObj[jss::ledger_hash] = to_string(lpAccepted->header().hash); - jvObj[jss::ledger_time] = Json::Value::UInt( - lpAccepted->header().closeTime.time_since_epoch().count()); + jvObj[jss::ledger_time] = Json::Value::UInt(lpAccepted->header().closeTime.time_since_epoch().count()); - jvObj[jss::network_id] = app_.config().NETWORK_ID; + jvObj[jss::network_id] = registry_.app().config().NETWORK_ID; if (!lpAccepted->rules().enabled(featureXRPFees)) jvObj[jss::fee_ref] = Config::FEE_UNITS_DEPRECATED; jvObj[jss::fee_base] = lpAccepted->fees().base.jsonClipped(); jvObj[jss::reserve_base] = lpAccepted->fees().reserve.jsonClipped(); - jvObj[jss::reserve_inc] = - lpAccepted->fees().increment.jsonClipped(); + jvObj[jss::reserve_inc] = lpAccepted->fees().increment.jsonClipped(); jvObj[jss::txn_count] = Json::UInt(alpAccepted->size()); if (mMode >= OperatingMode::SYNCING) { - jvObj[jss::validated_ledgers] = - app_.getLedgerMaster().getCompleteLedgers(); + jvObj[jss::validated_ledgers] = registry_.getLedgerMaster().getCompleteLedgers(); } auto it = mStreamMaps[sLedger].begin(); @@ -3178,8 +2904,7 @@ NetworkOPsImp::pubLedger(std::shared_ptr const& lpAccepted) auto& subInfo = inner.second; if (subInfo.index_->separationLedgerSeq_ == 0) { - subAccountHistoryStart( - alpAccepted->getLedger(), subInfo); + subAccountHistoryStart(alpAccepted->getLedger(), subInfo); } } } @@ -3191,8 +2916,7 @@ NetworkOPsImp::pubLedger(std::shared_ptr const& lpAccepted) for (auto const& accTx : *alpAccepted) { JLOG(m_journal.trace()) << "pubAccepted: " << accTx->getJson(); - pubValidatedTransaction( - lpAccepted, *accTx, accTx == *(--alpAccepted->end())); + pubValidatedTransaction(lpAccepted, *accTx, accTx == *(--alpAccepted->end())); } } @@ -3200,27 +2924,21 @@ void NetworkOPsImp::reportFeeChange() { ServerFeeSummary f{ - app_.openLedger().current()->fees().base, - app_.getTxQ().getMetrics(*app_.openLedger().current()), - app_.getFeeTrack()}; + registry_.openLedger().current()->fees().base, + registry_.getTxQ().getMetrics(*registry_.openLedger().current()), + registry_.getFeeTrack()}; // only schedule the job if something has changed if (f != mLastFeeSummary) { - m_job_queue.addJob( - jtCLIENT_FEE_CHANGE, "reportFeeChange->pubServer", [this]() { - pubServer(); - }); + m_job_queue.addJob(jtCLIENT_FEE_CHANGE, "PubFee", [this]() { pubServer(); }); } } void NetworkOPsImp::reportConsensusStateChange(ConsensusPhase phase) { - m_job_queue.addJob( - jtCLIENT_CONSENSUS, - "reportConsensusStateChange->pubConsensus", - [this, phase]() { pubConsensus(phase); }); + m_job_queue.addJob(jtCLIENT_CONSENSUS, "PubCons", [this, phase]() { pubConsensus(phase); }); } inline void @@ -3254,17 +2972,14 @@ NetworkOPsImp::transJson( // NOTE jvObj is not a finished object for either API version. After // it's populated, we need to finish it for a specific API version. This is // done in a loop, near the end of this function. - jvObj[jss::transaction] = - transaction->getJson(JsonOptions::disable_API_prior_V2, false); + jvObj[jss::transaction] = transaction->getJson(JsonOptions::disable_API_prior_V2, false); if (meta) { jvObj[jss::meta] = meta->get().getJson(JsonOptions::none); - RPC::insertDeliveredAmount( - jvObj[jss::meta], *ledger, transaction, meta->get()); + RPC::insertDeliveredAmount(jvObj[jss::meta], *ledger, transaction, meta->get()); RPC::insertNFTSyntheticInJson(jvObj, transaction, meta->get()); - RPC::insertMPTokenIssuanceID( - jvObj[jss::meta], transaction, meta->get()); + RPC::insertMPTokenIssuanceID(jvObj[jss::meta], transaction, meta->get()); } // add CTID where the needed data for it exists @@ -3272,13 +2987,11 @@ NetworkOPsImp::transJson( lookup.second && lookup.second->isFieldPresent(sfTransactionIndex)) { uint32_t const txnSeq = lookup.second->getFieldU32(sfTransactionIndex); - uint32_t netID = app_.config().NETWORK_ID; + uint32_t netID = registry_.app().config().NETWORK_ID; if (transaction->isFieldPresent(sfNetworkID)) netID = transaction->getFieldU32(sfNetworkID); - if (std::optional ctid = - RPC::encodeCTID(ledger->header().seq, txnSeq, netID); - ctid) + if (std::optional ctid = RPC::encodeCTID(ledger->header().seq, txnSeq, netID); ctid) jvObj[jss::ctid] = *ctid; } if (!ledger->open()) @@ -3287,8 +3000,7 @@ NetworkOPsImp::transJson( if (validated) { jvObj[jss::ledger_index] = ledger->header().seq; - jvObj[jss::transaction][jss::date] = - ledger->header().closeTime.time_since_epoch().count(); + jvObj[jss::transaction][jss::date] = ledger->header().closeTime.time_since_epoch().count(); jvObj[jss::validated] = true; jvObj[jss::close_time_iso] = to_string_iso(ledger->header().closeTime); @@ -3313,12 +3025,7 @@ NetworkOPsImp::transJson( // If the offer create is not self funded then add the owner balance if (account != amount.issue().account) { - auto const ownerFunds = accountFunds( - *ledger, - account, - amount, - fhIGNORE_FREEZE, - app_.journal("View")); + auto const ownerFunds = accountFunds(*ledger, account, amount, fhIGNORE_FREEZE, registry_.journal("View")); jvObj[jss::transaction][jss::owner_funds] = ownerFunds.getText(); } } @@ -3327,10 +3034,8 @@ NetworkOPsImp::transJson( MultiApiJson multiObj{jvObj}; forAllApiVersions( multiObj.visit(), // - [&]( - Json::Value& jvTx, std::integral_constant) { - RPC::insertDeliverMax( - jvTx[jss::transaction], transaction->getTxnType(), Version); + [&](Json::Value& jvTx, std::integral_constant) { + RPC::insertDeliverMax(jvTx[jss::transaction], transaction->getTxnType(), Version); if constexpr (Version > 1) { @@ -3397,7 +3102,7 @@ NetworkOPsImp::pubValidatedTransaction( } if (transaction.getResult() == tesSUCCESS) - app_.getOrderBookDB().processTxn(ledger, transaction, jvObj); + registry_.getOrderBookDB().processTxn(ledger, transaction, jvObj); pubAccountTransaction(ledger, transaction, last); } @@ -3417,13 +3122,11 @@ NetworkOPsImp::pubAccountTransaction( { std::lock_guard sl(mSubLock); - if (!mSubAccount.empty() || !mSubRTAccount.empty() || - !mSubAccountHistory.empty()) + if (!mSubAccount.empty() || !mSubRTAccount.empty() || !mSubAccountHistory.empty()) { for (auto const& affectedAccount : transaction.getAffected()) { - if (auto simiIt = mSubRTAccount.find(affectedAccount); - simiIt != mSubRTAccount.end()) + if (auto simiIt = mSubRTAccount.find(affectedAccount); simiIt != mSubRTAccount.end()) { auto it = simiIt->second.begin(); @@ -3442,8 +3145,7 @@ NetworkOPsImp::pubAccountTransaction( } } - if (auto simiIt = mSubAccount.find(affectedAccount); - simiIt != mSubAccount.end()) + if (auto simiIt = mSubAccount.find(affectedAccount); simiIt != mSubAccount.end()) { auto it = simiIt->second.begin(); while (it != simiIt->second.end()) @@ -3461,8 +3163,7 @@ NetworkOPsImp::pubAccountTransaction( } } - if (auto historyIt = mSubAccountHistory.find(affectedAccount); - historyIt != mSubAccountHistory.end()) + if (auto historyIt = mSubAccountHistory.find(affectedAccount); historyIt != mSubAccountHistory.end()) { auto& subs = historyIt->second; auto it = subs.begin(); @@ -3477,8 +3178,7 @@ NetworkOPsImp::pubAccountTransaction( if (auto isSptr = info.sinkWptr_.lock(); isSptr) { - accountHistoryNotify.emplace_back( - SubAccountHistoryInfo{isSptr, info.index_}); + accountHistoryNotify.emplace_back(SubAccountHistoryInfo{isSptr, info.index_}); ++it; } else @@ -3493,9 +3193,8 @@ NetworkOPsImp::pubAccountTransaction( } } - JLOG(m_journal.trace()) - << "pubAccountTransaction: " - << "proposed=" << iProposed << ", accepted=" << iAccepted; + JLOG(m_journal.trace()) << "pubAccountTransaction: " + << "proposed=" << iProposed << ", accepted=" << iAccepted; if (!notify.empty() || !accountHistoryNotify.empty()) { @@ -3517,8 +3216,7 @@ NetworkOPsImp::pubAccountTransaction( jvObj.set(jss::account_history_boundary, true); XRPL_ASSERT( - jvObj.isMember(jss::account_history_tx_stream) == - MultiApiJson::none, + jvObj.isMember(jss::account_history_tx_stream) == MultiApiJson::none, "xrpl::NetworkOPsImp::pubAccountTransaction : " "account_history_tx_stream not set"); for (auto& info : accountHistoryNotify) @@ -3553,13 +3251,11 @@ NetworkOPsImp::pubProposedAccountTransaction( if (mSubRTAccount.empty()) return; - if (!mSubAccount.empty() || !mSubRTAccount.empty() || - !mSubAccountHistory.empty()) + if (!mSubAccount.empty() || !mSubRTAccount.empty() || !mSubAccountHistory.empty()) { for (auto const& affectedAccount : tx->getMentionedAccounts()) { - if (auto simiIt = mSubRTAccount.find(affectedAccount); - simiIt != mSubRTAccount.end()) + if (auto simiIt = mSubRTAccount.find(affectedAccount); simiIt != mSubRTAccount.end()) { auto it = simiIt->second.begin(); @@ -3594,8 +3290,7 @@ NetworkOPsImp::pubProposedAccountTransaction( [&](Json::Value const& jv) { isrListener->send(jv, true); }); XRPL_ASSERT( - jvObj.isMember(jss::account_history_tx_stream) == - MultiApiJson::none, + jvObj.isMember(jss::account_history_tx_stream) == MultiApiJson::none, "xrpl::NetworkOPs::pubProposedAccountTransaction : " "account_history_tx_stream not set"); for (auto& info : accountHistoryNotify) @@ -3616,17 +3311,13 @@ NetworkOPsImp::pubProposedAccountTransaction( // void -NetworkOPsImp::subAccount( - InfoSub::ref isrListener, - hash_set const& vnaAccountIDs, - bool rt) +NetworkOPsImp::subAccount(InfoSub::ref isrListener, hash_set const& vnaAccountIDs, bool rt) { SubInfoMapType& subMap = rt ? mSubRTAccount : mSubAccount; for (auto const& naAccountID : vnaAccountIDs) { - JLOG(m_journal.trace()) - << "subAccount: account: " << toBase58(naAccountID); + JLOG(m_journal.trace()) << "subAccount: account: " << toBase58(naAccountID); isrListener->insertSubAccountInfo(naAccountID, rt); } @@ -3653,10 +3344,7 @@ NetworkOPsImp::subAccount( } void -NetworkOPsImp::unsubAccount( - InfoSub::ref isrListener, - hash_set const& vnaAccountIDs, - bool rt) +NetworkOPsImp::unsubAccount(InfoSub::ref isrListener, hash_set const& vnaAccountIDs, bool rt) { for (auto const& naAccountID : vnaAccountIDs) { @@ -3669,10 +3357,7 @@ NetworkOPsImp::unsubAccount( } void -NetworkOPsImp::unsubAccountInternal( - std::uint64_t uSeq, - hash_set const& vnaAccountIDs, - bool rt) +NetworkOPsImp::unsubAccountInternal(std::uint64_t uSeq, hash_set const& vnaAccountIDs, bool rt) { std::lock_guard sl(mSubLock); @@ -3703,7 +3388,7 @@ NetworkOPsImp::addAccountHistoryJob(SubAccountHistoryInfoWeak subInfo) static auto const databaseType = [&]() -> DatabaseType { // Use a dynamic_cast to return DatabaseType::None // on failure. - if (dynamic_cast(&app_.getRelationalDatabase())) + if (dynamic_cast(®istry_.getRelationalDatabase())) { return DatabaseType::Sqlite; } @@ -3714,9 +3399,8 @@ NetworkOPsImp::addAccountHistoryJob(SubAccountHistoryInfoWeak subInfo) { // LCOV_EXCL_START UNREACHABLE("xrpl::NetworkOPsImp::addAccountHistoryJob : no database"); - JLOG(m_journal.error()) - << "AccountHistory job for account " - << toBase58(subInfo.index_->accountId_) << " no database"; + JLOG(m_journal.error()) << "AccountHistory job for account " << toBase58(subInfo.index_->accountId_) + << " no database"; if (auto sptr = subInfo.sinkWptr_.lock(); sptr) { sptr->send(rpcError(rpcINTERNAL), true); @@ -3726,299 +3410,253 @@ NetworkOPsImp::addAccountHistoryJob(SubAccountHistoryInfoWeak subInfo) // LCOV_EXCL_STOP } - app_.getJobQueue().addJob( - jtCLIENT_ACCT_HIST, - "AccountHistoryTxStream", - [this, dbType = databaseType, subInfo]() { - auto const& accountId = subInfo.index_->accountId_; - auto& lastLedgerSeq = subInfo.index_->historyLastLedgerSeq_; - auto& txHistoryIndex = subInfo.index_->historyTxIndex_; + registry_.getJobQueue().addJob(jtCLIENT_ACCT_HIST, "HistTxStream", [this, dbType = databaseType, subInfo]() { + auto const& accountId = subInfo.index_->accountId_; + auto& lastLedgerSeq = subInfo.index_->historyLastLedgerSeq_; + auto& txHistoryIndex = subInfo.index_->historyTxIndex_; - JLOG(m_journal.trace()) - << "AccountHistory job for account " << toBase58(accountId) - << " started. lastLedgerSeq=" << lastLedgerSeq; + JLOG(m_journal.trace()) << "AccountHistory job for account " << toBase58(accountId) + << " started. lastLedgerSeq=" << lastLedgerSeq; - auto isFirstTx = [&](std::shared_ptr const& tx, - std::shared_ptr const& meta) -> bool { - /* - * genesis account: first tx is the one with seq 1 - * other account: first tx is the one created the account - */ - if (accountId == genesisAccountId) + auto isFirstTx = [&](std::shared_ptr const& tx, std::shared_ptr const& meta) -> bool { + /* + * genesis account: first tx is the one with seq 1 + * other account: first tx is the one created the account + */ + if (accountId == genesisAccountId) + { + auto stx = tx->getSTransaction(); + if (stx->getAccountID(sfAccount) == accountId && stx->getSeqValue() == 1) + return true; + } + + for (auto& node : meta->getNodes()) + { + if (node.getFieldU16(sfLedgerEntryType) != ltACCOUNT_ROOT) + continue; + + if (node.isFieldPresent(sfNewFields)) { - auto stx = tx->getSTransaction(); - if (stx->getAccountID(sfAccount) == accountId && - stx->getSeqValue() == 1) - return true; - } - - for (auto& node : meta->getNodes()) - { - if (node.getFieldU16(sfLedgerEntryType) != ltACCOUNT_ROOT) - continue; - - if (node.isFieldPresent(sfNewFields)) + if (auto inner = dynamic_cast(node.peekAtPField(sfNewFields)); inner) { - if (auto inner = dynamic_cast( - node.peekAtPField(sfNewFields)); - inner) + if (inner->isFieldPresent(sfAccount) && inner->getAccountID(sfAccount) == accountId) { - if (inner->isFieldPresent(sfAccount) && - inner->getAccountID(sfAccount) == accountId) - { - return true; - } + return true; } } } + } - return false; - }; + return false; + }; - auto send = [&](Json::Value const& jvObj, - bool unsubscribe) -> bool { - if (auto sptr = subInfo.sinkWptr_.lock()) - { - sptr->send(jvObj, true); - if (unsubscribe) - unsubAccountHistory(sptr, accountId, false); - return true; - } - - return false; - }; - - auto sendMultiApiJson = [&](MultiApiJson const& jvObj, - bool unsubscribe) -> bool { - if (auto sptr = subInfo.sinkWptr_.lock()) - { - jvObj.visit( - sptr->getApiVersion(), // - [&](Json::Value const& jv) { sptr->send(jv, true); }); - - if (unsubscribe) - unsubAccountHistory(sptr, accountId, false); - return true; - } - - return false; - }; - - auto getMoreTxns = - [&](std::uint32_t minLedger, - std::uint32_t maxLedger, - std::optional marker) - -> std::optional>> { - switch (dbType) - { - case Sqlite: { - auto db = static_cast( - &app_.getRelationalDatabase()); - RelationalDatabase::AccountTxPageOptions options{ - accountId, minLedger, maxLedger, marker, 0, true}; - return db->newestAccountTxPage(options); - } - // LCOV_EXCL_START - default: { - UNREACHABLE( - "xrpl::NetworkOPsImp::addAccountHistoryJob : " - "getMoreTxns : invalid database type"); - return {}; - } - // LCOV_EXCL_STOP - } - }; - - /* - * search backward until the genesis ledger or asked to stop - */ - while (lastLedgerSeq >= 2 && !subInfo.index_->stopHistorical_) + auto send = [&](Json::Value const& jvObj, bool unsubscribe) -> bool { + if (auto sptr = subInfo.sinkWptr_.lock()) { - int feeChargeCount = 0; - if (auto sptr = subInfo.sinkWptr_.lock(); sptr) - { - sptr->getConsumer().charge(Resource::feeMediumBurdenRPC); - ++feeChargeCount; + sptr->send(jvObj, true); + if (unsubscribe) + unsubAccountHistory(sptr, accountId, false); + return true; + } + + return false; + }; + + auto sendMultiApiJson = [&](MultiApiJson const& jvObj, bool unsubscribe) -> bool { + if (auto sptr = subInfo.sinkWptr_.lock()) + { + jvObj.visit( + sptr->getApiVersion(), // + [&](Json::Value const& jv) { sptr->send(jv, true); }); + + if (unsubscribe) + unsubAccountHistory(sptr, accountId, false); + return true; + } + + return false; + }; + + auto getMoreTxns = [&](std::uint32_t minLedger, + std::uint32_t maxLedger, + std::optional marker) + -> std::optional< + std::pair>> { + switch (dbType) + { + case Sqlite: { + auto db = static_cast(®istry_.getRelationalDatabase()); + RelationalDatabase::AccountTxPageOptions options{accountId, minLedger, maxLedger, marker, 0, true}; + return db->newestAccountTxPage(options); } - else - { - JLOG(m_journal.trace()) - << "AccountHistory job for account " - << toBase58(accountId) << " no InfoSub. Fee charged " - << feeChargeCount << " times."; - return; + // LCOV_EXCL_START + default: { + UNREACHABLE( + "xrpl::NetworkOPsImp::addAccountHistoryJob : " + "getMoreTxns : invalid database type"); + return {}; } + // LCOV_EXCL_STOP + } + }; - // try to search in 1024 ledgers till reaching genesis ledgers - auto startLedgerSeq = - (lastLedgerSeq > 1024 + 2 ? lastLedgerSeq - 1024 : 2); - JLOG(m_journal.trace()) - << "AccountHistory job for account " << toBase58(accountId) - << ", working on ledger range [" << startLedgerSeq << "," - << lastLedgerSeq << "]"; + /* + * search backward until the genesis ledger or asked to stop + */ + while (lastLedgerSeq >= 2 && !subInfo.index_->stopHistorical_) + { + int feeChargeCount = 0; + if (auto sptr = subInfo.sinkWptr_.lock(); sptr) + { + sptr->getConsumer().charge(Resource::feeMediumBurdenRPC); + ++feeChargeCount; + } + else + { + JLOG(m_journal.trace()) << "AccountHistory job for account " << toBase58(accountId) + << " no InfoSub. Fee charged " << feeChargeCount << " times."; + return; + } - auto haveRange = [&]() -> bool { - std::uint32_t validatedMin = UINT_MAX; - std::uint32_t validatedMax = 0; - auto haveSomeValidatedLedgers = - app_.getLedgerMaster().getValidatedRange( - validatedMin, validatedMax); + // try to search in 1024 ledgers till reaching genesis ledgers + auto startLedgerSeq = (lastLedgerSeq > 1024 + 2 ? lastLedgerSeq - 1024 : 2); + JLOG(m_journal.trace()) << "AccountHistory job for account " << toBase58(accountId) + << ", working on ledger range [" << startLedgerSeq << "," << lastLedgerSeq << "]"; - return haveSomeValidatedLedgers && - validatedMin <= startLedgerSeq && - lastLedgerSeq <= validatedMax; - }(); + auto haveRange = [&]() -> bool { + std::uint32_t validatedMin = UINT_MAX; + std::uint32_t validatedMax = 0; + auto haveSomeValidatedLedgers = + registry_.getLedgerMaster().getValidatedRange(validatedMin, validatedMax); - if (!haveRange) + return haveSomeValidatedLedgers && validatedMin <= startLedgerSeq && lastLedgerSeq <= validatedMax; + }(); + + if (!haveRange) + { + JLOG(m_journal.debug()) << "AccountHistory reschedule job for account " << toBase58(accountId) + << ", incomplete ledger range [" << startLedgerSeq << "," << lastLedgerSeq + << "]"; + setAccountHistoryJobTimer(subInfo); + return; + } + + std::optional marker{}; + while (!subInfo.index_->stopHistorical_) + { + auto dbResult = getMoreTxns(startLedgerSeq, lastLedgerSeq, marker); + if (!dbResult) { + // LCOV_EXCL_START + UNREACHABLE( + "xrpl::NetworkOPsImp::addAccountHistoryJob : " + "getMoreTxns failed"); JLOG(m_journal.debug()) - << "AccountHistory reschedule job for account " - << toBase58(accountId) << ", incomplete ledger range [" - << startLedgerSeq << "," << lastLedgerSeq << "]"; - setAccountHistoryJobTimer(subInfo); + << "AccountHistory job for account " << toBase58(accountId) << " getMoreTxns failed."; + send(rpcError(rpcINTERNAL), true); return; + // LCOV_EXCL_STOP } - std::optional marker{}; - while (!subInfo.index_->stopHistorical_) + auto const& txns = dbResult->first; + marker = dbResult->second; + size_t num_txns = txns.size(); + for (size_t i = 0; i < num_txns; ++i) { - auto dbResult = - getMoreTxns(startLedgerSeq, lastLedgerSeq, marker); - if (!dbResult) + auto const& [tx, meta] = txns[i]; + + if (!tx || !meta) + { + JLOG(m_journal.debug()) + << "AccountHistory job for account " << toBase58(accountId) << " empty tx or meta."; + send(rpcError(rpcINTERNAL), true); + return; + } + auto curTxLedger = registry_.getLedgerMaster().getLedgerBySeq(tx->getLedger()); + if (!curTxLedger) { // LCOV_EXCL_START UNREACHABLE( "xrpl::NetworkOPsImp::addAccountHistoryJob : " - "getMoreTxns failed"); + "getLedgerBySeq failed"); JLOG(m_journal.debug()) - << "AccountHistory job for account " - << toBase58(accountId) << " getMoreTxns failed."; + << "AccountHistory job for account " << toBase58(accountId) << " no ledger."; + send(rpcError(rpcINTERNAL), true); + return; + // LCOV_EXCL_STOP + } + std::shared_ptr stTxn = tx->getSTransaction(); + if (!stTxn) + { + // LCOV_EXCL_START + UNREACHABLE( + "NetworkOPsImp::addAccountHistoryJob : " + "getSTransaction failed"); + JLOG(m_journal.debug()) + << "AccountHistory job for account " << toBase58(accountId) << " getSTransaction failed."; send(rpcError(rpcINTERNAL), true); return; // LCOV_EXCL_STOP } - auto const& txns = dbResult->first; - marker = dbResult->second; - size_t num_txns = txns.size(); - for (size_t i = 0; i < num_txns; ++i) + auto const mRef = std::ref(*meta); + auto const trR = meta->getResultTER(); + MultiApiJson jvTx = transJson(stTxn, trR, true, curTxLedger, mRef); + + jvTx.set(jss::account_history_tx_index, txHistoryIndex--); + if (i + 1 == num_txns || txns[i + 1].first->getLedger() != tx->getLedger()) + jvTx.set(jss::account_history_boundary, true); + + if (isFirstTx(tx, meta)) { - auto const& [tx, meta] = txns[i]; + jvTx.set(jss::account_history_tx_first, true); + sendMultiApiJson(jvTx, false); - if (!tx || !meta) - { - JLOG(m_journal.debug()) - << "AccountHistory job for account " - << toBase58(accountId) << " empty tx or meta."; - send(rpcError(rpcINTERNAL), true); - return; - } - auto curTxLedger = - app_.getLedgerMaster().getLedgerBySeq( - tx->getLedger()); - if (!curTxLedger) - { - // LCOV_EXCL_START - UNREACHABLE( - "xrpl::NetworkOPsImp::addAccountHistoryJob : " - "getLedgerBySeq failed"); - JLOG(m_journal.debug()) - << "AccountHistory job for account " - << toBase58(accountId) << " no ledger."; - send(rpcError(rpcINTERNAL), true); - return; - // LCOV_EXCL_STOP - } - std::shared_ptr stTxn = - tx->getSTransaction(); - if (!stTxn) - { - // LCOV_EXCL_START - UNREACHABLE( - "NetworkOPsImp::addAccountHistoryJob : " - "getSTransaction failed"); - JLOG(m_journal.debug()) - << "AccountHistory job for account " - << toBase58(accountId) - << " getSTransaction failed."; - send(rpcError(rpcINTERNAL), true); - return; - // LCOV_EXCL_STOP - } - - auto const mRef = std::ref(*meta); - auto const trR = meta->getResultTER(); - MultiApiJson jvTx = - transJson(stTxn, trR, true, curTxLedger, mRef); - - jvTx.set( - jss::account_history_tx_index, txHistoryIndex--); - if (i + 1 == num_txns || - txns[i + 1].first->getLedger() != tx->getLedger()) - jvTx.set(jss::account_history_boundary, true); - - if (isFirstTx(tx, meta)) - { - jvTx.set(jss::account_history_tx_first, true); - sendMultiApiJson(jvTx, false); - - JLOG(m_journal.trace()) - << "AccountHistory job for account " - << toBase58(accountId) - << " done, found last tx."; - return; - } - else - { - sendMultiApiJson(jvTx, false); - } - } - - if (marker) - { JLOG(m_journal.trace()) - << "AccountHistory job for account " - << toBase58(accountId) - << " paging, marker=" << marker->ledgerSeq << ":" - << marker->txnSeq; + << "AccountHistory job for account " << toBase58(accountId) << " done, found last tx."; + return; } else { - break; + sendMultiApiJson(jvTx, false); } } - if (!subInfo.index_->stopHistorical_) + if (marker) { - lastLedgerSeq = startLedgerSeq - 1; - if (lastLedgerSeq <= 1) - { - JLOG(m_journal.trace()) - << "AccountHistory job for account " - << toBase58(accountId) - << " done, reached genesis ledger."; - return; - } + JLOG(m_journal.trace()) << "AccountHistory job for account " << toBase58(accountId) + << " paging, marker=" << marker->ledgerSeq << ":" << marker->txnSeq; + } + else + { + break; } } - }); + + if (!subInfo.index_->stopHistorical_) + { + lastLedgerSeq = startLedgerSeq - 1; + if (lastLedgerSeq <= 1) + { + JLOG(m_journal.trace()) + << "AccountHistory job for account " << toBase58(accountId) << " done, reached genesis ledger."; + return; + } + } + } + }); } void -NetworkOPsImp::subAccountHistoryStart( - std::shared_ptr const& ledger, - SubAccountHistoryInfoWeak& subInfo) +NetworkOPsImp::subAccountHistoryStart(std::shared_ptr const& ledger, SubAccountHistoryInfoWeak& subInfo) { subInfo.index_->separationLedgerSeq_ = ledger->seq(); auto const& accountId = subInfo.index_->accountId_; auto const accountKeylet = keylet::account(accountId); if (!ledger->exists(accountKeylet)) { - JLOG(m_journal.debug()) - << "subAccountHistoryStart, no account " << toBase58(accountId) - << ", no need to add AccountHistory job."; + JLOG(m_journal.debug()) << "subAccountHistoryStart, no account " << toBase58(accountId) + << ", no need to add AccountHistory job."; return; } if (accountId == genesisAccountId) @@ -4027,10 +3665,8 @@ NetworkOPsImp::subAccountHistoryStart( { if (sleAcct->getFieldU32(sfSequence) == 1) { - JLOG(m_journal.debug()) - << "subAccountHistoryStart, genesis account " - << toBase58(accountId) - << " does not have tx, no need to add AccountHistory job."; + JLOG(m_journal.debug()) << "subAccountHistoryStart, genesis account " << toBase58(accountId) + << " does not have tx, no need to add AccountHistory job."; return; } } @@ -4047,43 +3683,36 @@ NetworkOPsImp::subAccountHistoryStart( subInfo.index_->historyLastLedgerSeq_ = ledger->seq(); subInfo.index_->haveHistorical_ = true; - JLOG(m_journal.debug()) - << "subAccountHistoryStart, add AccountHistory job: accountId=" - << toBase58(accountId) << ", currentLedgerSeq=" << ledger->seq(); + JLOG(m_journal.debug()) << "subAccountHistoryStart, add AccountHistory job: accountId=" << toBase58(accountId) + << ", currentLedgerSeq=" << ledger->seq(); addAccountHistoryJob(subInfo); } error_code_i -NetworkOPsImp::subAccountHistory( - InfoSub::ref isrListener, - AccountID const& accountId) +NetworkOPsImp::subAccountHistory(InfoSub::ref isrListener, AccountID const& accountId) { if (!isrListener->insertSubAccountHistory(accountId)) { - JLOG(m_journal.debug()) - << "subAccountHistory, already subscribed to account " - << toBase58(accountId); + JLOG(m_journal.debug()) << "subAccountHistory, already subscribed to account " << toBase58(accountId); return rpcINVALID_PARAMS; } std::lock_guard sl(mSubLock); - SubAccountHistoryInfoWeak ahi{ - isrListener, std::make_shared(accountId)}; + SubAccountHistoryInfoWeak ahi{isrListener, std::make_shared(accountId)}; auto simIterator = mSubAccountHistory.find(accountId); if (simIterator == mSubAccountHistory.end()) { hash_map inner; inner.emplace(isrListener->getSeq(), ahi); - mSubAccountHistory.insert( - simIterator, std::make_pair(accountId, inner)); + mSubAccountHistory.insert(simIterator, std::make_pair(accountId, inner)); } else { simIterator->second.emplace(isrListener->getSeq(), ahi); } - auto const ledger = app_.getLedgerMaster().getValidatedLedger(); + auto const ledger = registry_.getLedgerMaster().getValidatedLedger(); if (ledger) { subAccountHistoryStart(ledger, ahi); @@ -4093,18 +3722,14 @@ NetworkOPsImp::subAccountHistory( // The node does not have validated ledgers, so wait for // one before start streaming. // In this case, the subscription is also considered successful. - JLOG(m_journal.debug()) - << "subAccountHistory, no validated ledger yet, delay start"; + JLOG(m_journal.debug()) << "subAccountHistory, no validated ledger yet, delay start"; } return rpcSUCCESS; } void -NetworkOPsImp::unsubAccountHistory( - InfoSub::ref isrListener, - AccountID const& account, - bool historyOnly) +NetworkOPsImp::unsubAccountHistory(InfoSub::ref isrListener, AccountID const& account, bool historyOnly) { if (!historyOnly) isrListener->deleteSubAccountHistory(account); @@ -4112,10 +3737,7 @@ NetworkOPsImp::unsubAccountHistory( } void -NetworkOPsImp::unsubAccountHistoryInternal( - std::uint64_t seq, - AccountID const& account, - bool historyOnly) +NetworkOPsImp::unsubAccountHistoryInternal(std::uint64_t seq, AccountID const& account, bool historyOnly) { std::lock_guard sl(mSubLock); auto simIterator = mSubAccountHistory.find(account); @@ -4136,16 +3758,15 @@ NetworkOPsImp::unsubAccountHistoryInternal( mSubAccountHistory.erase(simIterator); } } - JLOG(m_journal.debug()) - << "unsubAccountHistory, account " << toBase58(account) - << ", historyOnly = " << (historyOnly ? "true" : "false"); + JLOG(m_journal.debug()) << "unsubAccountHistory, account " << toBase58(account) + << ", historyOnly = " << (historyOnly ? "true" : "false"); } } bool NetworkOPsImp::subBook(InfoSub::ref isrListener, Book const& book) { - if (auto listeners = app_.getOrderBookDB().makeBookListeners(book)) + if (auto listeners = registry_.getOrderBookDB().makeBookListeners(book)) listeners->addSubscriber(isrListener); else { @@ -4159,29 +3780,26 @@ NetworkOPsImp::subBook(InfoSub::ref isrListener, Book const& book) bool NetworkOPsImp::unsubBook(std::uint64_t uSeq, Book const& book) { - if (auto listeners = app_.getOrderBookDB().getBookListeners(book)) + if (auto listeners = registry_.getOrderBookDB().getBookListeners(book)) listeners->removeSubscriber(uSeq); return true; } std::uint32_t -NetworkOPsImp::acceptLedger( - std::optional consensusDelay) +NetworkOPsImp::acceptLedger(std::optional consensusDelay) { // This code-path is exclusively used when the server is in standalone // mode via `ledger_accept` - XRPL_ASSERT( - m_standalone, "xrpl::NetworkOPsImp::acceptLedger : is standalone"); + XRPL_ASSERT(m_standalone, "xrpl::NetworkOPsImp::acceptLedger : is standalone"); if (!m_standalone) - Throw( - "Operation only possible in STANDALONE mode."); + Throw("Operation only possible in STANDALONE mode."); // FIXME Could we improve on this and remove the need for a specialized // API in Consensus? beginConsensus(m_ledgerMaster.getClosedLedger()->header().hash, {}); - mConsensus.simulate(app_.timeKeeper().closeTime(), consensusDelay); + mConsensus.simulate(registry_.timeKeeper().closeTime(), consensusDelay); return m_ledgerMaster.getCurrentLedger()->header().seq; } @@ -4193,26 +3811,22 @@ NetworkOPsImp::subLedger(InfoSub::ref isrListener, Json::Value& jvResult) { jvResult[jss::ledger_index] = lpClosed->header().seq; jvResult[jss::ledger_hash] = to_string(lpClosed->header().hash); - jvResult[jss::ledger_time] = Json::Value::UInt( - lpClosed->header().closeTime.time_since_epoch().count()); + jvResult[jss::ledger_time] = Json::Value::UInt(lpClosed->header().closeTime.time_since_epoch().count()); if (!lpClosed->rules().enabled(featureXRPFees)) jvResult[jss::fee_ref] = Config::FEE_UNITS_DEPRECATED; jvResult[jss::fee_base] = lpClosed->fees().base.jsonClipped(); jvResult[jss::reserve_base] = lpClosed->fees().reserve.jsonClipped(); jvResult[jss::reserve_inc] = lpClosed->fees().increment.jsonClipped(); - jvResult[jss::network_id] = app_.config().NETWORK_ID; + jvResult[jss::network_id] = registry_.app().config().NETWORK_ID; } if ((mMode >= OperatingMode::SYNCING) && !isNeedNetworkLedger()) { - jvResult[jss::validated_ledgers] = - app_.getLedgerMaster().getCompleteLedgers(); + jvResult[jss::validated_ledgers] = registry_.getLedgerMaster().getCompleteLedgers(); } std::lock_guard sl(mSubLock); - return mStreamMaps[sLedger] - .emplace(isrListener->getSeq(), isrListener) - .second; + return mStreamMaps[sLedger].emplace(isrListener->getSeq(), isrListener).second; } // <-- bool: true=added, false=already there @@ -4220,9 +3834,7 @@ bool NetworkOPsImp::subBookChanges(InfoSub::ref isrListener) { std::lock_guard sl(mSubLock); - return mStreamMaps[sBookChanges] - .emplace(isrListener->getSeq(), isrListener) - .second; + return mStreamMaps[sBookChanges].emplace(isrListener->getSeq(), isrListener).second; } // <-- bool: true=erased, false=was not there @@ -4246,9 +3858,7 @@ bool NetworkOPsImp::subManifests(InfoSub::ref isrListener) { std::lock_guard sl(mSubLock); - return mStreamMaps[sManifests] - .emplace(isrListener->getSeq(), isrListener) - .second; + return mStreamMaps[sManifests].emplace(isrListener->getSeq(), isrListener).second; } // <-- bool: true=erased, false=was not there @@ -4261,10 +3871,7 @@ NetworkOPsImp::unsubManifests(std::uint64_t uSeq) // <-- bool: true=added, false=already there bool -NetworkOPsImp::subServer( - InfoSub::ref isrListener, - Json::Value& jvResult, - bool admin) +NetworkOPsImp::subServer(InfoSub::ref isrListener, Json::Value& jvResult, bool admin) { uint256 uRandom; @@ -4274,19 +3881,16 @@ NetworkOPsImp::subServer( // CHECKME: is it necessary to provide a random number here? beast::rngfill(uRandom.begin(), uRandom.size(), crypto_prng()); - auto const& feeTrack = app_.getFeeTrack(); + auto const& feeTrack = registry_.getFeeTrack(); jvResult[jss::random] = to_string(uRandom); jvResult[jss::server_status] = strOperatingMode(admin); jvResult[jss::load_base] = feeTrack.getLoadBase(); jvResult[jss::load_factor] = feeTrack.getLoadFactor(); jvResult[jss::hostid] = getHostId(admin); - jvResult[jss::pubkey_node] = - toBase58(TokenType::NodePublic, app_.nodeIdentity().first); + jvResult[jss::pubkey_node] = toBase58(TokenType::NodePublic, registry_.app().nodeIdentity().first); std::lock_guard sl(mSubLock); - return mStreamMaps[sServer] - .emplace(isrListener->getSeq(), isrListener) - .second; + return mStreamMaps[sServer].emplace(isrListener->getSeq(), isrListener).second; } // <-- bool: true=erased, false=was not there @@ -4302,9 +3906,7 @@ bool NetworkOPsImp::subTransactions(InfoSub::ref isrListener) { std::lock_guard sl(mSubLock); - return mStreamMaps[sTransactions] - .emplace(isrListener->getSeq(), isrListener) - .second; + return mStreamMaps[sTransactions].emplace(isrListener->getSeq(), isrListener).second; } // <-- bool: true=erased, false=was not there @@ -4320,9 +3922,7 @@ bool NetworkOPsImp::subRTTransactions(InfoSub::ref isrListener) { std::lock_guard sl(mSubLock); - return mStreamMaps[sRTTransactions] - .emplace(isrListener->getSeq(), isrListener) - .second; + return mStreamMaps[sRTTransactions].emplace(isrListener->getSeq(), isrListener).second; } // <-- bool: true=erased, false=was not there @@ -4338,9 +3938,7 @@ bool NetworkOPsImp::subValidations(InfoSub::ref isrListener) { std::lock_guard sl(mSubLock); - return mStreamMaps[sValidations] - .emplace(isrListener->getSeq(), isrListener) - .second; + return mStreamMaps[sValidations].emplace(isrListener->getSeq(), isrListener).second; } void @@ -4362,9 +3960,7 @@ bool NetworkOPsImp::subPeerStatus(InfoSub::ref isrListener) { std::lock_guard sl(mSubLock); - return mStreamMaps[sPeerStatus] - .emplace(isrListener->getSeq(), isrListener) - .second; + return mStreamMaps[sPeerStatus].emplace(isrListener->getSeq(), isrListener).second; } // <-- bool: true=erased, false=was not there @@ -4380,9 +3976,7 @@ bool NetworkOPsImp::subConsensus(InfoSub::ref isrListener) { std::lock_guard sl(mSubLock); - return mStreamMaps[sConsensusPhase] - .emplace(isrListener->getSeq(), isrListener) - .second; + return mStreamMaps[sConsensusPhase].emplace(isrListener->getSeq(), isrListener).second; } // <-- bool: true=erased, false=was not there @@ -4451,8 +4045,7 @@ NetworkOPsImp::getBookPage( Json::Value const& jvMarker, Json::Value& jvResult) { // CAUTION: This is the old get book page logic - Json::Value& jvOffers = - (jvResult[jss::offers] = Json::Value(Json::arrayValue)); + Json::Value& jvOffers = (jvResult[jss::offers] = Json::Value(Json::arrayValue)); std::unordered_map umBalance; uint256 const uBookBase = getBookBase(book); @@ -4469,8 +4062,7 @@ NetworkOPsImp::getBookPage( ReadView const& view = *lpLedger; - bool const bGlobalFreeze = isGlobalFrozen(view, book.out.account) || - isGlobalFrozen(view, book.in.account); + bool const bGlobalFreeze = isGlobalFrozen(view, book.out.account) || isGlobalFrozen(view, book.in.account); bool bDone = false; bool bDirectAdvance = true; @@ -4481,7 +4073,7 @@ NetworkOPsImp::getBookPage( STAmount saDirRate; auto const rate = transferRate(view, book.out.account); - auto viewJ = app_.journal("View"); + auto viewJ = registry_.journal("View"); while (!bDone && iLimit-- > 0) { @@ -4509,10 +4101,8 @@ NetworkOPsImp::getBookPage( cdirFirst(view, uTipIndex, sleOfferDir, uBookEntry, offerIndex); - JLOG(m_journal.trace()) - << "getBookPage: uTipIndex=" << uTipIndex; - JLOG(m_journal.trace()) - << "getBookPage: offerIndex=" << offerIndex; + JLOG(m_journal.trace()) << "getBookPage: uTipIndex=" << uTipIndex; + JLOG(m_journal.trace()) << "getBookPage: offerIndex=" << offerIndex; } } @@ -4555,12 +4145,7 @@ NetworkOPsImp::getBookPage( // Did not find balance in table. saOwnerFunds = accountHolds( - view, - uOfferOwnerID, - book.out.currency, - book.out.account, - fhZERO_IF_FROZEN, - viewJ); + view, uOfferOwnerID, book.out.currency, book.out.account, fhZERO_IF_FROZEN, viewJ); if (saOwnerFunds < beast::zero) { @@ -4601,17 +4186,13 @@ NetworkOPsImp::getBookPage( saTakerGetsFunded = saOwnerFundsLimit; saTakerGetsFunded.setJson(jvOffer[jss::taker_gets_funded]); - std::min( - saTakerPays, - multiply( - saTakerGetsFunded, saDirRate, saTakerPays.issue())) + std::min(saTakerPays, multiply(saTakerGetsFunded, saDirRate, saTakerPays.issue())) .setJson(jvOffer[jss::taker_pays_funded]); } STAmount saOwnerPays = (parityRate == offerRate) ? saTakerGetsFunded - : std::min( - saOwnerFunds, multiply(saTakerGetsFunded, offerRate)); + : std::min(saOwnerFunds, multiply(saTakerGetsFunded, offerRate)); umBalance[uOfferOwnerID] = saOwnerFunds - saOwnerPays; @@ -4633,8 +4214,7 @@ NetworkOPsImp::getBookPage( } else { - JLOG(m_journal.trace()) - << "getBookPage: offerIndex=" << offerIndex; + JLOG(m_journal.trace()) << "getBookPage: offerIndex=" << offerIndex; } } } @@ -4667,8 +4247,7 @@ NetworkOPsImp::getBookPage( auto const rate = transferRate(lesActive, book.out.account); - bool const bGlobalFreeze = lesActive.isGlobalFrozen(book.out.account) || - lesActive.isGlobalFrozen(book.in.account); + bool const bGlobalFreeze = lesActive.isGlobalFrozen(book.out.account) || lesActive.isGlobalFrozen(book.in.account); while (iLimit-- > 0 && obIterator.nextOffer()) { @@ -4706,11 +4285,8 @@ NetworkOPsImp::getBookPage( { // Did not find balance in table. - saOwnerFunds = lesActive.accountHolds( - uOfferOwnerID, - book.out.currency, - book.out.account, - fhZERO_IF_FROZEN); + saOwnerFunds = + lesActive.accountHolds(uOfferOwnerID, book.out.currency, book.out.account, fhZERO_IF_FROZEN); if (saOwnerFunds.isNegative()) { @@ -4753,16 +4329,13 @@ NetworkOPsImp::getBookPage( // TODO(tom): The result of this expression is not used - what's // going on here? - std::min( - saTakerPays, - multiply(saTakerGetsFunded, saDirRate, saTakerPays.issue())) + std::min(saTakerPays, multiply(saTakerGetsFunded, saDirRate, saTakerPays.issue())) .setJson(jvOffer[jss::taker_pays_funded]); } STAmount saOwnerPays = (parityRate == offerRate) ? saTakerGetsFunded - : std::min( - saOwnerFunds, multiply(saTakerGetsFunded, offerRate)); + : std::min(saOwnerFunds, multiply(saTakerGetsFunded, offerRate)); umBalance[uOfferOwnerID] = saOwnerFunds - saOwnerPays; @@ -4785,38 +4358,22 @@ inline void NetworkOPsImp::collect_metrics() { auto [counters, mode, start, initialSync] = accounting_.getCounterData(); - auto const current = std::chrono::duration_cast( - std::chrono::steady_clock::now() - start); + auto const current = + std::chrono::duration_cast(std::chrono::steady_clock::now() - start); counters[static_cast(mode)].dur += current; std::lock_guard lock(m_statsMutex); - m_stats.disconnected_duration.set( - counters[static_cast(OperatingMode::DISCONNECTED)] - .dur.count()); - m_stats.connected_duration.set( - counters[static_cast(OperatingMode::CONNECTED)] - .dur.count()); - m_stats.syncing_duration.set( - counters[static_cast(OperatingMode::SYNCING)].dur.count()); - m_stats.tracking_duration.set( - counters[static_cast(OperatingMode::TRACKING)] - .dur.count()); - m_stats.full_duration.set( - counters[static_cast(OperatingMode::FULL)].dur.count()); + m_stats.disconnected_duration.set(counters[static_cast(OperatingMode::DISCONNECTED)].dur.count()); + m_stats.connected_duration.set(counters[static_cast(OperatingMode::CONNECTED)].dur.count()); + m_stats.syncing_duration.set(counters[static_cast(OperatingMode::SYNCING)].dur.count()); + m_stats.tracking_duration.set(counters[static_cast(OperatingMode::TRACKING)].dur.count()); + m_stats.full_duration.set(counters[static_cast(OperatingMode::FULL)].dur.count()); - m_stats.disconnected_transitions.set( - counters[static_cast(OperatingMode::DISCONNECTED)] - .transitions); - m_stats.connected_transitions.set( - counters[static_cast(OperatingMode::CONNECTED)] - .transitions); - m_stats.syncing_transitions.set( - counters[static_cast(OperatingMode::SYNCING)].transitions); - m_stats.tracking_transitions.set( - counters[static_cast(OperatingMode::TRACKING)] - .transitions); - m_stats.full_transitions.set( - counters[static_cast(OperatingMode::FULL)].transitions); + m_stats.disconnected_transitions.set(counters[static_cast(OperatingMode::DISCONNECTED)].transitions); + m_stats.connected_transitions.set(counters[static_cast(OperatingMode::CONNECTED)].transitions); + m_stats.syncing_transitions.set(counters[static_cast(OperatingMode::SYNCING)].transitions); + m_stats.tracking_transitions.set(counters[static_cast(OperatingMode::TRACKING)].transitions); + m_stats.full_transitions.set(counters[static_cast(OperatingMode::FULL)].transitions); } void @@ -4826,12 +4383,9 @@ NetworkOPsImp::StateAccounting::mode(OperatingMode om) std::lock_guard lock(mutex_); ++counters_[static_cast(om)].transitions; - if (om == OperatingMode::FULL && - counters_[static_cast(om)].transitions == 1) + if (om == OperatingMode::FULL && counters_[static_cast(om)].transitions == 1) { - initialSyncUs_ = std::chrono::duration_cast( - now - processStart_) - .count(); + initialSyncUs_ = std::chrono::duration_cast(now - processStart_).count(); } counters_[static_cast(mode_)].dur += std::chrono::duration_cast(now - start_); @@ -4844,8 +4398,8 @@ void NetworkOPsImp::StateAccounting::json(Json::Value& obj) const { auto [counters, mode, start, initialSync] = getCounterData(); - auto const current = std::chrono::duration_cast( - std::chrono::steady_clock::now() - start); + auto const current = + std::chrono::duration_cast(std::chrono::steady_clock::now() - start); counters[static_cast(mode)].dur += current; obj[jss::state_accounting] = Json::objectValue; @@ -4867,7 +4421,7 @@ NetworkOPsImp::StateAccounting::json(Json::Value& obj) const std::unique_ptr make_NetworkOPs( - Application& app, + ServiceRegistry& registry, NetworkOPs::clock_type& clock, bool standalone, std::size_t minPeerCount, @@ -4880,7 +4434,7 @@ make_NetworkOPs( beast::insight::Collector::ptr const& collector) { return std::make_unique( - app, + registry, clock, standalone, minPeerCount, diff --git a/src/xrpld/app/misc/PermissionedDEXHelpers.cpp b/src/xrpld/app/misc/PermissionedDEXHelpers.cpp index 0cf41ac6f0..f88c2ab9d4 100644 --- a/src/xrpld/app/misc/PermissionedDEXHelpers.cpp +++ b/src/xrpld/app/misc/PermissionedDEXHelpers.cpp @@ -6,10 +6,7 @@ namespace xrpl { namespace permissioned_dex { bool -accountInDomain( - ReadView const& view, - AccountID const& account, - Domain const& domainID) +accountInDomain(ReadView const& view, AccountID const& account, Domain const& domainID) { auto const sleDomain = view.read(keylet::permissionedDomain(domainID)); if (!sleDomain) @@ -21,26 +18,19 @@ accountInDomain( auto const& credentials = sleDomain->getFieldArray(sfAcceptedCredentials); - bool const inDomain = std::any_of( - credentials.begin(), credentials.end(), [&](auto const& credential) { - auto const sleCred = view.read(keylet::credential( - account, credential[sfIssuer], credential[sfCredentialType])); - if (!sleCred || !sleCred->isFlag(lsfAccepted)) - return false; + bool const inDomain = std::any_of(credentials.begin(), credentials.end(), [&](auto const& credential) { + auto const sleCred = view.read(keylet::credential(account, credential[sfIssuer], credential[sfCredentialType])); + if (!sleCred || !sleCred->isFlag(lsfAccepted)) + return false; - return !credentials::checkExpired( - sleCred, view.header().parentCloseTime); - }); + return !credentials::checkExpired(sleCred, view.header().parentCloseTime); + }); return inDomain; } bool -offerInDomain( - ReadView const& view, - uint256 const& offerID, - Domain const& domainID, - beast::Journal j) +offerInDomain(ReadView const& view, uint256 const& offerID, Domain const& domainID, beast::Journal j) { auto const sleOffer = view.read(keylet::offer(offerID)); @@ -54,11 +44,9 @@ offerInDomain( if (sleOffer->getFieldH256(sfDomainID) != domainID) return false; // LCOV_EXCL_LINE - if (sleOffer->isFlag(lsfHybrid) && - !sleOffer->isFieldPresent(sfAdditionalBooks)) + if (sleOffer->isFlag(lsfHybrid) && !sleOffer->isFieldPresent(sfAdditionalBooks)) { - JLOG(j.error()) << "Hybrid offer " << offerID - << " missing AdditionalBooks field"; + JLOG(j.error()) << "Hybrid offer " << offerID << " missing AdditionalBooks field"; return false; // LCOV_EXCL_LINE } diff --git a/src/xrpld/app/misc/PermissionedDEXHelpers.h b/src/xrpld/app/misc/PermissionedDEXHelpers.h index 9b6d23d09d..832129db2f 100644 --- a/src/xrpld/app/misc/PermissionedDEXHelpers.h +++ b/src/xrpld/app/misc/PermissionedDEXHelpers.h @@ -6,18 +6,11 @@ namespace permissioned_dex { // Check if an account is in a permissioned domain [[nodiscard]] bool -accountInDomain( - ReadView const& view, - AccountID const& account, - Domain const& domainID); +accountInDomain(ReadView const& view, AccountID const& account, Domain const& domainID); // Check if an offer is in the permissioned domain [[nodiscard]] bool -offerInDomain( - ReadView const& view, - uint256 const& offerID, - Domain const& domainID, - beast::Journal j); +offerInDomain(ReadView const& view, uint256 const& offerID, Domain const& domainID, beast::Journal j); } // namespace permissioned_dex diff --git a/src/xrpld/app/misc/SHAMapStore.h b/src/xrpld/app/misc/SHAMapStore.h index 26d6120f32..67477593cb 100644 --- a/src/xrpld/app/misc/SHAMapStore.h +++ b/src/xrpld/app/misc/SHAMapStore.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_MISC_SHAMAPSTORE_H_INCLUDED -#define XRPL_APP_MISC_SHAMAPSTORE_H_INCLUDED +#pragma once #include @@ -84,10 +83,5 @@ public: //------------------------------------------------------------------------------ std::unique_ptr -make_SHAMapStore( - Application& app, - NodeStore::Scheduler& scheduler, - beast::Journal journal); +make_SHAMapStore(Application& app, NodeStore::Scheduler& scheduler, beast::Journal journal); } // namespace xrpl - -#endif diff --git a/src/xrpld/app/misc/SHAMapStoreImp.cpp b/src/xrpld/app/misc/SHAMapStoreImp.cpp index 98be038554..8de47207a6 100644 --- a/src/xrpld/app/misc/SHAMapStoreImp.cpp +++ b/src/xrpld/app/misc/SHAMapStoreImp.cpp @@ -1,22 +1,20 @@ #include -#include #include -#include #include #include #include #include #include +#include +#include #include #include namespace xrpl { void -SHAMapStoreImp::SavedStateDB::init( - BasicConfig const& config, - std::string const& dbName) +SHAMapStoreImp::SavedStateDB::init(BasicConfig const& config, std::string const& dbName) { std::lock_guard lock(mutex_); initStateDB(sqlDb_, config, dbName); @@ -62,10 +60,7 @@ SHAMapStoreImp::SavedStateDB::setLastRotated(LedgerIndex seq) //------------------------------------------------------------------------------ -SHAMapStoreImp::SHAMapStoreImp( - Application& app, - NodeStore::Scheduler& scheduler, - beast::Journal journal) +SHAMapStoreImp::SHAMapStoreImp(Application& app, NodeStore::Scheduler& scheduler, beast::Journal journal) : app_(app) , scheduler_(scheduler) , journal_(journal) @@ -77,9 +72,7 @@ SHAMapStoreImp::SHAMapStoreImp( Section& section{config.section(ConfigSection::nodeDatabase())}; if (section.empty()) { - Throw( - "Missing [" + ConfigSection::nodeDatabase() + - "] entry in configuration file"); + Throw("Missing [" + ConfigSection::nodeDatabase() + "] entry in configuration file"); } // RocksDB only. Use sensible defaults if no values specified. @@ -87,9 +80,7 @@ SHAMapStoreImp::SHAMapStoreImp( { if (!section.exists("cache_mb")) { - section.set( - "cache_mb", - std::to_string(config.getValueFor(SizedItem::hashNodeDBCache))); + section.set("cache_mb", std::to_string(config.getValueFor(SizedItem::hashNodeDBCache))); } if (!section.exists("filter_bits") && (config.NODE_SIZE >= 2)) @@ -116,14 +107,10 @@ SHAMapStoreImp::SHAMapStoreImp( get_if_exists(section, "advisory_delete", advisoryDelete_); - auto const minInterval = config.standalone() - ? minimumDeletionIntervalSA_ - : minimumDeletionInterval_; + auto const minInterval = config.standalone() ? minimumDeletionIntervalSA_ : minimumDeletionInterval_; if (deleteInterval_ < minInterval) { - Throw( - "online_delete must be at least " + - std::to_string(minInterval)); + Throw("online_delete must be at least " + std::to_string(minInterval)); } if (config.LEDGER_HISTORY > deleteInterval_) @@ -143,20 +130,6 @@ std::unique_ptr SHAMapStoreImp::makeNodeStore(int readThreads) { auto nscfg = app_.config().section(ConfigSection::nodeDatabase()); - - // Provide default values: - if (!nscfg.exists("cache_size")) - nscfg.set( - "cache_size", - std::to_string(app_.config().getValueFor( - SizedItem::treeCacheSize, std::nullopt))); - - if (!nscfg.exists("cache_age")) - nscfg.set( - "cache_age", - std::to_string(app_.config().getValueFor( - SizedItem::treeCacheAge, std::nullopt))); - std::unique_ptr db; if (deleteInterval_) @@ -187,8 +160,7 @@ SHAMapStoreImp::makeNodeStore(int readThreads) else { db = NodeStore::Manager::instance().make_Database( - megabytes( - app_.config().getValueFor(SizedItem::burstSize, std::nullopt)), + megabytes(app_.config().getValueFor(SizedItem::burstSize, std::nullopt)), scheduler_, readThreads, nscfg, @@ -229,11 +201,7 @@ bool SHAMapStoreImp::copyNode(std::uint64_t& nodeCount, SHAMapTreeNode const& node) { // Copy a single record from node to dbRotating_ - dbRotating_->fetchNodeObject( - node.getHash().as_uint256(), - 0, - NodeStore::FetchType::synchronous, - true); + dbRotating_->fetchNodeObject(node.getHash().as_uint256(), 0, NodeStore::FetchType::synchronous, true); if (!(++nodeCount % checkHealthInterval_)) { if (healthWait() == stopping) @@ -250,8 +218,6 @@ SHAMapStoreImp::run() LedgerIndex lastRotated = state_db_.getState().lastRotated; netOPs_ = &app_.getOPs(); ledgerMaster_ = &app_.getLedgerMaster(); - fullBelowCache_ = &(*app_.getNodeFamily().getFullBelowCache()); - treeNodeCache_ = &(*app_.getNodeFamily().getTreeNodeCache()); if (advisoryDelete_) canDelete_ = state_db_.getCanDelete(); @@ -286,18 +252,15 @@ SHAMapStoreImp::run() } bool const readyToRotate = - validatedSeq >= lastRotated + deleteInterval_ && - canDelete_ >= lastRotated - 1 && healthWait() == keepGoing; + validatedSeq >= lastRotated + deleteInterval_ && canDelete_ >= lastRotated - 1 && healthWait() == keepGoing; // will delete up to (not including) lastRotated if (readyToRotate) { - JLOG(journal_.warn()) - << "rotating validatedSeq " << validatedSeq << " lastRotated " - << lastRotated << " deleteInterval " << deleteInterval_ - << " canDelete_ " << canDelete_ << " state " - << app_.getOPs().strOperatingMode(false) << " age " - << ledgerMaster_->getValidatedLedgerAge().count() << 's'; + JLOG(journal_.warn()) << "rotating validatedSeq " << validatedSeq << " lastRotated " << lastRotated + << " deleteInterval " << deleteInterval_ << " canDelete_ " << canDelete_ << " state " + << app_.getOPs().strOperatingMode(false) << " age " + << ledgerMaster_->getValidatedLedgerAge().count() << 's'; clearPrior(lastRotated); if (healthWait() == stopping) @@ -309,25 +272,18 @@ SHAMapStoreImp::run() try { validatedLedger->stateMap().snapShot(false)->visitNodes( - std::bind( - &SHAMapStoreImp::copyNode, - this, - std::ref(nodeCount), - std::placeholders::_1)); + std::bind(&SHAMapStoreImp::copyNode, this, std::ref(nodeCount), std::placeholders::_1)); } catch (SHAMapMissingNode const& e) { - JLOG(journal_.error()) - << "Missing node while copying ledger before rotate: " - << e.what(); + JLOG(journal_.error()) << "Missing node while copying ledger before rotate: " << e.what(); continue; } if (healthWait() == stopping) return; // Only log if we completed without a "health" abort - JLOG(journal_.debug()) << "copied ledger " << validatedSeq - << " nodecount " << nodeCount; + JLOG(journal_.debug()) << "copied ledger " << validatedSeq << " nodecount " << nodeCount; JLOG(journal_.debug()) << "freshening caches"; freshenCaches(); @@ -338,8 +294,7 @@ SHAMapStoreImp::run() JLOG(journal_.trace()) << "Making a new backend"; auto newBackend = makeBackendRotating(); - JLOG(journal_.debug()) - << validatedSeq << " new backend " << newBackend->getName(); + JLOG(journal_.debug()) << validatedSeq << " new backend " << newBackend->getName(); clearCaches(validatedSeq); if (healthWait() == stopping) @@ -348,9 +303,7 @@ SHAMapStoreImp::run() lastRotated = validatedSeq; dbRotating_->rotate( - std::move(newBackend), - [&](std::string const& writableName, - std::string const& archiveName) { + std::move(newBackend), [&](std::string const& writableName, std::string const& archiveName) { SavedState savedState; savedState.writableDb = writableName; savedState.archiveDb = archiveName; @@ -375,8 +328,7 @@ SHAMapStoreImp::dbPaths() { if (!boost::filesystem::is_directory(dbPath)) { - journal_.error() - << "node db path must be a directory. " << dbPath.string(); + journal_.error() << "node db path must be a directory. " << dbPath.string(); Throw("node db path must be a directory."); } } @@ -413,9 +365,7 @@ SHAMapStoreImp::dbPaths() bool archiveDbExists = false; std::vector pathsToDelete; - for (boost::filesystem::directory_iterator it(dbPath); - it != boost::filesystem::directory_iterator(); - ++it) + for (boost::filesystem::directory_iterator it(dbPath); it != boost::filesystem::directory_iterator(); ++it) { if (!state.writableDb.compare(it->path().string())) writableDbExists = true; @@ -425,30 +375,23 @@ SHAMapStoreImp::dbPaths() pathsToDelete.push_back(it->path()); } - if ((!writableDbExists && state.writableDb.size()) || - (!archiveDbExists && state.archiveDb.size()) || - (writableDbExists != archiveDbExists) || - state.writableDb.empty() != state.archiveDb.empty()) + if ((!writableDbExists && state.writableDb.size()) || (!archiveDbExists && state.archiveDb.size()) || + (writableDbExists != archiveDbExists) || state.writableDb.empty() != state.archiveDb.empty()) { - boost::filesystem::path stateDbPathName = - app_.config().legacy("database_path"); + boost::filesystem::path stateDbPathName = app_.config().legacy("database_path"); stateDbPathName /= dbName_; stateDbPathName += "*"; - journal_.error() - << "state db error:\n" - << " writableDbExists " << writableDbExists << " archiveDbExists " - << archiveDbExists << '\n' - << " writableDb '" << state.writableDb << "' archiveDb '" - << state.archiveDb << "\n\n" - << "The existing data is in a corrupted state.\n" - << "To resume operation, remove the files matching " - << stateDbPathName.string() << " and contents of the directory " - << get(section, "path") << '\n' - << "Optionally, you can move those files to another\n" - << "location if you wish to analyze or back up the data.\n" - << "However, there is no guarantee that the data in its\n" - << "existing form is usable."; + journal_.error() << "state db error:\n" + << " writableDbExists " << writableDbExists << " archiveDbExists " << archiveDbExists << '\n' + << " writableDb '" << state.writableDb << "' archiveDb '" << state.archiveDb << "\n\n" + << "The existing data is in a corrupted state.\n" + << "To resume operation, remove the files matching " << stateDbPathName.string() + << " and contents of the directory " << get(section, "path") << '\n' + << "Optionally, you can move those files to another\n" + << "location if you wish to analyze or back up the data.\n" + << "However, there is no guarantee that the data in its\n" + << "existing form is usable."; Throw("state db error"); } @@ -479,8 +422,7 @@ SHAMapStoreImp::makeBackendRotating(std::string path) auto backend{NodeStore::Manager::instance().make_Backend( section, - megabytes( - app_.config().getValueFor(SizedItem::burstSize, std::nullopt)), + megabytes(app_.config().getValueFor(SizedItem::burstSize, std::nullopt)), scheduler_, app_.logs().journal(nodeStoreName_))}; backend->open(); @@ -494,14 +436,11 @@ SHAMapStoreImp::clearSql( std::function()> const& getMinSeq, std::function const& deleteBeforeSeq) { - XRPL_ASSERT( - deleteInterval_, - "xrpl::SHAMapStoreImp::clearSql : nonzero delete interval"); + XRPL_ASSERT(deleteInterval_, "xrpl::SHAMapStoreImp::clearSql : nonzero delete interval"); LedgerIndex min = std::numeric_limits::max(); { - JLOG(journal_.trace()) - << "Begin: Look up lowest value of: " << TableName; + JLOG(journal_.trace()) << "Begin: Look up lowest value of: " << TableName; auto m = getMinSeq(); JLOG(journal_.trace()) << "End: Look up lowest value of: " << TableName; if (!m) @@ -518,18 +457,15 @@ SHAMapStoreImp::clearSql( return; } - JLOG(journal_.debug()) << "start deleting in: " << TableName << " from " - << min << " to " << lastRotated; + JLOG(journal_.debug()) << "start deleting in: " << TableName << " from " << min << " to " << lastRotated; while (min < lastRotated) { min = std::min(lastRotated, min + deleteBatch_); - JLOG(journal_.trace()) - << "Begin: Delete up to " << deleteBatch_ - << " rows with LedgerSeq < " << min << " from: " << TableName; + JLOG(journal_.trace()) << "Begin: Delete up to " << deleteBatch_ << " rows with LedgerSeq < " << min + << " from: " << TableName; deleteBeforeSeq(min); - JLOG(journal_.trace()) - << "End: Delete up to " << deleteBatch_ << " rows with LedgerSeq < " - << min << " from: " << TableName; + JLOG(journal_.trace()) << "End: Delete up to " << deleteBatch_ << " rows with LedgerSeq < " << min + << " from: " << TableName; if (healthWait() == stopping) return; if (min < lastRotated) @@ -544,16 +480,19 @@ void SHAMapStoreImp::clearCaches(LedgerIndex validatedSeq) { ledgerMaster_->clearLedgerCachePrior(validatedSeq); - fullBelowCache_->clear(); + // Also clear the FullBelowCache so its generation counter is bumped. + // This prevents stale "full below" markers from persisting across + // backend rotation/online deletion and interfering with SHAMap sync. + app_.getNodeFamily().getFullBelowCache()->clear(); } void SHAMapStoreImp::freshenCaches() { - if (freshenCache(*treeNodeCache_)) - return; - if (freshenCache(app_.getMasterTransaction().getCache())) + if (freshenCache(*app_.getNodeFamily().getTreeNodeCache())) return; + + freshenCache(app_.getMasterTransaction().getCache()); } void @@ -562,25 +501,19 @@ SHAMapStoreImp::clearPrior(LedgerIndex lastRotated) // Do not allow ledgers to be acquired from the network // that are about to be deleted. minimumOnline_ = lastRotated + 1; - JLOG(journal_.trace()) << "Begin: Clear internal ledgers up to " - << lastRotated; + JLOG(journal_.trace()) << "Begin: Clear internal ledgers up to " << lastRotated; ledgerMaster_->clearPriorLedgers(lastRotated); - JLOG(journal_.trace()) << "End: Clear internal ledgers up to " - << lastRotated; + JLOG(journal_.trace()) << "End: Clear internal ledgers up to " << lastRotated; if (healthWait() == stopping) return; - SQLiteDatabase* const db = - dynamic_cast(&app_.getRelationalDatabase()); - - if (!db) - Throw("Failed to get relational database"); + auto& db = app_.getRelationalDatabase(); clearSql( lastRotated, "Ledgers", - [db]() -> std::optional { return db->getMinLedgerSeq(); }, - [db](LedgerIndex min) -> void { db->deleteBeforeLedgerSeq(min); }); + [&db]() -> std::optional { return db.getMinLedgerSeq(); }, + [&db](LedgerIndex min) -> void { db.deleteBeforeLedgerSeq(min); }); if (healthWait() == stopping) return; @@ -590,24 +523,16 @@ SHAMapStoreImp::clearPrior(LedgerIndex lastRotated) clearSql( lastRotated, "Transactions", - [&db]() -> std::optional { - return db->getTransactionsMinLedgerSeq(); - }, - [&db](LedgerIndex min) -> void { - db->deleteTransactionsBeforeLedgerSeq(min); - }); + [&db]() -> std::optional { return db.getTransactionsMinLedgerSeq(); }, + [&db](LedgerIndex min) -> void { db.deleteTransactionsBeforeLedgerSeq(min); }); if (healthWait() == stopping) return; clearSql( lastRotated, "AccountTransactions", - [&db]() -> std::optional { - return db->getAccountTransactionsMinLedgerSeq(); - }, - [&db](LedgerIndex min) -> void { - db->deleteAccountTransactionsBeforeLedgerSeq(min); - }); + [&db]() -> std::optional { return db.getAccountTransactionsMinLedgerSeq(); }, + [&db](LedgerIndex min) -> void { db.deleteAccountTransactionsBeforeLedgerSeq(min); }); if (healthWait() == stopping) return; } @@ -622,8 +547,7 @@ SHAMapStoreImp::healthWait() { lock.unlock(); JLOG(journal_.warn()) << "Waiting " << recoveryWaitTime_.count() - << "s for node to stabilize. state: " - << app_.getOPs().strOperatingMode(mode, false) + << "s for node to stabilize. state: " << app_.getOPs().strOperatingMode(mode, false) << ". age " << age.count() << 's'; std::this_thread::sleep_for(recoveryWaitTime_); age = ledgerMaster_->getValidatedLedgerAge(); @@ -661,10 +585,7 @@ SHAMapStoreImp::minimumOnline() const //------------------------------------------------------------------------------ std::unique_ptr -make_SHAMapStore( - Application& app, - NodeStore::Scheduler& scheduler, - beast::Journal journal) +make_SHAMapStore(Application& app, NodeStore::Scheduler& scheduler, beast::Journal journal) { return std::make_unique(app, scheduler, journal); } diff --git a/src/xrpld/app/misc/SHAMapStoreImp.h b/src/xrpld/app/misc/SHAMapStoreImp.h index 38997c2997..df3c16b24f 100644 --- a/src/xrpld/app/misc/SHAMapStoreImp.h +++ b/src/xrpld/app/misc/SHAMapStoreImp.h @@ -1,13 +1,12 @@ -#ifndef XRPL_APP_MISC_SHAMAPSTOREIMP_H_INCLUDED -#define XRPL_APP_MISC_SHAMAPSTOREIMP_H_INCLUDED +#pragma once #include #include -#include -#include #include #include +#include +#include #include #include @@ -94,22 +93,16 @@ private: // as of run() or before NetworkOPs* netOPs_ = nullptr; LedgerMaster* ledgerMaster_ = nullptr; - FullBelowCache* fullBelowCache_ = nullptr; - TreeNodeCache* treeNodeCache_ = nullptr; static constexpr auto nodeStoreName_ = "NodeStore"; public: - SHAMapStoreImp( - Application& app, - NodeStore::Scheduler& scheduler, - beast::Journal journal); + SHAMapStoreImp(Application& app, NodeStore::Scheduler& scheduler, beast::Journal journal); std::uint32_t clampFetchDepth(std::uint32_t fetch_depth) const override { - return deleteInterval_ ? std::min(fetch_depth, deleteInterval_) - : fetch_depth; + return deleteInterval_ ? std::min(fetch_depth, deleteInterval_) : fetch_depth; } std::unique_ptr @@ -176,8 +169,7 @@ private: for (auto const& key : cache.getKeys()) { - dbRotating_->fetchNodeObject( - key, 0, NodeStore::FetchType::synchronous, true); + dbRotating_->fetchNodeObject(key, 0, NodeStore::FetchType::synchronous, true); if (!(++check % checkHealthInterval_) && healthWait() == stopping) return true; } @@ -226,5 +218,3 @@ public: }; } // namespace xrpl - -#endif diff --git a/src/xrpld/app/misc/Transaction.h b/src/xrpld/app/misc/Transaction.h index 9f75387744..0a51e1c021 100644 --- a/src/xrpld/app/misc/Transaction.h +++ b/src/xrpld/app/misc/Transaction.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_MISC_TRANSACTION_H_INCLUDED -#define XRPL_APP_MISC_TRANSACTION_H_INCLUDED +#pragma once #include #include @@ -9,6 +8,7 @@ #include #include #include +#include #include #include @@ -36,21 +36,15 @@ enum TransStatus { INCOMPLETE = 8 // needs more signatures }; -enum class TxSearched { all, some, unknown }; - // This class is for constructing and examining transactions. // Transactions are static so manipulation functions are unnecessary. -class Transaction : public std::enable_shared_from_this, - public CountedObject +class Transaction : public std::enable_shared_from_this, public CountedObject { public: using pointer = std::shared_ptr; using ref = pointer const&; - Transaction( - std::shared_ptr const&, - std::string&, - Application&) noexcept; + Transaction(std::shared_ptr const&, std::string&, Application&) noexcept; // The two boost::optional parameters are because SOCI requires // boost::optional (not std::optional) parameters. @@ -251,15 +245,8 @@ public: { CurrentLedgerState() = delete; - CurrentLedgerState( - LedgerIndex li, - XRPAmount fee, - std::uint32_t accSeqNext, - std::uint32_t accSeqAvail) - : validatedLedger{li} - , minFeeRequired{fee} - , accountSeqNext{accSeqNext} - , accountSeqAvail{accSeqAvail} + CurrentLedgerState(LedgerIndex li, XRPAmount fee, std::uint32_t accSeqNext, std::uint32_t accSeqAvail) + : validatedLedger{li}, minFeeRequired{fee}, accountSeqNext{accSeqNext}, accountSeqAvail{accSeqAvail} { } @@ -293,8 +280,7 @@ public: std::uint32_t accountSeq, std::uint32_t availableSeq) { - currentLedgerState_.emplace( - validatedLedger, fee, accountSeq, availableSeq); + currentLedgerState_.emplace(validatedLedger, fee, accountSeq, availableSeq); } Json::Value @@ -306,8 +292,7 @@ public: // at the time of search. struct Locator { - std::variant, ClosedInterval> - locator; + std::variant, ClosedInterval> locator; // @return true if transaction was found, false otherwise // @@ -317,8 +302,7 @@ public: bool isFound() { - return std::holds_alternative>( - locator); + return std::holds_alternative>(locator); } // @return key used to find transaction in nodestore @@ -352,29 +336,15 @@ public: static Locator locate(uint256 const& id, Application& app); - static std::variant< - std::pair, std::shared_ptr>, - TxSearched> + static std::variant, std::shared_ptr>, TxSearched> load(uint256 const& id, Application& app, error_code_i& ec); - static std::variant< - std::pair, std::shared_ptr>, - TxSearched> - load( - uint256 const& id, - Application& app, - ClosedInterval const& range, - error_code_i& ec); + static std::variant, std::shared_ptr>, TxSearched> + load(uint256 const& id, Application& app, ClosedInterval const& range, error_code_i& ec); private: - static std::variant< - std::pair, std::shared_ptr>, - TxSearched> - load( - uint256 const& id, - Application& app, - std::optional> const& range, - error_code_i& ec); + static std::variant, std::shared_ptr>, TxSearched> + load(uint256 const& id, Application& app, std::optional> const& range, error_code_i& ec); uint256 mTransactionID; @@ -414,5 +384,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/src/xrpld/app/misc/TxQ.h b/src/xrpld/app/misc/TxQ.h index 10ed4adeea..b50ff1a0b5 100644 --- a/src/xrpld/app/misc/TxQ.h +++ b/src/xrpld/app/misc/TxQ.h @@ -1,5 +1,4 @@ -#ifndef XRPL_TXQ_H_INCLUDED -#define XRPL_TXQ_H_INCLUDED +#pragma once #include @@ -252,12 +251,7 @@ public: will return `{ terQUEUED, false }`. */ ApplyResult - apply( - Application& app, - OpenView& view, - std::shared_ptr const& tx, - ApplyFlags flags, - beast::Journal j); + apply(Application& app, OpenView& view, std::shared_ptr const& tx, ApplyFlags flags, beast::Journal j); /** Fill the new open ledger with transactions from the queue. @@ -314,9 +308,7 @@ public: * and first available sequence */ FeeAndSeq - getTxRequiredFeeAndSeq( - OpenView const& view, - std::shared_ptr const& tx) const; + getTxRequiredFeeAndSeq(OpenView const& view, std::shared_ptr const& tx) const; /** Returns information about the transactions currently in the queue for the account. @@ -346,9 +338,7 @@ public: private: // Implementation for nextQueuableSeq(). The passed lock must be held. SeqProxy - nextQueuableSeqImpl( - std::shared_ptr const& sleAccount, - std::lock_guard const&) const; + nextQueuableSeqImpl(std::shared_ptr const& sleAccount, std::lock_guard const&) const; /** Track and use the fee escalation metrics of the @@ -381,18 +371,11 @@ private: public: /// Constructor FeeMetrics(Setup const& setup, beast::Journal j) - : minimumTxnCount_( - setup.standAlone ? setup.minimumTxnInLedgerSA - : setup.minimumTxnInLedger) - , targetTxnCount_( - setup.targetTxnInLedger < minimumTxnCount_ - ? minimumTxnCount_ - : setup.targetTxnInLedger) + : minimumTxnCount_(setup.standAlone ? setup.minimumTxnInLedgerSA : setup.minimumTxnInLedger) + , targetTxnCount_(setup.targetTxnInLedger < minimumTxnCount_ ? minimumTxnCount_ : setup.targetTxnInLedger) , maximumTxnCount_( setup.maximumTxnInLedger - ? *setup.maximumTxnInLedger < targetTxnCount_ - ? targetTxnCount_ - : *setup.maximumTxnInLedger + ? *setup.maximumTxnInLedger < targetTxnCount_ ? targetTxnCount_ : *setup.maximumTxnInLedger : std::optional(std::nullopt)) , txnsExpected_(minimumTxnCount_) , recentTxnCounts_(setup.ledgersInQueue) @@ -412,11 +395,7 @@ private: @param setup Customization params. */ std::size_t - update( - Application& app, - ReadView const& view, - bool timeLeap, - TxQ::Setup const& setup); + update(Application& app, ReadView const& view, bool timeLeap, TxQ::Setup const& setup); /// Snapshot of the externally relevant FeeMetrics /// fields at any given time. @@ -634,8 +613,7 @@ private: operator()(MaybeTx const& lhs, MaybeTx const& rhs) const { if (lhs.feeLevel == rhs.feeLevel) - return (lhs.txID ^ MaybeTx::parentHashComp) < - (rhs.txID ^ MaybeTx::parentHashComp); + return (lhs.txID ^ MaybeTx::parentHashComp) < (rhs.txID ^ MaybeTx::parentHashComp); return lhs.feeLevel > rhs.feeLevel; } }; @@ -728,13 +706,10 @@ private: std::optional const& replacedTxIter, std::shared_ptr const& tx); - using FeeHook = boost::intrusive::member_hook< - MaybeTx, - boost::intrusive::set_member_hook<>, - &MaybeTx::byFeeListHook>; + using FeeHook = + boost::intrusive::member_hook, &MaybeTx::byFeeListHook>; - using FeeMultiSet = boost::intrusive:: - multiset>; + using FeeMultiSet = boost::intrusive::multiset>; using AccountMap = std::map; @@ -804,14 +779,10 @@ private: is higher), or next entry in byFee_ (lower fee level). Used to get the next "applicable" MaybeTx for accept(). */ - FeeMultiSet::iterator_type eraseAndAdvance( - FeeMultiSet::const_iterator_type); + FeeMultiSet::iterator_type eraseAndAdvance(FeeMultiSet::const_iterator_type); /// Erase a range of items, based on TxQAccount::TxMap iterators TxQAccount::TxMap::iterator - erase( - TxQAccount& txQAccount, - TxQAccount::TxMap::const_iterator begin, - TxQAccount::TxMap::const_iterator end); + erase(TxQAccount& txQAccount, TxQAccount::TxMap::const_iterator begin, TxQAccount::TxMap::const_iterator end); /** All-or-nothing attempt to try to apply the queued txs for @@ -843,17 +814,13 @@ template XRPAmount toDrops(FeeLevel const& level, XRPAmount baseFee) { - return mulDiv(level, baseFee, TxQ::baseLevel) - .value_or(XRPAmount(STAmount::cMaxNativeN)); + return mulDiv(level, baseFee, TxQ::baseLevel).value_or(XRPAmount(STAmount::cMaxNativeN)); } inline FeeLevel64 toFeeLevel(XRPAmount const& drops, XRPAmount const& baseFee) { - return mulDiv(drops, TxQ::baseLevel, baseFee) - .value_or(FeeLevel64(std::numeric_limits::max())); + return mulDiv(drops, TxQ::baseLevel, baseFee).value_or(FeeLevel64(std::numeric_limits::max())); } } // namespace xrpl - -#endif diff --git a/src/xrpld/app/misc/ValidatorKeys.h b/src/xrpld/app/misc/ValidatorKeys.h index a1511c134a..296c63e09e 100644 --- a/src/xrpld/app/misc/ValidatorKeys.h +++ b/src/xrpld/app/misc/ValidatorKeys.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_MISC_VALIDATOR_KEYS_H_INCLUDED -#define XRPL_APP_MISC_VALIDATOR_KEYS_H_INCLUDED +#pragma once #include #include @@ -26,13 +25,8 @@ public: SecretKey secretKey; Keys() = delete; - Keys( - PublicKey const& masterPublic_, - PublicKey const& public_, - SecretKey const& secret_) - : masterPublicKey(masterPublic_) - , publicKey(public_) - , secretKey(secret_) + Keys(PublicKey const& masterPublic_, PublicKey const& public_, SecretKey const& secret_) + : masterPublicKey(masterPublic_), publicKey(public_), secretKey(secret_) { } }; @@ -60,5 +54,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/src/xrpld/app/misc/ValidatorList.h b/src/xrpld/app/misc/ValidatorList.h index 45b24e8609..f93ac8a32f 100644 --- a/src/xrpld/app/misc/ValidatorList.h +++ b/src/xrpld/app/misc/ValidatorList.h @@ -1,7 +1,5 @@ -#ifndef XRPL_APP_MISC_VALIDATORLIST_H_INCLUDED -#define XRPL_APP_MISC_VALIDATORLIST_H_INCLUDED +#pragma once -#include #include #include @@ -10,6 +8,7 @@ #include #include #include +#include #include @@ -273,11 +272,7 @@ public: { explicit PublisherListStats() = default; explicit PublisherListStats(ListDisposition d); - PublisherListStats( - ListDisposition d, - PublicKey key, - PublisherStatus stat, - std::size_t seq); + PublisherListStats(ListDisposition d, PublicKey key, PublisherStatus stat, std::size_t seq); ListDisposition bestDisposition() const; @@ -297,10 +292,7 @@ public: struct MessageWithHash { explicit MessageWithHash() = default; - explicit MessageWithHash( - std::shared_ptr const& message_, - uint256 hash_, - std::size_t num_); + explicit MessageWithHash(std::shared_ptr const& message_, uint256 hash_, std::size_t num_); std::shared_ptr message; uint256 hash; std::size_t numVLs = 0; @@ -604,22 +596,19 @@ public: May be called concurrently */ void - for_each_available( - std::function const& blobInfos, - PublicKey const& pubKey, - std::size_t maxSequence, - uint256 const& hash)> func) const; + for_each_available(std::function const& blobInfos, + PublicKey const& pubKey, + std::size_t maxSequence, + uint256 const& hash)> func) const; /** Returns the current valid list for the given publisher key, if available, as a Json object. */ std::optional - getAvailable( - std::string_view pubKey, - std::optional forceVersion = {}); + getAvailable(std::string_view pubKey, std::optional forceVersion = {}); /** Return the number of configured validator list sites. */ std::size_t @@ -692,8 +681,7 @@ public: * @return a filtered copy of the validations */ std::vector> - negativeUNLFilter( - std::vector>&& validations) const; + negativeUNLFilter(std::vector>&& validations) const; private: /** Return the number of configured validator list sites. */ @@ -779,9 +767,7 @@ private: lock_guard const&); static void - buildBlobInfos( - std::map& blobInfos, - PublisherListCollection const& lists); + buildBlobInfos(std::map& blobInfos, PublisherListCollection const& lists); static std::map buildBlobInfos(PublisherListCollection const& lists); @@ -818,10 +804,7 @@ private: writing to a cache file, or serving to a /vl/ query */ static Json::Value - buildFileData( - std::string const& pubKey, - PublisherListCollection const& pubCollection, - beast::Journal j); + buildFileData(std::string const& pubKey, PublisherListCollection const& pubCollection, beast::Journal j); /** Build a Json representation of the collection, suitable for writing to a cache file, or serving to a /vl/ query @@ -873,10 +856,7 @@ private: Calling public member function is expected to lock mutex */ bool - removePublisherList( - lock_guard const&, - PublicKey const& publisherKey, - PublisherStatus reason); + removePublisherList(lock_guard const&, PublicKey const& publisherKey, PublisherStatus reason); /** Return quorum for trusted validator set @@ -889,10 +869,7 @@ private: recently received validations */ std::size_t - calculateQuorum( - std::size_t unlSize, - std::size_t effectiveUnlSize, - std::size_t seenSize); + calculateQuorum(std::size_t unlSize, std::size_t effectiveUnlSize, std::size_t seenSize); }; // hashing helpers @@ -944,10 +921,7 @@ void hash_append(Hasher& h, TMValidatorListCollection const& msg) { using beast::hash_append; - hash_append( - h, msg.manifest(), xrpl::ValidatorList::parseBlobs(msg), msg.version()); + hash_append(h, msg.manifest(), xrpl::ValidatorList::parseBlobs(msg), msg.version()); } } // namespace protocol - -#endif diff --git a/src/xrpld/app/misc/ValidatorSite.h b/src/xrpld/app/misc/ValidatorSite.h index 64b22f065d..dc44e28bcb 100644 --- a/src/xrpld/app/misc/ValidatorSite.h +++ b/src/xrpld/app/misc/ValidatorSite.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_MISC_VALIDATORSITE_H_INCLUDED -#define XRPL_APP_MISC_VALIDATORSITE_H_INCLUDED +#pragma once #include #include @@ -178,16 +177,12 @@ public: private: /// Load configured site URIs. bool - load( - std::vector const& siteURIs, - std::lock_guard const&); + load(std::vector const& siteURIs, std::lock_guard const&); /// Queue next site to be fetched /// lock over site_mutex_ and state_mutex_ required void - setTimer( - std::lock_guard const&, - std::lock_guard const&); + setTimer(std::lock_guard const&, std::lock_guard const&); /// request took too long void @@ -207,34 +202,22 @@ private: /// Store latest list fetched from anywhere void - onTextFetch( - boost::system::error_code const& ec, - std::string const& res, - std::size_t siteIdx); + onTextFetch(boost::system::error_code const& ec, std::string const& res, std::size_t siteIdx); /// Initiate request to given resource. /// lock over sites_mutex_ required void - makeRequest( - std::shared_ptr resource, - std::size_t siteIdx, - std::lock_guard const&); + makeRequest(std::shared_ptr resource, std::size_t siteIdx, std::lock_guard const&); /// Parse json response from validator list site. /// lock over sites_mutex_ required void - parseJsonResponse( - std::string const& res, - std::size_t siteIdx, - std::lock_guard const&); + parseJsonResponse(std::string const& res, std::size_t siteIdx, std::lock_guard const&); /// Interpret a redirect response. /// lock over sites_mutex_ required std::shared_ptr - processRedirect( - detail::response_type& res, - std::size_t siteIdx, - std::lock_guard const&); + processRedirect(detail::response_type& res, std::size_t siteIdx, std::lock_guard const&); /// If no sites are provided, or a site fails to load, /// get a list of local cache files from the ValidatorList. @@ -243,5 +226,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/src/xrpld/app/misc/detail/AMMHelpers.cpp b/src/xrpld/app/misc/detail/AMMHelpers.cpp index 0b741c8d36..ff3474f33d 100644 --- a/src/xrpld/app/misc/detail/AMMHelpers.cpp +++ b/src/xrpld/app/misc/detail/AMMHelpers.cpp @@ -3,14 +3,10 @@ namespace xrpl { STAmount -ammLPTokens( - STAmount const& asset1, - STAmount const& asset2, - Issue const& lptIssue) +ammLPTokens(STAmount const& asset1, STAmount const& asset2, Issue const& lptIssue) { // AMM invariant: sqrt(asset1 * asset2) >= LPTokensBalance - auto const rounding = - isFeatureEnabled(fixAMMv1_3) ? Number::downward : Number::getround(); + auto const rounding = isFeatureEnabled(fixAMMv1_3) ? Number::downward : Number::getround(); NumberRoundModeGuard g(rounding); auto const tokens = root2(asset1 * asset2); return toSTAmount(lptIssue, tokens); @@ -58,11 +54,7 @@ lpTokensOut( * (R/t2)**2 + R*(2*d/t2 - 1/f1) + d**2 - f2**2 = 0 */ STAmount -ammAssetIn( - STAmount const& asset1Balance, - STAmount const& lptAMMBalance, - STAmount const& lpTokens, - std::uint16_t tfee) +ammAssetIn(STAmount const& asset1Balance, STAmount const& lptAMMBalance, STAmount const& lpTokens, std::uint16_t tfee) { auto const f1 = feeMult(tfee); auto const f2 = feeMultHalf(tfee) / f1; @@ -74,8 +66,7 @@ ammAssetIn( auto const c = d * d - f2 * f2; if (!isFeatureEnabled(fixAMMv1_3)) { - return toSTAmount( - asset1Balance.issue(), asset1Balance * solveQuadraticEq(a, b, c)); + return toSTAmount(asset1Balance.issue(), asset1Balance * solveQuadraticEq(a, b, c)); } else { @@ -123,11 +114,7 @@ lpTokensIn( * R = (t1**2 + t1*(f - 2)) / (t1*f - 1) */ STAmount -ammAssetOut( - STAmount const& assetBalance, - STAmount const& lptAMMBalance, - STAmount const& lpTokens, - std::uint16_t tfee) +ammAssetOut(STAmount const& assetBalance, STAmount const& lptAMMBalance, STAmount const& lpTokens, std::uint16_t tfee) { auto const f = getFee(tfee); Number const t1 = lpTokens / lptAMMBalance; @@ -151,10 +138,7 @@ square(Number const& n) } STAmount -adjustLPTokens( - STAmount const& lptAMMBalance, - STAmount const& lpTokens, - IsDeposit isDeposit) +adjustLPTokens(STAmount const& lptAMMBalance, STAmount const& lpTokens, IsDeposit isDeposit) { // Force rounding downward to ensure adjusted tokens are less or equal // to requested tokens. @@ -178,21 +162,18 @@ adjustAmountsByLPTokens( if (isFeatureEnabled(fixAMMv1_3)) return std::make_tuple(amount, amount2, lpTokens); - auto const lpTokensActual = - adjustLPTokens(lptAMMBalance, lpTokens, isDeposit); + auto const lpTokensActual = adjustLPTokens(lptAMMBalance, lpTokens, isDeposit); if (lpTokensActual == beast::zero) { - auto const amount2Opt = - amount2 ? std::make_optional(STAmount{}) : std::nullopt; + auto const amount2Opt = amount2 ? std::make_optional(STAmount{}) : std::nullopt; return std::make_tuple(STAmount{}, amount2Opt, lpTokensActual); } if (lpTokensActual < lpTokens) { bool const ammRoundingEnabled = [&]() { - if (auto const& rules = getCurrentTransactionRules(); - rules && rules->enabled(fixAMMv1_1)) + if (auto const& rules = getCurrentTransactionRules(); rules && rules->enabled(fixAMMv1_1)) return true; return false; }(); @@ -202,41 +183,33 @@ adjustAmountsByLPTokens( { Number const fr = lpTokensActual / lpTokens; auto const amountActual = toSTAmount(amount.issue(), fr * amount); - auto const amount2Actual = - toSTAmount(amount2->issue(), fr * *amount2); + auto const amount2Actual = toSTAmount(amount2->issue(), fr * *amount2); if (!ammRoundingEnabled) return std::make_tuple( amountActual < amount ? amountActual : amount, amount2Actual < amount2 ? amount2Actual : amount2, lpTokensActual); else - return std::make_tuple( - amountActual, amount2Actual, lpTokensActual); + return std::make_tuple(amountActual, amount2Actual, lpTokensActual); } // Single trade auto const amountActual = [&]() { if (isDeposit == IsDeposit::Yes) - return ammAssetIn( - amountBalance, lptAMMBalance, lpTokensActual, tfee); + return ammAssetIn(amountBalance, lptAMMBalance, lpTokensActual, tfee); else if (!ammRoundingEnabled) - return ammAssetOut( - amountBalance, lptAMMBalance, lpTokens, tfee); + return ammAssetOut(amountBalance, lptAMMBalance, lpTokens, tfee); else - return ammAssetOut( - amountBalance, lptAMMBalance, lpTokensActual, tfee); + return ammAssetOut(amountBalance, lptAMMBalance, lpTokensActual, tfee); }(); if (!ammRoundingEnabled) - return amountActual < amount - ? std::make_tuple(amountActual, std::nullopt, lpTokensActual) - : std::make_tuple(amount, std::nullopt, lpTokensActual); + return amountActual < amount ? std::make_tuple(amountActual, std::nullopt, lpTokensActual) + : std::make_tuple(amount, std::nullopt, lpTokensActual); else return std::make_tuple(amountActual, std::nullopt, lpTokensActual); } - XRPL_ASSERT( - lpTokensActual == lpTokens, - "xrpl::adjustAmountsByLPTokens : LP tokens match actual"); + XRPL_ASSERT(lpTokensActual == lpTokens, "xrpl::adjustAmountsByLPTokens : LP tokens match actual"); return {amount, amount2, lpTokensActual}; } @@ -289,11 +262,7 @@ getRoundedAsset( } STAmount -getRoundedLPTokens( - Rules const& rules, - STAmount const& balance, - Number const& frac, - IsDeposit isDeposit) +getRoundedLPTokens(Rules const& rules, STAmount const& balance, Number const& frac, IsDeposit isDeposit) { if (!rules.enabled(fixAMMv1_3)) return toSTAmount(balance.issue(), balance * frac); @@ -379,11 +348,7 @@ adjustAssetOutByTokens( } Number -adjustFracByTokens( - Rules const& rules, - STAmount const& lptAMMBalance, - STAmount const& tokens, - Number const& frac) +adjustFracByTokens(Rules const& rules, STAmount const& lptAMMBalance, STAmount const& tokens, Number const& frac) { if (!rules.enabled(fixAMMv1_3)) return frac; diff --git a/src/xrpld/app/misc/detail/AMMUtils.cpp b/src/xrpld/app/misc/detail/AMMUtils.cpp index c0cda2bd73..36a40f1709 100644 --- a/src/xrpld/app/misc/detail/AMMUtils.cpp +++ b/src/xrpld/app/misc/detail/AMMUtils.cpp @@ -17,10 +17,8 @@ ammPoolHolds( FreezeHandling freezeHandling, beast::Journal const j) { - auto const assetInBalance = - accountHolds(view, ammAccountID, issue1, freezeHandling, j); - auto const assetOutBalance = - accountHolds(view, ammAccountID, issue2, freezeHandling, j); + auto const assetInBalance = accountHolds(view, ammAccountID, issue1, freezeHandling, j); + auto const assetOutBalance = accountHolds(view, ammAccountID, issue2, freezeHandling, j); return std::make_pair(assetInBalance, assetOutBalance); } @@ -38,32 +36,25 @@ ammHolds( auto const issue2 = ammSle[sfAsset2].get(); if (optIssue1 && optIssue2) { - if (invalidAMMAssetPair( - *optIssue1, - *optIssue2, - std::make_optional(std::make_pair(issue1, issue2)))) + if (invalidAMMAssetPair(*optIssue1, *optIssue2, std::make_optional(std::make_pair(issue1, issue2)))) { // This error can only be hit if the AMM is corrupted // LCOV_EXCL_START - JLOG(j.debug()) << "ammHolds: Invalid optIssue1 or optIssue2 " - << *optIssue1 << " " << *optIssue2; + JLOG(j.debug()) << "ammHolds: Invalid optIssue1 or optIssue2 " << *optIssue1 << " " << *optIssue2; return std::nullopt; // LCOV_EXCL_STOP } return std::make_optional(std::make_pair(*optIssue1, *optIssue2)); } - auto const singleIssue = - [&issue1, &issue2, &j]( - Issue checkIssue, - char const* label) -> std::optional> { + auto const singleIssue = [&issue1, &issue2, &j]( + Issue checkIssue, char const* label) -> std::optional> { if (checkIssue == issue1) return std::make_optional(std::make_pair(issue1, issue2)); else if (checkIssue == issue2) return std::make_optional(std::make_pair(issue2, issue1)); // Unreachable unless AMM corrupted. // LCOV_EXCL_START - JLOG(j.debug()) - << "ammHolds: Invalid " << label << " " << checkIssue; + JLOG(j.debug()) << "ammHolds: Invalid " << label << " " << checkIssue; return std::nullopt; // LCOV_EXCL_STOP }; @@ -80,13 +71,8 @@ ammHolds( }(); if (!issues) return Unexpected(tecAMM_INVALID_TOKENS); - auto const [asset1, asset2] = ammPoolHolds( - view, - ammSle.getAccountID(sfAccount), - issues->first, - issues->second, - freezeHandling, - j); + auto const [asset1, asset2] = + ammPoolHolds(view, ammSle.getAccountID(sfAccount), issues->first, issues->second, freezeHandling, j); return std::make_tuple(asset1, asset2, ammSle[sfLPTokenBalance]); } @@ -112,15 +98,13 @@ ammLPHolds( { amount.clear(Issue{currency, ammAccount}); JLOG(j.trace()) << "ammLPHolds: no SLE " - << " lpAccount=" << to_string(lpAccount) - << " amount=" << amount.getFullText(); + << " lpAccount=" << to_string(lpAccount) << " amount=" << amount.getFullText(); } else if (isFrozen(view, lpAccount, currency, ammAccount)) { amount.clear(Issue{currency, ammAccount}); JLOG(j.trace()) << "ammLPHolds: frozen currency " - << " lpAccount=" << to_string(lpAccount) - << " amount=" << amount.getFullText(); + << " lpAccount=" << to_string(lpAccount) << " amount=" << amount.getFullText(); } else { @@ -133,19 +117,14 @@ ammLPHolds( amount.setIssuer(ammAccount); JLOG(j.trace()) << "ammLPHolds:" - << " lpAccount=" << to_string(lpAccount) - << " amount=" << amount.getFullText(); + << " lpAccount=" << to_string(lpAccount) << " amount=" << amount.getFullText(); } return view.balanceHook(lpAccount, ammAccount, amount); } STAmount -ammLPHolds( - ReadView const& view, - SLE const& ammSle, - AccountID const& lpAccount, - beast::Journal const j) +ammLPHolds(ReadView const& view, SLE const& ammSle, AccountID const& lpAccount, beast::Journal const j) { return ammLPHolds( view, @@ -161,25 +140,20 @@ getTradingFee(ReadView const& view, SLE const& ammSle, AccountID const& account) { using namespace std::chrono; XRPL_ASSERT( - !view.rules().enabled(fixInnerObjTemplate) || - ammSle.isFieldPresent(sfAuctionSlot), + !view.rules().enabled(fixInnerObjTemplate) || ammSle.isFieldPresent(sfAuctionSlot), "xrpl::getTradingFee : auction present"); if (ammSle.isFieldPresent(sfAuctionSlot)) { - auto const& auctionSlot = - static_cast(ammSle.peekAtField(sfAuctionSlot)); + auto const& auctionSlot = static_cast(ammSle.peekAtField(sfAuctionSlot)); // Not expired if (auto const expiration = auctionSlot[~sfExpiration]; - duration_cast( - view.header().parentCloseTime.time_since_epoch()) - .count() < expiration) + duration_cast(view.header().parentCloseTime.time_since_epoch()).count() < expiration) { if (auctionSlot[~sfAccount] == account) return auctionSlot[sfDiscountedFee]; if (auctionSlot.isFieldPresent(sfAuthAccounts)) { - for (auto const& acct : - auctionSlot.getFieldArray(sfAuthAccounts)) + for (auto const& acct : auctionSlot.getFieldArray(sfAuthAccounts)) if (acct[~sfAccount] == account) return auctionSlot[sfDiscountedFee]; } @@ -189,20 +163,15 @@ getTradingFee(ReadView const& view, SLE const& ammSle, AccountID const& account) } STAmount -ammAccountHolds( - ReadView const& view, - AccountID const& ammAccountID, - Issue const& issue) +ammAccountHolds(ReadView const& view, AccountID const& ammAccountID, Issue const& issue) { if (isXRP(issue)) { if (auto const sle = view.read(keylet::account(ammAccountID))) return (*sle)[sfBalance]; } - else if (auto const sle = view.read( - keylet::line(ammAccountID, issue.account, issue.currency)); - sle && - !isFrozen(view, ammAccountID, issue.currency, issue.account)) + else if (auto const sle = view.read(keylet::line(ammAccountID, issue.account, issue.currency)); + sle && !isFrozen(view, ammAccountID, issue.currency, issue.account)) { auto amount = (*sle)[sfBalance]; if (ammAccountID > issue.account) @@ -215,18 +184,12 @@ ammAccountHolds( } static TER -deleteAMMTrustLines( - Sandbox& sb, - AccountID const& ammAccountID, - std::uint16_t maxTrustlinesToDelete, - beast::Journal j) +deleteAMMTrustLines(Sandbox& sb, AccountID const& ammAccountID, std::uint16_t maxTrustlinesToDelete, beast::Journal j) { return cleanupOnAccountDelete( sb, keylet::ownerDir(ammAccountID), - [&](LedgerEntryType nodeType, - uint256 const&, - std::shared_ptr& sleItem) -> std::pair { + [&](LedgerEntryType nodeType, uint256 const&, std::shared_ptr& sleItem) -> std::pair { // Skip AMM if (nodeType == LedgerEntryType::ltAMM) return {tesSUCCESS, SkipEntry::Yes}; @@ -234,9 +197,7 @@ deleteAMMTrustLines( if (nodeType != LedgerEntryType::ltRIPPLE_STATE) { // LCOV_EXCL_START - JLOG(j.error()) - << "deleteAMMTrustLines: deleting non-trustline " - << nodeType; + JLOG(j.error()) << "deleteAMMTrustLines: deleting non-trustline " << nodeType; return {tecINTERNAL, SkipEntry::No}; // LCOV_EXCL_STOP } @@ -245,34 +206,26 @@ deleteAMMTrustLines( if (sleItem->getFieldAmount(sfBalance) != beast::zero) { // LCOV_EXCL_START - JLOG(j.error()) - << "deleteAMMTrustLines: deleting trustline with " - "non-zero balance."; + JLOG(j.error()) << "deleteAMMTrustLines: deleting trustline with " + "non-zero balance."; return {tecINTERNAL, SkipEntry::No}; // LCOV_EXCL_STOP } - return { - deleteAMMTrustLine(sb, sleItem, ammAccountID, j), - SkipEntry::No}; + return {deleteAMMTrustLine(sb, sleItem, ammAccountID, j), SkipEntry::No}; }, j, maxTrustlinesToDelete); } TER -deleteAMMAccount( - Sandbox& sb, - Issue const& asset, - Issue const& asset2, - beast::Journal j) +deleteAMMAccount(Sandbox& sb, Issue const& asset, Issue const& asset2, beast::Journal j) { auto ammSle = sb.peek(keylet::amm(asset, asset2)); if (!ammSle) { // LCOV_EXCL_START - JLOG(j.error()) << "deleteAMMAccount: AMM object does not exist " - << asset << " " << asset2; + JLOG(j.error()) << "deleteAMMAccount: AMM object does not exist " << asset << " " << asset2; return tecINTERNAL; // LCOV_EXCL_STOP } @@ -282,20 +235,16 @@ deleteAMMAccount( if (!sleAMMRoot) { // LCOV_EXCL_START - JLOG(j.error()) << "deleteAMMAccount: AMM account does not exist " - << to_string(ammAccountID); + JLOG(j.error()) << "deleteAMMAccount: AMM account does not exist " << to_string(ammAccountID); return tecINTERNAL; // LCOV_EXCL_STOP } - if (auto const ter = - deleteAMMTrustLines(sb, ammAccountID, maxDeletableAMMTrustLines, j); - ter != tesSUCCESS) + if (auto const ter = deleteAMMTrustLines(sb, ammAccountID, maxDeletableAMMTrustLines, j); ter != tesSUCCESS) return ter; auto const ownerDirKeylet = keylet::ownerDir(ammAccountID); - if (!sb.dirRemove( - ownerDirKeylet, (*ammSle)[sfOwnerNode], ammSle->key(), false)) + if (!sb.dirRemove(ownerDirKeylet, (*ammSle)[sfOwnerNode], ammSle->key(), false)) { // LCOV_EXCL_START JLOG(j.error()) << "deleteAMMAccount: failed to remove dir link"; @@ -305,8 +254,7 @@ deleteAMMAccount( if (sb.exists(ownerDirKeylet) && !sb.emptyDirDelete(ownerDirKeylet)) { // LCOV_EXCL_START - JLOG(j.error()) << "deleteAMMAccount: cannot delete root dir node of " - << toBase58(ammAccountID); + JLOG(j.error()) << "deleteAMMAccount: cannot delete root dir node of " << toBase58(ammAccountID); return tecINTERNAL; // LCOV_EXCL_STOP } @@ -338,8 +286,7 @@ initializeFeeAuctionVote( // AMM creator gets the auction slot for free. // AuctionSlot is created on AMMCreate and updated on AMMDeposit // when AMM is in an empty state - if (rules.enabled(fixInnerObjTemplate) && - !ammSle->isFieldPresent(sfAuctionSlot)) + if (rules.enabled(fixInnerObjTemplate) && !ammSle->isFieldPresent(sfAuctionSlot)) { STObject auctionSlot = STObject::makeInnerObject(sfAuctionSlot); ammSle->set(std::move(auctionSlot)); @@ -348,9 +295,7 @@ initializeFeeAuctionVote( auctionSlot.setAccountID(sfAccount, account); // current + sec in 24h auto const expiration = - std::chrono::duration_cast( - view.header().parentCloseTime.time_since_epoch()) - .count() + + std::chrono::duration_cast(view.header().parentCloseTime.time_since_epoch()).count() + TOTAL_TIME_SLOT_SECS; auctionSlot.setFieldU32(sfExpiration, expiration); auctionSlot.setFieldAmount(sfPrice, STAmount{lptIssue, 0}); @@ -366,10 +311,7 @@ initializeFeeAuctionVote( } Expected -isOnlyLiquidityProvider( - ReadView const& view, - Issue const& ammIssue, - AccountID const& lpAccount) +isOnlyLiquidityProvider(ReadView const& view, Issue const& ammIssue, AccountID const& lpAccount) { // Liquidity Provider (LP) must have one LPToken trustline std::uint8_t nLPTokenTrustLines = 0; @@ -411,10 +353,8 @@ isOnlyLiquidityProvider( return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE auto const lowLimit = sle->getFieldAmount(sfLowLimit); auto const highLimit = sle->getFieldAmount(sfHighLimit); - auto const isLPTrustline = lowLimit.getIssuer() == lpAccount || - highLimit.getIssuer() == lpAccount; - auto const isLPTokenTrustline = - lowLimit.issue() == ammIssue || highLimit.issue() == ammIssue; + auto const isLPTrustline = lowLimit.getIssuer() == lpAccount || highLimit.getIssuer() == lpAccount; + auto const isLPTokenTrustline = lowLimit.issue() == ammIssue || highLimit.issue() == ammIssue; // Liquidity Provider trustline if (isLPTrustline) @@ -437,8 +377,7 @@ isOnlyLiquidityProvider( auto const uNodeNext = ownerDir->getFieldU64(sfIndexNext); if (uNodeNext == 0) { - if (nLPTokenTrustLines != 1 || nIOUTrustLines == 0 || - nIOUTrustLines > 2) + if (nLPTokenTrustLines != 1 || nIOUTrustLines == 0 || nIOUTrustLines > 2) return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE return true; } @@ -454,15 +393,11 @@ verifyAndAdjustLPTokenBalance( std::shared_ptr& ammSle, AccountID const& account) { - if (auto const res = isOnlyLiquidityProvider(sb, lpTokens.issue(), account); - !res) + if (auto const res = isOnlyLiquidityProvider(sb, lpTokens.issue(), account); !res) return Unexpected(res.error()); else if (res.value()) { - if (withinRelativeDistance( - lpTokens, - ammSle->getFieldAmount(sfLPTokenBalance), - Number{1, -3})) + if (withinRelativeDistance(lpTokens, ammSle->getFieldAmount(sfLPTokenBalance), Number{1, -3})) { ammSle->setFieldAmount(sfLPTokenBalance, lpTokens); sb.update(ammSle); diff --git a/src/xrpld/app/misc/detail/AccountTxPaging.h b/src/xrpld/app/misc/detail/AccountTxPaging.h index cbfe8c89bb..209ca67ab6 100644 --- a/src/xrpld/app/misc/detail/AccountTxPaging.h +++ b/src/xrpld/app/misc/detail/AccountTxPaging.h @@ -1,7 +1,6 @@ -#ifndef XRPL_APP_MISC_IMPL_ACCOUNTTXPAGING_H_INCLUDED -#define XRPL_APP_MISC_IMPL_ACCOUNTTXPAGING_H_INCLUDED +#pragma once -#include +#include #include @@ -22,5 +21,3 @@ void saveLedgerAsync(Application& app, std::uint32_t seq); } // namespace xrpl - -#endif diff --git a/src/xrpld/app/misc/detail/AmendmentTable.cpp b/src/xrpld/app/misc/detail/AmendmentTable.cpp index 8ed9bc12c5..767a3d87f9 100644 --- a/src/xrpld/app/misc/detail/AmendmentTable.cpp +++ b/src/xrpld/app/misc/detail/AmendmentTable.cpp @@ -1,12 +1,12 @@ -#include #include -#include #include +#include #include #include #include #include +#include #include #include @@ -37,15 +37,12 @@ parseSection(Section const& section) boost::smatch match; if (!boost::regex_match(line, match, re1)) - Throw( - "Invalid entry '" + line + "' in [" + section.name() + "]"); + Throw("Invalid entry '" + line + "' in [" + section.name() + "]"); uint256 id; if (!id.parseHex(match[1])) - Throw( - "Invalid amendment ID '" + match[1] + "' in [" + - section.name() + "]"); + Throw("Invalid amendment ID '" + match[1] + "' in [" + section.name() + "]"); names.push_back(std::make_pair(id, match[2])); } @@ -98,9 +95,7 @@ public: // // Call with AmendmentTable::mutex_ locked. void - trustChanged( - hash_set const& allTrusted, - std::lock_guard const& lock) + trustChanged(hash_set const& allTrusted, std::lock_guard const& lock) { decltype(recordedVotes_) newRecordedVotes; newRecordedVotes.reserve(allTrusted.size()); @@ -158,25 +153,20 @@ public: // validators with these newest votes. for (auto const& val : valSet) { - auto const pkHuman = - toBase58(TokenType::NodePublic, val->getSignerPublic()); + auto const pkHuman = toBase58(TokenType::NodePublic, val->getSignerPublic()); // If this validation comes from one of our trusted validators... - if (auto const iter = recordedVotes_.find(val->getSignerPublic()); - iter != recordedVotes_.end()) + if (auto const iter = recordedVotes_.find(val->getSignerPublic()); iter != recordedVotes_.end()) { iter->second.timeout = newTimeout; if (val->isFieldPresent(sfAmendments)) { auto const& choices = val->getFieldV256(sfAmendments); iter->second.upVotes.assign(choices.begin(), choices.end()); - JLOG(j.debug()) - << "recordVotes: Validation from trusted " << pkHuman - << " has " << choices.size() << " amendment votes: " - << boost::algorithm::join( - iter->second.upVotes | - boost::adaptors::transformed( - to_string<256, void>), - ", "); + JLOG(j.debug()) << "recordVotes: Validation from trusted " << pkHuman << " has " << choices.size() + << " amendment votes: " + << boost::algorithm::join( + iter->second.upVotes | boost::adaptors::transformed(to_string<256, void>), + ", "); // TODO: Maybe transform using to_short_string once #5126 is // merged // @@ -187,15 +177,12 @@ public: { // This validator does not upVote any amendments right now. iter->second.upVotes.clear(); - JLOG(j.debug()) << "recordVotes: Validation from trusted " - << pkHuman << " has no amendment votes."; + JLOG(j.debug()) << "recordVotes: Validation from trusted " << pkHuman << " has no amendment votes."; } } else { - JLOG(j.debug()) - << "recordVotes: Ignoring validation from untrusted " - << pkHuman; + JLOG(j.debug()) << "recordVotes: Ignoring validation from untrusted " << pkHuman; } } @@ -203,26 +190,21 @@ public: std::for_each( recordedVotes_.begin(), recordedVotes_.end(), - [&closeTime, newTimeout, &j]( - decltype(recordedVotes_)::value_type& votes) { - auto const pkHuman = - toBase58(TokenType::NodePublic, votes.first); + [&closeTime, newTimeout, &j](decltype(recordedVotes_)::value_type& votes) { + auto const pkHuman = toBase58(TokenType::NodePublic, votes.first); if (!votes.second.timeout) { XRPL_ASSERT( votes.second.upVotes.empty(), "xrpl::TrustedVotes::recordVotes : received no " "upvotes"); - JLOG(j.debug()) - << "recordVotes: Have not received any " - "amendment votes from " - << pkHuman << " since last timeout or startup"; + JLOG(j.debug()) << "recordVotes: Have not received any " + "amendment votes from " + << pkHuman << " since last timeout or startup"; } else if (closeTime > votes.second.timeout) { - JLOG(j.debug()) - << "recordVotes: Timeout: Clearing votes from " - << pkHuman; + JLOG(j.debug()) << "recordVotes: Timeout: Clearing votes from " << pkHuman; votes.second.timeout.reset(); votes.second.upVotes.clear(); } @@ -233,10 +215,8 @@ public: "xrpl::TrustedVotes::recordVotes : votes not " "expired"); using namespace std::chrono; - auto const age = duration_cast( - newTimeout - *votes.second.timeout); - JLOG(j.debug()) << "recordVotes: Using " << age.count() - << "min old cached votes from " << pkHuman; + auto const age = duration_cast(newTimeout - *votes.second.timeout); + JLOG(j.debug()) << "recordVotes: Using " << age.count() << "min old cached votes from " << pkHuman; } }); } @@ -252,8 +232,7 @@ public: for (auto& validatorVotes : recordedVotes_) { XRPL_ASSERT( - validatorVotes.second.timeout || - validatorVotes.second.upVotes.empty(), + validatorVotes.second.timeout || validatorVotes.second.upVotes.empty(), "xrpl::TrustedVotes::getVotes : valid votes"); if (validatorVotes.second.timeout) ++available; @@ -303,10 +282,7 @@ private: int threshold_ = 0; public: - AmendmentSet( - Rules const& rules, - TrustedVotes const& trustedVotes, - std::lock_guard const& lock) + AmendmentSet(Rules const& rules, TrustedVotes const& trustedVotes, std::lock_guard const& lock) { // process validations for ledger before flag ledger. auto [trustedCount, newVotes] = trustedVotes.getVotes(rules, lock); @@ -317,8 +293,7 @@ public: threshold_ = std::max( 1L, static_cast( - (trustedValidations_ * amendmentMajorityCalcThreshold.num) / - amendmentMajorityCalcThreshold.den)); + (trustedValidations_ * amendmentMajorityCalcThreshold.num) / amendmentMajorityCalcThreshold.den)); } bool @@ -409,8 +384,7 @@ private: get(uint256 const& amendment, std::lock_guard const& lock); AmendmentState const* - get(uint256 const& amendment, - std::lock_guard const& lock) const; + get(uint256 const& amendment, std::lock_guard const& lock) const; // Injects amendment json into v. Must be called with mutex_ locked. void @@ -422,14 +396,11 @@ private: std::lock_guard const& lock) const; void - persistVote( - uint256 const& amendment, - std::string const& name, - AmendmentVote vote) const; + persistVote(uint256 const& amendment, std::string const& name, AmendmentVote vote) const; public: AmendmentTableImpl( - Application& app, + ServiceRegistry& registry, std::chrono::seconds majorityTime, std::vector const& supported, Section const& enabled, @@ -467,10 +438,7 @@ public: needValidatedLedger(LedgerIndex seq) const override; void - doValidatedLedger( - LedgerIndex seq, - std::set const& enabled, - majorityAmendments_t const& majority) override; + doValidatedLedger(LedgerIndex seq, std::set const& enabled, majorityAmendments_t const& majority) override; void trustChanged(hash_set const& allTrusted) override; @@ -493,7 +461,7 @@ public: //------------------------------------------------------------------------------ AmendmentTableImpl::AmendmentTableImpl( - Application& app, + ServiceRegistry& registry, std::chrono::seconds majorityTime, std::vector const& supported, Section const& enabled, @@ -503,7 +471,7 @@ AmendmentTableImpl::AmendmentTableImpl( , majorityTime_(majorityTime) , unsupportedEnabled_(false) , j_(journal) - , db_(app.getWalletDB()) + , db_(registry.getWalletDB()) { std::lock_guard lock(mutex_); @@ -535,8 +503,7 @@ AmendmentTableImpl::AmendmentTableImpl( break; } - JLOG(j_.debug()) << "Amendment " << amendment << " (" << s.name - << ") is supported and will be " + JLOG(j_.debug()) << "Amendment " << amendment << " (" << s.name << ") is supported and will be " << (s.vote == AmendmentVote::up ? "up" : "down") << " voted by default if not enabled on the ledger."; } @@ -563,9 +530,8 @@ AmendmentTableImpl::AmendmentTableImpl( { if (featureVotesExist) { // If the table existed, warn about duplicate config info - JLOG(j_.warn()) - << "[veto_amendments] section in config file ignored" - " in favor of data in db/wallet.db."; + JLOG(j_.warn()) << "[veto_amendments] section in config file ignored" + " in favor of data in db/wallet.db."; break; } else @@ -576,10 +542,8 @@ AmendmentTableImpl::AmendmentTableImpl( } else { - JLOG(j_.warn()) - << "[veto_amendments] section in config has amendment " - << '(' << a.first << ", " << a.second - << ") both [veto_amendments] and [amendments]."; + JLOG(j_.warn()) << "[veto_amendments] section in config has amendment " << '(' << a.first << ", " + << a.second << ") both [veto_amendments] and [amendments]."; } } } @@ -595,22 +559,18 @@ AmendmentTableImpl::AmendmentTableImpl( if (!amendment_hash || !amendment_name || !vote) { // These fields should never have nulls, but check - Throw( - "Invalid FeatureVotes row in wallet.db"); + Throw("Invalid FeatureVotes row in wallet.db"); } if (!amend_hash.parseHex(*amendment_hash)) { - Throw( - "Invalid amendment ID '" + *amendment_hash + - " in wallet.db"); + Throw("Invalid amendment ID '" + *amendment_hash + " in wallet.db"); } if (*vote == AmendmentVote::down) { // Unknown amendments are effectively vetoed already if (auto s = get(amend_hash, lock)) { - JLOG(j_.info()) << "Amendment {" << *amendment_name << ", " - << amend_hash << "} is downvoted."; + JLOG(j_.info()) << "Amendment {" << *amendment_name << ", " << amend_hash << "} is downvoted."; if (!amendment_name->empty()) s->name = *amendment_name; // An obsolete amendment's vote can never be changed @@ -622,8 +582,7 @@ AmendmentTableImpl::AmendmentTableImpl( { AmendmentState& s = add(amend_hash, lock); - JLOG(j_.debug()) << "Amendment {" << *amendment_name << ", " - << amend_hash << "} is upvoted."; + JLOG(j_.debug()) << "Amendment {" << *amendment_name << ", " << amend_hash << "} is upvoted."; if (!amendment_name->empty()) s.name = *amendment_name; // An obsolete amendment's vote can never be changed @@ -634,28 +593,21 @@ AmendmentTableImpl::AmendmentTableImpl( } AmendmentState& -AmendmentTableImpl::add( - uint256 const& amendmentHash, - std::lock_guard const&) +AmendmentTableImpl::add(uint256 const& amendmentHash, std::lock_guard const&) { // call with the mutex held return amendmentMap_[amendmentHash]; } AmendmentState* -AmendmentTableImpl::get( - uint256 const& amendmentHash, - std::lock_guard const& lock) +AmendmentTableImpl::get(uint256 const& amendmentHash, std::lock_guard const& lock) { // Forward to the const version of get. - return const_cast( - std::as_const(*this).get(amendmentHash, lock)); + return const_cast(std::as_const(*this).get(amendmentHash, lock)); } AmendmentState const* -AmendmentTableImpl::get( - uint256 const& amendmentHash, - std::lock_guard const&) const +AmendmentTableImpl::get(uint256 const& amendmentHash, std::lock_guard const&) const { // call with the mutex held auto ret = amendmentMap_.find(amendmentHash); @@ -681,14 +633,9 @@ AmendmentTableImpl::find(std::string const& name) const } void -AmendmentTableImpl::persistVote( - uint256 const& amendment, - std::string const& name, - AmendmentVote vote) const +AmendmentTableImpl::persistVote(uint256 const& amendment, std::string const& name, AmendmentVote vote) const { - XRPL_ASSERT( - vote != AmendmentVote::obsolete, - "xrpl::AmendmentTableImpl::persistVote : valid vote input"); + XRPL_ASSERT(vote != AmendmentVote::obsolete, "xrpl::AmendmentTableImpl::persistVote : valid vote input"); auto db = db_.checkoutDb(); voteAmendment(*db, amendment, name, vote); } @@ -732,8 +679,7 @@ AmendmentTableImpl::enable(uint256 const& amendment) if (!s.supported) { - JLOG(j_.error()) << "Unsupported amendment " << amendment - << " activated."; + JLOG(j_.error()) << "Unsupported amendment " << amendment << " activated."; unsupportedEnabled_ = true; } @@ -782,8 +728,7 @@ AmendmentTableImpl::doValidation(std::set const& enabled) const amendments.reserve(amendmentMap_.size()); for (auto const& e : amendmentMap_) { - if (e.second.supported && e.second.vote == AmendmentVote::up && - (enabled.count(e.first) == 0)) + if (e.second.supported && e.second.vote == AmendmentVote::up && (enabled.count(e.first) == 0)) { amendments.push_back(e.first); JLOG(j_.info()) << "Voting for amendment " << e.second.name; @@ -812,8 +757,7 @@ AmendmentTableImpl::doVoting( majorityAmendments_t const& majorityAmendments, std::vector> const& valSet) { - JLOG(j_.trace()) << "voting at " << closeTime.time_since_epoch().count() - << ": " << enabledAmendments.size() << ", " + JLOG(j_.trace()) << "voting at " << closeTime.time_since_epoch().count() << ": " << enabledAmendments.size() << ", " << majorityAmendments.size() << ", " << valSet.size(); std::lock_guard lock(mutex_); @@ -822,11 +766,9 @@ AmendmentTableImpl::doVoting( previousTrustedVotes_.recordVotes(rules, valSet, closeTime, j_, lock); // Tally the most recent votes. - auto vote = - std::make_unique(rules, previousTrustedVotes_, lock); + auto vote = std::make_unique(rules, previousTrustedVotes_, lock); JLOG(j_.debug()) << "Counted votes from " << vote->trustedValidations() - << " valid trusted validations, threshold is: " - << vote->threshold(); + << " valid trusted validations, threshold is: " << vote->threshold(); // Map of amendments to the action to be taken for each one. The action is // the value of the flags in the pseudo-transaction @@ -855,13 +797,11 @@ AmendmentTableImpl::doVoting( auto const logStr = [&entry, &vote]() { std::stringstream ss; - ss << entry.first << " (" << entry.second.name << ") has " - << vote->votes(entry.first) << " votes"; + ss << entry.first << " (" << entry.second.name << ") has " << vote->votes(entry.first) << " votes"; return ss.str(); }(); - if (hasValMajority && !hasLedgerMajority && - entry.second.vote == AmendmentVote::up) + if (hasValMajority && !hasLedgerMajority && entry.second.vote == AmendmentVote::up) { // Ledger says no majority, validators say yes, and voting yes // locally @@ -875,8 +815,7 @@ AmendmentTableImpl::doVoting( actions[entry.first] = tfLostMajority; } else if ( - hasLedgerMajority && - ((*majorityTime + majorityTime_) <= closeTime) && + hasLedgerMajority && ((*majorityTime + majorityTime_) <= closeTime) && entry.second.vote == AmendmentVote::up) { // Ledger says majority held @@ -886,9 +825,7 @@ AmendmentTableImpl::doVoting( // Logging only below this point else if (hasValMajority && hasLedgerMajority) { - JLOG(j_.debug()) - << logStr - << ": amendment holding majority, waiting to be enabled"; + JLOG(j_.debug()) << logStr << ": amendment holding majority, waiting to be enabled"; } else if (!hasValMajority) { @@ -939,8 +876,7 @@ AmendmentTableImpl::doValidatedLedger( if (!s.supported) { - JLOG(j_.info()) << "Unsupported amendment " << hash - << " reached majority at " << to_string(time); + JLOG(j_.info()) << "Unsupported amendment " << hash << " reached majority at " << to_string(time); if (!firstUnsupportedExpected_ || firstUnsupportedExpected_ > time) firstUnsupportedExpected_ = time; } @@ -999,12 +935,7 @@ AmendmentTableImpl::getJson(bool isAdmin) const std::lock_guard lock(mutex_); for (auto const& e : amendmentMap_) { - injectJson( - ret[to_string(e.first)] = Json::objectValue, - e.first, - e.second, - isAdmin, - lock); + injectJson(ret[to_string(e.first)] = Json::objectValue, e.first, e.second, isAdmin, lock); } } return ret; @@ -1020,8 +951,7 @@ AmendmentTableImpl::getJson(uint256 const& amendmentID, bool isAdmin) const AmendmentState const* a = get(amendmentID, lock); if (a) { - Json::Value& jAmendment = - (ret[to_string(amendmentID)] = Json::objectValue); + Json::Value& jAmendment = (ret[to_string(amendmentID)] = Json::objectValue); injectJson(jAmendment, amendmentID, *a, isAdmin, lock); } } @@ -1031,15 +961,14 @@ AmendmentTableImpl::getJson(uint256 const& amendmentID, bool isAdmin) const std::unique_ptr make_AmendmentTable( - Application& app, + ServiceRegistry& registry, std::chrono::seconds majorityTime, std::vector const& supported, Section const& enabled, Section const& vetoed, beast::Journal journal) { - return std::make_unique( - app, majorityTime, supported, enabled, vetoed, journal); + return std::make_unique(registry, majorityTime, supported, enabled, vetoed, journal); } } // namespace xrpl diff --git a/src/xrpld/app/misc/detail/DelegateUtils.cpp b/src/xrpld/app/misc/detail/DelegateUtils.cpp index 027f2f1cc6..74ec55cdee 100644 --- a/src/xrpld/app/misc/detail/DelegateUtils.cpp +++ b/src/xrpld/app/misc/detail/DelegateUtils.cpp @@ -35,10 +35,8 @@ loadGranularPermission( for (auto const& permission : permissionArray) { auto const permissionValue = permission[sfPermissionValue]; - auto const granularValue = - static_cast(permissionValue); - auto const& type = - Permission::getInstance().getGranularTxType(granularValue); + auto const granularValue = static_cast(permissionValue); + auto const& type = Permission::getInstance().getGranularTxType(granularValue); if (type && *type == txType) granularPermissions.insert(granularValue); } diff --git a/src/xrpld/app/misc/detail/LendingHelpers.cpp b/src/xrpld/app/misc/detail/LendingHelpers.cpp index a8354ff049..106eeb9301 100644 --- a/src/xrpld/app/misc/detail/LendingHelpers.cpp +++ b/src/xrpld/app/misc/detail/LendingHelpers.cpp @@ -7,8 +7,7 @@ namespace xrpl { bool checkLendingProtocolDependencies(PreflightContext const& ctx) { - return ctx.rules.enabled(featureSingleAssetVault) && - VaultCreate::checkExtraFeatures(ctx); + return ctx.rules.enabled(featureSingleAssetVault) && VaultCreate::checkExtraFeatures(ctx); } LoanPaymentParts& @@ -38,8 +37,7 @@ LoanPaymentParts::operator+=(LoanPaymentParts const& other) bool LoanPaymentParts::operator==(LoanPaymentParts const& other) const { - return principalPaid == other.principalPaid && - interestPaid == other.interestPaid && + return principalPaid == other.principalPaid && interestPaid == other.interestPaid && valueChange == other.valueChange && feePaid == other.feePaid; } @@ -52,8 +50,7 @@ Number loanPeriodicRate(TenthBips32 interestRate, std::uint32_t paymentInterval) { // Need floating point math, since we're dividing by a large number - return tenthBipsOfValue(Number(paymentInterval), interestRate) / - secondsInYear; + return tenthBipsOfValue(Number(paymentInterval), interestRate) / secondsInYear; } /* Checks if a value is already rounded to the specified scale. @@ -63,8 +60,7 @@ loanPeriodicRate(TenthBips32 interestRate, std::uint32_t paymentInterval) bool isRounded(Asset const& asset, Number const& value, std::int32_t scale) { - return roundToAsset(asset, value, scale, Number::downward) == - roundToAsset(asset, value, scale, Number::upward); + return roundToAsset(asset, value, scale, Number::downward) == roundToAsset(asset, value, scale, Number::upward); } namespace detail { @@ -96,9 +92,7 @@ computeRaisedRate(Number const& periodicRate, std::uint32_t paymentsRemaining) * Equation (6) from XLS-66 spec, Section A-2 Equation Glossary */ Number -computePaymentFactor( - Number const& periodicRate, - std::uint32_t paymentsRemaining) +computePaymentFactor(Number const& periodicRate, std::uint32_t paymentsRemaining) { if (paymentsRemaining == 0) return numZero; @@ -107,8 +101,7 @@ computePaymentFactor( if (periodicRate == beast::zero) return Number{1} / paymentsRemaining; - Number const raisedRate = - computeRaisedRate(periodicRate, paymentsRemaining); + Number const raisedRate = computeRaisedRate(periodicRate, paymentsRemaining); return (periodicRate * raisedRate) / (raisedRate - 1); } @@ -119,10 +112,7 @@ computePaymentFactor( * Equation (7) from XLS-66 spec, Section A-2 Equation Glossary */ Number -loanPeriodicPayment( - Number const& principalOutstanding, - Number const& periodicRate, - std::uint32_t paymentsRemaining) +loanPeriodicPayment(Number const& principalOutstanding, Number const& periodicRate, std::uint32_t paymentsRemaining) { if (principalOutstanding == 0 || paymentsRemaining == 0) return 0; @@ -131,8 +121,7 @@ loanPeriodicPayment( if (periodicRate == beast::zero) return principalOutstanding / paymentsRemaining; - return principalOutstanding * - computePaymentFactor(periodicRate, paymentsRemaining); + return principalOutstanding * computePaymentFactor(periodicRate, paymentsRemaining); } /* Reverse-calculates principal from periodic payment amount. @@ -152,8 +141,7 @@ loanPrincipalFromPeriodicPayment( if (periodicRate == 0) return periodicPayment * paymentsRemaining; - return periodicPayment / - computePaymentFactor(periodicRate, paymentsRemaining); + return periodicPayment / computePaymentFactor(periodicRate, paymentsRemaining); } /* @@ -168,8 +156,7 @@ computeInterestAndFeeParts( TenthBips16 managementFeeRate, std::int32_t loanScale) { - auto const fee = - computeManagementFee(asset, interest, managementFeeRate, loanScale); + auto const fee = computeManagementFee(asset, interest, managementFeeRate, loanScale); return std::make_pair(interest - fee, fee); } @@ -241,8 +228,7 @@ loanAccruedInterest( // Division is more likely to introduce rounding errors, which will then get // amplified by multiplication. Therefore, we first multiply, and only then // divide. - return principalOutstanding * periodicRate * secondsSinceLastPayment / - paymentInterval; + return principalOutstanding * periodicRate * secondsSinceLastPayment / paymentInterval; } /* Applies a payment to the loan state and returns the breakdown of amounts @@ -266,8 +252,7 @@ doPayment( UInt32OptionalProxy& nextDueDateProxy, std::uint32_t paymentInterval) { - XRPL_ASSERT_PARTS( - nextDueDateProxy, "xrpl::detail::doPayment", "Next due date proxy set"); + XRPL_ASSERT_PARTS(nextDueDateProxy, "xrpl::detail::doPayment", "Next due date proxy set"); if (payment.specialCase == PaymentSpecialCase::final) { @@ -276,9 +261,7 @@ doPayment( "xrpl::detail::doPayment", "Full principal payment"); XRPL_ASSERT_PARTS( - totalValueOutstandingProxy == payment.trackedValueDelta, - "xrpl::detail::doPayment", - "Full value payment"); + totalValueOutstandingProxy == payment.trackedValueDelta, "xrpl::detail::doPayment", "Full value payment"); XRPL_ASSERT_PARTS( managementFeeOutstandingProxy == payment.trackedManagementFeeDelta, "xrpl::detail::doPayment", @@ -316,9 +299,7 @@ doPayment( "xrpl::detail::doPayment", "Partial principal payment"); XRPL_ASSERT_PARTS( - totalValueOutstandingProxy > payment.trackedValueDelta, - "xrpl::detail::doPayment", - "Partial value payment"); + totalValueOutstandingProxy > payment.trackedValueDelta, "xrpl::detail::doPayment", "Partial value payment"); // Management fees are expected to be relatively small, and could get to // zero before the loan is paid off XRPL_ASSERT_PARTS( @@ -336,8 +317,7 @@ doPayment( XRPL_ASSERT_PARTS( // Use an explicit cast because the template parameter can be // ValueProxy or Number - static_cast(principalOutstandingProxy) <= - static_cast(totalValueOutstandingProxy), + static_cast(principalOutstandingProxy) <= static_cast(totalValueOutstandingProxy), "xrpl::detail::doPayment", "principal does not exceed total"); @@ -348,26 +328,23 @@ doPayment( "xrpl::detail::doPayment", "fee outstanding stays valid"); - return LoanPaymentParts{ - // Principal paid is straightforward - it's the tracked delta - .principalPaid = payment.trackedPrincipalDelta, + return LoanPaymentParts{// Principal paid is straightforward - it's the tracked delta + .principalPaid = payment.trackedPrincipalDelta, - // Interest paid combines: - // 1. Tracked interest from the amortization schedule - // (derived from the tracked deltas) - // 2. Untracked interest (e.g., late payment penalties) - .interestPaid = - payment.trackedInterestPart() + payment.untrackedInterest, + // Interest paid combines: + // 1. Tracked interest from the amortization schedule + // (derived from the tracked deltas) + // 2. Untracked interest (e.g., late payment penalties) + .interestPaid = payment.trackedInterestPart() + payment.untrackedInterest, - // Value change represents how the loan's total value changed beyond - // normal amortization. - .valueChange = payment.untrackedInterest, + // Value change represents how the loan's total value changed beyond + // normal amortization. + .valueChange = payment.untrackedInterest, - // Fee paid combines: - // 1. Tracked management fees from the amortization schedule - // 2. Untracked fees (e.g., late payment fees, service fees) - .feePaid = - payment.trackedManagementFeeDelta + payment.untrackedManagementFee}; + // Fee paid combines: + // 1. Tracked management fees from the amortization schedule + // 2. Untracked fees (e.g., late payment fees, service fees) + .feePaid = payment.trackedManagementFeeDelta + payment.untrackedManagementFee}; } /* Simulates an overpayment to validate it won't break the loan's amortization. @@ -393,8 +370,8 @@ tryOverpayment( beast::Journal j) { // Calculate what the loan state SHOULD be theoretically (at full precision) - auto const theoreticalState = computeTheoreticalLoanState( - periodicPayment, periodicRate, paymentRemaining, managementFeeRate); + auto const theoreticalState = + computeTheoreticalLoanState(periodicPayment, periodicRate, paymentRemaining, managementFeeRate); // Calculate the accumulated rounding errors. These need to be preserved // across the re-amortization to maintain consistency with the loan's @@ -404,61 +381,40 @@ tryOverpayment( // Compute the new principal by applying the overpayment to the theoretical // principal. Use max with 0 to ensure we never go negative. - auto const newTheoreticalPrincipal = std::max( - theoreticalState.principalOutstanding - - overpaymentComponents.trackedPrincipalDelta, - Number{0}); + auto const newTheoreticalPrincipal = + std::max(theoreticalState.principalOutstanding - overpaymentComponents.trackedPrincipalDelta, Number{0}); // Compute new loan properties based on the reduced principal. This // recalculates the periodic payment, total value, and management fees // for the remaining payment schedule. auto newLoanProperties = computeLoanProperties( - asset, - newTheoreticalPrincipal, - periodicRate, - paymentRemaining, - managementFeeRate, - loanScale); + asset, newTheoreticalPrincipal, periodicRate, paymentRemaining, managementFeeRate, loanScale); - JLOG(j.debug()) << "new periodic payment: " - << newLoanProperties.periodicPayment - << ", new total value: " - << newLoanProperties.loanState.valueOutstanding - << ", first payment principal: " - << newLoanProperties.firstPaymentPrincipal; + JLOG(j.debug()) << "new periodic payment: " << newLoanProperties.periodicPayment + << ", new total value: " << newLoanProperties.loanState.valueOutstanding + << ", first payment principal: " << newLoanProperties.firstPaymentPrincipal; // Calculate what the new loan state should be with the new periodic payment // including rounding errors - auto const newTheoreticalState = computeTheoreticalLoanState( - newLoanProperties.periodicPayment, - periodicRate, - paymentRemaining, - managementFeeRate) + + auto const newTheoreticalState = + computeTheoreticalLoanState( + newLoanProperties.periodicPayment, periodicRate, paymentRemaining, managementFeeRate) + errors; - JLOG(j.debug()) << "new theoretical value: " - << newTheoreticalState.valueOutstanding << ", principal: " - << newTheoreticalState.principalOutstanding - << ", interest gross: " - << newTheoreticalState.interestOutstanding(); + JLOG(j.debug()) << "new theoretical value: " << newTheoreticalState.valueOutstanding + << ", principal: " << newTheoreticalState.principalOutstanding + << ", interest gross: " << newTheoreticalState.interestOutstanding(); // Update the loan state variables with the new values that include the // preserved rounding errors. This ensures the loan's tracked state remains // consistent with its payment history. auto const principalOutstanding = std::clamp( - roundToAsset( - asset, - newTheoreticalState.principalOutstanding, - loanScale, - Number::upward), + roundToAsset(asset, newTheoreticalState.principalOutstanding, loanScale, Number::upward), numZero, roundedOldState.principalOutstanding); auto const totalValueOutstanding = std::clamp( roundToAsset( - asset, - principalOutstanding + newTheoreticalState.interestOutstanding(), - loanScale, - Number::upward), + asset, principalOutstanding + newTheoreticalState.interestOutstanding(), loanScale, Number::upward), numZero, roundedOldState.valueOutstanding); auto const managementFeeOutstanding = std::clamp( @@ -466,8 +422,8 @@ tryOverpayment( numZero, roundedOldState.managementFeeDue); - auto const roundedNewState = constructLoanState( - totalValueOutstanding, principalOutstanding, managementFeeOutstanding); + auto const roundedNewState = + constructLoanState(totalValueOutstanding, principalOutstanding, managementFeeOutstanding); // Update newLoanProperties so that checkLoanGuards can make an accurate // evaluation. @@ -475,8 +431,7 @@ tryOverpayment( JLOG(j.debug()) << "new rounded value: " << roundedNewState.valueOutstanding << ", principal: " << roundedNewState.principalOutstanding - << ", interest gross: " - << roundedNewState.interestOutstanding(); + << ", interest gross: " << roundedNewState.interestOutstanding(); // check that the loan is still valid if (auto const ter = checkLoanGuards( @@ -499,8 +454,7 @@ tryOverpayment( // Validate that all computed properties are reasonable. These checks should // never fail under normal circumstances, but we validate defensively. - if (newLoanProperties.periodicPayment <= 0 || - newLoanProperties.loanState.valueOutstanding <= 0 || + if (newLoanProperties.periodicPayment <= 0 || newLoanProperties.loanState.valueOutstanding <= 0 || newLoanProperties.loanState.managementFeeDue < 0) { // LCOV_EXCL_START @@ -508,10 +462,8 @@ tryOverpayment( "properties are invalid. Does " "not compute. TotalValueOutstanding: " << newLoanProperties.loanState.valueOutstanding - << ", PeriodicPayment : " - << newLoanProperties.periodicPayment - << ", ManagementFeeOwedToBroker: " - << newLoanProperties.loanState.managementFeeDue; + << ", PeriodicPayment : " << newLoanProperties.periodicPayment + << ", ManagementFeeOwedToBroker: " << newLoanProperties.loanState.managementFeeDue; return Unexpected(tesSUCCESS); // LCOV_EXCL_STOP } @@ -521,8 +473,7 @@ tryOverpayment( // The change in loan management fee is equal to the change between the old // and the new outstanding management fees XRPL_ASSERT_PARTS( - deltas.managementFee == - roundedOldState.managementFeeDue - managementFeeOutstanding, + deltas.managementFee == roundedOldState.managementFeeDue - managementFeeOutstanding, "xrpl::detail::tryOverpayment", "no fee change"); @@ -550,12 +501,10 @@ tryOverpayment( // Value change includes both the reduction from paying down // principal (negative) and any untracked interest penalties // (positive, e.g., if the overpayment itself incurs a fee) - .valueChange = - valueChange + overpaymentComponents.untrackedInterest, + .valueChange = valueChange + overpaymentComponents.untrackedInterest, // Fee paid includes both the reduction in tracked management fees // and any untracked fees on the overpayment itself - .feePaid = overpaymentComponents.untrackedManagementFee + - overpaymentComponents.trackedManagementFeeDelta, + .feePaid = overpaymentComponents.untrackedManagementFee + overpaymentComponents.trackedManagementFeeDelta, }, newLoanProperties); } @@ -586,22 +535,17 @@ doOverpayment( TenthBips16 const managementFeeRate, beast::Journal j) { - auto const loanState = constructLoanState( - totalValueOutstandingProxy, - principalOutstandingProxy, - managementFeeOutstandingProxy); + auto const loanState = + constructLoanState(totalValueOutstandingProxy, principalOutstandingProxy, managementFeeOutstandingProxy); auto const periodicPayment = periodicPaymentProxy; - JLOG(j.debug()) - << "overpayment components:" - << ", totalValue before: " << *totalValueOutstandingProxy - << ", valueDelta: " << overpaymentComponents.trackedValueDelta - << ", principalDelta: " << overpaymentComponents.trackedPrincipalDelta - << ", managementFeeDelta: " - << overpaymentComponents.trackedManagementFeeDelta - << ", interestPart: " << overpaymentComponents.trackedInterestPart() - << ", untrackedInterest: " << overpaymentComponents.untrackedInterest - << ", totalDue: " << overpaymentComponents.totalDue - << ", payments remaining :" << paymentRemaining; + JLOG(j.debug()) << "overpayment components:" + << ", totalValue before: " << *totalValueOutstandingProxy + << ", valueDelta: " << overpaymentComponents.trackedValueDelta + << ", principalDelta: " << overpaymentComponents.trackedPrincipalDelta + << ", managementFeeDelta: " << overpaymentComponents.trackedManagementFeeDelta + << ", interestPart: " << overpaymentComponents.trackedInterestPart() + << ", untrackedInterest: " << overpaymentComponents.untrackedInterest + << ", totalDue: " << overpaymentComponents.totalDue << ", payments remaining :" << paymentRemaining; // Attempt to re-amortize the loan with the overpayment applied. // This modifies the temporary copies, leaving the proxies unchanged. @@ -628,9 +572,8 @@ doOverpayment( { // LCOV_EXCL_START JLOG(j.warn()) << "Overpayment not allowed: principal " - << "outstanding did not decrease. Before: " - << *principalOutstandingProxy << ". After: " - << newRoundedLoanState.principalOutstanding; + << "outstanding did not decrease. Before: " << *principalOutstandingProxy + << ". After: " << newRoundedLoanState.principalOutstanding; return Unexpected(tesSUCCESS); // LCOV_EXCL_STOP } @@ -641,38 +584,32 @@ doOverpayment( XRPL_ASSERT_PARTS( overpaymentComponents.trackedPrincipalDelta == - principalOutstandingProxy - - newRoundedLoanState.principalOutstanding, + principalOutstandingProxy - newRoundedLoanState.principalOutstanding, "xrpl::detail::doOverpayment", "principal change agrees"); // I'm not 100% sure the following asserts are correct. If in doubt, and // everything else works, remove any that cause trouble. - JLOG(j.debug()) - << "valueChange: " << loanPaymentParts.valueChange - << ", totalValue before: " << *totalValueOutstandingProxy - << ", totalValue after: " << newRoundedLoanState.valueOutstanding - << ", totalValue delta: " - << (totalValueOutstandingProxy - newRoundedLoanState.valueOutstanding) - << ", principalDelta: " << overpaymentComponents.trackedPrincipalDelta - << ", principalPaid: " << loanPaymentParts.principalPaid - << ", Computed difference: " - << overpaymentComponents.trackedPrincipalDelta - + JLOG(j.debug()) << "valueChange: " << loanPaymentParts.valueChange + << ", totalValue before: " << *totalValueOutstandingProxy + << ", totalValue after: " << newRoundedLoanState.valueOutstanding + << ", totalValue delta: " << (totalValueOutstandingProxy - newRoundedLoanState.valueOutstanding) + << ", principalDelta: " << overpaymentComponents.trackedPrincipalDelta + << ", principalPaid: " << loanPaymentParts.principalPaid << ", Computed difference: " + << overpaymentComponents.trackedPrincipalDelta - (totalValueOutstandingProxy - newRoundedLoanState.valueOutstanding); XRPL_ASSERT_PARTS( loanPaymentParts.valueChange == newRoundedLoanState.valueOutstanding - - (totalValueOutstandingProxy - - overpaymentComponents.trackedPrincipalDelta) + + (totalValueOutstandingProxy - overpaymentComponents.trackedPrincipalDelta) + overpaymentComponents.trackedInterestPart(), "xrpl::detail::doOverpayment", "interest paid agrees"); XRPL_ASSERT_PARTS( - overpaymentComponents.trackedPrincipalDelta == - loanPaymentParts.principalPaid, + overpaymentComponents.trackedPrincipalDelta == loanPaymentParts.principalPaid, "xrpl::detail::doOverpayment", "principal payment matches"); @@ -719,25 +656,18 @@ computeLatePayment( return Unexpected(tecTOO_SOON); // Calculate the penalty interest based on how long the payment is overdue. - auto const latePaymentInterest = loanLatePaymentInterest( - principalOutstanding, - lateInterestRate, - view.parentCloseTime(), - nextDueDate); + auto const latePaymentInterest = + loanLatePaymentInterest(principalOutstanding, lateInterestRate, view.parentCloseTime(), nextDueDate); // Round the late interest and split it between the vault (net interest) // and the broker (management fee portion). This lambda ensures we // round before splitting to maintain precision. auto const [roundedLateInterest, roundedLateManagementFee] = [&]() { - auto const interest = - roundToAsset(asset, latePaymentInterest, loanScale); - return computeInterestAndFeeParts( - asset, interest, managementFeeRate, loanScale); + auto const interest = roundToAsset(asset, latePaymentInterest, loanScale); + return computeInterestAndFeeParts(asset, interest, managementFeeRate, loanScale); }(); - XRPL_ASSERT( - roundedLateInterest >= 0, - "xrpl::detail::computeLatePayment : valid late interest"); + XRPL_ASSERT(roundedLateInterest >= 0, "xrpl::detail::computeLatePayment : valid late interest"); XRPL_ASSERT_PARTS( periodic.specialCase != PaymentSpecialCase::extra, "xrpl::detail::computeLatePayment", @@ -754,8 +684,7 @@ computeLatePayment( // 1. Regular service fee (from periodic.untrackedManagementFee) // 2. Late payment fee (fixed penalty) // 3. Management fee portion of late interest - periodic.untrackedManagementFee + latePaymentFee + - roundedLateManagementFee, + periodic.untrackedManagementFee + latePaymentFee + roundedLateManagementFee, // Untracked interest includes: // 1. Any untracked interest from the regular payment (usually 0) @@ -765,17 +694,14 @@ computeLatePayment( periodic.untrackedInterest + roundedLateInterest}; XRPL_ASSERT_PARTS( - isRounded(asset, late.totalDue, loanScale), - "xrpl::detail::computeLatePayment", - "total due is rounded"); + isRounded(asset, late.totalDue, loanScale), "xrpl::detail::computeLatePayment", "total due is rounded"); // Check that the borrower provided enough funds to cover the late payment. // The late payment is more expensive than a regular payment due to the // penalties. if (amount < late.totalDue) { - JLOG(j.warn()) << "Late loan payment amount is insufficient. Due: " - << late.totalDue << ", paid: " << amount; + JLOG(j.warn()) << "Late loan payment amount is insufficient. Due: " << late.totalDue << ", paid: " << amount; return Unexpected(tecINSUFFICIENT_PAYMENT); } @@ -833,8 +759,7 @@ computeFullPayment( // This theoretical (unrounded) value is used to compute interest and // penalties accurately. Number const theoreticalPrincipalOutstanding = - loanPrincipalFromPeriodicPayment( - periodicPayment, periodicRate, paymentRemaining); + loanPrincipalFromPeriodicPayment(periodicPayment, periodicRate, paymentRemaining); // Full payment interest includes both accrued interest (time since last // payment) and prepayment penalty (for closing early). @@ -850,10 +775,8 @@ computeFullPayment( // Split the full payment interest into net interest (to vault) and // management fee (to broker), applying proper rounding. auto const [roundedFullInterest, roundedFullManagementFee] = [&]() { - auto const interest = roundToAsset( - asset, fullPaymentInterest, loanScale, Number::downward); - return computeInterestAndFeeParts( - asset, interest, managementFeeRate, loanScale); + auto const interest = roundToAsset(asset, fullPaymentInterest, loanScale, Number::downward); + return computeInterestAndFeeParts(asset, interest, managementFeeRate, loanScale); }(); ExtendedPaymentComponents const full{ @@ -861,8 +784,7 @@ computeFullPayment( // Pay off all tracked outstanding balances: principal, interest, // and fees. // This marks the loan as complete (final payment). - .trackedValueDelta = principalOutstanding + - totalInterestOutstanding + managementFeeOutstanding, + .trackedValueDelta = principalOutstanding + totalInterestOutstanding + managementFeeOutstanding, .trackedPrincipalDelta = principalOutstanding, // All outstanding management fees are paid. This zeroes out the @@ -891,19 +813,14 @@ computeFullPayment( }; XRPL_ASSERT_PARTS( - isRounded(asset, full.totalDue, loanScale), - "xrpl::detail::computeFullPayment", - "total due is rounded"); + isRounded(asset, full.totalDue, loanScale), "xrpl::detail::computeFullPayment", "total due is rounded"); - JLOG(j.trace()) << "computeFullPayment result: periodicPayment: " - << periodicPayment << ", periodicRate: " << periodicRate - << ", paymentRemaining: " << paymentRemaining - << ", theoreticalPrincipalOutstanding: " - << theoreticalPrincipalOutstanding + JLOG(j.trace()) << "computeFullPayment result: periodicPayment: " << periodicPayment + << ", periodicRate: " << periodicRate << ", paymentRemaining: " << paymentRemaining + << ", theoreticalPrincipalOutstanding: " << theoreticalPrincipalOutstanding << ", fullPaymentInterest: " << fullPaymentInterest << ", roundedFullInterest: " << roundedFullInterest - << ", roundedFullManagementFee: " - << roundedFullManagementFee + << ", roundedFullManagementFee: " << roundedFullManagementFee << ", untrackedInterest: " << full.untrackedInterest; if (amount < full.totalDue) @@ -917,8 +834,7 @@ computeFullPayment( Number PaymentComponents::trackedInterestPart() const { - return trackedValueDelta - - (trackedPrincipalDelta + trackedManagementFeeDelta); + return trackedValueDelta - (trackedPrincipalDelta + trackedManagementFeeDelta); } /* Computes the breakdown of a regular periodic payment into principal, @@ -952,23 +868,17 @@ computePaymentComponents( TenthBips16 managementFeeRate) { XRPL_ASSERT_PARTS( - isRounded(asset, totalValueOutstanding, scale) && - isRounded(asset, principalOutstanding, scale) && + isRounded(asset, totalValueOutstanding, scale) && isRounded(asset, principalOutstanding, scale) && isRounded(asset, managementFeeOutstanding, scale), "xrpl::detail::computePaymentComponents", "Outstanding values are rounded"); - XRPL_ASSERT_PARTS( - paymentRemaining > 0, - "xrpl::detail::computePaymentComponents", - "some payments remaining"); + XRPL_ASSERT_PARTS(paymentRemaining > 0, "xrpl::detail::computePaymentComponents", "some payments remaining"); - auto const roundedPeriodicPayment = - roundPeriodicPayment(asset, periodicPayment, scale); + auto const roundedPeriodicPayment = roundPeriodicPayment(asset, periodicPayment, scale); // Final payment: pay off everything remaining, ignoring the normal // periodic payment amount. This ensures the loan completes cleanly. - if (paymentRemaining == 1 || - totalValueOutstanding <= roundedPeriodicPayment) + if (paymentRemaining == 1 || totalValueOutstanding <= roundedPeriodicPayment) { // If there's only one payment left, we need to pay off each of the loan // parts. @@ -981,23 +891,20 @@ computePaymentComponents( // Calculate what the loan state SHOULD be after this payment (the target). // This is computed at full precision using the theoretical amortization. - LoanState const trueTarget = computeTheoreticalLoanState( - periodicPayment, periodicRate, paymentRemaining - 1, managementFeeRate); + LoanState const trueTarget = + computeTheoreticalLoanState(periodicPayment, periodicRate, paymentRemaining - 1, managementFeeRate); // Round the target to the loan's scale to match how actual loan values // are stored. LoanState const roundedTarget = LoanState{ - .valueOutstanding = - roundToAsset(asset, trueTarget.valueOutstanding, scale), - .principalOutstanding = - roundToAsset(asset, trueTarget.principalOutstanding, scale), + .valueOutstanding = roundToAsset(asset, trueTarget.valueOutstanding, scale), + .principalOutstanding = roundToAsset(asset, trueTarget.principalOutstanding, scale), .interestDue = roundToAsset(asset, trueTarget.interestDue, scale), - .managementFeeDue = - roundToAsset(asset, trueTarget.managementFeeDue, scale)}; + .managementFeeDue = roundToAsset(asset, trueTarget.managementFeeDue, scale)}; // Get the current actual loan state from the ledger values - LoanState const currentLedgerState = constructLoanState( - totalValueOutstanding, principalOutstanding, managementFeeOutstanding); + LoanState const currentLedgerState = + constructLoanState(totalValueOutstanding, principalOutstanding, managementFeeOutstanding); // The difference between current and target states gives us the payment // components. Any discrepancies from accumulated rounding are captured @@ -1014,8 +921,7 @@ computePaymentComponents( "principal delta not greater than outstanding"); // Cap each component to never exceed what's actually outstanding - deltas.principal = - std::min(deltas.principal, currentLedgerState.principalOutstanding); + deltas.principal = std::min(deltas.principal, currentLedgerState.principalOutstanding); XRPL_ASSERT_PARTS( deltas.interest <= currentLedgerState.interestDue, @@ -1052,10 +958,7 @@ computePaymentComponents( component -= part; excess -= part; } - XRPL_ASSERT_PARTS( - excess >= beast::zero, - "xrpl::detail::computePaymentComponents", - "excess non-negative"); + XRPL_ASSERT_PARTS(excess >= beast::zero, "xrpl::detail::computePaymentComponents", "excess non-negative"); }; // Helper to reduce deltas when they collectively exceed a limit. // Order matters: we prefer to reduce interest first (most flexible), @@ -1069,8 +972,7 @@ computePaymentComponents( // Check if deltas exceed the total outstanding value. This should never // happen due to earlier caps, but handle it defensively. - Number totalOverpayment = - deltas.total() - currentLedgerState.valueOutstanding; + Number totalOverpayment = deltas.total() - currentLedgerState.valueOutstanding; if (totalOverpayment > beast::zero) { @@ -1086,9 +988,7 @@ computePaymentComponents( Number shortage = roundedPeriodicPayment - deltas.total(); XRPL_ASSERT_PARTS( - isRounded(asset, shortage, scale), - "xrpl::detail::computePaymentComponents", - "shortage is rounded"); + isRounded(asset, shortage, scale), "xrpl::detail::computePaymentComponents", "shortage is rounded"); if (shortage < beast::zero) { @@ -1101,31 +1001,24 @@ computePaymentComponents( // At this point, shortage >= 0 means we're paying less than the full // periodic payment (due to rounding or component caps). // shortage < 0 would mean we're trying to pay more than allowed (bug). - XRPL_ASSERT_PARTS( - shortage >= beast::zero, - "xrpl::detail::computePaymentComponents", - "no shortage or excess"); + XRPL_ASSERT_PARTS(shortage >= beast::zero, "xrpl::detail::computePaymentComponents", "no shortage or excess"); // Final validation that all components are valid XRPL_ASSERT_PARTS( - deltas.total() == - deltas.principal + deltas.interest + deltas.managementFee, + deltas.total() == deltas.principal + deltas.interest + deltas.managementFee, "xrpl::detail::computePaymentComponents", "total value adds up"); XRPL_ASSERT_PARTS( - deltas.principal >= beast::zero && - deltas.principal <= currentLedgerState.principalOutstanding, + deltas.principal >= beast::zero && deltas.principal <= currentLedgerState.principalOutstanding, "xrpl::detail::computePaymentComponents", "valid principal result"); XRPL_ASSERT_PARTS( - deltas.interest >= beast::zero && - deltas.interest <= currentLedgerState.interestDue, + deltas.interest >= beast::zero && deltas.interest <= currentLedgerState.interestDue, "xrpl::detail::computePaymentComponents", "valid interest result"); XRPL_ASSERT_PARTS( - deltas.managementFee >= beast::zero && - deltas.managementFee <= currentLedgerState.managementFeeDue, + deltas.managementFee >= beast::zero && deltas.managementFee <= currentLedgerState.managementFeeDue, "xrpl::detail::computePaymentComponents", "valid fee result"); @@ -1136,12 +1029,9 @@ computePaymentComponents( // Final safety clamp to ensure no value exceeds its outstanding balance return PaymentComponents{ - .trackedValueDelta = std::clamp( - deltas.total(), numZero, currentLedgerState.valueOutstanding), - .trackedPrincipalDelta = std::clamp( - deltas.principal, numZero, currentLedgerState.principalOutstanding), - .trackedManagementFeeDelta = std::clamp( - deltas.managementFee, numZero, currentLedgerState.managementFeeDue), + .trackedValueDelta = std::clamp(deltas.total(), numZero, currentLedgerState.valueOutstanding), + .trackedPrincipalDelta = std::clamp(deltas.principal, numZero, currentLedgerState.principalOutstanding), + .trackedManagementFeeDelta = std::clamp(deltas.managementFee, numZero, currentLedgerState.managementFeeDue), }; } @@ -1180,22 +1070,16 @@ computeOverpaymentComponents( // First, deduct the fixed overpayment fee from the total amount. // This reduces the effective payment that will be applied to the loan. // Equation (22) from XLS-66 spec, Section A-2 Equation Glossary - Number const overpaymentFee = roundToAsset( - asset, tenthBipsOfValue(overpayment, overpaymentFeeRate), loanScale); + Number const overpaymentFee = roundToAsset(asset, tenthBipsOfValue(overpayment, overpaymentFeeRate), loanScale); // Calculate the penalty interest on the effective payment amount. // This interest doesn't follow the normal amortization schedule - it's // a one-time charge for paying early. // Equation (20) and (21) from XLS-66 spec, Section A-2 Equation Glossary - auto const [roundedOverpaymentInterest, roundedOverpaymentManagementFee] = - [&]() { - auto const interest = roundToAsset( - asset, - tenthBipsOfValue(overpayment, overpaymentInterestRate), - loanScale); - return detail::computeInterestAndFeeParts( - asset, interest, managementFeeRate, loanScale); - }(); + auto const [roundedOverpaymentInterest, roundedOverpaymentManagementFee] = [&]() { + auto const interest = roundToAsset(asset, tenthBipsOfValue(overpayment, overpaymentInterestRate), loanScale); + return detail::computeInterestAndFeeParts(asset, interest, managementFeeRate, loanScale); + }(); auto const result = detail::ExtendedPaymentComponents{ // Build the payment components, after fees and penalty @@ -1203,8 +1087,8 @@ computeOverpaymentComponents( // reduction. detail::PaymentComponents{ .trackedValueDelta = overpayment - overpaymentFee, - .trackedPrincipalDelta = overpayment - roundedOverpaymentInterest - - roundedOverpaymentManagementFee - overpaymentFee, + .trackedPrincipalDelta = + overpayment - roundedOverpaymentInterest - roundedOverpaymentManagementFee - overpaymentFee, .trackedManagementFeeDelta = roundedOverpaymentManagementFee, .specialCase = detail::PaymentSpecialCase::extra}, // Untracked management fee is the fixed overpayment fee @@ -1271,8 +1155,7 @@ checkLoanGuards( LoanProperties const& properties, beast::Journal j) { - auto const totalInterestOutstanding = - properties.loanState.valueOutstanding - principalRequested; + auto const totalInterestOutstanding = properties.loanState.valueOutstanding - principalRequested; // Guard 1: if there is no computed total interest over the life of the // loan for a non-zero interest rate, we cannot properly amortize the // loan @@ -1280,8 +1163,7 @@ checkLoanGuards( { // Unless this is a zero-interest loan, there must be some interest // due on the loan, even if it's (measurable) dust - JLOG(j.warn()) << "Loan for " << principalRequested - << " with interest has no interest due"; + JLOG(j.warn()) << "Loan for " << principalRequested << " with interest has no interest due"; return tecPRECISION_LOSS; } // Guard 1a: If there is any interest computed over the life of the @@ -1289,8 +1171,7 @@ checkLoanGuards( if (!expectInterest && totalInterestOutstanding > 0) { // LCOV_EXCL_START - JLOG(j.warn()) << "Loan for " << principalRequested - << " with no interest has interest due"; + JLOG(j.warn()) << "Loan for " << principalRequested << " with no interest has interest due"; return tecINTERNAL; // LCOV_EXCL_STOP } @@ -1311,12 +1192,10 @@ checkLoanGuards( // Guard 3: If the periodic payment is so small that it can't even be // rounded to a representable value, then the loan can't be paid. Also, // avoids dividing by 0. - auto const roundedPayment = roundPeriodicPayment( - vaultAsset, properties.periodicPayment, properties.loanScale); + auto const roundedPayment = roundPeriodicPayment(vaultAsset, properties.periodicPayment, properties.loanScale); if (roundedPayment == beast::zero) { - JLOG(j.warn()) << "Loan Periodic payment (" - << properties.periodicPayment << ") rounds to 0. "; + JLOG(j.warn()) << "Loan Periodic payment (" << properties.periodicPayment << ") rounds to 0. "; return tecPRECISION_LOSS; } @@ -1326,14 +1205,11 @@ checkLoanGuards( { NumberRoundModeGuard mg(Number::upward); - if (std::int64_t const computedPayments{ - properties.loanState.valueOutstanding / roundedPayment}; + if (std::int64_t const computedPayments{properties.loanState.valueOutstanding / roundedPayment}; computedPayments != paymentTotal) { - JLOG(j.warn()) << "Loan Periodic payment (" - << properties.periodicPayment << ") rounding (" - << roundedPayment << ") on a total value of " - << properties.loanState.valueOutstanding + JLOG(j.warn()) << "Loan Periodic payment (" << properties.periodicPayment << ") rounding (" + << roundedPayment << ") on a total value of " << properties.loanState.valueOutstanding << " can not complete the loan in the specified " "number of payments (" << computedPayments << " != " << paymentTotal << ")"; @@ -1360,12 +1236,7 @@ computeFullPaymentInterest( TenthBips32 closeInterestRate) { auto const accruedInterest = detail::loanAccruedInterest( - theoreticalPrincipalOutstanding, - periodicRate, - parentCloseTime, - startDate, - prevPaymentDate, - paymentInterval); + theoreticalPrincipalOutstanding, periodicRate, parentCloseTime, startDate, prevPaymentDate, paymentInterval); XRPL_ASSERT( accruedInterest >= 0, "xrpl::detail::computeFullPaymentInterest : valid accrued " @@ -1416,31 +1287,23 @@ computeTheoreticalLoanState( { if (paymentRemaining == 0) { - return LoanState{ - .valueOutstanding = 0, - .principalOutstanding = 0, - .interestDue = 0, - .managementFeeDue = 0}; + return LoanState{.valueOutstanding = 0, .principalOutstanding = 0, .interestDue = 0, .managementFeeDue = 0}; } // Equation (30) from XLS-66 spec, Section A-2 Equation Glossary Number const totalValueOutstanding = periodicPayment * paymentRemaining; Number const principalOutstanding = - detail::loanPrincipalFromPeriodicPayment( - periodicPayment, periodicRate, paymentRemaining); + detail::loanPrincipalFromPeriodicPayment(periodicPayment, periodicRate, paymentRemaining); // Equation (31) from XLS-66 spec, Section A-2 Equation Glossary - Number const interestOutstandingGross = - totalValueOutstanding - principalOutstanding; + Number const interestOutstandingGross = totalValueOutstanding - principalOutstanding; // Equation (32) from XLS-66 spec, Section A-2 Equation Glossary - Number const managementFeeOutstanding = - tenthBipsOfValue(interestOutstandingGross, managementFeeRate); + Number const managementFeeOutstanding = tenthBipsOfValue(interestOutstandingGross, managementFeeRate); // Equation (33) from XLS-66 spec, Section A-2 Equation Glossary - Number const interestOutstandingNet = - interestOutstandingGross - managementFeeOutstanding; + Number const interestOutstandingNet = interestOutstandingGross - managementFeeOutstanding; return LoanState{ .valueOutstanding = totalValueOutstanding, @@ -1481,8 +1344,7 @@ constructLoanState( return LoanState{ .valueOutstanding = totalValueOutstanding, .principalOutstanding = principalOutstanding, - .interestDue = totalValueOutstanding - principalOutstanding - - managementFeeOutstanding, + .interestDue = totalValueOutstanding - principalOutstanding - managementFeeOutstanding, .managementFeeDue = managementFeeOutstanding}; } @@ -1490,9 +1352,7 @@ LoanState constructRoundedLoanState(SLE::const_ref loan) { return constructLoanState( - loan->at(sfTotalValueOutstanding), - loan->at(sfPrincipalOutstanding), - loan->at(sfManagementFeeOutstanding)); + loan->at(sfTotalValueOutstanding), loan->at(sfPrincipalOutstanding), loan->at(sfManagementFeeOutstanding)); } /* @@ -1502,17 +1362,9 @@ constructRoundedLoanState(SLE::const_ref loan) * Equation (32) from XLS-66 spec, Section A-2 Equation Glossary */ Number -computeManagementFee( - Asset const& asset, - Number const& value, - TenthBips32 managementFeeRate, - std::int32_t scale) +computeManagementFee(Asset const& asset, Number const& value, TenthBips32 managementFeeRate, std::int32_t scale) { - return roundToAsset( - asset, - tenthBipsOfValue(value, managementFeeRate), - scale, - Number::downward); + return roundToAsset(asset, tenthBipsOfValue(value, managementFeeRate), scale, Number::downward); } /* @@ -1534,16 +1386,9 @@ computeLoanProperties( std::int32_t minimumScale) { auto const periodicRate = loanPeriodicRate(interestRate, paymentInterval); - XRPL_ASSERT( - interestRate == 0 || periodicRate > 0, - "xrpl::computeLoanProperties : valid rate"); + XRPL_ASSERT(interestRate == 0 || periodicRate > 0, "xrpl::computeLoanProperties : valid rate"); return computeLoanProperties( - asset, - principalOutstanding, - periodicRate, - paymentsRemaining, - managementFeeRate, - minimumScale); + asset, principalOutstanding, periodicRate, paymentsRemaining, managementFeeRate, minimumScale); } /* @@ -1563,13 +1408,11 @@ computeLoanProperties( TenthBips32 managementFeeRate, std::int32_t minimumScale) { - auto const periodicPayment = detail::loanPeriodicPayment( - principalOutstanding, periodicRate, paymentsRemaining); + auto const periodicPayment = detail::loanPeriodicPayment(principalOutstanding, periodicRate, paymentsRemaining); auto const [totalValueOutstanding, loanScale] = [&]() { // only round up if there should be interest - NumberRoundModeGuard mg( - periodicRate == 0 ? Number::to_nearest : Number::upward); + NumberRoundModeGuard mg(periodicRate == 0 ? Number::to_nearest : Number::upward); // Use STAmount's internal rounding instead of roundToAsset, because // we're going to use this result to determine the scale for all the // other rounding. @@ -1583,8 +1426,7 @@ computeLoanProperties( auto const loanScale = std::max(minimumScale, amount.exponent()); XRPL_ASSERT_PARTS( (amount.integral() && loanScale == 0) || - (!amount.integral() && - loanScale >= static_cast(amount).exponent()), + (!amount.integral() && loanScale >= static_cast(amount).exponent()), "xrpl::computeLoanProperties", "loanScale value fits expectations"); @@ -1598,14 +1440,11 @@ computeLoanProperties( // Since we just figured out the loan scale, we haven't been able to // validate that the principal fits in it, so to allow this function to // succeed, round it here, and let the caller do the validation. - auto const roundedPrincipalOutstanding = roundToAsset( - asset, principalOutstanding, loanScale, Number::to_nearest); + auto const roundedPrincipalOutstanding = roundToAsset(asset, principalOutstanding, loanScale, Number::to_nearest); // Equation (31) from XLS-66 spec, Section A-2 Equation Glossary - auto const totalInterestOutstanding = - totalValueOutstanding - roundedPrincipalOutstanding; - auto const feeOwedToBroker = computeManagementFee( - asset, totalInterestOutstanding, managementFeeRate, loanScale); + auto const totalInterestOutstanding = totalValueOutstanding - roundedPrincipalOutstanding; + auto const feeOwedToBroker = computeManagementFee(asset, totalInterestOutstanding, managementFeeRate, loanScale); // Compute the principal part of the first payment. This is needed // because the principal part may be rounded down to zero, which @@ -1613,30 +1452,20 @@ computeLoanProperties( auto const firstPaymentPrincipal = [&]() { // Compute the parts for the first payment. Ensure that the // principal payment will actually change the principal. - auto const startingState = computeTheoreticalLoanState( - periodicPayment, - periodicRate, - paymentsRemaining, - managementFeeRate); + auto const startingState = + computeTheoreticalLoanState(periodicPayment, periodicRate, paymentsRemaining, managementFeeRate); - auto const firstPaymentState = computeTheoreticalLoanState( - periodicPayment, - periodicRate, - paymentsRemaining - 1, - managementFeeRate); + auto const firstPaymentState = + computeTheoreticalLoanState(periodicPayment, periodicRate, paymentsRemaining - 1, managementFeeRate); // The unrounded principal part needs to be large enough to affect // the principal. What to do if not is left to the caller - return startingState.principalOutstanding - - firstPaymentState.principalOutstanding; + return startingState.principalOutstanding - firstPaymentState.principalOutstanding; }(); return LoanProperties{ .periodicPayment = periodicPayment, - .loanState = constructLoanState( - totalValueOutstanding, - roundedPrincipalOutstanding, - feeOwedToBroker), + .loanState = constructLoanState(totalValueOutstanding, roundedPrincipalOutstanding, feeOwedToBroker), .loanScale = loanScale, .firstPaymentPrincipal = firstPaymentPrincipal, }; @@ -1700,29 +1529,23 @@ loanMakePayment( // Compute the periodic rate that will be used for calculations // throughout Number const periodicRate = loanPeriodicRate(interestRate, paymentInterval); - XRPL_ASSERT( - interestRate == 0 || periodicRate > 0, - "xrpl::loanMakePayment : valid rate"); + XRPL_ASSERT(interestRate == 0 || periodicRate > 0, "xrpl::loanMakePayment : valid rate"); - XRPL_ASSERT( - *totalValueOutstandingProxy > 0, - "xrpl::loanMakePayment : valid total value"); + XRPL_ASSERT(*totalValueOutstandingProxy > 0, "xrpl::loanMakePayment : valid total value"); view.update(loan); // ------------------------------------------------------------- // A late payment not flagged as late overrides all other options. - if (paymentType != LoanPaymentType::late && - hasExpired(view, nextDueDateProxy)) + if (paymentType != LoanPaymentType::late && hasExpired(view, nextDueDateProxy)) { // If the payment is late, and the late flag was not set, it's not // valid JLOG(j.warn()) << "Loan payment is overdue. Use the tfLoanLatePayment " "transaction " "flag to make a late payment. Loan was created on " - << startDate << ", prev payment due date is " - << prevPaymentDateProxy << ", next payment due date is " - << nextDueDateProxy << ", ledger time is " + << startDate << ", prev payment due date is " << prevPaymentDateProxy + << ", next payment due date is " << nextDueDateProxy << ", ledger time is " << view.parentCloseTime().time_since_epoch().count(); return Unexpected(tecEXPIRED); } @@ -1732,13 +1555,10 @@ loanMakePayment( if (paymentType == LoanPaymentType::full) { TenthBips32 const closeInterestRate{loan->at(sfCloseInterestRate)}; - Number const closePaymentFee = - roundToAsset(asset, loan->at(sfClosePaymentFee), loanScale); + Number const closePaymentFee = roundToAsset(asset, loan->at(sfClosePaymentFee), loanScale); - LoanState const roundedLoanState = constructLoanState( - totalValueOutstandingProxy, - principalOutstandingProxy, - managementFeeOutstandingProxy); + LoanState const roundedLoanState = + constructLoanState(totalValueOutstandingProxy, principalOutstandingProxy, managementFeeOutstandingProxy); if (auto const fullPaymentComponents = detail::computeFullPayment( asset, @@ -1797,10 +1617,7 @@ loanMakePayment( paymentRemainingProxy, managementFeeRate), serviceFee}; - XRPL_ASSERT_PARTS( - periodic.trackedPrincipalDelta >= 0, - "xrpl::loanMakePayment", - "regular payment valid principal"); + XRPL_ASSERT_PARTS(periodic.trackedPrincipalDelta >= 0, "xrpl::loanMakePayment", "regular payment valid principal"); // ------------------------------------------------------------- // late payment handling @@ -1850,8 +1667,7 @@ loanMakePayment( // regular periodic payment handling XRPL_ASSERT_PARTS( - paymentType == LoanPaymentType::regular || - paymentType == LoanPaymentType::overpayment, + paymentType == LoanPaymentType::regular || paymentType == LoanPaymentType::overpayment, "xrpl::loanMakePayment", "regular payment type"); @@ -1860,15 +1676,12 @@ loanMakePayment( Number totalPaid; std::size_t numPayments = 0; - while ((amount >= (totalPaid + periodic.totalDue)) && - paymentRemainingProxy > 0 && + while ((amount >= (totalPaid + periodic.totalDue)) && paymentRemainingProxy > 0 && numPayments < loanMaximumPaymentsPerTransaction) { // Try to make more payments XRPL_ASSERT_PARTS( - periodic.trackedPrincipalDelta >= 0, - "xrpl::loanMakePayment", - "payment pays non-negative principal"); + periodic.trackedPrincipalDelta >= 0, "xrpl::loanMakePayment", "payment pays non-negative principal"); totalPaid += periodic.totalDue; totalParts += detail::doPayment( @@ -1883,8 +1696,7 @@ loanMakePayment( ++numPayments; XRPL_ASSERT_PARTS( - (periodic.specialCase == detail::PaymentSpecialCase::final) == - (paymentRemainingProxy == 0), + (periodic.specialCase == detail::PaymentSpecialCase::final) == (paymentRemainingProxy == 0), "xrpl::loanMakePayment", "final payment is the final payment"); @@ -1908,46 +1720,32 @@ loanMakePayment( if (numPayments == 0) { - JLOG(j.warn()) << "Regular loan payment amount is insufficient. Due: " - << periodic.totalDue << ", paid: " << amount; + JLOG(j.warn()) << "Regular loan payment amount is insufficient. Due: " << periodic.totalDue + << ", paid: " << amount; return Unexpected(tecINSUFFICIENT_PAYMENT); } XRPL_ASSERT_PARTS( - totalParts.principalPaid + totalParts.interestPaid + - totalParts.feePaid == - totalPaid, + totalParts.principalPaid + totalParts.interestPaid + totalParts.feePaid == totalPaid, "xrpl::loanMakePayment", "payment parts add up"); - XRPL_ASSERT_PARTS( - totalParts.valueChange == 0, - "xrpl::loanMakePayment", - "no value change"); + XRPL_ASSERT_PARTS(totalParts.valueChange == 0, "xrpl::loanMakePayment", "no value change"); // ------------------------------------------------------------- // overpayment handling - if (paymentType == LoanPaymentType::overpayment && - loan->isFlag(lsfLoanOverpayment) && paymentRemainingProxy > 0 && + if (paymentType == LoanPaymentType::overpayment && loan->isFlag(lsfLoanOverpayment) && paymentRemainingProxy > 0 && totalPaid < amount && numPayments < loanMaximumPaymentsPerTransaction) { - TenthBips32 const overpaymentInterestRate{ - loan->at(sfOverpaymentInterestRate)}; + TenthBips32 const overpaymentInterestRate{loan->at(sfOverpaymentInterestRate)}; TenthBips32 const overpaymentFeeRate{loan->at(sfOverpaymentFee)}; // It shouldn't be possible for the overpayment to be greater than // totalValueOutstanding, because that would have been processed as // another normal payment. But cap it just in case. - Number const overpayment = - std::min(amount - totalPaid, *totalValueOutstandingProxy); + Number const overpayment = std::min(amount - totalPaid, *totalValueOutstandingProxy); - detail::ExtendedPaymentComponents const overpaymentComponents = - detail::computeOverpaymentComponents( - asset, - loanScale, - overpayment, - overpaymentInterestRate, - overpaymentFeeRate, - managementFeeRate); + detail::ExtendedPaymentComponents const overpaymentComponents = detail::computeOverpaymentComponents( + asset, loanScale, overpayment, overpaymentInterestRate, overpaymentFeeRate, managementFeeRate); // Don't process an overpayment if the whole amount (or more!) // gets eaten by fees and interest. @@ -1985,19 +1783,15 @@ loanMakePayment( // Check the final results are rounded, to double-check that the // intermediate steps were rounded. XRPL_ASSERT( - isRounded(asset, totalParts.principalPaid, loanScale) && - totalParts.principalPaid >= beast::zero, + isRounded(asset, totalParts.principalPaid, loanScale) && totalParts.principalPaid >= beast::zero, "xrpl::loanMakePayment : total principal paid is valid"); XRPL_ASSERT( - isRounded(asset, totalParts.interestPaid, loanScale) && - totalParts.interestPaid >= beast::zero, + isRounded(asset, totalParts.interestPaid, loanScale) && totalParts.interestPaid >= beast::zero, "xrpl::loanMakePayment : total interest paid is valid"); XRPL_ASSERT( - isRounded(asset, totalParts.valueChange, loanScale), - "xrpl::loanMakePayment : loan value change is valid"); + isRounded(asset, totalParts.valueChange, loanScale), "xrpl::loanMakePayment : loan value change is valid"); XRPL_ASSERT( - isRounded(asset, totalParts.feePaid, loanScale) && - totalParts.feePaid >= beast::zero, + isRounded(asset, totalParts.feePaid, loanScale) && totalParts.feePaid >= beast::zero, "xrpl::loanMakePayment : fee paid is valid"); return totalParts; } diff --git a/src/xrpld/app/misc/detail/LoadFeeTrack.cpp b/src/xrpld/app/misc/detail/LoadFeeTrack.cpp index 6166656aee..91a40c6a9d 100644 --- a/src/xrpld/app/misc/detail/LoadFeeTrack.cpp +++ b/src/xrpld/app/misc/detail/LoadFeeTrack.cpp @@ -32,8 +32,7 @@ LoadFeeTrack::raiseLocalFee() if (origFee == localTxnLoadFee_) return false; - JLOG(j_.debug()) << "Local load fee raised from " << origFee << " to " - << localTxnLoadFee_; + JLOG(j_.debug()) << "Local load fee raised from " << origFee << " to " << localTxnLoadFee_; return true; } @@ -53,8 +52,7 @@ LoadFeeTrack::lowerLocalFee() if (origFee == localTxnLoadFee_) return false; - JLOG(j_.debug()) << "Local load fee lowered from " << origFee << " to " - << localTxnLoadFee_; + JLOG(j_.debug()) << "Local load fee lowered from " << origFee << " to " << localTxnLoadFee_; return true; } @@ -62,11 +60,7 @@ LoadFeeTrack::lowerLocalFee() // Scale using load as well as base rate XRPAmount -scaleFeeLoad( - XRPAmount fee, - LoadFeeTrack const& feeTrack, - Fees const& fees, - bool bUnlimited) +scaleFeeLoad(XRPAmount fee, LoadFeeTrack const& feeTrack, Fees const& fees, bool bUnlimited) { if (fee == 0) return fee; @@ -83,8 +77,7 @@ scaleFeeLoad( // fee = fee * feeFactor / (lftNormalFee); // without overflow, and as accurately as possible - auto const result = mulDiv( - fee, feeFactor, safe_cast(feeTrack.getLoadBase())); + auto const result = mulDiv(fee, feeFactor, safe_cast(feeTrack.getLoadBase())); if (!result) Throw("scaleFeeLoad"); return *result; diff --git a/src/xrpld/app/misc/detail/Manifest.cpp b/src/xrpld/app/misc/detail/Manifest.cpp index 59a1325e32..dfcbdbb3ad 100644 --- a/src/xrpld/app/misc/detail/Manifest.cpp +++ b/src/xrpld/app/misc/detail/Manifest.cpp @@ -1,13 +1,12 @@ -#include -#include -#include - #include #include #include #include #include #include +#include +#include +#include #include @@ -130,45 +129,31 @@ deserializeManifest(Slice s, beast::Journal journal) return std::nullopt; } - std::string const serialized( - reinterpret_cast(s.data()), s.size()); + std::string const serialized(reinterpret_cast(s.data()), s.size()); // If the manifest is revoked, then the signingKey will be unseated return Manifest(serialized, masterKey, signingKey, seq, domain); } catch (std::exception const& ex) { - JLOG(journal.error()) - << "Exception in " << __func__ << ": " << ex.what(); + JLOG(journal.error()) << "Exception in " << __func__ << ": " << ex.what(); return std::nullopt; } } template Stream& -logMftAct( - Stream& s, - std::string const& action, - PublicKey const& pk, - std::uint32_t seq) +logMftAct(Stream& s, std::string const& action, PublicKey const& pk, std::uint32_t seq) { - s << "Manifest: " << action - << ";Pk: " << toBase58(TokenType::NodePublic, pk) << ";Seq: " << seq - << ";"; + s << "Manifest: " << action << ";Pk: " << toBase58(TokenType::NodePublic, pk) << ";Seq: " << seq << ";"; return s; } template Stream& -logMftAct( - Stream& s, - std::string const& action, - PublicKey const& pk, - std::uint32_t seq, - std::uint32_t oldSeq) +logMftAct(Stream& s, std::string const& action, PublicKey const& pk, std::uint32_t seq, std::uint32_t oldSeq) { - s << "Manifest: " << action - << ";Pk: " << toBase58(TokenType::NodePublic, pk) << ";Seq: " << seq + s << "Manifest: " << action << ";Pk: " << toBase58(TokenType::NodePublic, pk) << ";Seq: " << seq << ";OldSeq: " << oldSeq << ";"; return s; } @@ -247,11 +232,8 @@ loadValidatorToken(std::vector const& blob, beast::Journal journal) { std::string tokenStr; - tokenStr.reserve(std::accumulate( - blob.cbegin(), - blob.cend(), - std::size_t(0), - [](std::size_t init, std::string const& s) { + tokenStr.reserve( + std::accumulate(blob.cbegin(), blob.cend(), std::size_t(0), [](std::size_t init, std::string const& s) { return init + s.size(); })); @@ -281,8 +263,7 @@ loadValidatorToken(std::vector const& blob, beast::Journal journal) } catch (std::exception const& ex) { - JLOG(journal.error()) - << "Exception in " << __func__ << ": " << ex.what(); + JLOG(journal.error()) << "Exception in " << __func__ << ": " << ex.what(); return std::nullopt; } } @@ -304,8 +285,7 @@ ManifestCache::getMasterKey(PublicKey const& pk) const { std::shared_lock lock{mutex_}; - if (auto const iter = signingToMasterKeys_.find(pk); - iter != signingToMasterKeys_.end()) + if (auto const iter = signingToMasterKeys_.find(pk); iter != signingToMasterKeys_.end()) return iter->second; return pk; @@ -369,11 +349,8 @@ ManifestCache::applyManifest(Manifest m) // comment below), `checkSignature` only needs to be set to true on the // first run. auto prewriteCheck = - [this, &m](auto const& iter, bool checkSignature, auto const& lock) - -> std::optional { - XRPL_ASSERT( - lock.owns_lock(), - "xrpl::ManifestCache::applyManifest::prewriteCheck : locked"); + [this, &m](auto const& iter, bool checkSignature, auto const& lock) -> std::optional { + XRPL_ASSERT(lock.owns_lock(), "xrpl::ManifestCache::applyManifest::prewriteCheck : locked"); (void)lock; // not used. parameter is present to ensure the mutex is // locked when the lambda is called. if (iter != map_.end() && m.sequence <= iter->second.sequence) @@ -383,12 +360,7 @@ ManifestCache::applyManifest(Manifest m) // several cases including when we receive manifests from a peer who // doesn't have the latest data. if (auto stream = j_.debug()) - logMftAct( - stream, - "Stale", - m.masterKey, - m.sequence, - iter->second.sequence); + logMftAct(stream, "Stale", m.masterKey, m.sequence, iter->second.sequence); return ManifestDisposition::stale; } @@ -413,11 +385,9 @@ ManifestCache::applyManifest(Manifest m) // Sanity check: the master key of this manifest should not be used as // the ephemeral key of another manifest: - if (auto const x = signingToMasterKeys_.find(m.masterKey); - x != signingToMasterKeys_.end()) + if (auto const x = signingToMasterKeys_.find(m.masterKey); x != signingToMasterKeys_.end()) { - JLOG(j_.warn()) << to_string(m) - << ": Master key already used as ephemeral key for " + JLOG(j_.warn()) << to_string(m) << ": Master key already used as ephemeral key for " << toBase58(TokenType::NodePublic, x->second); return ManifestDisposition::badMasterKey; @@ -436,22 +406,17 @@ ManifestCache::applyManifest(Manifest m) // Sanity check: the ephemeral key of this manifest should not be // used as the master or ephemeral key of another manifest: - if (auto const x = signingToMasterKeys_.find(*m.signingKey); - x != signingToMasterKeys_.end()) + if (auto const x = signingToMasterKeys_.find(*m.signingKey); x != signingToMasterKeys_.end()) { - JLOG(j_.warn()) - << to_string(m) - << ": Ephemeral key already used as ephemeral key for " - << toBase58(TokenType::NodePublic, x->second); + JLOG(j_.warn()) << to_string(m) << ": Ephemeral key already used as ephemeral key for " + << toBase58(TokenType::NodePublic, x->second); return ManifestDisposition::badEphemeralKey; } if (auto const x = map_.find(*m.signingKey); x != map_.end()) { - JLOG(j_.warn()) - << to_string(m) << ": Ephemeral key used as master key for " - << to_string(x->second); + JLOG(j_.warn()) << to_string(m) << ": Ephemeral key used as master key for " << to_string(x->second); return ManifestDisposition::badEphemeralKey; } @@ -462,8 +427,7 @@ ManifestCache::applyManifest(Manifest m) { std::shared_lock sl{mutex_}; - if (auto d = - prewriteCheck(map_.find(m.masterKey), /*checkSig*/ true, sl)) + if (auto d = prewriteCheck(map_.find(m.masterKey), /*checkSig*/ true, sl)) return *d; } @@ -494,18 +458,17 @@ ManifestCache::applyManifest(Manifest m) auto masterKey = m.masterKey; map_.emplace(std::move(masterKey), std::move(m)); + + // Something has changed. Keep track of it. + seq_++; + return ManifestDisposition::accepted; } // An ephemeral key was revoked and superseded by a new key. This is // expected, but should happen infrequently. if (auto stream = j_.info()) - logMftAct( - stream, - "AcceptedUpdate", - m.masterKey, - m.sequence, - iter->second.sequence); + logMftAct(stream, "AcceptedUpdate", m.masterKey, m.sequence, iter->second.sequence); signingToMasterKeys_.erase(*iter->second.signingKey); @@ -564,17 +527,14 @@ ManifestCache::load( configRevocation.cbegin(), configRevocation.cend(), std::size_t(0), - [](std::size_t init, std::string const& s) { - return init + s.size(); - })); + [](std::size_t init, std::string const& s) { return init + s.size(); })); for (auto const& line : configRevocation) revocationStr += boost::algorithm::trim_copy(line); auto mo = deserializeManifest(base64_decode(revocationStr)); - if (!mo || !mo->revoked() || - applyManifest(std::move(*mo)) == ManifestDisposition::invalid) + if (!mo || !mo->revoked() || applyManifest(std::move(*mo)) == ManifestDisposition::invalid) { JLOG(j_.error()) << "Invalid validator key revocation in config"; return false; diff --git a/src/xrpld/app/misc/detail/Transaction.cpp b/src/xrpld/app/misc/detail/Transaction.cpp index 77a8897d9c..d45c49c3c4 100644 --- a/src/xrpld/app/misc/detail/Transaction.cpp +++ b/src/xrpld/app/misc/detail/Transaction.cpp @@ -1,21 +1,18 @@ #include #include -#include #include -#include #include #include #include +#include #include #include +#include namespace xrpl { -Transaction::Transaction( - std::shared_ptr const& stx, - std::string& reason, - Application& app) noexcept +Transaction::Transaction(std::shared_ptr const& stx, std::string& reason, Application& app) noexcept : mTransaction(stx), mApp(app), j_(app.journal("Ledger")) { try @@ -83,8 +80,7 @@ Transaction::transactionFromSQL( Blob const& rawTxn, Application& app) { - std::uint32_t const inLedger = - rangeCheckedCast(ledgerSeq.value_or(0)); + std::uint32_t const inLedger = rangeCheckedCast(ledgerSeq.value_or(0)); SerialIter it(makeSlice(rawTxn)); auto txn = std::make_shared(it); @@ -96,45 +92,30 @@ Transaction::transactionFromSQL( return tr; } -std::variant< - std::pair, std::shared_ptr>, - TxSearched> +std::variant, std::shared_ptr>, TxSearched> Transaction::load(uint256 const& id, Application& app, error_code_i& ec) { return load(id, app, std::nullopt, ec); } -std::variant< - std::pair, std::shared_ptr>, - TxSearched> -Transaction::load( - uint256 const& id, - Application& app, - ClosedInterval const& range, - error_code_i& ec) +std::variant, std::shared_ptr>, TxSearched> +Transaction::load(uint256 const& id, Application& app, ClosedInterval const& range, error_code_i& ec) { using op = std::optional>; return load(id, app, op{range}, ec); } -std::variant< - std::pair, std::shared_ptr>, - TxSearched> +std::variant, std::shared_ptr>, TxSearched> Transaction::load( uint256 const& id, Application& app, std::optional> const& range, error_code_i& ec) { - auto const db = dynamic_cast(&app.getRelationalDatabase()); + auto& db = app.getRelationalDatabase(); - if (!db) - { - Throw("Failed to get relational database"); - } - - return db->getTransaction(id, range, ec); + return db.getTransaction(id, range, ec); } // options 1 to include the date of the transaction @@ -142,8 +123,7 @@ Json::Value Transaction::getJson(JsonOptions options, bool binary) const { // Note, we explicitly suppress `include_date` option here - Json::Value ret( - mTransaction->getJson(options & ~JsonOptions::include_date, binary)); + Json::Value ret(mTransaction->getJson(options & ~JsonOptions::include_date, binary)); // NOTE Binary STTx::getJson output might not be a JSON object if (ret.isObject() && mLedgerIndex) @@ -173,8 +153,7 @@ Transaction::getJson(JsonOptions options, bool binary) const if (mTxnSeq && netID) { - std::optional const ctid = - RPC::encodeCTID(mLedgerIndex, *mTxnSeq, *netID); + std::optional const ctid = RPC::encodeCTID(mLedgerIndex, *mTxnSeq, *netID); if (ctid) ret[jss::ctid] = *ctid; } diff --git a/src/xrpld/app/misc/detail/TxQ.cpp b/src/xrpld/app/misc/detail/TxQ.cpp index 01abcc9c7d..61741b73f0 100644 --- a/src/xrpld/app/misc/detail/TxQ.cpp +++ b/src/xrpld/app/misc/detail/TxQ.cpp @@ -55,38 +55,27 @@ getLastLedgerSequence(STTx const& tx) static FeeLevel64 increase(FeeLevel64 level, std::uint32_t increasePercent) { - return mulDiv(level, 100 + increasePercent, 100) - .value_or(static_cast(xrpl::muldiv_max)); + return mulDiv(level, 100 + increasePercent, 100).value_or(static_cast(xrpl::muldiv_max)); } ////////////////////////////////////////////////////////////////////////// std::size_t -TxQ::FeeMetrics::update( - Application& app, - ReadView const& view, - bool timeLeap, - TxQ::Setup const& setup) +TxQ::FeeMetrics::update(Application& app, ReadView const& view, bool timeLeap, TxQ::Setup const& setup) { std::vector feeLevels; auto const txBegin = view.txs.begin(); auto const txEnd = view.txs.end(); auto const size = std::distance(txBegin, txEnd); feeLevels.reserve(size); - std::for_each(txBegin, txEnd, [&](auto const& tx) { - feeLevels.push_back(getFeeLevelPaid(view, *tx.first)); - }); + std::for_each(txBegin, txEnd, [&](auto const& tx) { feeLevels.push_back(getFeeLevelPaid(view, *tx.first)); }); std::sort(feeLevels.begin(), feeLevels.end()); - XRPL_ASSERT( - size == feeLevels.size(), - "xrpl::TxQ::FeeMetrics::update : fee levels size"); + XRPL_ASSERT(size == feeLevels.size(), "xrpl::TxQ::FeeMetrics::update : fee levels size"); JLOG((timeLeap ? j_.warn() : j_.debug())) - << "Ledger " << view.header().seq << " has " << size - << " transactions. " - << "Ledgers are processing " << (timeLeap ? "slowly" : "as expected") - << ". Expected transactions is currently " << txnsExpected_ - << " and multiplier is " << escalationMultiplier_; + << "Ledger " << view.header().seq << " has " << size << " transactions. " + << "Ledgers are processing " << (timeLeap ? "slowly" : "as expected") << ". Expected transactions is currently " + << txnsExpected_ << " and multiplier is " << escalationMultiplier_; if (timeLeap) { @@ -95,22 +84,17 @@ TxQ::FeeMetrics::update( auto const cutPct = 100 - setup.slowConsensusDecreasePercent; // upperLimit must be >= minimumTxnCount_ or std::clamp can give // unexpected results - auto const upperLimit = std::max( - mulDiv(txnsExpected_, cutPct, 100).value_or(xrpl::muldiv_max), - minimumTxnCount_); + auto const upperLimit = + std::max(mulDiv(txnsExpected_, cutPct, 100).value_or(xrpl::muldiv_max), minimumTxnCount_); txnsExpected_ = std::clamp( - mulDiv(size, cutPct, 100).value_or(xrpl::muldiv_max), - minimumTxnCount_, - upperLimit); + mulDiv(size, cutPct, 100).value_or(xrpl::muldiv_max), minimumTxnCount_, upperLimit); recentTxnCounts_.clear(); } else if (size > txnsExpected_ || size > targetTxnCount_) { recentTxnCounts_.push_back( - mulDiv(size, 100 + setup.normalConsensusIncreasePercent, 100) - .value_or(xrpl::muldiv_max)); - auto const iter = - std::max_element(recentTxnCounts_.begin(), recentTxnCounts_.end()); + mulDiv(size, 100 + setup.normalConsensusIncreasePercent, 100).value_or(xrpl::muldiv_max)); + auto const iter = std::max_element(recentTxnCounts_.begin(), recentTxnCounts_.end()); BOOST_ASSERT(iter != recentTxnCounts_.end()); auto const next = [&] { // Grow quickly: If the max_element is >= the @@ -139,14 +123,11 @@ TxQ::FeeMetrics::update( // evaluates to the middle element; for an even // number of elements, it will add the two elements // on either side of the "middle" and average them. - escalationMultiplier_ = - (feeLevels[size / 2] + feeLevels[(size - 1) / 2] + FeeLevel64{1}) / - 2; - escalationMultiplier_ = - std::max(escalationMultiplier_, setup.minimumEscalationMultiplier); + escalationMultiplier_ = (feeLevels[size / 2] + feeLevels[(size - 1) / 2] + FeeLevel64{1}) / 2; + escalationMultiplier_ = std::max(escalationMultiplier_, setup.minimumEscalationMultiplier); } - JLOG(j_.debug()) << "Expected transactions updated to " << txnsExpected_ - << " and multiplier updated to " << escalationMultiplier_; + JLOG(j_.debug()) << "Expected transactions updated to " << txnsExpected_ << " and multiplier updated to " + << escalationMultiplier_; return size; } @@ -205,10 +186,7 @@ static_assert(sumOfFirstSquares(0x1FFFFF).first == true, ""); static_assert(sumOfFirstSquares(0x1FFFFF).second == 0x2AAAA8AAAAB00000ul, ""); static_assert(sumOfFirstSquares(0x200000).first == false, ""); -static_assert( - sumOfFirstSquares(0x200000).second == - std::numeric_limits::max(), - ""); +static_assert(sumOfFirstSquares(0x200000).second == std::numeric_limits::max(), ""); } // namespace detail @@ -250,8 +228,7 @@ TxQ::FeeMetrics::escalatedSeriesFeeLevel( // are nearly nil. if (!sumNlast.first) return {sumNlast.first, FeeLevel64{sumNlast.second}}; - auto const totalFeeLevel = mulDiv( - multiplier, sumNlast.second - sumNcurrent.second, target * target); + auto const totalFeeLevel = mulDiv(multiplier, sumNlast.second - sumNcurrent.second, target * target); return {totalFeeLevel.has_value(), *totalFeeLevel}; } @@ -280,18 +257,15 @@ ApplyResult TxQ::MaybeTx::apply(Application& app, OpenView& view, beast::Journal j) { // If the rules or flags change, preflight again - XRPL_ASSERT( - pfResult, "xrpl::TxQ::MaybeTx::apply : preflight result is set"); + XRPL_ASSERT(pfResult, "xrpl::TxQ::MaybeTx::apply : preflight result is set"); NumberSO stNumberSO{view.rules().enabled(fixUniversalNumber)}; if (pfResult->rules != view.rules() || pfResult->flags != flags) { - JLOG(j.debug()) << "Queued transaction " << txID - << " rules or flags have changed. Flags from " + JLOG(j.debug()) << "Queued transaction " << txID << " rules or flags have changed. Flags from " << pfResult->flags << " to " << flags; - pfResult.emplace( - preflight(app, view.rules(), pfResult->tx, flags, pfResult->j)); + pfResult.emplace(preflight(app, view.rules(), pfResult->tx, flags, pfResult->j)); } auto pcresult = preclaim(*pfResult, app, view); @@ -299,8 +273,7 @@ TxQ::MaybeTx::apply(Application& app, OpenView& view, beast::Journal j) return doApply(pcresult, app, view); } -TxQ::TxQAccount::TxQAccount(std::shared_ptr const& txn) - : TxQAccount(txn->getAccountID(sfAccount)) +TxQ::TxQAccount::TxQAccount(std::shared_ptr const& txn) : TxQAccount(txn->getAccountID(sfAccount)) { } @@ -325,11 +298,8 @@ TxQ::TxQAccount::add(MaybeTx&& txn) auto const seqProx = txn.seqProxy; auto result = transactions.emplace(seqProx, std::move(txn)); - XRPL_ASSERT( - result.second, "xrpl::TxQ::TxQAccount::add : emplace succeeded"); - XRPL_ASSERT( - &result.first->second != &txn, - "xrpl::TxQ::TxQAccount::add : transaction moved"); + XRPL_ASSERT(result.second, "xrpl::TxQ::TxQAccount::add : emplace succeeded"); + XRPL_ASSERT(&result.first->second != &txn, "xrpl::TxQ::TxQAccount::add : transaction moved"); return result.first->second; } @@ -342,8 +312,7 @@ TxQ::TxQAccount::remove(SeqProxy seqProx) ////////////////////////////////////////////////////////////////////////// -TxQ::TxQ(Setup const& setup, beast::Journal j) - : setup_(setup), j_(j), feeMetrics_(setup, j), maxSize_(std::nullopt) +TxQ::TxQ(Setup const& setup, beast::Journal j) : setup_(setup), j_(j), feeMetrics_(setup, j), maxSize_(std::nullopt) { } @@ -356,8 +325,7 @@ template bool TxQ::isFull() const { - static_assert( - fillPercentage > 0 && fillPercentage <= 100, "Invalid fill percentage"); + static_assert(fillPercentage > 0 && fillPercentage <= 100, "Invalid fill percentage"); return maxSize_ && byFee_.size() >= (*maxSize_ * fillPercentage / 100); } @@ -375,8 +343,7 @@ TxQ::canBeHeld( // AccountTxnID is not supported by the transaction // queue yet, but should be added in the future. // tapFAIL_HARD transactions are never held - if (tx.isFieldPresent(sfPreviousTxnID) || - tx.isFieldPresent(sfAccountTxnID) || (flags & tapFAIL_HARD)) + if (tx.isFieldPresent(sfPreviousTxnID) || tx.isFieldPresent(sfAccountTxnID) || (flags & tapFAIL_HARD)) return telCAN_NOT_QUEUE; { @@ -384,8 +351,7 @@ TxQ::canBeHeld( // promise to stick around for long enough that it has // a realistic chance of getting into a ledger. auto const lastValid = getLastLedgerSequence(tx); - if (lastValid && - *lastValid < view.header().seq + setup_.minimumLastLedgerBuffer) + if (lastValid && *lastValid < view.header().seq + setup_.minimumLastLedgerBuffer) return telCAN_NOT_QUEUE; } @@ -428,8 +394,7 @@ TxQ::canBeHeld( } auto -TxQ::erase(TxQ::FeeMultiSet::const_iterator_type candidateIter) - -> FeeMultiSet::iterator_type +TxQ::erase(TxQ::FeeMultiSet::const_iterator_type candidateIter) -> FeeMultiSet::iterator_type { auto& txQAccount = byAccount_.at(candidateIter->account); auto const seqProx = candidateIter->seqProxy; @@ -444,42 +409,33 @@ TxQ::erase(TxQ::FeeMultiSet::const_iterator_type candidateIter) } auto -TxQ::eraseAndAdvance(TxQ::FeeMultiSet::const_iterator_type candidateIter) - -> FeeMultiSet::iterator_type +TxQ::eraseAndAdvance(TxQ::FeeMultiSet::const_iterator_type candidateIter) -> FeeMultiSet::iterator_type { auto& txQAccount = byAccount_.at(candidateIter->account); - auto const accountIter = - txQAccount.transactions.find(candidateIter->seqProxy); - XRPL_ASSERT( - accountIter != txQAccount.transactions.end(), - "xrpl::TxQ::eraseAndAdvance : account found"); + auto const accountIter = txQAccount.transactions.find(candidateIter->seqProxy); + XRPL_ASSERT(accountIter != txQAccount.transactions.end(), "xrpl::TxQ::eraseAndAdvance : account found"); // Note that sequence-based transactions must be applied in sequence order // from smallest to largest. But ticket-based transactions can be // applied in any order. XRPL_ASSERT( - candidateIter->seqProxy.isTicket() || - accountIter == txQAccount.transactions.begin(), + candidateIter->seqProxy.isTicket() || accountIter == txQAccount.transactions.begin(), "xrpl::TxQ::eraseAndAdvance : ticket or sequence"); XRPL_ASSERT( - byFee_.iterator_to(accountIter->second) == candidateIter, - "xrpl::TxQ::eraseAndAdvance : found in byFee"); + byFee_.iterator_to(accountIter->second) == candidateIter, "xrpl::TxQ::eraseAndAdvance : found in byFee"); auto const accountNextIter = std::next(accountIter); // Check if the next transaction for this account is earlier in the queue, // which means we skipped it earlier, and need to try it again. auto const feeNextIter = std::next(candidateIter); - bool const useAccountNext = - accountNextIter != txQAccount.transactions.end() && + bool const useAccountNext = accountNextIter != txQAccount.transactions.end() && accountNextIter->first > candidateIter->seqProxy && - (feeNextIter == byFee_.end() || - byFee_.value_comp()(accountNextIter->second, *feeNextIter)); + (feeNextIter == byFee_.end() || byFee_.value_comp()(accountNextIter->second, *feeNextIter)); auto const candidateNextIter = byFee_.erase(candidateIter); txQAccount.transactions.erase(accountIter); - return useAccountNext ? byFee_.iterator_to(accountNextIter->second) - : candidateNextIter; + return useAccountNext ? byFee_.iterator_to(accountNextIter->second) : candidateNextIter; } auto @@ -519,19 +475,16 @@ TxQ::tryClearAccountQueueUpThruTx( auto endTxIter = accountIter->second.transactions.lower_bound(tSeqProx); auto const dist = std::distance(beginTxIter, endTxIter); - auto const requiredTotalFeeLevel = FeeMetrics::escalatedSeriesFeeLevel( - metricsSnapshot, view, txExtraCount, dist + 1); + auto const requiredTotalFeeLevel = + FeeMetrics::escalatedSeriesFeeLevel(metricsSnapshot, view, txExtraCount, dist + 1); // If the computation for the total manages to overflow (however extremely // unlikely), then there's no way we can confidently verify if the queue // can be cleared. if (!requiredTotalFeeLevel.first) return {telINSUF_FEE_P, false}; - auto const totalFeeLevelPaid = std::accumulate( - beginTxIter, - endTxIter, - feeLevelPaid, - [](auto const& total, auto const& txn) { + auto const totalFeeLevelPaid = + std::accumulate(beginTxIter, endTxIter, feeLevelPaid, [](auto const& total, auto const& txn) { return total + txn.second.feeLevel; }); @@ -586,8 +539,7 @@ TxQ::tryClearAccountQueueUpThruTx( // queue. endTxIter = erase(accountIter->second, beginTxIter, endTxIter); // If `tx` is replacing a queued tx, delete that one, too. - if (endTxIter != accountIter->second.transactions.end() && - endTxIter->first == tSeqProx) + if (endTxIter != accountIter->second.transactions.end() && endTxIter->first == tSeqProx) erase(accountIter->second, endTxIter, std::next(endTxIter)); } @@ -708,12 +660,7 @@ TxQ::tryClearAccountQueueUpThruTx( // beyond that limit are rejected. // ApplyResult -TxQ::apply( - Application& app, - OpenView& view, - std::shared_ptr const& tx, - ApplyFlags flags, - beast::Journal j) +TxQ::apply(Application& app, OpenView& view, std::shared_ptr const& tx, ApplyFlags flags, beast::Journal j) { NumberSO stNumberSO{view.rules().enabled(fixUniversalNumber)}; @@ -746,8 +693,7 @@ TxQ::apply( // If the transaction needs a Ticket is that Ticket in the ledger? SeqProxy const acctSeqProx = SeqProxy::sequence((*sleAccount)[sfSequence]); SeqProxy const txSeqProx = tx->getSeqProxy(); - if (txSeqProx.isTicket() && - !view.exists(keylet::ticket(account, txSeqProx))) + if (txSeqProx.isTicket() && !view.exists(keylet::ticket(account, txSeqProx))) { if (txSeqProx.value() < acctSeqProx.value()) // The ticket number is low enough that it should already be @@ -775,10 +721,7 @@ TxQ::apply( // to individually check each queued ticket against the ledger. struct TxIter { - TxIter( - TxQAccount::TxMap::iterator first_, - TxQAccount::TxMap::iterator end_) - : first(first_), end(end_) + TxIter(TxQAccount::TxMap::iterator first_, TxQAccount::TxMap::iterator end_) : first(first_), end(end_) { } @@ -786,17 +729,13 @@ TxQ::apply( TxQAccount::TxMap::iterator end; }; - std::optional const txIter = - [accountIter, - accountIsInQueue, - acctSeqProx]() -> std::optional { + std::optional const txIter = [accountIter, accountIsInQueue, acctSeqProx]() -> std::optional { if (!accountIsInQueue) return {}; // Find the first transaction in the queue that we might apply. TxQAccount::TxMap& acctTxs = accountIter->second.transactions; - TxQAccount::TxMap::iterator const firstIter = - acctTxs.lower_bound(acctSeqProx); + TxQAccount::TxMap::iterator const firstIter = acctTxs.lower_bound(acctSeqProx); if (firstIter == acctTxs.end()) // Even though there may be transactions in the queue, there are @@ -806,8 +745,7 @@ TxQ::apply( return {TxIter{firstIter, acctTxs.end()}}; }(); - auto const acctTxCount{ - !txIter ? 0 : std::distance(txIter->first, txIter->end)}; + auto const acctTxCount{!txIter ? 0 : std::distance(txIter->first, txIter->end)}; // Is tx a blocker? If so there are very limited conditions when it // is allowed in the TxQ: @@ -820,25 +758,22 @@ TxQ::apply( { // A blocker may not be co-resident with other transactions in // the account's queue. - JLOG(j_.trace()) - << "Rejecting blocker transaction " << transactionID - << ". Account has other queued transactions."; + JLOG(j_.trace()) << "Rejecting blocker transaction " << transactionID + << ". Account has other queued transactions."; return {telCAN_NOT_QUEUE_BLOCKS, false}; } if (acctTxCount == 1 && (txSeqProx != txIter->first->first)) { // The blocker is not replacing the lone queued transaction. - JLOG(j_.trace()) - << "Rejecting blocker transaction " << transactionID - << ". Blocker does not replace lone queued transaction."; + JLOG(j_.trace()) << "Rejecting blocker transaction " << transactionID + << ". Blocker does not replace lone queued transaction."; return {telCAN_NOT_QUEUE_BLOCKS, false}; } } // If the transaction is intending to replace a transaction in the queue // identify the one that might be replaced. - auto replacedTxIter = [accountIsInQueue, &accountIter, txSeqProx]() - -> std::optional { + auto replacedTxIter = [accountIsInQueue, &accountIter, txSeqProx]() -> std::optional { if (accountIsInQueue) { TxQAccount& txQAcct = accountIter->second; @@ -853,8 +788,7 @@ TxQ::apply( // replacement, so just pull it up now. auto const metricsSnapshot = feeMetrics_.getSnapshot(); auto const feeLevelPaid = getFeeLevelPaid(view, *tx); - auto const requiredFeeLevel = - getRequiredFeeLevel(view, flags, metricsSnapshot, lock); + auto const requiredFeeLevel = getRequiredFeeLevel(view, flags, metricsSnapshot, lock); // Is there a blocker already in the account's queue? If so, don't // allow additional transactions in the queue. @@ -865,9 +799,7 @@ TxQ::apply( // // We only need to check if txIter->first is a blocker because we // require that a blocker be alone in the account's queue. - if (acctTxCount == 1 && - txIter->first->second.consequences().isBlocker() && - (txIter->first->first != txSeqProx)) + if (acctTxCount == 1 && txIter->first->second.consequences().isBlocker() && (txIter->first->first != txSeqProx)) { return {telCAN_NOT_QUEUE_BLOCKED, false}; } @@ -882,29 +814,23 @@ TxQ::apply( // Is the current transaction's fee higher than // the queued transaction's fee + a percentage TxQAccount::TxMap::iterator const& existingIter = *replacedTxIter; - auto requiredRetryLevel = increase( - existingIter->second.feeLevel, setup_.retrySequencePercent); - JLOG(j_.trace()) - << "Found transaction in queue for account " << account - << " with " << txSeqProx << " new txn fee level is " - << feeLevelPaid << ", old txn fee level is " - << existingIter->second.feeLevel - << ", new txn needs fee level of " << requiredRetryLevel; + auto requiredRetryLevel = increase(existingIter->second.feeLevel, setup_.retrySequencePercent); + JLOG(j_.trace()) << "Found transaction in queue for account " << account << " with " << txSeqProx + << " new txn fee level is " << feeLevelPaid << ", old txn fee level is " + << existingIter->second.feeLevel << ", new txn needs fee level of " << requiredRetryLevel; if (feeLevelPaid > requiredRetryLevel) { // Continue, leaving the queued transaction marked for removal. // DO NOT REMOVE if the new tx fails, because there may // be other txs dependent on it in the queue. - JLOG(j_.trace()) << "Removing transaction from queue " - << existingIter->second.txID << " in favor of " + JLOG(j_.trace()) << "Removing transaction from queue " << existingIter->second.txID << " in favor of " << transactionID; } else { // Drop the current transaction - JLOG(j_.trace()) - << "Ignoring transaction " << transactionID - << " in favor of queued " << existingIter->second.txID; + JLOG(j_.trace()) << "Ignoring transaction " << transactionID << " in favor of queued " + << existingIter->second.txID; return {telCAN_NOT_QUEUE_FEE, false}; } } @@ -915,8 +841,7 @@ TxQ::apply( ApplyViewImpl applyView; OpenView openView; - MultiTxn(OpenView& view, ApplyFlags flags) - : applyView(&view, flags), openView(&applyView) + MultiTxn(OpenView& view, ApplyFlags flags) : applyView(&view, flags), openView(&applyView) { } }; @@ -957,14 +882,7 @@ TxQ::apply( { // If the transaction is queueable, create the multiTxn // object to hold the info we need to adjust for prior txns. - TER const ter{canBeHeld( - *tx, - flags, - view, - sleAccount, - accountIter, - replacedTxIter, - lock)}; + TER const ter{canBeHeld(*tx, flags, view, sleAccount, accountIter, replacedTxIter, lock)}; if (!isTesSuccess(ter)) return {ter, false}; @@ -985,8 +903,7 @@ TxQ::apply( // Find the entry in the queue that precedes the new // transaction, if one does. - TxQAccount::TxMap::const_iterator const prevIter = - txQAcct.getPrevTx(txSeqProx); + TxQAccount::TxMap::const_iterator const prevIter = txQAcct.getPrevTx(txSeqProx); // Does the new transaction go to the front of the queue? // This can happen if: @@ -1014,8 +931,7 @@ TxQ::apply( // front of this one in the queue. Make sure the current // transaction fits in proper sequence order with the // previous transaction or is a ticket. - if (txSeqProx.isSeq() && - nextQueuableSeqImpl(sleAccount, lock) != txSeqProx) + if (txSeqProx.isSeq() && nextQueuableSeqImpl(sleAccount, lock) != txSeqProx) return {telCAN_NOT_QUEUE, false}; } @@ -1032,8 +948,7 @@ TxQ::apply( if (iter->first != txSeqProx) { totalFee += iter->second.consequences().fee(); - potentialSpend += - iter->second.consequences().potentialSpend(); + potentialSpend += iter->second.consequences().potentialSpend(); } else if (std::next(iter) != txIter->end) { @@ -1094,12 +1009,10 @@ TxQ::apply( */ auto const reserve = view.fees().reserve; auto const base = view.fees().base; - if (totalFee >= balance || - (reserve > 10 * base && totalFee >= reserve)) + if (totalFee >= balance || (reserve > 10 * base && totalFee >= reserve)) { // Drop the current transaction - JLOG(j_.trace()) << "Ignoring transaction " << transactionID - << ". Total fees in flight too high."; + JLOG(j_.trace()) << "Ignoring transaction " << transactionID << ". Total fees in flight too high."; return {telCAN_NOT_QUEUE_BALANCE, false}; } @@ -1113,12 +1026,10 @@ TxQ::apply( // Subtract the fees and XRP spend from all of the other // transactions in the queue. That prevents a transaction // inserted in the middle from fouling up later transactions. - auto const potentialTotalSpend = totalFee + - std::min(balance - std::min(balance, reserve), potentialSpend); + auto const potentialTotalSpend = totalFee + std::min(balance - std::min(balance, reserve), potentialSpend); XRPL_ASSERT( potentialTotalSpend > XRPAmount{0} || - (potentialTotalSpend == XRPAmount{0} && - multiTxn->applyView.fees().base == 0), + (potentialTotalSpend == XRPAmount{0} && multiTxn->applyView.fees().base == 0), "xrpl::TxQ::apply : total spend check"); sleBump->setFieldAmount(sfBalance, balance - potentialTotalSpend); // The transaction's sequence/ticket will be valid when the other @@ -1126,9 +1037,8 @@ TxQ::apply( // sequence, set the account to match it. If it has a ticket, use // the next queueable sequence, which is the closest approximation // to the most successful case. - sleBump->at(sfSequence) = txSeqProx.isSeq() - ? txSeqProx.value() - : nextQueuableSeqImpl(sleAccount, lock).value(); + sleBump->at(sfSequence) = + txSeqProx.isSeq() ? txSeqProx.value() : nextQueuableSeqImpl(sleAccount, lock).value(); } } @@ -1143,19 +1053,16 @@ TxQ::apply( // Note that earlier code has already verified that the sequence/ticket // is valid. So we use a special entry point that runs all of the // preclaim checks with the exception of the sequence check. - auto const pcresult = - preclaim(pfResult, app, multiTxn ? multiTxn->openView : view); + auto const pcresult = preclaim(pfResult, app, multiTxn ? multiTxn->openView : view); if (!pcresult.likelyToClaimFee) return {pcresult.ter, false}; // Too low of a fee should get caught by preclaim XRPL_ASSERT(feeLevelPaid >= baseLevel, "xrpl::TxQ::apply : minimum fee"); - JLOG(j_.trace()) << "Transaction " << transactionID << " from account " - << account << " has fee level of " << feeLevelPaid - << " needs at least " << requiredFeeLevel - << " to get in the open ledger, which has " - << view.txCount() << " entries."; + JLOG(j_.trace()) << "Transaction " << transactionID << " from account " << account << " has fee level of " + << feeLevelPaid << " needs at least " << requiredFeeLevel + << " to get in the open ledger, which has " << view.txCount() << " entries."; /* Quick heuristic check to see if it's worth checking that this tx has a high enough fee to clear all the txs in front of it in the queue. @@ -1175,8 +1082,8 @@ TxQ::apply( conditions change, but don't waste the effort to clear). */ if (txSeqProx.isSeq() && txIter && multiTxn.has_value() && - txIter->first->second.retriesRemaining == MaybeTx::retriesAllowed && - feeLevelPaid > requiredFeeLevel && requiredFeeLevel > baseLevel) + txIter->first->second.retriesRemaining == MaybeTx::retriesAllowed && feeLevelPaid > requiredFeeLevel && + requiredFeeLevel > baseLevel) { OpenView sandbox(open_ledger, &view, view.rules()); @@ -1205,13 +1112,11 @@ TxQ::apply( // If `multiTxn` has a value, then `canBeHeld` has already been verified if (!multiTxn) { - TER const ter{canBeHeld( - *tx, flags, view, sleAccount, accountIter, replacedTxIter, lock)}; + TER const ter{canBeHeld(*tx, flags, view, sleAccount, accountIter, replacedTxIter, lock)}; if (!isTesSuccess(ter)) { // Bail, transaction cannot be held - JLOG(j_.trace()) - << "Transaction " << transactionID << " cannot be held"; + JLOG(j_.trace()) << "Transaction " << transactionID << " cannot be held"; return {ter, false}; } } @@ -1234,10 +1139,8 @@ TxQ::apply( // is 2000, and an account can only have 10 transactions // queued. However, it can occur if settings are changed, // and there is unit test coverage. - JLOG(j_.info()) - << "Queue is full, and transaction " << transactionID - << " would kick a transaction from the same account (" - << account << ") out of the queue."; + JLOG(j_.info()) << "Queue is full, and transaction " << transactionID + << " would kick a transaction from the same account (" << account << ") out of the queue."; return {telCAN_NOT_QUEUE_FULL, false}; } auto const& endAccount = byAccount_.at(lastRIter->account); @@ -1245,8 +1148,7 @@ TxQ::apply( // Compute the average of all the txs for the endAccount, // but only if the last tx in the queue has a lower fee // level than this candidate tx. - if (lastRIter->feeLevel > feeLevelPaid || - endAccount.transactions.size() == 1) + if (lastRIter->feeLevel > feeLevelPaid || endAccount.transactions.size() == 1) return lastRIter->feeLevel; constexpr FeeLevel64 max{std::numeric_limits::max()}; @@ -1254,20 +1156,16 @@ TxQ::apply( endAccount.transactions.begin(), endAccount.transactions.end(), std::pair(0, 0), - [&](auto const& total, - auto const& txn) -> std::pair { + [&](auto const& total, auto const& txn) -> std::pair { // Check for overflow. - auto next = - txn.second.feeLevel / endAccount.transactions.size(); - auto mod = - txn.second.feeLevel % endAccount.transactions.size(); + auto next = txn.second.feeLevel / endAccount.transactions.size(); + auto mod = txn.second.feeLevel % endAccount.transactions.size(); if (total.first >= max - next || total.second >= max - mod) return {max, FeeLevel64{0}}; return {total.first + next, total.second + mod}; }); - return endTotal.first + - endTotal.second / endAccount.transactions.size(); + return endTotal.first + endTotal.second / endAccount.transactions.size(); }(); if (feeLevelPaid > endEffectiveFeeLevel) { @@ -1275,20 +1173,16 @@ TxQ::apply( // valuable, so kick out the cheapest transaction. auto dropRIter = endAccount.transactions.rbegin(); XRPL_ASSERT( - dropRIter->second.account == lastRIter->account, - "xrpl::TxQ::apply : cheapest transaction found"); - JLOG(j_.info()) - << "Removing last item of account " << lastRIter->account - << " from queue with average fee of " << endEffectiveFeeLevel - << " in favor of " << transactionID << " with fee of " - << feeLevelPaid; + dropRIter->second.account == lastRIter->account, "xrpl::TxQ::apply : cheapest transaction found"); + JLOG(j_.info()) << "Removing last item of account " << lastRIter->account + << " from queue with average fee of " << endEffectiveFeeLevel << " in favor of " + << transactionID << " with fee of " << feeLevelPaid; erase(byFee_.iterator_to(dropRIter->second)); } else { - JLOG(j_.info()) - << "Queue is full, and transaction " << transactionID - << " fee is lower than end item's account average fee"; + JLOG(j_.info()) << "Queue is full, and transaction " << transactionID + << " fee is lower than end item's account average fee"; return {telCAN_NOT_QUEUE_FULL, false}; } } @@ -1303,8 +1197,7 @@ TxQ::apply( { // Create a new TxQAccount object and add the byAccount lookup. [[maybe_unused]] bool created = false; - std::tie(accountIter, created) = - byAccount_.emplace(account, TxQAccount(tx)); + std::tie(accountIter, created) = byAccount_.emplace(account, TxQAccount(tx)); XRPL_ASSERT(created, "xrpl::TxQ::apply : account created"); } // Modify the flags for use when coming out of the queue. @@ -1315,15 +1208,13 @@ TxQ::apply( // Don't allow soft failures, which can lead to retries flags &= ~tapRETRY; - auto& candidate = accountIter->second.add( - {tx, transactionID, feeLevelPaid, flags, pfResult}); + auto& candidate = accountIter->second.add({tx, transactionID, feeLevelPaid, flags, pfResult}); // Then index it into the byFee lookup. byFee_.insert(candidate); - JLOG(j_.debug()) << "Added transaction " << candidate.txID - << " with result " << transToken(pfResult.ter) << " from " - << (accountIsInQueue ? "existing" : "new") << " account " - << candidate.account << " to queue." + JLOG(j_.debug()) << "Added transaction " << candidate.txID << " with result " << transToken(pfResult.ter) + << " from " << (accountIsInQueue ? "existing" : "new") << " account " << candidate.account + << " to queue." << " Flags: " << flags; return {terQUEUED, false}; @@ -1352,8 +1243,7 @@ TxQ::processClosedLedger(Application& app, ReadView const& view, bool timeLeap) auto ledgerSeq = view.header().seq; if (!timeLeap) - maxSize_ = std::max( - snapshot.txnsExpected * setup_.ledgersInQueue, setup_.queueSizeMin); + maxSize_ = std::max(snapshot.txnsExpected * setup_.ledgersInQueue, setup_.queueSizeMin); // Remove any queued candidates whose LastLedgerSequence has gone by. for (auto candidateIter = byFee_.begin(); candidateIter != byFee_.end();) @@ -1371,8 +1261,7 @@ TxQ::processClosedLedger(Application& app, ReadView const& view, bool timeLeap) // Remove any TxQAccounts that don't have candidates // under them - for (auto txQAccountIter = byAccount_.begin(); - txQAccountIter != byAccount_.end();) + for (auto txQAccountIter = byAccount_.begin(); txQAccountIter != byAccount_.end();) { if (txQAccountIter->second.empty()) txQAccountIter = byAccount_.erase(txQAccountIter); @@ -1429,72 +1318,56 @@ TxQ::accept(Application& app, OpenView& view) { auto& account = byAccount_.at(candidateIter->account); auto const beginIter = account.transactions.begin(); - if (candidateIter->seqProxy.isSeq() && - candidateIter->seqProxy > beginIter->first) + if (candidateIter->seqProxy.isSeq() && candidateIter->seqProxy > beginIter->first) { // There is a sequence transaction at the front of the queue and // candidate has a later sequence, so skip this candidate. We // need to process sequence-based transactions in sequence order. - JLOG(j_.trace()) - << "Skipping queued transaction " << candidateIter->txID - << " from account " << candidateIter->account - << " as it is not the first."; + JLOG(j_.trace()) << "Skipping queued transaction " << candidateIter->txID << " from account " + << candidateIter->account << " as it is not the first."; candidateIter++; continue; } - auto const requiredFeeLevel = - getRequiredFeeLevel(view, tapNONE, metricsSnapshot, lock); + auto const requiredFeeLevel = getRequiredFeeLevel(view, tapNONE, metricsSnapshot, lock); auto const feeLevelPaid = candidateIter->feeLevel; - JLOG(j_.trace()) << "Queued transaction " << candidateIter->txID - << " from account " << candidateIter->account - << " has fee level of " << feeLevelPaid - << " needs at least " << requiredFeeLevel; + JLOG(j_.trace()) << "Queued transaction " << candidateIter->txID << " from account " << candidateIter->account + << " has fee level of " << feeLevelPaid << " needs at least " << requiredFeeLevel; if (feeLevelPaid >= requiredFeeLevel) { - JLOG(j_.trace()) << "Applying queued transaction " - << candidateIter->txID << " to open ledger."; + JLOG(j_.trace()) << "Applying queued transaction " << candidateIter->txID << " to open ledger."; - auto const [txnResult, didApply, _metadata] = - candidateIter->apply(app, view, j_); + auto const [txnResult, didApply, _metadata] = candidateIter->apply(app, view, j_); if (didApply) { // Remove the candidate from the queue - JLOG(j_.debug()) - << "Queued transaction " << candidateIter->txID - << " applied successfully with " << transToken(txnResult) - << ". Remove from queue."; + JLOG(j_.debug()) << "Queued transaction " << candidateIter->txID << " applied successfully with " + << transToken(txnResult) << ". Remove from queue."; candidateIter = eraseAndAdvance(candidateIter); ledgerChanged = true; } - else if ( - isTefFailure(txnResult) || isTemMalformed(txnResult) || - candidateIter->retriesRemaining <= 0) + else if (isTefFailure(txnResult) || isTemMalformed(txnResult) || candidateIter->retriesRemaining <= 0) { if (candidateIter->retriesRemaining <= 0) account.retryPenalty = true; else account.dropPenalty = true; - JLOG(j_.debug()) << "Queued transaction " << candidateIter->txID - << " failed with " << transToken(txnResult) - << ". Remove from queue."; + JLOG(j_.debug()) << "Queued transaction " << candidateIter->txID << " failed with " + << transToken(txnResult) << ". Remove from queue."; candidateIter = eraseAndAdvance(candidateIter); } else { - JLOG(j_.debug()) << "Queued transaction " << candidateIter->txID - << " failed with " << transToken(txnResult) - << ". Leave in queue." - << " Applied: " << didApply - << ". Flags: " << candidateIter->flags; + JLOG(j_.debug()) << "Queued transaction " << candidateIter->txID << " failed with " + << transToken(txnResult) << ". Leave in queue." + << " Applied: " << didApply << ". Flags: " << candidateIter->flags; if (account.retryPenalty && candidateIter->retriesRemaining > 2) candidateIter->retriesRemaining = 1; else --candidateIter->retriesRemaining; candidateIter->lastResult = txnResult; - if (account.dropPenalty && account.transactions.size() > 1 && - isFull<95>()) + if (account.dropPenalty && account.transactions.size() > 1 && isFull<95>()) { // The queue is close to full, this account has multiple // txs queued, and this account has had a transaction @@ -1503,12 +1376,9 @@ TxQ::accept(Application& app, OpenView& view) { // Since the failed transaction has a ticket, order // doesn't matter. Drop this one. - JLOG(j_.info()) - << "Queue is nearly full, and transaction " - << candidateIter->txID << " failed with " - << transToken(txnResult) - << ". Removing ticketed tx from account " - << account.account; + JLOG(j_.info()) << "Queue is nearly full, and transaction " << candidateIter->txID + << " failed with " << transToken(txnResult) + << ". Removing ticketed tx from account " << account.account; candidateIter = eraseAndAdvance(candidateIter); } else @@ -1519,15 +1389,11 @@ TxQ::accept(Application& app, OpenView& view) // this account. auto dropRIter = account.transactions.rbegin(); XRPL_ASSERT( - dropRIter->second.account == candidateIter->account, - "xrpl::TxQ::accept : account check"); + dropRIter->second.account == candidateIter->account, "xrpl::TxQ::accept : account check"); - JLOG(j_.info()) - << "Queue is nearly full, and transaction " - << candidateIter->txID << " failed with " - << transToken(txnResult) - << ". Removing last item from account " - << account.account; + JLOG(j_.info()) << "Queue is nearly full, and transaction " << candidateIter->txID + << " failed with " << transToken(txnResult) + << ". Removing last item from account " << account.account; auto endIter = byFee_.iterator_to(dropRIter->second); if (endIter != candidateIter) erase(endIter); @@ -1574,8 +1440,7 @@ TxQ::accept(Application& app, OpenView& view) byFee_.insert(candidate); } } - XRPL_ASSERT( - byFee_.size() == startingSize, "xrpl::TxQ::accept : byFee size match"); + XRPL_ASSERT(byFee_.size() == startingSize, "xrpl::TxQ::accept : byFee size match"); return ledgerChanged; } @@ -1597,9 +1462,7 @@ TxQ::nextQueuableSeq(std::shared_ptr const& sleAccount) const // sequence number, that is not used by a transaction in the queue, must // be found and returned. SeqProxy -TxQ::nextQueuableSeqImpl( - std::shared_ptr const& sleAccount, - std::lock_guard const&) const +TxQ::nextQueuableSeqImpl(std::shared_ptr const& sleAccount, std::lock_guard const&) const { // If the account is not in the ledger or a non-account was passed // then return zero. We have no idea. @@ -1610,8 +1473,7 @@ TxQ::nextQueuableSeqImpl( // If the account is not in the queue then acctSeqProx is good enough. auto const accountIter = byAccount_.find((*sleAccount)[sfAccount]); - if (accountIter == byAccount_.end() || - accountIter->second.transactions.empty()) + if (accountIter == byAccount_.end() || accountIter->second.transactions.empty()) return acctSeqProx; TxQAccount::TxMap const& acctTxs = accountIter->second.transactions; @@ -1621,8 +1483,7 @@ TxQ::nextQueuableSeqImpl( // wild, but it's uncommon. TxQAccount::TxMap::const_iterator txIter = acctTxs.lower_bound(acctSeqProx); - if (txIter == acctTxs.end() || !txIter->first.isSeq() || - txIter->first != acctSeqProx) + if (txIter == acctTxs.end() || !txIter->first.isSeq() || txIter->first != acctSeqProx) // Either... // o There are no queued sequence-based transactions equal to or // following acctSeqProx or @@ -1678,8 +1539,7 @@ TxQ::tryDirectApply( FeeLevel64 const requiredFeeLevel = [this, &view, flags]() { std::lock_guard lock(mutex_); - return getRequiredFeeLevel( - view, flags, feeMetrics_.getSnapshot(), lock); + return getRequiredFeeLevel(view, flags, feeMetrics_.getSnapshot(), lock); }(); // If the transaction's fee is high enough we may be able to put the @@ -1690,16 +1550,12 @@ TxQ::tryDirectApply( { // Attempt to apply the transaction directly. auto const transactionID = tx->getTransactionID(); - JLOG(j_.trace()) << "Applying transaction " << transactionID - << " to open ledger."; + JLOG(j_.trace()) << "Applying transaction " << transactionID << " to open ledger."; - auto const [txnResult, didApply, metadata] = - xrpl::apply(app, view, *tx, flags, j); + auto const [txnResult, didApply, metadata] = xrpl::apply(app, view, *tx, flags, j); JLOG(j_.trace()) << "New transaction " << transactionID - << (didApply ? " applied successfully with " - : " failed with ") - << transToken(txnResult); + << (didApply ? " applied successfully with " : " failed with ") << transToken(txnResult); if (didApply) { @@ -1711,8 +1567,7 @@ TxQ::tryDirectApply( if (accountIter != byAccount_.end()) { TxQAccount& txQAcct = accountIter->second; - if (auto const existingIter = - txQAcct.transactions.find(txSeqProx); + if (auto const existingIter = txQAcct.transactions.find(txSeqProx); existingIter != txQAcct.transactions.end()) { removeFromByFee(existingIter, tx); @@ -1734,18 +1589,10 @@ TxQ::removeFromByFee( // If the transaction we're holding replaces a transaction in the // queue, remove the transaction that is being replaced. auto deleteIter = byFee_.iterator_to((*replacedTxIter)->second); - XRPL_ASSERT( - deleteIter != byFee_.end(), - "xrpl::TxQ::removeFromByFee : found in byFee"); - XRPL_ASSERT( - &(*replacedTxIter)->second == &*deleteIter, - "xrpl::TxQ::removeFromByFee : matching transaction"); - XRPL_ASSERT( - deleteIter->seqProxy == tx->getSeqProxy(), - "xrpl::TxQ::removeFromByFee : matching sequence"); - XRPL_ASSERT( - deleteIter->account == (*tx)[sfAccount], - "xrpl::TxQ::removeFromByFee : matching account"); + XRPL_ASSERT(deleteIter != byFee_.end(), "xrpl::TxQ::removeFromByFee : found in byFee"); + XRPL_ASSERT(&(*replacedTxIter)->second == &*deleteIter, "xrpl::TxQ::removeFromByFee : matching transaction"); + XRPL_ASSERT(deleteIter->seqProxy == tx->getSeqProxy(), "xrpl::TxQ::removeFromByFee : matching sequence"); + XRPL_ASSERT(deleteIter->account == (*tx)[sfAccount], "xrpl::TxQ::removeFromByFee : matching account"); erase(deleteIter); } @@ -1766,8 +1613,7 @@ TxQ::getMetrics(OpenView const& view) const result.txInLedger = view.txCount(); result.txPerLedger = snapshot.txnsExpected; result.referenceFeeLevel = baseLevel; - result.minProcessingFeeLevel = - isFull() ? byFee_.rbegin()->feeLevel + FeeLevel64{1} : baseLevel; + result.minProcessingFeeLevel = isFull() ? byFee_.rbegin()->feeLevel + FeeLevel64{1} : baseLevel; result.medFeeLevel = snapshot.escalationMultiplier; result.openLedgerFeeLevel = FeeMetrics::scaleFeeLevel(snapshot, view); @@ -1775,9 +1621,7 @@ TxQ::getMetrics(OpenView const& view) const } TxQ::FeeAndSeq -TxQ::getTxRequiredFeeAndSeq( - OpenView const& view, - std::shared_ptr const& tx) const +TxQ::getTxRequiredFeeAndSeq(OpenView const& view, std::shared_ptr const& tx) const { auto const account = (*tx)[sfAccount]; @@ -1792,8 +1636,7 @@ TxQ::getTxRequiredFeeAndSeq( std::uint32_t const accountSeq = sle ? (*sle)[sfSequence] : 0; std::uint32_t const availableSeq = nextQueuableSeqImpl(sle, lock).value(); return { - mulDiv(fee, baseFee, baseLevel) - .value_or(XRPAmount(std::numeric_limits::max())), + mulDiv(fee, baseFee, baseLevel).value_or(XRPAmount(std::numeric_limits::max())), accountSeq, availableSeq}; } @@ -1807,8 +1650,7 @@ TxQ::getAccountTxs(AccountID const& account) const AccountMap::const_iterator const accountIter{byAccount_.find(account)}; - if (accountIter == byAccount_.end() || - accountIter->second.transactions.empty()) + if (accountIter == byAccount_.end() || accountIter->second.transactions.empty()) return result; result.reserve(accountIter->second.transactions.size()); @@ -1875,12 +1717,10 @@ TxQ::doRPC(Application& app) const drops[jss::base_fee] = to_string(baseFee); drops[jss::median_fee] = to_string(toDrops(metrics.medFeeLevel, baseFee)); - drops[jss::minimum_fee] = to_string(toDrops( - metrics.minProcessingFeeLevel, - metrics.txCount >= metrics.txQMaxSize ? effectiveBaseFee : baseFee)); + drops[jss::minimum_fee] = to_string( + toDrops(metrics.minProcessingFeeLevel, metrics.txCount >= metrics.txQMaxSize ? effectiveBaseFee : baseFee)); auto openFee = toDrops(metrics.openLedgerFeeLevel, effectiveBaseFee); - if (effectiveBaseFee && - toFeeLevel(openFee, effectiveBaseFee) < metrics.openLedgerFeeLevel) + if (effectiveBaseFee && toFeeLevel(openFee, effectiveBaseFee) < metrics.openLedgerFeeLevel) openFee += 1; drops[jss::open_ledger_fee] = to_string(openFee); @@ -1897,13 +1737,9 @@ setup_TxQ(Config const& config) set(setup.ledgersInQueue, "ledgers_in_queue", section); set(setup.queueSizeMin, "minimum_queue_size", section); set(setup.retrySequencePercent, "retry_sequence_percent", section); - set(setup.minimumEscalationMultiplier, - "minimum_escalation_multiplier", - section); + set(setup.minimumEscalationMultiplier, "minimum_escalation_multiplier", section); set(setup.minimumTxnInLedger, "minimum_txn_in_ledger", section); - set(setup.minimumTxnInLedgerSA, - "minimum_txn_in_ledger_standalone", - section); + set(setup.minimumTxnInLedgerSA, "minimum_txn_in_ledger_standalone", section); set(setup.targetTxnInLedger, "target_txn_in_ledger", section); std::uint32_t max; if (set(max, "maximum_txn_in_ledger", section)) @@ -1934,21 +1770,15 @@ setup_TxQ(Config const& config) moot. (There are other ways to do that, including minimum_txn_in_ledger.) */ - set(setup.normalConsensusIncreasePercent, - "normal_consensus_increase_percent", - section); - setup.normalConsensusIncreasePercent = - std::clamp(setup.normalConsensusIncreasePercent, 0u, 1000u); + set(setup.normalConsensusIncreasePercent, "normal_consensus_increase_percent", section); + setup.normalConsensusIncreasePercent = std::clamp(setup.normalConsensusIncreasePercent, 0u, 1000u); /* If this percentage is outside of the 0-100 range, the results are nonsensical (uint overflows happen, so the limit grows instead of shrinking). 0 is not recommended. */ - set(setup.slowConsensusDecreasePercent, - "slow_consensus_decrease_percent", - section); - setup.slowConsensusDecreasePercent = - std::clamp(setup.slowConsensusDecreasePercent, 0u, 100u); + set(setup.slowConsensusDecreasePercent, "slow_consensus_decrease_percent", section); + setup.slowConsensusDecreasePercent = std::clamp(setup.slowConsensusDecreasePercent, 0u, 100u); set(setup.maximumTxnPerAccount, "maximum_txn_per_account", section); set(setup.minimumLastLedgerBuffer, "minimum_last_ledger_buffer", section); diff --git a/src/xrpld/app/misc/detail/ValidatorKeys.cpp b/src/xrpld/app/misc/detail/ValidatorKeys.cpp index 757a18aa47..8f24f14b40 100644 --- a/src/xrpld/app/misc/detail/ValidatorKeys.cpp +++ b/src/xrpld/app/misc/detail/ValidatorKeys.cpp @@ -1,39 +1,33 @@ -#include #include #include #include #include #include +#include namespace xrpl { ValidatorKeys::ValidatorKeys(Config const& config, beast::Journal j) { - if (config.exists(SECTION_VALIDATOR_TOKEN) && - config.exists(SECTION_VALIDATION_SEED)) + if (config.exists(SECTION_VALIDATOR_TOKEN) && config.exists(SECTION_VALIDATION_SEED)) { configInvalid_ = true; - JLOG(j.fatal()) << "Cannot specify both [" SECTION_VALIDATION_SEED - "] and [" SECTION_VALIDATOR_TOKEN "]"; + JLOG(j.fatal()) << "Cannot specify both [" SECTION_VALIDATION_SEED "] and [" SECTION_VALIDATOR_TOKEN "]"; return; } if (config.exists(SECTION_VALIDATOR_TOKEN)) { // token is non-const so it can be moved from - if (auto token = loadValidatorToken( - config.section(SECTION_VALIDATOR_TOKEN).lines())) + if (auto token = loadValidatorToken(config.section(SECTION_VALIDATOR_TOKEN).lines())) { - auto const pk = - derivePublicKey(KeyType::secp256k1, token->validationSecret); + auto const pk = derivePublicKey(KeyType::secp256k1, token->validationSecret); auto const m = deserializeManifest(base64_decode(token->manifest)); if (!m || pk != m->signingKey) { configInvalid_ = true; - JLOG(j.fatal()) - << "Invalid token specified in [" SECTION_VALIDATOR_TOKEN - "]"; + JLOG(j.fatal()) << "Invalid token specified in [" SECTION_VALIDATOR_TOKEN "]"; } else { @@ -46,19 +40,16 @@ ValidatorKeys::ValidatorKeys(Config const& config, beast::Journal j) else { configInvalid_ = true; - JLOG(j.fatal()) - << "Invalid token specified in [" SECTION_VALIDATOR_TOKEN "]"; + JLOG(j.fatal()) << "Invalid token specified in [" SECTION_VALIDATOR_TOKEN "]"; } } else if (config.exists(SECTION_VALIDATION_SEED)) { - auto const seed = parseBase58( - config.section(SECTION_VALIDATION_SEED).lines().front()); + auto const seed = parseBase58(config.section(SECTION_VALIDATION_SEED).lines().front()); if (!seed) { configInvalid_ = true; - JLOG(j.fatal()) - << "Invalid seed specified in [" SECTION_VALIDATION_SEED "]"; + JLOG(j.fatal()) << "Invalid seed specified in [" SECTION_VALIDATION_SEED "]"; } else { diff --git a/src/xrpld/app/misc/detail/ValidatorList.cpp b/src/xrpld/app/misc/detail/ValidatorList.cpp index 5c1c5e80a1..4730df4983 100644 --- a/src/xrpld/app/misc/detail/ValidatorList.cpp +++ b/src/xrpld/app/misc/detail/ValidatorList.cpp @@ -1,5 +1,3 @@ -#include -#include #include #include @@ -7,12 +5,14 @@ #include #include #include +#include #include #include #include #include #include #include +#include #include @@ -67,20 +67,17 @@ ValidatorList::PublisherListStats::PublisherListStats( ListDisposition ValidatorList::PublisherListStats::bestDisposition() const { - return dispositions.empty() ? ListDisposition::invalid - : dispositions.begin()->first; + return dispositions.empty() ? ListDisposition::invalid : dispositions.begin()->first; } ListDisposition ValidatorList::PublisherListStats::worstDisposition() const { - return dispositions.empty() ? ListDisposition::invalid - : dispositions.rbegin()->first; + return dispositions.empty() ? ListDisposition::invalid : dispositions.rbegin()->first; } void -ValidatorList::PublisherListStats::mergeDispositions( - PublisherListStats const& src) +ValidatorList::PublisherListStats::mergeDispositions(PublisherListStats const& src) { for (auto const& [disp, count] : src.dispositions) { @@ -137,8 +134,7 @@ ValidatorList::load( std::lock_guard lock{mutex_}; - JLOG(j_.debug()) - << "Loading configured trusted validator list publisher keys"; + JLOG(j_.debug()) << "Loading configured trusted validator list publisher keys"; std::size_t count = 0; for (auto key : publisherKeys) @@ -158,16 +154,13 @@ ValidatorList::load( if (publisherManifests_.revoked(id)) { - JLOG(j_.warn()) - << "Configured validator list publisher key is revoked: " - << key; + JLOG(j_.warn()) << "Configured validator list publisher key is revoked: " << key; status = PublisherStatus::revoked; } if (publisherLists_.count(id)) { - JLOG(j_.warn()) - << "Duplicate validator list publisher key: " << key; + JLOG(j_.warn()) << "Duplicate validator list publisher key: " << key; continue; } @@ -182,17 +175,14 @@ ValidatorList::load( XRPL_ASSERT( listThreshold_ > 0 && listThreshold_ <= publisherLists_.size(), "xrpl::ValidatorList::load : list threshold inside range"); - JLOG(j_.debug()) << "Validator list threshold set in configuration to " - << listThreshold_; + JLOG(j_.debug()) << "Validator list threshold set in configuration to " << listThreshold_; } else { // Want truncated result when dividing an odd integer - listThreshold_ = (publisherLists_.size() < 3) - ? 1 // - : publisherLists_.size() / 2 + 1; - JLOG(j_.debug()) << "Validator list threshold computed as " - << listThreshold_; + listThreshold_ = (publisherLists_.size() < 3) ? 1 // + : publisherLists_.size() / 2 + 1; + JLOG(j_.debug()) << "Validator list threshold computed as " << listThreshold_; } JLOG(j_.debug()) << "Loaded " << count << " keys"; @@ -205,12 +195,10 @@ ValidatorList::load( { // The local validator must meet listThreshold_ so the validator does // not ignore itself. - auto const [_, inserted] = - keyListings_.insert({*localPubKey_, listThreshold_}); + auto const [_, inserted] = keyListings_.insert({*localPubKey_, listThreshold_}); if (inserted) { - JLOG(j_.debug()) << "Added own master key " - << toBase58(TokenType::NodePublic, *localPubKey_); + JLOG(j_.debug()) << "Added own master key " << toBase58(TokenType::NodePublic, *localPubKey_); } } @@ -229,8 +217,7 @@ ValidatorList::load( return false; } - auto const id = - parseBase58(TokenType::NodePublic, match[1].str()); + auto const id = parseBase58(TokenType::NodePublic, match[1].str()); if (!id) { @@ -264,9 +251,7 @@ ValidatorList::load( } boost::filesystem::path -ValidatorList::getCacheFileName( - ValidatorList::lock_guard const&, - PublicKey const& pubKey) const +ValidatorList::getCacheFileName(ValidatorList::lock_guard const&, PublicKey const& pubKey) const { return dataPath_ / (filePrefix_ + strHex(pubKey)); } @@ -294,8 +279,7 @@ ValidatorList::buildFileData( XRPL_ASSERT( pubCollection.rawVersion == 2 || pubCollection.remaining.empty(), "xrpl::ValidatorList::buildFileData : valid publisher list input"); - auto const effectiveVersion = - forceVersion ? *forceVersion : pubCollection.rawVersion; + auto const effectiveVersion = forceVersion ? *forceVersion : pubCollection.rawVersion; value[jss::manifest] = pubCollection.rawManifest; value[jss::version] = effectiveVersion; @@ -309,21 +293,18 @@ ValidatorList::buildFileData( value[jss::signature] = current.rawSignature; // This is only possible if "downgrading" a v2 UNL to v1, for // example for the /vl/ endpoint. - if (current.rawManifest && - *current.rawManifest != pubCollection.rawManifest) + if (current.rawManifest && *current.rawManifest != pubCollection.rawManifest) value[jss::manifest] = *current.rawManifest; break; } case 2: { Json::Value blobs(Json::arrayValue); - auto add = [&blobs, &outerManifest = pubCollection.rawManifest]( - PublisherList const& pubList) { + auto add = [&blobs, &outerManifest = pubCollection.rawManifest](PublisherList const& pubList) { auto& blob = blobs.append(Json::objectValue); blob[jss::blob] = pubList.rawBlob; blob[jss::signature] = pubList.rawSignature; - if (pubList.rawManifest && - *pubList.rawManifest != outerManifest) + if (pubList.rawManifest && *pubList.rawManifest != outerManifest) blob[jss::manifest] = *pubList.rawManifest; }; @@ -338,8 +319,7 @@ ValidatorList::buildFileData( break; } default: - JLOG(j.trace()) - << "Invalid VL version provided: " << effectiveVersion; + JLOG(j.trace()) << "Invalid VL version provided: " << effectiveVersion; value = Json::nullValue; } @@ -347,9 +327,7 @@ ValidatorList::buildFileData( } void -ValidatorList::cacheValidatorFile( - ValidatorList::lock_guard const& lock, - PublicKey const& pubKey) const +ValidatorList::cacheValidatorFile(ValidatorList::lock_guard const& lock, PublicKey const& pubKey) const { if (dataPath_.empty()) return; @@ -358,8 +336,7 @@ ValidatorList::cacheValidatorFile( boost::system::error_code ec; - Json::Value value = - buildFileData(strHex(pubKey), publisherLists_.at(pubKey), j_); + Json::Value value = buildFileData(strHex(pubKey), publisherLists_.at(pubKey), j_); // rippled should be the only process writing to this file, so // if it ever needs to be read, it is not expected to change externally, so // delay the refresh as long as possible: 24 hours. (See also @@ -371,8 +348,7 @@ ValidatorList::cacheValidatorFile( if (ec) { // Log and ignore any file I/O exceptions - JLOG(j_.error()) << "Problem writing " << filename << " " << ec.value() - << ": " << ec.message(); + JLOG(j_.error()) << "Problem writing " << filename << " " << ec.value() << ": " << ec.message(); } } @@ -384,8 +360,7 @@ ValidatorList::parseBlobs(std::uint32_t version, Json::Value const& body) switch (version) { case 1: { - if (!body.isMember(jss::blob) || !body[jss::blob].isString() || - !body.isMember(jss::signature) || + if (!body.isMember(jss::blob) || !body[jss::blob].isString() || !body.isMember(jss::signature) || !body[jss::signature].isString() || // If the v2 field is present, the VL is malformed body.isMember(jss::blobs_v2)) @@ -393,9 +368,7 @@ ValidatorList::parseBlobs(std::uint32_t version, Json::Value const& body) ValidatorBlobInfo& info = result.emplace_back(); info.blob = body[jss::blob].asString(); info.signature = body[jss::signature].asString(); - XRPL_ASSERT( - result.size() == 1, - "xrpl::ValidatorList::parseBlobs : single element result"); + XRPL_ASSERT(result.size() == 1, "xrpl::ValidatorList::parseBlobs : single element result"); return result; } // Treat unknown versions as if they're the latest version. This @@ -404,8 +377,7 @@ ValidatorList::parseBlobs(std::uint32_t version, Json::Value const& body) // validated elsewhere. case 2: default: { - if (!body.isMember(jss::blobs_v2) || - !body[jss::blobs_v2].isArray() || + if (!body.isMember(jss::blobs_v2) || !body[jss::blobs_v2].isArray() || body[jss::blobs_v2].size() > maxSupportedBlobs || // If any of the v1 fields are present, the VL is malformed body.isMember(jss::blob) || body.isMember(jss::signature)) @@ -414,10 +386,8 @@ ValidatorList::parseBlobs(std::uint32_t version, Json::Value const& body) result.reserve(blobs.size()); for (auto const& blobInfo : blobs) { - if (!blobInfo.isObject() || - !blobInfo.isMember(jss::signature) || - !blobInfo[jss::signature].isString() || - !blobInfo.isMember(jss::blob) || + if (!blobInfo.isObject() || !blobInfo.isMember(jss::signature) || + !blobInfo[jss::signature].isString() || !blobInfo.isMember(jss::blob) || !blobInfo[jss::blob].isString()) return {}; ValidatorBlobInfo& info = result.emplace_back(); @@ -524,13 +494,9 @@ splitMessageParts( smallMsg.set_manifest(blob.manifest()); XRPL_ASSERT( - Message::totalSize(smallMsg) <= maximumMessageSize, - "xrpl::splitMessageParts : maximum message size"); + Message::totalSize(smallMsg) <= maximumMessageSize, "xrpl::splitMessageParts : maximum message size"); - messages.emplace_back( - std::make_shared(smallMsg, protocol::mtVALIDATOR_LIST), - sha512Half(smallMsg), - 1); + messages.emplace_back(std::make_shared(smallMsg, protocol::mtVALIDATOR_LIST), sha512Half(smallMsg), 1); return messages.back().numVLs; } else @@ -554,8 +520,7 @@ splitMessageParts( else { messages.emplace_back( - std::make_shared( - *smallMsg, protocol::mtVALIDATOR_LIST_COLLECTION), + std::make_shared(*smallMsg, protocol::mtVALIDATOR_LIST_COLLECTION), sha512Half(*smallMsg), smallMsg->blobs_size()); return messages.back().numVLs; @@ -578,8 +543,7 @@ buildValidatorListMessage( "xrpl::buildValidatorListMessage(ValidatorBlobInfo) : empty messages " "input"); protocol::TMValidatorList msg; - auto const manifest = - currentBlob.manifest ? *currentBlob.manifest : rawManifest; + auto const manifest = currentBlob.manifest ? *currentBlob.manifest : rawManifest; auto const version = 1; msg.set_manifest(manifest); msg.set_blob(currentBlob.blob); @@ -591,10 +555,7 @@ buildValidatorListMessage( Message::totalSize(msg) <= maximumMessageSize, "xrpl::buildValidatorListMessage(ValidatorBlobInfo) : maximum " "message size"); - messages.emplace_back( - std::make_shared(msg, protocol::mtVALIDATOR_LIST), - sha512Half(msg), - 1); + messages.emplace_back(std::make_shared(msg, protocol::mtVALIDATOR_LIST), sha512Half(msg), 1); return 1; } @@ -640,10 +601,7 @@ buildValidatorListMessage( else { messages.emplace_back( - std::make_shared( - msg, protocol::mtVALIDATOR_LIST_COLLECTION), - sha512Half(msg), - msg.blobs_size()); + std::make_shared(msg, protocol::mtVALIDATOR_LIST_COLLECTION), sha512Half(msg), msg.blobs_size()); return messages.back().numVLs; } } @@ -666,25 +624,15 @@ ValidatorList::buildValidatorListMessages( "xrpl::ValidatorList::buildValidatorListMessages : empty messages " "input"); auto const& [currentSeq, currentBlob] = *blobInfos.begin(); - auto numVLs = std::accumulate( - messages.begin(), - messages.end(), - 0, - [](std::size_t total, MessageWithHash const& m) { - return total + m.numVLs; - }); + auto numVLs = std::accumulate(messages.begin(), messages.end(), 0, [](std::size_t total, MessageWithHash const& m) { + return total + m.numVLs; + }); if (messageVersion == 2 && peerSequence < maxSequence) { // Version 2 if (messages.empty()) { - numVLs = buildValidatorListMessage( - messages, - peerSequence, - rawVersion, - rawManifest, - blobInfos, - maxSize); + numVLs = buildValidatorListMessage(messages, peerSequence, rawVersion, rawManifest, blobInfos, maxSize); if (messages.empty()) // No message was generated. Create an empty placeholder so we // dont' repeat the work later. @@ -700,11 +648,7 @@ ValidatorList::buildValidatorListMessages( if (messages.empty()) { numVLs = buildValidatorListMessage( - messages, - rawVersion, - currentBlob.manifest ? *currentBlob.manifest : rawManifest, - currentBlob, - maxSize); + messages, rawVersion, currentBlob.manifest ? *currentBlob.manifest : rawManifest, currentBlob, maxSize); if (messages.empty()) // No message was generated. Create an empty placeholder so we // dont' repeat the work later. @@ -731,20 +675,13 @@ ValidatorList::sendValidatorList( HashRouter& hashRouter, beast::Journal j) { - std::size_t const messageVersion = - peer.supportsFeature(ProtocolFeature::ValidatorList2Propagation) ? 2 - : peer.supportsFeature(ProtocolFeature::ValidatorListPropagation) ? 1 - : 0; + std::size_t const messageVersion = peer.supportsFeature(ProtocolFeature::ValidatorList2Propagation) ? 2 + : peer.supportsFeature(ProtocolFeature::ValidatorListPropagation) ? 1 + : 0; if (!messageVersion) return; auto const [newPeerSequence, numVLs] = buildValidatorListMessages( - messageVersion, - peerSequence, - maxSequence, - rawVersion, - rawManifest, - blobInfos, - messages); + messageVersion, peerSequence, maxSequence, rawVersion, rawManifest, blobInfos, messages); if (newPeerSequence) { XRPL_ASSERT( @@ -766,28 +703,21 @@ ValidatorList::sendValidatorList( } // The only way sent wil be false is if the messages was too big, and // thus there will only be one entry without a message - XRPL_ASSERT( - sent || messages.size() == 1, - "xrpl::ValidatorList::sendValidatorList : sent or one message"); + XRPL_ASSERT(sent || messages.size() == 1, "xrpl::ValidatorList::sendValidatorList : sent or one message"); if (sent) { if (messageVersion > 1) - JLOG(j.debug()) - << "Sent " << messages.size() - << " validator list collection(s) containing " << numVLs - << " validator list(s) for " << strHex(publisherKey) - << " with sequence range " << peerSequence << ", " - << newPeerSequence << " to " << peer.fingerprint(); + JLOG(j.debug()) << "Sent " << messages.size() << " validator list collection(s) containing " << numVLs + << " validator list(s) for " << strHex(publisherKey) << " with sequence range " + << peerSequence << ", " << newPeerSequence << " to " << peer.fingerprint(); else { XRPL_ASSERT( numVLs == 1, "xrpl::ValidatorList::sendValidatorList : one validator " "list"); - JLOG(j.debug()) - << "Sent validator list for " << strHex(publisherKey) - << " with sequence " << newPeerSequence << " to " - << peer.fingerprint(); + JLOG(j.debug()) << "Sent validator list for " << strHex(publisherKey) << " with sequence " + << newPeerSequence << " to " << peer.fingerprint(); } } } @@ -808,16 +738,7 @@ ValidatorList::sendValidatorList( { std::vector messages; sendValidatorList( - peer, - peerSequence, - publisherKey, - maxSequence, - rawVersion, - rawManifest, - blobInfos, - messages, - hashRouter, - j); + peer, peerSequence, publisherKey, maxSequence, rawVersion, rawManifest, blobInfos, messages, hashRouter, j); } // static @@ -828,8 +749,7 @@ ValidatorList::buildBlobInfos( { auto const& current = lists.current; auto const& remaining = lists.remaining; - blobInfos[current.sequence] = { - current.rawBlob, current.rawSignature, current.rawManifest}; + blobInfos[current.sequence] = {current.rawBlob, current.rawSignature, current.rawManifest}; for (auto const& [sequence, vl] : remaining) { blobInfos[sequence] = {vl.rawBlob, vl.rawSignature, vl.rawManifest}; @@ -838,8 +758,7 @@ ValidatorList::buildBlobInfos( // static std::map -ValidatorList::buildBlobInfos( - ValidatorList::PublisherListCollection const& lists) +ValidatorList::buildBlobInfos(ValidatorList::PublisherListCollection const& lists) { std::map result; buildBlobInfos(result, lists); @@ -871,15 +790,13 @@ ValidatorList::broadcastBlobs( // This will hold v2 messages indexed by the peer's // `publisherListSequence`. For each `publisherListSequence`, we'll // only send the VLs with higher sequences. - std::map> - messages2; + std::map> messages2; // If any peers are found that are worth considering, this list will // be built to hold info for all of the valid VLs. std::map blobInfos; XRPL_ASSERT( - lists.current.sequence == maxSequence || - lists.remaining.count(maxSequence) == 1, + lists.current.sequence == maxSequence || lists.remaining.count(maxSequence) == 1, "xrpl::ValidatorList::broadcastBlobs : valid sequence"); // Can't use overlay.foreach here because we need to modify // the peer, and foreach provides a const& @@ -887,14 +804,12 @@ ValidatorList::broadcastBlobs( { if (toSkip->count(peer->id()) == 0) { - auto const peerSequence = - peer->publisherListSequence(publisherKey).value_or(0); + auto const peerSequence = peer->publisherListSequence(publisherKey).value_or(0); if (peerSequence < maxSequence) { if (blobInfos.empty()) buildBlobInfos(blobInfos, lists); - auto const v2 = peer->supportsFeature( - ProtocolFeature::ValidatorList2Propagation); + auto const v2 = peer->supportsFeature(ProtocolFeature::ValidatorList2Propagation); sendValidatorList( *peer, peerSequence, @@ -926,8 +841,7 @@ ValidatorList::applyListsAndBroadcast( HashRouter& hashRouter, NetworkOPs& networkOPs) { - auto const result = - applyLists(manifest, version, blobs, std::move(siteUri), hash); + auto const result = applyLists(manifest, version, blobs, std::move(siteUri), hash); auto const disposition = result.bestDisposition(); if (disposition == ListDisposition::accepted) @@ -954,20 +868,12 @@ ValidatorList::applyListsAndBroadcast( // this function is only called for PublicKeys which are not specified // in the config file (Note: Keys specified in the local config file are // stored in ValidatorList::localPublisherList data member). - if (broadcast && result.status <= PublisherStatus::expired && - result.publisherKey && + if (broadcast && result.status <= PublisherStatus::expired && result.publisherKey && publisherLists_[*result.publisherKey].maxSequence) { auto const& pubCollection = publisherLists_[*result.publisherKey]; - broadcastBlobs( - *result.publisherKey, - pubCollection, - *pubCollection.maxSequence, - hash, - overlay, - hashRouter, - j_); + broadcastBlobs(*result.publisherKey, pubCollection, *pubCollection.maxSequence, hash, overlay, hashRouter, j_); } return result; @@ -981,10 +887,7 @@ ValidatorList::applyLists( std::string siteUri, std::optional const& hash /* = {} */) { - if (std::count( - std::begin(supportedListVersions), - std::end(supportedListVersions), - version) != 1) + if (std::count(std::begin(supportedListVersions), std::end(supportedListVersions), version) != 1) return PublisherListStats{ListDisposition::unsupported_version}; std::lock_guard lock{mutex_}; @@ -992,19 +895,11 @@ ValidatorList::applyLists( PublisherListStats result; for (auto const& blobInfo : blobs) { - auto stats = applyList( - manifest, - blobInfo.manifest, - blobInfo.blob, - blobInfo.signature, - version, - siteUri, - hash, - lock); + auto stats = + applyList(manifest, blobInfo.manifest, blobInfo.blob, blobInfo.signature, version, siteUri, hash, lock); if (stats.bestDisposition() < result.bestDisposition() || - (stats.bestDisposition() == result.bestDisposition() && - stats.sequence > result.sequence)) + (stats.bestDisposition() == result.bestDisposition() && stats.sequence > result.sequence)) { stats.mergeDispositions(result); result = std::move(stats); @@ -1028,8 +923,7 @@ ValidatorList::applyLists( next == remaining.end() || next->first > iter->first, "xrpl::ValidatorList::applyLists : next is valid"); if (iter->first <= current.sequence || - (next != remaining.end() && - next->second.validFrom <= iter->second.validFrom)) + (next != remaining.end() && next->second.validFrom <= iter->second.validFrom)) { iter = remaining.erase(iter); } @@ -1063,16 +957,13 @@ ValidatorList::updatePublisherList( auto iOld = oldList.begin(); while (iNew != publisherList.end() || iOld != oldList.end()) { - if (iOld == oldList.end() || - (iNew != publisherList.end() && *iNew < *iOld)) + if (iOld == oldList.end() || (iNew != publisherList.end() && *iNew < *iOld)) { // Increment list count for added keys ++keyListings_[*iNew]; ++iNew; } - else if ( - iNew == publisherList.end() || - (iOld != oldList.end() && *iOld < *iNew)) + else if (iNew == publisherList.end() || (iOld != oldList.end() && *iOld < *iNew)) { // Decrement list count for removed keys if (keyListings_[*iOld] <= 1) @@ -1099,16 +990,13 @@ ValidatorList::updatePublisherList( if (!m || !keyListings_.count(m->masterKey)) { - JLOG(j_.warn()) << "List for " << strHex(pubKey) - << " contained untrusted validator manifest"; + JLOG(j_.warn()) << "List for " << strHex(pubKey) << " contained untrusted validator manifest"; continue; } - if (auto const r = validatorManifests_.applyManifest(std::move(*m)); - r == ManifestDisposition::invalid) + if (auto const r = validatorManifests_.applyManifest(std::move(*m)); r == ManifestDisposition::invalid) { - JLOG(j_.warn()) << "List for " << strHex(pubKey) - << " contained invalid validator manifest"; + JLOG(j_.warn()) << "List for " << strHex(pubKey) << " contained invalid validator manifest"; } } } @@ -1135,13 +1023,11 @@ ValidatorList::applyList( return PublisherListStats{ListDisposition::invalid}; } - auto [result, pubKeyOpt] = - verify(lock, list, std::move(*m), blob, signature); + auto [result, pubKeyOpt] = verify(lock, list, std::move(*m), blob, signature); if (!pubKeyOpt) { - JLOG(j_.warn()) - << "UNL manifest is signed with an unrecognized master public key"; + JLOG(j_.warn()) << "UNL manifest is signed with an unrecognized master public key"; return PublisherListStats{result}; } @@ -1164,16 +1050,11 @@ ValidatorList::applyList( { auto const& pubCollection = publisherLists_[pubKey]; if (pubCollection.maxSequence && - (result == ListDisposition::same_sequence || - result == ListDisposition::known_sequence)) + (result == ListDisposition::same_sequence || result == ListDisposition::known_sequence)) { // We've seen something valid list for this publisher // already, so return what we know about it. - return PublisherListStats{ - result, - pubKey, - pubCollection.status, - *pubCollection.maxSequence}; + return PublisherListStats{result, pubKey, pubCollection.status, *pubCollection.maxSequence}; } } return PublisherListStats{result}; @@ -1182,14 +1063,11 @@ ValidatorList::applyList( // Update publisher's list auto& pubCollection = publisherLists_[pubKey]; auto const sequence = list[jss::sequence].asUInt(); - auto const accepted = - (result == ListDisposition::accepted || - result == ListDisposition::expired); + auto const accepted = (result == ListDisposition::accepted || result == ListDisposition::expired); if (accepted) - pubCollection.status = result == ListDisposition::accepted - ? PublisherStatus::available - : PublisherStatus::expired; + pubCollection.status = + result == ListDisposition::accepted ? PublisherStatus::available : PublisherStatus::expired; pubCollection.rawManifest = globalManifest; if (!pubCollection.maxSequence || sequence > *pubCollection.maxSequence) pubCollection.maxSequence = sequence; @@ -1211,19 +1089,15 @@ ValidatorList::applyList( // Remove the entry in "remaining" pubCollection.remaining.erase(sequence); // Done - XRPL_ASSERT( - publisher.sequence == sequence, - "xrpl::ValidatorList::applyList : publisher sequence match"); + XRPL_ASSERT(publisher.sequence == sequence, "xrpl::ValidatorList::applyList : publisher sequence match"); } else { - auto& publisher = accepted ? pubCollection.current - : pubCollection.remaining[sequence]; + auto& publisher = accepted ? pubCollection.current : pubCollection.remaining[sequence]; publisher.sequence = sequence; - publisher.validFrom = TimeKeeper::time_point{TimeKeeper::duration{ - list.isMember(jss::effective) ? list[jss::effective].asUInt() : 0}}; - publisher.validUntil = TimeKeeper::time_point{ - TimeKeeper::duration{list[jss::expiration].asUInt()}}; + publisher.validFrom = TimeKeeper::time_point{ + TimeKeeper::duration{list.isMember(jss::effective) ? list[jss::effective].asUInt() : 0}}; + publisher.validUntil = TimeKeeper::time_point{TimeKeeper::duration{list[jss::expiration].asUInt()}}; publisher.siteUri = std::move(siteUri); publisher.rawBlob = blob; publisher.rawSignature = signature; @@ -1244,23 +1118,18 @@ ValidatorList::applyList( if (val.isObject() && val.isMember(jss::validation_public_key) && val[jss::validation_public_key].isString()) { - std::optional const ret = - strUnHex(val[jss::validation_public_key].asString()); + std::optional const ret = strUnHex(val[jss::validation_public_key].asString()); if (!ret || !publicKeyType(makeSlice(*ret))) { - JLOG(j_.error()) - << "Invalid node identity: " - << val[jss::validation_public_key].asString(); + JLOG(j_.error()) << "Invalid node identity: " << val[jss::validation_public_key].asString(); } else { - publisherList.push_back( - PublicKey(Slice{ret->data(), ret->size()})); + publisherList.push_back(PublicKey(Slice{ret->data(), ret->size()})); } - if (val.isMember(jss::manifest) && - val[jss::manifest].isString()) + if (val.isMember(jss::manifest) && val[jss::manifest].isString()) manifests.push_back(val[jss::manifest].asString()); } } @@ -1278,8 +1147,7 @@ ValidatorList::applyList( pubCollection.rawVersion = std::max(pubCollection.rawVersion, 2u); } - PublisherListStats const applyResult{ - result, pubKey, pubCollection.status, *pubCollection.maxSequence}; + PublisherListStats const applyResult{result, pubKey, pubCollection.status, *pubCollection.maxSequence}; if (accepted) { @@ -1381,16 +1249,14 @@ ValidatorList::verify( if (!r.parse(data, list)) return {ListDisposition::invalid, masterPubKey}; - if (list.isMember(jss::sequence) && list[jss::sequence].isInt() && - list.isMember(jss::expiration) && list[jss::expiration].isInt() && - (!list.isMember(jss::effective) || list[jss::effective].isInt()) && + if (list.isMember(jss::sequence) && list[jss::sequence].isInt() && list.isMember(jss::expiration) && + list[jss::expiration].isInt() && (!list.isMember(jss::effective) || list[jss::effective].isInt()) && list.isMember(jss::validators) && list[jss::validators].isArray()) { auto const sequence = list[jss::sequence].asUInt(); - auto const validFrom = TimeKeeper::time_point{TimeKeeper::duration{ - list.isMember(jss::effective) ? list[jss::effective].asUInt() : 0}}; - auto const validUntil = TimeKeeper::time_point{ - TimeKeeper::duration{list[jss::expiration].asUInt()}}; + auto const validFrom = TimeKeeper::time_point{ + TimeKeeper::duration{list.isMember(jss::effective) ? list[jss::effective].asUInt() : 0}}; + auto const validUntil = TimeKeeper::time_point{TimeKeeper::duration{list[jss::expiration].asUInt()}}; auto const now = timeKeeper_.now(); auto const& listCollection = publisherLists_[masterPubKey]; if (validUntil <= validFrom) @@ -1412,12 +1278,9 @@ ValidatorList::verify( // order. This may result in some duplicated processing, but // prevents the risk of missing valid data. Else return // known_sequence - return !listCollection.maxSequence || - sequence > *listCollection.maxSequence || + return !listCollection.maxSequence || sequence > *listCollection.maxSequence || (listCollection.remaining.count(sequence) == 0 && - validFrom < listCollection.remaining - .at(*listCollection.maxSequence) - .validFrom) + validFrom < listCollection.remaining.at(*listCollection.maxSequence).validFrom) ? std::make_pair(ListDisposition::pending, masterPubKey) : std::make_pair(ListDisposition::known_sequence, masterPubKey); } @@ -1439,9 +1302,7 @@ ValidatorList::listed(PublicKey const& identity) const } bool -ValidatorList::trusted( - ValidatorList::shared_lock const&, - PublicKey const& identity) const +ValidatorList::trusted(ValidatorList::shared_lock const&, PublicKey const& identity) const { auto const pubKey = validatorManifests_.getMasterKey(identity); return trustedMasterKeys_.find(pubKey) != trustedMasterKeys_.end(); @@ -1466,9 +1327,7 @@ ValidatorList::getListedKey(PublicKey const& identity) const } std::optional -ValidatorList::getTrustedKey( - ValidatorList::shared_lock const&, - PublicKey const& identity) const +ValidatorList::getTrustedKey(ValidatorList::shared_lock const&, PublicKey const& identity) const { auto const pubKey = validatorManifests_.getMasterKey(identity); if (trustedMasterKeys_.find(pubKey) != trustedMasterKeys_.end()) @@ -1506,15 +1365,13 @@ ValidatorList::removePublisherList( PublisherStatus reason) { XRPL_ASSERT( - reason != PublisherStatus::available && - reason != PublisherStatus::unavailable, + reason != PublisherStatus::available && reason != PublisherStatus::unavailable, "xrpl::ValidatorList::removePublisherList : valid reason input"); auto const iList = publisherLists_.find(publisherKey); if (iList == publisherLists_.end()) return false; - JLOG(j_.debug()) << "Removing validator list for publisher " - << strHex(publisherKey); + JLOG(j_.debug()) << "Removing validator list for publisher " << strHex(publisherKey); for (auto const& val : iList->second.current.list) { @@ -1644,29 +1501,24 @@ ValidatorList::getJson() const } // Validator keys listed in the local config file - Json::Value& jLocalStaticKeys = - (res[jss::local_static_keys] = Json::arrayValue); + Json::Value& jLocalStaticKeys = (res[jss::local_static_keys] = Json::arrayValue); for (auto const& key : localPublisherList.list) jLocalStaticKeys.append(toBase58(TokenType::NodePublic, key)); // Publisher lists - Json::Value& jPublisherLists = - (res[jss::publisher_lists] = Json::arrayValue); + Json::Value& jPublisherLists = (res[jss::publisher_lists] = Json::arrayValue); for (auto const& [publicKey, pubCollection] : publisherLists_) { Json::Value& curr = jPublisherLists.append(Json::objectValue); curr[jss::pubkey_publisher] = strHex(publicKey); - curr[jss::available] = - pubCollection.status == PublisherStatus::available; + curr[jss::available] = pubCollection.status == PublisherStatus::available; - auto appendList = [](PublisherList const& publisherList, - Json::Value& target) { + auto appendList = [](PublisherList const& publisherList, Json::Value& target) { target[jss::uri] = publisherList.siteUri; if (publisherList.validUntil != TimeKeeper::time_point{}) { - target[jss::seq] = - static_cast(publisherList.sequence); + target[jss::seq] = static_cast(publisherList.sequence); target[jss::expiration] = to_string(publisherList.validUntil); } if (publisherList.validFrom != TimeKeeper::time_point{}) @@ -1696,16 +1548,14 @@ ValidatorList::getJson() const appendList(future, r); // Race conditions can happen, so make this check "fuzzy" XRPL_ASSERT( - future.validFrom > timeKeeper_.now() + 600s, - "xrpl::ValidatorList::getJson : minimum valid from"); + future.validFrom > timeKeeper_.now() + 600s, "xrpl::ValidatorList::getJson : minimum valid from"); } if (remaining.size()) curr[jss::remaining] = std::move(remaining); } // Trusted validator keys - Json::Value& jValidatorKeys = - (res[jss::trusted_validator_keys] = Json::arrayValue); + Json::Value& jValidatorKeys = (res[jss::trusted_validator_keys] = Json::arrayValue); for (auto const& k : trustedMasterKeys_) { jValidatorKeys.append(toBase58(TokenType::NodePublic, k)); @@ -1713,8 +1563,7 @@ ValidatorList::getJson() const // signing keys Json::Value& jSigningKeys = (res[jss::signing_keys] = Json::objectValue); - validatorManifests_.for_each_manifest([&jSigningKeys, - this](Manifest const& manifest) { + validatorManifests_.for_each_manifest([&jSigningKeys, this](Manifest const& manifest) { auto it = keyListings_.find(manifest.masterKey); if (it != keyListings_.end() && manifest.signingKey) { @@ -1737,8 +1586,7 @@ ValidatorList::getJson() const } void -ValidatorList::for_each_listed( - std::function func) const +ValidatorList::for_each_listed(std::function func) const { std::shared_lock read_lock{mutex_}; @@ -1747,14 +1595,13 @@ ValidatorList::for_each_listed( } void -ValidatorList::for_each_available( - std::function const& blobInfos, - PublicKey const& pubKey, - std::size_t maxSequence, - uint256 const& hash)> func) const +ValidatorList::for_each_available(std::function const& blobInfos, + PublicKey const& pubKey, + std::size_t maxSequence, + uint256 const& hash)> func) const { std::shared_lock read_lock{mutex_}; @@ -1762,9 +1609,7 @@ ValidatorList::for_each_available( { if (plCollection.status != PublisherStatus::available) continue; - XRPL_ASSERT( - plCollection.maxSequence != 0, - "xrpl::ValidatorList::for_each_available : nonzero maxSequence"); + XRPL_ASSERT(plCollection.maxSequence != 0, "xrpl::ValidatorList::for_each_available : nonzero maxSequence"); func( plCollection.rawManifest, plCollection.rawVersion, @@ -1776,9 +1621,7 @@ ValidatorList::for_each_available( } std::optional -ValidatorList::getAvailable( - std::string_view pubKey, - std::optional forceVersion /* = {} */) +ValidatorList::getAvailable(std::string_view pubKey, std::optional forceVersion /* = {} */) { std::shared_lock read_lock{mutex_}; @@ -1786,8 +1629,7 @@ ValidatorList::getAvailable( if (!keyBlob || !publicKeyType(makeSlice(*keyBlob))) { - JLOG(j_.warn()) << "Invalid requested validator list publisher key: " - << pubKey; + JLOG(j_.warn()) << "Invalid requested validator list publisher key: " << pubKey; return {}; } @@ -1795,27 +1637,21 @@ ValidatorList::getAvailable( auto const iter = publisherLists_.find(id); - if (iter == publisherLists_.end() || - iter->second.status != PublisherStatus::available) + if (iter == publisherLists_.end() || iter->second.status != PublisherStatus::available) return {}; - Json::Value value = - buildFileData(std::string{pubKey}, iter->second, forceVersion, j_); + Json::Value value = buildFileData(std::string{pubKey}, iter->second, forceVersion, j_); return value; } std::size_t -ValidatorList::calculateQuorum( - std::size_t unlSize, - std::size_t effectiveUnlSize, - std::size_t seenSize) +ValidatorList::calculateQuorum(std::size_t unlSize, std::size_t effectiveUnlSize, std::size_t seenSize) { // Use quorum if specified via command line. if (minimumQuorum_ > 0) { - JLOG(j_.warn()) << "Using potentially unsafe quorum of " - << *minimumQuorum_ + JLOG(j_.warn()) << "Using potentially unsafe quorum of " << *minimumQuorum_ << " as specified on the command line"; return *minimumQuorum_; } @@ -1852,9 +1688,7 @@ ValidatorList::calculateQuorum( auto const errorThreshold = std::min( listThreshold_, // publisherLists_.size() - listThreshold_ + 1); - XRPL_ASSERT( - errorThreshold > 0, - "xrpl::ValidatorList::calculateQuorum : nonzero error threshold"); + XRPL_ASSERT(errorThreshold > 0, "xrpl::ValidatorList::calculateQuorum : nonzero error threshold"); if (unavailable >= errorThreshold) return std::numeric_limits::max(); } @@ -1893,8 +1727,7 @@ ValidatorList::calculateQuorum( // Note that the negative UNL protocol introduced the // AbsoluteMinimumQuorum which is 60% of the original UNL size. The // effective quorum should not be lower than it. - return static_cast(std::max( - std::ceil(effectiveUnlSize * 0.8f), std::ceil(unlSize * 0.6f))); + return static_cast(std::max(std::ceil(effectiveUnlSize * 0.8f), std::ceil(unlSize * 0.6f))); } TrustChanges @@ -1925,8 +1758,7 @@ ValidatorList::updateTrusted( if (iter != remaining.end() && iter->second.validFrom <= closeTime) { // Find the LAST candidate that is ready to go live. - for (auto next = std::next(iter); next != remaining.end() && - next->second.validFrom <= closeTime; + for (auto next = std::next(iter); next != remaining.end() && next->second.validFrom <= closeTime; ++iter, ++next) { XRPL_ASSERT( @@ -1943,17 +1775,13 @@ ValidatorList::updateTrusted( auto sequence = iter->first; auto& candidate = iter->second; auto& current = collection.current; - XRPL_ASSERT( - candidate.validFrom <= closeTime, - "xrpl::ValidatorList::updateTrusted : maximum time"); + XRPL_ASSERT(candidate.validFrom <= closeTime, "xrpl::ValidatorList::updateTrusted : maximum time"); auto const oldList = current.list; current = std::move(candidate); if (collection.status != PublisherStatus::available) collection.status = PublisherStatus::available; - XRPL_ASSERT( - current.sequence == sequence, - "xrpl::ValidatorList::updateTrusted : sequence match"); + XRPL_ASSERT(current.sequence == sequence, "xrpl::ValidatorList::updateTrusted : sequence match"); // If the list is expired, remove the validators so they don't // get processed in. The expiration check below will do the rest // of the work @@ -1967,14 +1795,7 @@ ValidatorList::updateTrusted( // unknown (unlikely). Those that do understand v2 should // already have this list and are in the process of // switching themselves. - broadcastBlobs( - pubKey, - collection, - sequence, - current.hash, - overlay, - hashRouter, - j_); + broadcastBlobs(pubKey, collection, sequence, current.hash, overlay, hashRouter, j_); // Erase any candidates that we skipped over, plus this one remaining.erase(firstIter, std::next(iter)); @@ -1983,8 +1804,7 @@ ValidatorList::updateTrusted( // Remove if expired // ValidatorLists specified in the local config file never expire. // Hence, the below steps are not relevant for localPublisherList - if (collection.status == PublisherStatus::available && - collection.current.validUntil <= closeTime) + if (collection.status == PublisherStatus::available && collection.current.validUntil <= closeTime) { removePublisherList(lock, pubKey, PublisherStatus::expired); ops.setUNLBlocked(); @@ -2010,17 +1830,14 @@ ValidatorList::updateTrusted( } else { - XRPL_ASSERT( - kit->second >= listThreshold_, - "xrpl::ValidatorList::updateTrusted : count meets threshold"); + XRPL_ASSERT(kit->second >= listThreshold_, "xrpl::ValidatorList::updateTrusted : count meets threshold"); ++it; } } for (auto const& val : keyListings_) { - if (val.second >= listThreshold_ && - !validatorManifests_.revoked(val.first) && + if (val.second >= listThreshold_ && !validatorManifests_.revoked(val.first) && trustedMasterKeys_.emplace(val.first).second) trustChanges.added.insert(calcNodeID(val.first)); } @@ -2035,18 +1852,14 @@ ValidatorList::updateTrusted( // manifests must contain a valid signingKey for (auto const& k : trustedMasterKeys_) { - std::optional const signingKey = - validatorManifests_.getSigningKey(k); - XRPL_ASSERT( - signingKey, - "xrpl::ValidatorList::updateTrusted : found signing key"); + std::optional const signingKey = validatorManifests_.getSigningKey(k); + XRPL_ASSERT(signingKey, "xrpl::ValidatorList::updateTrusted : found signing key"); trustedSigningKeys_.insert(*signingKey); } } - JLOG(j_.debug()) - << trustedMasterKeys_.size() << " of " << keyListings_.size() - << " listed validators eligible for inclusion in the trusted set"; + JLOG(j_.debug()) << trustedMasterKeys_.size() << " of " << keyListings_.size() + << " listed validators eligible for inclusion in the trusted set"; auto const unlSize = trustedMasterKeys_.size(); auto effectiveUnlSize = unlSize; @@ -2071,20 +1884,16 @@ ValidatorList::updateTrusted( } quorum_ = calculateQuorum(unlSize, effectiveUnlSize, seenSize); - JLOG(j_.debug()) << "Using quorum of " << quorum_ << " for new set of " - << unlSize << " trusted validators (" - << trustChanges.added.size() << " added, " - << trustChanges.removed.size() << " removed)"; + JLOG(j_.debug()) << "Using quorum of " << quorum_ << " for new set of " << unlSize << " trusted validators (" + << trustChanges.added.size() << " added, " << trustChanges.removed.size() << " removed)"; if (unlSize < quorum_) { - JLOG(j_.warn()) << "New quorum of " << quorum_ - << " exceeds the number of trusted validators (" - << unlSize << ")"; + JLOG(j_.warn()) << "New quorum of " << quorum_ << " exceeds the number of trusted validators (" << unlSize + << ")"; } - if ((publisherLists_.size() || localPublisherList.list.size()) && - unlSize == 0) + if ((publisherLists_.size() || localPublisherList.list.size()) && unlSize == 0) { // No validators. Lock down. ops.setUNLBlocked(); @@ -2122,8 +1931,7 @@ ValidatorList::setNegativeUNL(hash_set const& negUnl) } std::vector> -ValidatorList::negativeUNLFilter( - std::vector>&& validations) const +ValidatorList::negativeUNLFilter(std::vector>&& validations) const { // Remove validations that are from validators on the negative UNL. auto ret = std::move(validations); @@ -2136,9 +1944,7 @@ ValidatorList::negativeUNLFilter( ret.begin(), ret.end(), [&](auto const& v) -> bool { - if (auto const masterKey = - getTrustedKey(read_lock, v->getSignerPublic()); - masterKey) + if (auto const masterKey = getTrustedKey(read_lock, v->getSignerPublic()); masterKey) { return negativeUNL_.count(*masterKey); } diff --git a/src/xrpld/app/misc/detail/ValidatorSite.cpp b/src/xrpld/app/misc/detail/ValidatorSite.cpp index a76980ac02..7d440028cf 100644 --- a/src/xrpld/app/misc/detail/ValidatorSite.cpp +++ b/src/xrpld/app/misc/detail/ValidatorSite.cpp @@ -66,10 +66,7 @@ ValidatorSite::Site::Site(std::string uri) { } -ValidatorSite::ValidatorSite( - Application& app, - std::optional j, - std::chrono::seconds timeout) +ValidatorSite::ValidatorSite(Application& app, std::optional j, std::chrono::seconds timeout) : app_{app} , j_{j ? *j : app_.logs().journal("ValidatorSite")} , timer_{app_.getIOContext()} @@ -115,9 +112,7 @@ ValidatorSite::load(std::vector const& siteURIs) } bool -ValidatorSite::load( - std::vector const& siteURIs, - std::lock_guard const& lock_sites) +ValidatorSite::load(std::vector const& siteURIs, std::lock_guard const& lock_sites) { // If no sites are provided, act as if a site failed to load. if (siteURIs.empty()) @@ -133,8 +128,7 @@ ValidatorSite::load( } catch (std::exception const& e) { - JLOG(j_.error()) - << "Invalid validator site uri: " << uri << ": " << e.what(); + JLOG(j_.error()) << "Invalid validator site uri: " << uri << ": " << e.what(); return false; } } @@ -187,14 +181,10 @@ ValidatorSite::stop() } void -ValidatorSite::setTimer( - std::lock_guard const& site_lock, - std::lock_guard const& state_lock) +ValidatorSite::setTimer(std::lock_guard const& site_lock, std::lock_guard const& state_lock) { auto next = std::min_element( - sites_.begin(), sites_.end(), [](Site const& a, Site const& b) { - return a.nextRefresh < b.nextRefresh; - }); + sites_.begin(), sites_.end(), [](Site const& a, Site const& b) { return a.nextRefresh < b.nextRefresh; }); if (next != sites_.end()) { @@ -202,9 +192,7 @@ ValidatorSite::setTimer( cv_.notify_all(); timer_.expires_at(next->nextRefresh); auto idx = std::distance(sites_.begin(), next); - timer_.async_wait([this, idx](boost::system::error_code const& ec) { - this->onTimer(idx, ec); - }); + timer_.async_wait([this, idx](boost::system::error_code const& ec) { this->onTimer(idx, ec); }); } } @@ -230,15 +218,12 @@ ValidatorSite::makeRequest( } }; auto onFetch = [this, siteIdx, timeoutCancel]( - error_code const& err, - endpoint_type const& endpoint, - detail::response_type&& resp) { + error_code const& err, endpoint_type const& endpoint, detail::response_type&& resp) { timeoutCancel(); onSiteFetch(err, endpoint, std::move(resp), siteIdx); }; - auto onFetchFile = [this, siteIdx, timeoutCancel]( - error_code const& err, std::string const& resp) { + auto onFetchFile = [this, siteIdx, timeoutCancel](error_code const& err, std::string const& resp) { timeoutCancel(); onTextFetch(err, resp, siteIdx); }; @@ -273,8 +258,7 @@ ValidatorSite::makeRequest( else { BOOST_ASSERT(resource->pUrl.scheme == "file"); - sp = std::make_shared( - resource->pUrl.path, app_.getIOContext(), onFetchFile); + sp = std::make_shared(resource->pUrl.path, app_.getIOContext(), onFetchFile); } sites_[siteIdx].lastRequestSuccessful = false; @@ -284,9 +268,7 @@ ValidatorSite::makeRequest( // than requestTimeout_ to complete std::lock_guard lock_state{state_mutex_}; timer_.expires_after(requestTimeout_); - timer_.async_wait([this, siteIdx](boost::system::error_code const& ec) { - this->onRequestTimeout(siteIdx, ec); - }); + timer_.async_wait([this, siteIdx](boost::system::error_code const& ec) { this->onRequestTimeout(siteIdx, ec); }); } void @@ -305,8 +287,7 @@ ValidatorSite::onRequestTimeout(std::size_t siteIdx, error_code const& ec) // first, which will leave activeResource empty. auto const& site = sites_[siteIdx]; if (site.activeResource) - JLOG(j_.warn()) << "Request for " << site.activeResource->uri - << " took too long"; + JLOG(j_.warn()) << "Request for " << site.activeResource->uri << " took too long"; else JLOG(j_.error()) << "Request took too long, but a response has " "already been processed"; @@ -332,8 +313,7 @@ ValidatorSite::onTimer(std::size_t siteIdx, error_code const& ec) try { std::lock_guard lock{sites_mutex_}; - sites_[siteIdx].nextRefresh = - clock_type::now() + sites_[siteIdx].refreshInterval; + sites_[siteIdx].nextRefresh = clock_type::now() + sites_[siteIdx].refreshInterval; sites_[siteIdx].redirCount = 0; // the WorkSSL client ctor can throw if SSL init fails makeRequest(sites_[siteIdx].startingResource, siteIdx, lock); @@ -342,10 +322,7 @@ ValidatorSite::onTimer(std::size_t siteIdx, error_code const& ec) { JLOG(j_.error()) << "Exception in " << __func__ << ": " << ex.what(); onSiteFetch( - boost::system::error_code{-1, boost::system::generic_category()}, - {}, - detail::response_type{}, - siteIdx); + boost::system::error_code{-1, boost::system::generic_category()}, {}, detail::response_type{}, siteIdx); } } @@ -360,8 +337,7 @@ ValidatorSite::parseJsonResponse( Json::Value body; if (!r.parse(res.data(), body)) { - JLOG(j_.warn()) << "Unable to parse JSON response from " - << sites_[siteIdx].activeResource->uri; + JLOG(j_.warn()) << "Unable to parse JSON response from " << sites_[siteIdx].activeResource->uri; throw std::runtime_error{"bad json"}; } return body; @@ -369,9 +345,8 @@ ValidatorSite::parseJsonResponse( auto const [valid, version, blobs] = [&body]() { // Check the easy fields first - bool valid = body.isObject() && body.isMember(jss::manifest) && - body[jss::manifest].isString() && body.isMember(jss::version) && - body[jss::version].isInt(); + bool valid = body.isObject() && body.isMember(jss::manifest) && body[jss::manifest].isString() && + body.isMember(jss::version) && body[jss::version].isInt(); // Check the version-specific blob & signature fields std::uint32_t version; std::vector blobs; @@ -386,90 +361,62 @@ ValidatorSite::parseJsonResponse( if (!valid) { - JLOG(j_.warn()) << "Missing fields in JSON response from " - << sites_[siteIdx].activeResource->uri; + JLOG(j_.warn()) << "Missing fields in JSON response from " << sites_[siteIdx].activeResource->uri; throw std::runtime_error{"missing fields"}; } auto const manifest = body[jss::manifest].asString(); - XRPL_ASSERT( - version == body[jss::version].asUInt(), - "xrpl::ValidatorSite::parseJsonResponse : version match"); + XRPL_ASSERT(version == body[jss::version].asUInt(), "xrpl::ValidatorSite::parseJsonResponse : version match"); auto const& uri = sites_[siteIdx].activeResource->uri; auto const hash = sha512Half(manifest, blobs, version); auto const applyResult = app_.validators().applyListsAndBroadcast( - manifest, - version, - blobs, - uri, - hash, - app_.overlay(), - app_.getHashRouter(), - app_.getOPs()); + manifest, version, blobs, uri, hash, app_.overlay(), app_.getHashRouter(), app_.getOPs()); - sites_[siteIdx].lastRefreshStatus.emplace( - Site::Status{clock_type::now(), applyResult.bestDisposition(), ""}); + sites_[siteIdx].lastRefreshStatus.emplace(Site::Status{clock_type::now(), applyResult.bestDisposition(), ""}); for (auto const& [disp, count] : applyResult.dispositions) { switch (disp) { case ListDisposition::accepted: - JLOG(j_.debug()) << "Applied " << count - << " new validator list(s) from " << uri; + JLOG(j_.debug()) << "Applied " << count << " new validator list(s) from " << uri; break; case ListDisposition::expired: - JLOG(j_.debug()) << "Applied " << count - << " expired validator list(s) from " << uri; + JLOG(j_.debug()) << "Applied " << count << " expired validator list(s) from " << uri; break; case ListDisposition::same_sequence: - JLOG(j_.debug()) - << "Ignored " << count - << " validator list(s) with current sequence from " << uri; + JLOG(j_.debug()) << "Ignored " << count << " validator list(s) with current sequence from " << uri; break; case ListDisposition::pending: - JLOG(j_.debug()) << "Processed " << count - << " future validator list(s) from " << uri; + JLOG(j_.debug()) << "Processed " << count << " future validator list(s) from " << uri; break; case ListDisposition::known_sequence: - JLOG(j_.debug()) - << "Ignored " << count - << " validator list(s) with future known sequence from " - << uri; + JLOG(j_.debug()) << "Ignored " << count << " validator list(s) with future known sequence from " << uri; break; case ListDisposition::stale: - JLOG(j_.warn()) << "Ignored " << count - << "stale validator list(s) from " << uri; + JLOG(j_.warn()) << "Ignored " << count << "stale validator list(s) from " << uri; break; case ListDisposition::untrusted: - JLOG(j_.warn()) << "Ignored " << count - << " untrusted validator list(s) from " << uri; + JLOG(j_.warn()) << "Ignored " << count << " untrusted validator list(s) from " << uri; break; case ListDisposition::invalid: - JLOG(j_.warn()) << "Ignored " << count - << " invalid validator list(s) from " << uri; + JLOG(j_.warn()) << "Ignored " << count << " invalid validator list(s) from " << uri; break; case ListDisposition::unsupported_version: - JLOG(j_.warn()) - << "Ignored " << count - << " unsupported version validator list(s) from " << uri; + JLOG(j_.warn()) << "Ignored " << count << " unsupported version validator list(s) from " << uri; break; default: BOOST_ASSERT(false); } } - if (body.isMember(jss::refresh_interval) && - body[jss::refresh_interval].isNumeric()) + if (body.isMember(jss::refresh_interval) && body[jss::refresh_interval].isNumeric()) { using namespace std::chrono_literals; - std::chrono::minutes const refresh = std::clamp( - std::chrono::minutes{body[jss::refresh_interval].asUInt()}, - 1min, - std::chrono::minutes{24h}); + std::chrono::minutes const refresh = + std::clamp(std::chrono::minutes{body[jss::refresh_interval].asUInt()}, 1min, std::chrono::minutes{24h}); sites_[siteIdx].refreshInterval = refresh; - sites_[siteIdx].nextRefresh = - clock_type::now() + sites_[siteIdx].refreshInterval; + sites_[siteIdx].nextRefresh = clock_type::now() + sites_[siteIdx].refreshInterval; } } @@ -483,37 +430,30 @@ ValidatorSite::processRedirect( std::shared_ptr newLocation; if (res.find(field::location) == res.end() || res[field::location].empty()) { - JLOG(j_.warn()) << "Request for validator list at " - << sites_[siteIdx].activeResource->uri + JLOG(j_.warn()) << "Request for validator list at " << sites_[siteIdx].activeResource->uri << " returned a redirect with no Location."; throw std::runtime_error{"missing location"}; } if (sites_[siteIdx].redirCount == max_redirects) { - JLOG(j_.warn()) << "Exceeded max redirects for validator list at " - << sites_[siteIdx].loadedResource->uri; + JLOG(j_.warn()) << "Exceeded max redirects for validator list at " << sites_[siteIdx].loadedResource->uri; throw std::runtime_error{"max redirects"}; } - JLOG(j_.debug()) << "Got redirect for validator list from " - << sites_[siteIdx].activeResource->uri + JLOG(j_.debug()) << "Got redirect for validator list from " << sites_[siteIdx].activeResource->uri << " to new location " << res[field::location]; try { - newLocation = - std::make_shared(std::string(res[field::location])); + newLocation = std::make_shared(std::string(res[field::location])); ++sites_[siteIdx].redirCount; - if (newLocation->pUrl.scheme != "http" && - newLocation->pUrl.scheme != "https") - throw std::runtime_error( - "invalid scheme in redirect " + newLocation->pUrl.scheme); + if (newLocation->pUrl.scheme != "http" && newLocation->pUrl.scheme != "https") + throw std::runtime_error("invalid scheme in redirect " + newLocation->pUrl.scheme); } catch (std::exception const& ex) { - JLOG(j_.error()) << "Invalid redirect location: " - << res[field::location]; + JLOG(j_.error()) << "Invalid redirect location: " << res[field::location]; throw; } return newLocation; @@ -530,15 +470,12 @@ ValidatorSite::onSiteFetch( { if (endpoint != endpoint_type{}) sites_[siteIdx].lastRequestEndpoint = endpoint; - JLOG(j_.debug()) << "Got completion for " - << sites_[siteIdx].activeResource->uri << " " - << endpoint; + JLOG(j_.debug()) << "Got completion for " << sites_[siteIdx].activeResource->uri << " " << endpoint; auto onError = [&](std::string const& errMsg, bool retry) { - sites_[siteIdx].lastRefreshStatus.emplace(Site::Status{ - clock_type::now(), ListDisposition::invalid, errMsg}); + sites_[siteIdx].lastRefreshStatus.emplace( + Site::Status{clock_type::now(), ListDisposition::invalid, errMsg}); if (retry) - sites_[siteIdx].nextRefresh = - clock_type::now() + error_retry_interval; + sites_[siteIdx].nextRefresh = clock_type::now() + error_retry_interval; // See if there's a copy saved locally from last time we // saw the list. @@ -546,10 +483,8 @@ ValidatorSite::onSiteFetch( }; if (ec) { - JLOG(j_.warn()) - << "Problem retrieving from " - << sites_[siteIdx].activeResource->uri << " " << endpoint << " " - << ec.value() << ":" << ec.message(); + JLOG(j_.warn()) << "Problem retrieving from " << sites_[siteIdx].activeResource->uri << " " << endpoint + << " " << ec.value() << ":" << ec.message(); onError("fetch error", true); } else @@ -567,15 +502,13 @@ ValidatorSite::onSiteFetch( case status::permanent_redirect: case status::found: case status::temporary_redirect: { - auto newLocation = - processRedirect(res, siteIdx, lock_sites); + auto newLocation = processRedirect(res, siteIdx, lock_sites); XRPL_ASSERT( newLocation, "xrpl::ValidatorSite::onSiteFetch : non-null " "validator"); // for perm redirects, also update our starting URI - if (res.result() == status::moved_permanently || - res.result() == status::permanent_redirect) + if (res.result() == status::moved_permanently || res.result() == status::permanent_redirect) { sites_[siteIdx].startingResource = newLocation; } @@ -584,19 +517,15 @@ ValidatorSite::onSiteFetch( // state update/notify below } default: { - JLOG(j_.warn()) - << "Request for validator list at " - << sites_[siteIdx].activeResource->uri << " " - << endpoint - << " returned bad status: " << res.result_int(); + JLOG(j_.warn()) << "Request for validator list at " << sites_[siteIdx].activeResource->uri + << " " << endpoint << " returned bad status: " << res.result_int(); onError("bad result code", true); } } } catch (std::exception const& ex) { - JLOG(j_.error()) - << "Exception in " << __func__ << ": " << ex.what(); + JLOG(j_.error()) << "Exception in " << __func__ << ": " << ex.what(); onError(ex.what(), false); } } @@ -611,10 +540,7 @@ ValidatorSite::onSiteFetch( } void -ValidatorSite::onTextFetch( - boost::system::error_code const& ec, - std::string const& res, - std::size_t siteIdx) +ValidatorSite::onTextFetch(boost::system::error_code const& ec, std::string const& res, std::size_t siteIdx) { std::lock_guard lock_sites{sites_mutex_}; { @@ -622,8 +548,7 @@ ValidatorSite::onTextFetch( { if (ec) { - JLOG(j_.warn()) << "Problem retrieving from " - << sites_[siteIdx].activeResource->uri << " " + JLOG(j_.warn()) << "Problem retrieving from " << sites_[siteIdx].activeResource->uri << " " << ec.value() << ": " << ec.message(); throw std::runtime_error{"fetch error"}; } @@ -634,10 +559,9 @@ ValidatorSite::onTextFetch( } catch (std::exception const& ex) { - JLOG(j_.error()) - << "Exception in " << __func__ << ": " << ex.what(); - sites_[siteIdx].lastRefreshStatus.emplace(Site::Status{ - clock_type::now(), ListDisposition::invalid, ex.what()}); + JLOG(j_.error()) << "Exception in " << __func__ << ": " << ex.what(); + sites_[siteIdx].lastRefreshStatus.emplace( + Site::Status{clock_type::now(), ListDisposition::invalid, ex.what()}); } sites_[siteIdx].activeResource.reset(); } @@ -670,16 +594,12 @@ ValidatorSite::getJson() const v[jss::next_refresh_time] = to_string(site.nextRefresh); if (site.lastRefreshStatus) { - v[jss::last_refresh_time] = - to_string(site.lastRefreshStatus->refreshed); - v[jss::last_refresh_status] = - to_string(site.lastRefreshStatus->disposition); + v[jss::last_refresh_time] = to_string(site.lastRefreshStatus->refreshed); + v[jss::last_refresh_status] = to_string(site.lastRefreshStatus->disposition); if (!site.lastRefreshStatus->message.empty()) - v[jss::last_refresh_message] = - site.lastRefreshStatus->message; + v[jss::last_refresh_message] = site.lastRefreshStatus->message; } - v[jss::refresh_interval_min] = - static_cast(site.refreshInterval.count()); + v[jss::refresh_interval_min] = static_cast(site.refreshInterval.count()); } } return jrr; diff --git a/src/xrpld/app/misc/detail/Work.h b/src/xrpld/app/misc/detail/Work.h index 4d1547c4fb..5261cf3bd7 100644 --- a/src/xrpld/app/misc/detail/Work.h +++ b/src/xrpld/app/misc/detail/Work.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_MISC_DETAIL_WORK_H_INCLUDED -#define XRPL_APP_MISC_DETAIL_WORK_H_INCLUDED +#pragma once #include #include @@ -8,8 +7,7 @@ namespace xrpl { namespace detail { -using response_type = - boost::beast::http::response; +using response_type = boost::beast::http::response; class Work { @@ -26,5 +24,3 @@ public: } // namespace detail } // namespace xrpl - -#endif diff --git a/src/xrpld/app/misc/detail/WorkBase.h b/src/xrpld/app/misc/detail/WorkBase.h index 6c46749f6d..e5fd72f118 100644 --- a/src/xrpld/app/misc/detail/WorkBase.h +++ b/src/xrpld/app/misc/detail/WorkBase.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_MISC_DETAIL_WORKBASE_H_INCLUDED -#define XRPL_APP_MISC_DETAIL_WORKBASE_H_INCLUDED +#pragma once #include @@ -25,15 +24,13 @@ protected: using endpoint_type = boost::asio::ip::tcp::endpoint; public: - using callback_type = std::function< - void(error_code const&, endpoint_type const&, response_type&&)>; + using callback_type = std::function; protected: using socket_type = boost::asio::ip::tcp::socket; using resolver_type = boost::asio::ip::tcp::resolver; using results_type = boost::asio::ip::tcp::resolver::results_type; - using request_type = - boost::beast::http::request; + using request_type = boost::beast::http::request; std::string host_; std::string path_; @@ -123,9 +120,7 @@ template WorkBase::~WorkBase() { if (cb_) - cb_(make_error_code(boost::system::errc::not_a_socket), - lastEndpoint_, - std::move(res_)); + cb_(make_error_code(boost::system::errc::not_a_socket), lastEndpoint_, std::move(res_)); close(); } @@ -135,20 +130,14 @@ WorkBase::run() { if (!strand_.running_in_this_thread()) return boost::asio::post( - ios_, - boost::asio::bind_executor( - strand_, std::bind(&WorkBase::run, impl().shared_from_this()))); + ios_, boost::asio::bind_executor(strand_, std::bind(&WorkBase::run, impl().shared_from_this()))); resolver_.async_resolve( host_, port_, boost::asio::bind_executor( strand_, - std::bind( - &WorkBase::onResolve, - impl().shared_from_this(), - std::placeholders::_1, - std::placeholders::_2))); + std::bind(&WorkBase::onResolve, impl().shared_from_this(), std::placeholders::_1, std::placeholders::_2))); } template @@ -160,9 +149,7 @@ WorkBase::cancel() return boost::asio::post( ios_, - boost::asio::bind_executor( - strand_, - std::bind(&WorkBase::cancel, impl().shared_from_this()))); + boost::asio::bind_executor(strand_, std::bind(&WorkBase::cancel, impl().shared_from_this()))); } error_code ec; @@ -193,11 +180,7 @@ WorkBase::onResolve(error_code const& ec, results_type results) results, boost::asio::bind_executor( strand_, - std::bind( - &WorkBase::onConnect, - impl().shared_from_this(), - std::placeholders::_1, - std::placeholders::_2))); + std::bind(&WorkBase::onConnect, impl().shared_from_this(), std::placeholders::_1, std::placeholders::_2))); } template @@ -226,11 +209,7 @@ WorkBase::onStart() impl().stream(), req_, boost::asio::bind_executor( - strand_, - std::bind( - &WorkBase::onRequest, - impl().shared_from_this(), - std::placeholders::_1))); + strand_, std::bind(&WorkBase::onRequest, impl().shared_from_this(), std::placeholders::_1))); } template @@ -245,11 +224,7 @@ WorkBase::onRequest(error_code const& ec) readBuf_, res_, boost::asio::bind_executor( - strand_, - std::bind( - &WorkBase::onResponse, - impl().shared_from_this(), - std::placeholders::_1))); + strand_, std::bind(&WorkBase::onResponse, impl().shared_from_this(), std::placeholders::_1))); } template @@ -282,5 +257,3 @@ WorkBase::close() } // namespace detail } // namespace xrpl - -#endif diff --git a/src/xrpld/app/misc/detail/WorkFile.h b/src/xrpld/app/misc/detail/WorkFile.h index ac926ede1f..8d2d4edb50 100644 --- a/src/xrpld/app/misc/detail/WorkFile.h +++ b/src/xrpld/app/misc/detail/WorkFile.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_MISC_DETAIL_WORKFILE_H_INCLUDED -#define XRPL_APP_MISC_DETAIL_WORKFILE_H_INCLUDED +#pragma once #include @@ -24,14 +23,10 @@ protected: using response_type = std::string; public: - using callback_type = - std::function; + using callback_type = std::function; public: - WorkFile( - std::string const& path, - boost::asio::io_context& ios, - callback_type cb); + WorkFile(std::string const& path, boost::asio::io_context& ios, callback_type cb); ~WorkFile(); void @@ -49,14 +44,8 @@ private: //------------------------------------------------------------------------------ -WorkFile::WorkFile( - std::string const& path, - boost::asio::io_context& ios, - callback_type cb) - : path_(path) - , cb_(std::move(cb)) - , ios_(ios) - , strand_(boost::asio::make_strand(ios)) +WorkFile::WorkFile(std::string const& path, boost::asio::io_context& ios, callback_type cb) + : path_(path), cb_(std::move(cb)), ios_(ios), strand_(boost::asio::make_strand(ios)) { } @@ -71,9 +60,7 @@ WorkFile::run() { if (!strand_.running_in_this_thread()) return boost::asio::post( - ios_, - boost::asio::bind_executor( - strand_, std::bind(&WorkFile::run, shared_from_this()))); + ios_, boost::asio::bind_executor(strand_, std::bind(&WorkFile::run, shared_from_this()))); error_code ec; auto const fileContents = getFileContents(ec, path_, megabytes(1)); @@ -92,5 +79,3 @@ WorkFile::cancel() } // namespace detail } // namespace xrpl - -#endif diff --git a/src/xrpld/app/misc/detail/WorkPlain.h b/src/xrpld/app/misc/detail/WorkPlain.h index 23bae20006..d1df5b4b3b 100644 --- a/src/xrpld/app/misc/detail/WorkPlain.h +++ b/src/xrpld/app/misc/detail/WorkPlain.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_MISC_DETAIL_WORKPLAIN_H_INCLUDED -#define XRPL_APP_MISC_DETAIL_WORKPLAIN_H_INCLUDED +#pragma once #include @@ -8,8 +7,7 @@ namespace xrpl { namespace detail { // Work over TCP/IP -class WorkPlain : public WorkBase, - public std::enable_shared_from_this +class WorkPlain : public WorkBase, public std::enable_shared_from_this { friend class WorkBase; @@ -61,5 +59,3 @@ WorkPlain::onConnect(error_code const& ec) } // namespace detail } // namespace xrpl - -#endif diff --git a/src/xrpld/app/misc/detail/WorkSSL.cpp b/src/xrpld/app/misc/detail/WorkSSL.cpp index 6ccc83f595..47902e900a 100644 --- a/src/xrpld/app/misc/detail/WorkSSL.cpp +++ b/src/xrpld/app/misc/detail/WorkSSL.cpp @@ -24,8 +24,7 @@ WorkSSL::WorkSSL( { auto ec = context_.preConnectVerify(stream_, host_); if (ec) - Throw( - boost::str(boost::format("preConnectVerify: %s") % ec.message())); + Throw(boost::str(boost::format("preConnectVerify: %s") % ec.message())); } void @@ -38,11 +37,7 @@ WorkSSL::onConnect(error_code const& ec) stream_.async_handshake( boost::asio::ssl::stream_base::client, boost::asio::bind_executor( - strand_, - std::bind( - &WorkSSL::onHandshake, - shared_from_this(), - std::placeholders::_1))); + strand_, std::bind(&WorkSSL::onHandshake, shared_from_this(), std::placeholders::_1))); } void diff --git a/src/xrpld/app/misc/detail/WorkSSL.h b/src/xrpld/app/misc/detail/WorkSSL.h index 7dd1a94c9e..b12c774f6e 100644 --- a/src/xrpld/app/misc/detail/WorkSSL.h +++ b/src/xrpld/app/misc/detail/WorkSSL.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_MISC_DETAIL_WORKSSL_H_INCLUDED -#define XRPL_APP_MISC_DETAIL_WORKSSL_H_INCLUDED +#pragma once #include #include @@ -17,8 +16,7 @@ namespace xrpl { namespace detail { // Work over SSL -class WorkSSL : public WorkBase, - public std::enable_shared_from_this +class WorkSSL : public WorkBase, public std::enable_shared_from_this { friend class WorkBase; @@ -58,5 +56,3 @@ private: } // namespace detail } // namespace xrpl - -#endif diff --git a/src/xrpld/app/misc/detail/setup_HashRouter.cpp b/src/xrpld/app/misc/detail/setup_HashRouter.cpp new file mode 100644 index 0000000000..a0e63dd67e --- /dev/null +++ b/src/xrpld/app/misc/detail/setup_HashRouter.cpp @@ -0,0 +1,42 @@ +#include +#include + +#include + +namespace xrpl { + +HashRouter::Setup +setup_HashRouter(Config const& config) +{ + using namespace std::chrono; + + HashRouter::Setup setup; + auto const& section = config.section("hashrouter"); + + std::int32_t tmp{}; + + if (set(tmp, "hold_time", section)) + { + if (tmp < 12) + Throw( + "HashRouter hold time must be at least 12 seconds (the " + "approximate validation time for three ledgers)."); + setup.holdTime = seconds(tmp); + } + if (set(tmp, "relay_time", section)) + { + if (tmp < 8) + Throw( + "HashRouter relay time must be at least 8 seconds (the " + "approximate validation time for two ledgers)."); + setup.relayTime = seconds(tmp); + } + if (setup.relayTime > setup.holdTime) + { + Throw("HashRouter relay time must be less than or equal to hold time"); + } + + return setup; +} + +} // namespace xrpl diff --git a/src/xrpld/app/misc/make_NetworkOPs.h b/src/xrpld/app/misc/make_NetworkOPs.h new file mode 100644 index 0000000000..7dce966f04 --- /dev/null +++ b/src/xrpld/app/misc/make_NetworkOPs.h @@ -0,0 +1,32 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include + +#include + +namespace xrpl { + +class LedgerMaster; +class ValidatorKeys; + +std::unique_ptr +make_NetworkOPs( + ServiceRegistry& registry, + NetworkOPs::clock_type& clock, + bool standalone, + std::size_t minPeerCount, + bool start_valid, + JobQueue& job_queue, + LedgerMaster& ledgerMaster, + ValidatorKeys const& validatorKeys, + boost::asio::io_context& io_svc, + beast::Journal journal, + beast::insight::Collector::ptr const& collector); + +} // namespace xrpl diff --git a/src/xrpld/app/misc/setup_HashRouter.h b/src/xrpld/app/misc/setup_HashRouter.h new file mode 100644 index 0000000000..3054233b89 --- /dev/null +++ b/src/xrpld/app/misc/setup_HashRouter.h @@ -0,0 +1,17 @@ +#ifndef XRPLD_APP_MISC_SETUP_HASHROUTER_H_INCLUDED +#define XRPLD_APP_MISC_SETUP_HASHROUTER_H_INCLUDED + +#include + +namespace xrpl { + +// Forward declaration +class Config; + +/** Create HashRouter setup from configuration */ +HashRouter::Setup +setup_HashRouter(Config const& config); + +} // namespace xrpl + +#endif diff --git a/src/xrpld/app/paths/AMMContext.h b/src/xrpld/app/paths/AMMContext.h index a272ba291e..b0ff44c5ec 100644 --- a/src/xrpld/app/paths/AMMContext.h +++ b/src/xrpld/app/paths/AMMContext.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_PATHS_AMMCONTEXT_H_INCLUDED -#define XRPL_APP_PATHS_AMMCONTEXT_H_INCLUDED +#pragma once #include @@ -32,8 +31,7 @@ private: std::uint16_t ammIters_{0}; public: - AMMContext(AccountID const& account, bool multiPath) - : account_(account), multiPath_(multiPath) + AMMContext(AccountID const& account, bool multiPath) : account_(account), multiPath_(multiPath) { } ~AMMContext() = default; @@ -96,5 +94,3 @@ public: }; } // namespace xrpl - -#endif // XRPL_APP_PATHS_AMMCONTEXT_H_INCLUDED diff --git a/src/xrpld/app/paths/AMMLiquidity.h b/src/xrpld/app/paths/AMMLiquidity.h index b5b865d80e..441c3b6e3d 100644 --- a/src/xrpld/app/paths/AMMLiquidity.h +++ b/src/xrpld/app/paths/AMMLiquidity.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_TX_AMMLIQUIDITY_H_INCLUDED -#define XRPL_APP_TX_AMMLIQUIDITY_H_INCLUDED +#pragma once #include #include @@ -63,8 +62,7 @@ public: * quality. */ std::optional> - getOffer(ReadView const& view, std::optional const& clobQuality) - const; + getOffer(ReadView const& view, std::optional const& clobQuality) const; AccountID const& ammAccount() const @@ -132,5 +130,3 @@ private: }; } // namespace xrpl - -#endif // XRPL_APP_TX_AMMLIQUIDITY_H_INCLUDED diff --git a/src/xrpld/app/paths/AMMOffer.h b/src/xrpld/app/paths/AMMOffer.h index 7a81e53176..ebaa7311c0 100644 --- a/src/xrpld/app/paths/AMMOffer.h +++ b/src/xrpld/app/paths/AMMOffer.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_AMMOFFER_H_INCLUDED -#define XRPL_APP_AMMOFFER_H_INCLUDED +#pragma once #include #include @@ -81,20 +80,14 @@ public: * current quality. */ TAmounts - limitOut( - TAmounts const& offerAmount, - TOut const& limit, - bool roundUp) const; + limitOut(TAmounts const& offerAmount, TOut const& limit, bool roundUp) const; /** Limit in of the provided offer. If one-path then swapIn * using current balances. If multi-path then ceil_in using * current quality. */ TAmounts - limitIn( - TAmounts const& offerAmount, - TIn const& limit, - bool roundUp) const; + limitIn(TAmounts const& offerAmount, TIn const& limit, bool roundUp) const; QualityFunction getQualityFunc() const; @@ -130,5 +123,3 @@ public: }; } // namespace xrpl - -#endif // XRPL_APP_AMMOFFER_H_INCLUDED diff --git a/src/xrpld/app/paths/AccountCurrencies.cpp b/src/xrpld/app/paths/AccountCurrencies.cpp index fbb9c63cd8..8e51999018 100644 --- a/src/xrpld/app/paths/AccountCurrencies.cpp +++ b/src/xrpld/app/paths/AccountCurrencies.cpp @@ -3,10 +3,7 @@ namespace xrpl { hash_set -accountSourceCurrencies( - AccountID const& account, - std::shared_ptr const& lrCache, - bool includeXRP) +accountSourceCurrencies(AccountID const& account, std::shared_ptr const& lrCache, bool includeXRP) { hash_set currencies; @@ -14,8 +11,7 @@ accountSourceCurrencies( if (includeXRP) currencies.insert(xrpCurrency()); - if (auto const lines = - lrCache->getRippleLines(account, LineDirection::outgoing)) + if (auto const lines = lrCache->getRippleLines(account, LineDirection::outgoing)) { for (auto const& rspEntry : *lines) { @@ -24,10 +20,9 @@ accountSourceCurrencies( // Filter out non if (saBalance > beast::zero // Have IOUs to send. - || - (rspEntry.getLimitPeer() - // Peer extends credit. - && ((-saBalance) < rspEntry.getLimitPeer()))) // Credit left. + || (rspEntry.getLimitPeer() + // Peer extends credit. + && ((-saBalance) < rspEntry.getLimitPeer()))) // Credit left. { currencies.insert(saBalance.getCurrency()); } @@ -39,10 +34,7 @@ accountSourceCurrencies( } hash_set -accountDestCurrencies( - AccountID const& account, - std::shared_ptr const& lrCache, - bool includeXRP) +accountDestCurrencies(AccountID const& account, std::shared_ptr const& lrCache, bool includeXRP) { hash_set currencies; @@ -50,8 +42,7 @@ accountDestCurrencies( currencies.insert(xrpCurrency()); // Even if account doesn't exist - if (auto const lines = - lrCache->getRippleLines(account, LineDirection::outgoing)) + if (auto const lines = lrCache->getRippleLines(account, LineDirection::outgoing)) { for (auto const& rspEntry : *lines) { diff --git a/src/xrpld/app/paths/AccountCurrencies.h b/src/xrpld/app/paths/AccountCurrencies.h index de46a13808..eb8cc92aec 100644 --- a/src/xrpld/app/paths/AccountCurrencies.h +++ b/src/xrpld/app/paths/AccountCurrencies.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_PATHS_ACCOUNTCURRENCIES_H_INCLUDED -#define XRPL_APP_PATHS_ACCOUNTCURRENCIES_H_INCLUDED +#pragma once #include @@ -8,17 +7,9 @@ namespace xrpl { hash_set -accountDestCurrencies( - AccountID const& account, - std::shared_ptr const& cache, - bool includeXRP); +accountDestCurrencies(AccountID const& account, std::shared_ptr const& cache, bool includeXRP); hash_set -accountSourceCurrencies( - AccountID const& account, - std::shared_ptr const& lrLedger, - bool includeXRP); +accountSourceCurrencies(AccountID const& account, std::shared_ptr const& lrLedger, bool includeXRP); } // namespace xrpl - -#endif diff --git a/src/xrpld/app/paths/Flow.cpp b/src/xrpld/app/paths/Flow.cpp index b5088d15b3..1f6d29bfb9 100644 --- a/src/xrpld/app/paths/Flow.cpp +++ b/src/xrpld/app/paths/Flow.cpp @@ -13,11 +13,7 @@ namespace xrpl { template static auto -finishFlow( - PaymentSandbox& sb, - Issue const& srcIssue, - Issue const& dstIssue, - FlowResult&& f) +finishFlow(PaymentSandbox& sb, Issue const& srcIssue, Issue const& dstIssue, FlowResult&& f) { path::RippleCalc::Output result; if (f.ter == tesSUCCESS) @@ -94,8 +90,7 @@ flow( if (j.trace()) { - j.trace() << "\nsrc: " << src << "\ndst: " << dst - << "\nsrcIssue: " << srcIssue << "\ndstIssue: " << dstIssue; + j.trace() << "\nsrc: " << src << "\ndst: " << dst << "\nsrcIssue: " << srcIssue << "\ndstIssue: " << dstIssue; j.trace() << "\nNumStrands: " << strands.size(); for (auto const& curStrand : strands) { diff --git a/src/xrpld/app/paths/Flow.h b/src/xrpld/app/paths/Flow.h index 5fafe294db..1a46ce221a 100644 --- a/src/xrpld/app/paths/Flow.h +++ b/src/xrpld/app/paths/Flow.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_PATHS_FLOW_H_INCLUDED -#define XRPL_APP_PATHS_FLOW_H_INCLUDED +#pragma once #include #include @@ -52,5 +51,3 @@ flow( path::detail::FlowDebugInfo* flowDebugInfo = nullptr); } // namespace xrpl - -#endif diff --git a/src/xrpld/app/paths/PathRequest.cpp b/src/xrpld/app/paths/PathRequest.cpp index 41bae4b178..53a4e03752 100644 --- a/src/xrpld/app/paths/PathRequest.cpp +++ b/src/xrpld/app/paths/PathRequest.cpp @@ -1,6 +1,5 @@ #include #include -#include #include #include #include @@ -14,6 +13,7 @@ #include #include #include +#include #include #include @@ -76,21 +76,17 @@ PathRequest::~PathRequest() if (quick_reply_ != steady_clock::time_point{}) { fast = " fast:"; - fast += std::to_string( - duration_cast(quick_reply_ - created_).count()); + fast += std::to_string(duration_cast(quick_reply_ - created_).count()); fast += "ms"; } if (full_reply_ != steady_clock::time_point{}) { full = " full:"; - full += std::to_string( - duration_cast(full_reply_ - created_).count()); + full += std::to_string(duration_cast(full_reply_ - created_).count()); full += "ms"; } - stream - << iIdentifier << " complete:" << fast << full << " total:" - << duration_cast(steady_clock::now() - created_).count() - << "ms"; + stream << iIdentifier << " complete:" << fast << full + << " total:" << duration_cast(steady_clock::now() - created_).count() << "ms"; } bool @@ -173,8 +169,7 @@ PathRequest::isValid(std::shared_ptr const& crCache) auto const sleDest = lrLedger->read(keylet::account(*raDstAccount)); - Json::Value& jvDestCur = - (jvStatus[jss::destination_currencies] = Json::arrayValue); + Json::Value& jvDestCur = (jvStatus[jss::destination_currencies] = Json::arrayValue); if (!sleDest) { @@ -197,13 +192,11 @@ PathRequest::isValid(std::shared_ptr const& crCache) { bool const disallowXRP(sleDest->getFlags() & lsfDisallowXRP); - auto usDestCurrID = - accountDestCurrencies(*raDstAccount, crCache, !disallowXRP); + auto usDestCurrID = accountDestCurrencies(*raDstAccount, crCache, !disallowXRP); for (auto const& currency : usDestCurrID) jvDestCur.append(to_string(currency)); - jvStatus[jss::destination_tag] = - (sleDest->getFlags() & lsfRequireDestTag); + jvStatus[jss::destination_tag] = (sleDest->getFlags() & lsfRequireDestTag); } jvStatus[jss::ledger_hash] = to_string(lrLedger->header().hash); @@ -221,9 +214,7 @@ PathRequest::isValid(std::shared_ptr const& crCache) in all cases. */ std::pair -PathRequest::doCreate( - std::shared_ptr const& cache, - Json::Value const& value) +PathRequest::doCreate(std::shared_ptr const& cache, Json::Value const& value) { bool valid = false; @@ -271,16 +262,14 @@ PathRequest::parseJson(Json::Value const& jvParams) return PFR_PJ_INVALID; } - raSrcAccount = - parseBase58(jvParams[jss::source_account].asString()); + raSrcAccount = parseBase58(jvParams[jss::source_account].asString()); if (!raSrcAccount) { jvStatus = rpcError(rpcSRC_ACT_MALFORMED); return PFR_PJ_INVALID; } - raDstAccount = - parseBase58(jvParams[jss::destination_account].asString()); + raDstAccount = parseBase58(jvParams[jss::destination_account].asString()); if (!raDstAccount) { jvStatus = rpcError(rpcDST_ACT_MALFORMED); @@ -295,10 +284,8 @@ PathRequest::parseJson(Json::Value const& jvParams) convert_all_ = saDstAmount == STAmount(saDstAmount.issue(), 1u, 0, true); - if ((saDstAmount.getCurrency().isZero() && - saDstAmount.getIssuer().isNonZero()) || - (saDstAmount.getCurrency() == badCurrency()) || - (!convert_all_ && saDstAmount <= beast::zero)) + if ((saDstAmount.getCurrency().isZero() && saDstAmount.getIssuer().isNonZero()) || + (saDstAmount.getCurrency() == badCurrency()) || (!convert_all_ && saDstAmount <= beast::zero)) { jvStatus = rpcError(rpcDST_AMT_MALFORMED); return PFR_PJ_INVALID; @@ -315,11 +302,9 @@ PathRequest::parseJson(Json::Value const& jvParams) saSendMax.emplace(); if (!amountFromJsonNoThrow(*saSendMax, jvParams[jss::send_max]) || - (saSendMax->getCurrency().isZero() && - saSendMax->getIssuer().isNonZero()) || + (saSendMax->getCurrency().isZero() && saSendMax->getIssuer().isNonZero()) || (saSendMax->getCurrency() == badCurrency()) || - (*saSendMax <= beast::zero && - *saSendMax != STAmount(saSendMax->issue(), 1u, 0, true))) + (*saSendMax <= beast::zero && *saSendMax != STAmount(saSendMax->issue(), 1u, 0, true))) { jvStatus = rpcError(rpcSENDMAX_MALFORMED); return PFR_PJ_INVALID; @@ -342,8 +327,7 @@ PathRequest::parseJson(Json::Value const& jvParams) { // Mandatory currency Currency srcCurrencyID; - if (!c.isObject() || !c.isMember(jss::currency) || - !c[jss::currency].isString() || + if (!c.isObject() || !c.isMember(jss::currency) || !c[jss::currency].isString() || !to_currency(srcCurrencyID, c[jss::currency].asString())) { jvStatus = rpcError(rpcSRC_CUR_MALFORMED); @@ -353,8 +337,7 @@ PathRequest::parseJson(Json::Value const& jvParams) // Optional issuer AccountID srcIssuerID; if (c.isMember(jss::issuer) && - (!c[jss::issuer].isString() || - !to_issuer(srcIssuerID, c[jss::issuer].asString()))) + (!c[jss::issuer].isString() || !to_issuer(srcIssuerID, c[jss::issuer].asString()))) { jvStatus = rpcError(rpcSRC_ISR_MALFORMED); return PFR_PJ_INVALID; @@ -380,8 +363,7 @@ PathRequest::parseJson(Json::Value const& jvParams) { // If neither is the source and they are not equal, then the // source issuer is illegal. - if (srcIssuerID != *raSrcAccount && - saSendMax->getIssuer() != *raSrcAccount && + if (srcIssuerID != *raSrcAccount && saSendMax->getIssuer() != *raSrcAccount && srcIssuerID != saSendMax->getIssuer()) { jvStatus = rpcError(rpcSRC_ISR_MALFORMED); @@ -392,18 +374,15 @@ PathRequest::parseJson(Json::Value const& jvParams) // Otherwise, use the one that's not the source. if (srcIssuerID != *raSrcAccount) { - sciSourceCurrencies.insert( - {srcCurrencyID, srcIssuerID}); + sciSourceCurrencies.insert({srcCurrencyID, srcIssuerID}); } else if (saSendMax->getIssuer() != *raSrcAccount) { - sciSourceCurrencies.insert( - {srcCurrencyID, saSendMax->getIssuer()}); + sciSourceCurrencies.insert({srcCurrencyID, saSendMax->getIssuer()}); } else { - sciSourceCurrencies.insert( - {srcCurrencyID, *raSrcAccount}); + sciSourceCurrencies.insert({srcCurrencyID, *raSrcAccount}); } } } @@ -420,8 +399,7 @@ PathRequest::parseJson(Json::Value const& jvParams) if (jvParams.isMember(jss::domain)) { uint256 num; - if (!jvParams[jss::domain].isString() || - !num.parseHex(jvParams[jss::domain].asString())) + if (!jvParams[jss::domain].isString() || !num.parseHex(jvParams[jss::domain].asString())) { jvStatus = rpcError(rpcDOMAIN_MALFORMED); return PFR_PJ_INVALID; @@ -471,15 +449,7 @@ PathRequest::getPathFinder( if (i != currency_map.end()) return i->second; auto pathfinder = std::make_unique( - cache, - *raSrcAccount, - *raDstAccount, - currency, - std::nullopt, - dst_amount, - saSendMax, - domain, - app_); + cache, *raSrcAccount, *raDstAccount, currency, std::nullopt, dst_amount, saSendMax, domain, app_); if (pathfinder->findPaths(level, continueCallback)) pathfinder->computePathRanks(max_paths_, continueCallback); else @@ -509,8 +479,7 @@ PathRequest::findPaths( { if (sourceCurrencies.size() >= RPC::Tuning::max_auto_src_cur) return false; - sourceCurrencies.insert( - {c, c.isZero() ? xrpAccount() : *raSrcAccount}); + sourceCurrencies.insert({c, c.isZero() ? xrpAccount() : *raSrcAccount}); } } } @@ -521,17 +490,9 @@ PathRequest::findPaths( { if (continueCallback && !continueCallback()) break; - JLOG(m_journal.debug()) - << iIdentifier - << " Trying to find paths: " << STAmount(issue, 1).getFullText(); + JLOG(m_journal.debug()) << iIdentifier << " Trying to find paths: " << STAmount(issue, 1).getFullText(); - auto& pathfinder = getPathFinder( - cache, - currency_map, - issue.currency, - dst_amount, - level, - continueCallback); + auto& pathfinder = getPathFinder(cache, currency_map, issue.currency, dst_amount, level, continueCallback); if (!pathfinder) { JLOG(m_journal.debug()) << iIdentifier << " No paths found"; @@ -539,12 +500,8 @@ PathRequest::findPaths( } STPath fullLiquidityPath; - auto ps = pathfinder->getBestPaths( - max_paths_, - fullLiquidityPath, - mContext[issue], - issue.account, - continueCallback); + auto ps = + pathfinder->getBestPaths(max_paths_, fullLiquidityPath, mContext[issue], issue.account, continueCallback); mContext[issue] = ps; auto const& sourceAccount = [&] { @@ -557,17 +514,14 @@ PathRequest::findPaths( return *raSrcAccount; }(); - STAmount saMaxAmount = saSendMax.value_or( - STAmount(Issue{issue.currency, sourceAccount}, 1u, 0, true)); + STAmount saMaxAmount = saSendMax.value_or(STAmount(Issue{issue.currency, sourceAccount}, 1u, 0, true)); - JLOG(m_journal.debug()) - << iIdentifier << " Paths found, calling rippleCalc"; + JLOG(m_journal.debug()) << iIdentifier << " Paths found, calling rippleCalc"; path::RippleCalc::Input rcInput; if (convert_all_) rcInput.partialPaymentAllowed = true; - auto sandbox = - std::make_unique(&*cache->getLedger(), tapNONE); + auto sandbox = std::make_unique(&*cache->getLedger(), tapNONE); auto rc = path::RippleCalc::rippleCalculate( *sandbox, saMaxAmount, // --> Amount to send is unlimited @@ -583,12 +537,10 @@ PathRequest::findPaths( if (!convert_all_ && !fullLiquidityPath.empty() && (rc.result() == terNO_LINE || rc.result() == tecPATH_PARTIAL)) { - JLOG(m_journal.debug()) - << iIdentifier << " Trying with an extra path element"; + JLOG(m_journal.debug()) << iIdentifier << " Trying with an extra path element"; ps.push_back(fullLiquidityPath); - sandbox = - std::make_unique(&*cache->getLedger(), tapNONE); + sandbox = std::make_unique(&*cache->getLedger(), tapNONE); rc = path::RippleCalc::rippleCalculate( *sandbox, saMaxAmount, // --> Amount to send is unlimited @@ -602,15 +554,11 @@ PathRequest::findPaths( if (rc.result() != tesSUCCESS) { - JLOG(m_journal.warn()) - << iIdentifier << " Failed with covering path " - << transHuman(rc.result()); + JLOG(m_journal.warn()) << iIdentifier << " Failed with covering path " << transHuman(rc.result()); } else { - JLOG(m_journal.debug()) - << iIdentifier << " Extra path element gives " - << transHuman(rc.result()); + JLOG(m_journal.debug()) << iIdentifier << " Extra path element gives " << transHuman(rc.result()); } } @@ -618,13 +566,11 @@ PathRequest::findPaths( { Json::Value jvEntry(Json::objectValue); rc.actualAmountIn.setIssuer(sourceAccount); - jvEntry[jss::source_amount] = - rc.actualAmountIn.getJson(JsonOptions::none); + jvEntry[jss::source_amount] = rc.actualAmountIn.getJson(JsonOptions::none); jvEntry[jss::paths_computed] = ps.getJson(JsonOptions::none); if (convert_all_) - jvEntry[jss::destination_amount] = - rc.actualAmountOut.getJson(JsonOptions::none); + jvEntry[jss::destination_amount] = rc.actualAmountOut.getJson(JsonOptions::none); if (hasCompletion()) { @@ -636,8 +582,7 @@ PathRequest::findPaths( } else { - JLOG(m_journal.debug()) << iIdentifier << " rippleCalc returns " - << transHuman(rc.result()); + JLOG(m_journal.debug()) << iIdentifier << " rippleCalc returns " << transHuman(rc.result()); } } @@ -657,8 +602,7 @@ PathRequest::doUpdate( std::function const& continueCallback) { using namespace std::chrono; - JLOG(m_journal.debug()) - << iIdentifier << " update " << (fast ? "fast" : "normal"); + JLOG(m_journal.debug()) << iIdentifier << " update " << (fast ? "fast" : "normal"); { std::lock_guard sl(mLock); @@ -672,8 +616,7 @@ PathRequest::doUpdate( if (hasCompletion()) { // Old ripple_path_find API gives destination_currencies - auto& destCurrencies = - (newStatus[jss::destination_currencies] = Json::arrayValue); + auto& destCurrencies = (newStatus[jss::destination_currencies] = Json::arrayValue); auto usCurrencies = accountDestCurrencies(*raDstAccount, cache, true); for (auto const& c : usCurrencies) destCurrencies.append(to_string(c)); @@ -707,8 +650,7 @@ PathRequest::doUpdate( else if (bLastSuccess) { // decrement, if possible - if (iLevel > app_.config().PATH_SEARCH || - (loaded && (iLevel > app_.config().PATH_SEARCH_FAST))) + if (iLevel > app_.config().PATH_SEARCH || (loaded && (iLevel > app_.config().PATH_SEARCH_FAST))) --iLevel; } else @@ -750,8 +692,7 @@ PathRequest::doUpdate( jvStatus = newStatus; } - JLOG(m_journal.debug()) - << iIdentifier << " update finished " << (fast ? "fast" : "normal"); + JLOG(m_journal.debug()) << iIdentifier << " update finished " << (fast ? "fast" : "normal"); return newStatus; } diff --git a/src/xrpld/app/paths/PathRequest.h b/src/xrpld/app/paths/PathRequest.h index 8f63cfa9a9..09e97e4497 100644 --- a/src/xrpld/app/paths/PathRequest.h +++ b/src/xrpld/app/paths/PathRequest.h @@ -1,14 +1,13 @@ -#ifndef XRPL_APP_PATHS_PATHREQUEST_H_INCLUDED -#define XRPL_APP_PATHS_PATHREQUEST_H_INCLUDED +#pragma once #include #include #include -#include #include #include #include +#include #include #include @@ -106,11 +105,7 @@ private: Returns false if the source currencies are invalid. */ bool - findPaths( - std::shared_ptr const&, - int const, - Json::Value&, - std::function const&); + findPaths(std::shared_ptr const&, int const, Json::Value&, std::function const&); int parseJson(Json::Value const&); @@ -159,5 +154,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/src/xrpld/app/paths/PathRequests.cpp b/src/xrpld/app/paths/PathRequests.cpp index cfe6080eac..2c1ef8cbad 100644 --- a/src/xrpld/app/paths/PathRequests.cpp +++ b/src/xrpld/app/paths/PathRequests.cpp @@ -16,9 +16,7 @@ namespace xrpl { Get the correct ledger to use. */ std::shared_ptr -PathRequests::getLineCache( - std::shared_ptr const& ledger, - bool authoritative) +PathRequests::getLineCache(std::shared_ptr const& ledger, bool authoritative) { std::lock_guard sl(mLock); @@ -26,22 +24,18 @@ PathRequests::getLineCache( std::uint32_t const lineSeq = lineCache ? lineCache->getLedger()->seq() : 0; std::uint32_t const lgrSeq = ledger->seq(); - JLOG(mJournal.debug()) << "getLineCache has cache for " << lineSeq - << ", considering " << lgrSeq; + JLOG(mJournal.debug()) << "getLineCache has cache for " << lineSeq << ", considering " << lgrSeq; - if ((lineSeq == 0) || // no ledger - (authoritative && (lgrSeq > lineSeq)) || // newer authoritative ledger - (authoritative && - ((lgrSeq + 8) < lineSeq)) || // we jumped way back for some reason - (lgrSeq > (lineSeq + 8))) // we jumped way forward for some reason + if ((lineSeq == 0) || // no ledger + (authoritative && (lgrSeq > lineSeq)) || // newer authoritative ledger + (authoritative && ((lgrSeq + 8) < lineSeq)) || // we jumped way back for some reason + (lgrSeq > (lineSeq + 8))) // we jumped way forward for some reason { - JLOG(mJournal.debug()) - << "getLineCache creating new cache for " << lgrSeq; + JLOG(mJournal.debug()) << "getLineCache creating new cache for " << lgrSeq; // Assign to the local before the member, because the member is a // weak_ptr, and will immediately discard it if there are no other // references. - lineCache_ = lineCache = std::make_shared( - ledger, app_.journal("RippleLineCache")); + lineCache_ = lineCache = std::make_shared(ledger, app_.journal("RippleLineCache")); } return lineCache; } @@ -49,8 +43,7 @@ PathRequests::getLineCache( void PathRequests::updateAll(std::shared_ptr const& inLedger) { - auto event = - app_.getJobQueue().makeLoadEvent(jtPATH_FIND, "PathRequest::updateAll"); + auto event = app_.getJobQueue().makeLoadEvent(jtPATH_FIND, "PathRequest::updateAll"); std::vector requests; std::shared_ptr cache; @@ -65,15 +58,12 @@ PathRequests::updateAll(std::shared_ptr const& inLedger) bool newRequests = app_.getLedgerMaster().isNewPathRequest(); bool mustBreak = false; - JLOG(mJournal.trace()) << "updateAll seq=" << cache->getLedger()->seq() - << ", " << requests.size() << " requests"; + JLOG(mJournal.trace()) << "updateAll seq=" << cache->getLedger()->seq() << ", " << requests.size() << " requests"; int processed = 0, removed = 0; - auto getSubscriber = - [](PathRequest::pointer const& request) -> InfoSub::pointer { - if (auto ipSub = request->getSubscriber(); - ipSub && ipSub->getRequest() == request) + auto getSubscriber = [](PathRequest::pointer const& request) -> InfoSub::pointer { + if (auto ipSub = request->getSubscriber(); ipSub && ipSub->getRequest() == request) { return ipSub; } @@ -91,8 +81,7 @@ PathRequests::updateAll(std::shared_ptr const& inLedger) auto request = wr.lock(); bool remove = true; - JLOG(mJournal.trace()) - << "updateAll request " << (request ? "" : "not ") << "found"; + JLOG(mJournal.trace()) << "updateAll request " << (request ? "" : "not ") << "found"; if (request) { @@ -102,8 +91,7 @@ PathRequests::updateAll(std::shared_ptr const& inLedger) // indicates that this request is no longer relevant. return (bool)getSubscriber(request); }; - if (!request->needsUpdate( - newRequests, cache->getLedger()->seq())) + if (!request->needsUpdate(newRequests, cache->getLedger()->seq())) remove = false; else { @@ -115,8 +103,7 @@ PathRequests::updateAll(std::shared_ptr const& inLedger) // it can be freed if the client disconnects, and // thus fail to lock later. ipSub.reset(); - Json::Value update = request->doUpdate( - cache, false, continueCallback); + Json::Value update = request->doUpdate(cache, false, continueCallback); request->updateComplete(); update[jss::type] = "path_find"; if ((ipSub = getSubscriber(request))) @@ -143,23 +130,19 @@ PathRequests::updateAll(std::shared_ptr const& inLedger) // Remove any dangling weak pointers or weak // pointers that refer to this path request. - auto ret = std::remove_if( - requests_.begin(), - requests_.end(), - [&removed, &request](auto const& wl) { - auto r = wl.lock(); + auto ret = std::remove_if(requests_.begin(), requests_.end(), [&removed, &request](auto const& wl) { + auto r = wl.lock(); - if (r && r != request) - return false; - ++removed; - return true; - }); + if (r && r != request) + return false; + ++removed; + return true; + }); requests_.erase(ret, requests_.end()); } - mustBreak = - !newRequests && app_.getLedgerMaster().isNewPathRequest(); + mustBreak = !newRequests && app_.getLedgerMaster().isNewPathRequest(); // We weren't handling new requests and then // there was a new request @@ -197,8 +180,7 @@ PathRequests::updateAll(std::shared_ptr const& inLedger) } } while (!app_.getJobQueue().isStopping()); - JLOG(mJournal.debug()) << "updateAll complete: " << processed - << " processed and " << removed << " removed"; + JLOG(mJournal.debug()) << "updateAll complete: " << processed << " processed and " << removed << " removed"; } bool @@ -215,13 +197,12 @@ PathRequests::insertPathRequest(PathRequest::pointer const& req) // Insert after any older unserviced requests but before // any serviced requests - auto ret = - std::find_if(requests_.begin(), requests_.end(), [](auto const& wl) { - auto r = wl.lock(); + auto ret = std::find_if(requests_.begin(), requests_.end(), [](auto const& wl) { + auto r = wl.lock(); - // We come before handled requests - return r && !r->isNew(); - }); + // We come before handled requests + return r && !r->isNew(); + }); requests_.emplace(ret, req); } @@ -233,11 +214,9 @@ PathRequests::makePathRequest( std::shared_ptr const& inLedger, Json::Value const& requestJson) { - auto req = std::make_shared( - app_, subscriber, ++mLastIdentifier, *this, mJournal); + auto req = std::make_shared(app_, subscriber, ++mLastIdentifier, *this, mJournal); - auto [valid, jvRes] = - req->doCreate(getLineCache(inLedger, false), requestJson); + auto [valid, jvRes] = req->doCreate(getLineCache(inLedger, false), requestJson); if (valid) { @@ -259,8 +238,7 @@ PathRequests::makeLegacyPathRequest( { // This assignment must take place before the // completion function is called - req = std::make_shared( - app_, completion, consumer, ++mLastIdentifier, *this, mJournal); + req = std::make_shared(app_, completion, consumer, ++mLastIdentifier, *this, mJournal); auto [valid, jvRes] = req->doCreate(getLineCache(inLedger, false), request); @@ -288,11 +266,9 @@ PathRequests::doLegacyPathRequest( std::shared_ptr const& inLedger, Json::Value const& request) { - auto cache = std::make_shared( - inLedger, app_.journal("RippleLineCache")); + auto cache = std::make_shared(inLedger, app_.journal("RippleLineCache")); - auto req = std::make_shared( - app_, [] {}, consumer, ++mLastIdentifier, *this, mJournal); + auto req = std::make_shared(app_, [] {}, consumer, ++mLastIdentifier, *this, mJournal); auto [valid, jvRes] = req->doCreate(cache, request); if (valid) diff --git a/src/xrpld/app/paths/PathRequests.h b/src/xrpld/app/paths/PathRequests.h index 5c97bafa8a..f89ca3c4da 100644 --- a/src/xrpld/app/paths/PathRequests.h +++ b/src/xrpld/app/paths/PathRequests.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_PATHS_PATHREQUESTS_H_INCLUDED -#define XRPL_APP_PATHS_PATHREQUESTS_H_INCLUDED +#pragma once #include #include @@ -15,10 +14,7 @@ class PathRequests { public: /** A collection of all PathRequest instances. */ - PathRequests( - Application& app, - beast::Journal journal, - beast::insight::Collector::ptr const& collector) + PathRequests(Application& app, beast::Journal journal, beast::insight::Collector::ptr const& collector) : app_(app), mJournal(journal), mLastIdentifier(0) { mFast = collector->make_event("pathfind_fast"); @@ -36,9 +32,7 @@ public: requestsPending() const; std::shared_ptr - getLineCache( - std::shared_ptr const& ledger, - bool authoritative); + getLineCache(std::shared_ptr const& ledger, bool authoritative); // Create a new-style path request that pushes // updates to a subscriber @@ -101,5 +95,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/src/xrpld/app/paths/Pathfinder.cpp b/src/xrpld/app/paths/Pathfinder.cpp index c99467dade..ea4fa2013a 100644 --- a/src/xrpld/app/paths/Pathfinder.cpp +++ b/src/xrpld/app/paths/Pathfinder.cpp @@ -1,4 +1,3 @@ -#include #include #include #include @@ -9,6 +8,7 @@ #include #include #include +#include #include #include @@ -62,10 +62,7 @@ struct AccountCandidate }; bool -compareAccountCandidate( - std::uint32_t seq, - AccountCandidate const& first, - AccountCandidate const& second) +compareAccountCandidate(std::uint32_t seq, AccountCandidate const& first, AccountCandidate const& second) { if (first.priority < second.priority) return false; @@ -151,17 +148,12 @@ Pathfinder::Pathfinder( Application& app) : mSrcAccount(uSrcAccount) , mDstAccount(uDstAccount) - , mEffectiveDst( - isXRP(saDstAmount.getIssuer()) ? uDstAccount - : saDstAmount.getIssuer()) + , mEffectiveDst(isXRP(saDstAmount.getIssuer()) ? uDstAccount : saDstAmount.getIssuer()) , mDstAmount(saDstAmount) , mSrcCurrency(uSrcCurrency) , mSrcIssuer(uSrcIssuer) , mSrcAmount(srcAmount.value_or(STAmount( - Issue{ - uSrcCurrency, - uSrcIssuer.value_or( - isXRP(uSrcCurrency) ? xrpAccount() : uSrcAccount)}, + Issue{uSrcCurrency, uSrcIssuer.value_or(isXRP(uSrcCurrency) ? xrpAccount() : uSrcAccount)}, 1u, 0, true))) @@ -173,14 +165,11 @@ Pathfinder::Pathfinder( , j_(app.journal("Pathfinder")) { XRPL_ASSERT( - !uSrcIssuer || isXRP(uSrcCurrency) == isXRP(uSrcIssuer.value()), - "xrpl::Pathfinder::Pathfinder : valid inputs"); + !uSrcIssuer || isXRP(uSrcCurrency) == isXRP(uSrcIssuer.value()), "xrpl::Pathfinder::Pathfinder : valid inputs"); } bool -Pathfinder::findPaths( - int searchLevel, - std::function const& continueCallback) +Pathfinder::findPaths(int searchLevel, std::function const& continueCallback) { JLOG(j_.trace()) << "findPaths start"; if (mDstAmount == beast::zero) @@ -194,8 +183,7 @@ Pathfinder::findPaths( // below - why don't we do it each time we return false? } - if (mSrcAccount == mDstAccount && mDstAccount == mEffectiveDst && - mSrcCurrency == mDstAmount.getCurrency()) + if (mSrcAccount == mDstAccount && mDstAccount == mEffectiveDst && mSrcCurrency == mDstAmount.getCurrency()) { // No need to send to same account with same currency. JLOG(j_.debug()) << "Tried to send to same issuer"; @@ -203,8 +191,7 @@ Pathfinder::findPaths( return false; } - if (mSrcAccount == mEffectiveDst && - mSrcCurrency == mDstAmount.getCurrency()) + if (mSrcAccount == mEffectiveDst && mSrcCurrency == mDstAmount.getCurrency()) { // Default path might work, but any path would loop return true; @@ -217,13 +204,10 @@ Pathfinder::findPaths( auto& account = useIssuerAccount ? *mSrcIssuer : mSrcAccount; auto issuer = currencyIsXRP ? AccountID() : account; mSource = STPathElement(account, mSrcCurrency, issuer); - auto issuerString = - mSrcIssuer ? to_string(*mSrcIssuer) : std::string("none"); + auto issuerString = mSrcIssuer ? to_string(*mSrcIssuer) : std::string("none"); JLOG(j_.trace()) << "findPaths>" - << " mSrcAccount=" << mSrcAccount - << " mDstAccount=" << mDstAccount - << " mDstAmount=" << mDstAmount.getFullText() - << " mSrcCurrency=" << mSrcCurrency + << " mSrcAccount=" << mSrcAccount << " mDstAccount=" << mDstAccount + << " mDstAmount=" << mDstAmount.getFullText() << " mSrcCurrency=" << mSrcCurrency << " mSrcIssuer=" << issuerString; if (!mLedger) @@ -242,8 +226,7 @@ Pathfinder::findPaths( return false; } - if ((mEffectiveDst != mDstAccount) && - !mLedger->exists(keylet::account(mEffectiveDst))) + if ((mEffectiveDst != mDstAccount) && !mLedger->exists(keylet::account(mEffectiveDst))) { JLOG(j_.debug()) << "Non-existent gateway"; return false; @@ -262,9 +245,7 @@ Pathfinder::findPaths( auto const reserve = STAmount(mLedger->fees().reserve); if (mDstAmount < reserve) { - JLOG(j_.debug()) - << "New account not getting enough funding: " << mDstAmount - << " < " << reserve; + JLOG(j_.debug()) << "New account not getting enough funding: " << mDstAmount << " < " << reserve; return false; } } @@ -349,15 +330,7 @@ Pathfinder::getPathLiquidity( rcInput.partialPaymentAllowed = true; auto rc = path::RippleCalc::rippleCalculate( - sandbox, - mSrcAmount, - minDstAmount, - mDstAccount, - mSrcAccount, - pathSet, - mDomain, - app_.logs(), - &rcInput); + sandbox, mSrcAmount, minDstAmount, mDstAccount, mSrcAccount, pathSet, mDomain, app_.logs(), &rcInput); // If we can't get even the minimum liquidity requested, we're done. if (rc.result() != tesSUCCESS) return rc.result(); @@ -389,16 +362,13 @@ Pathfinder::getPathLiquidity( } catch (std::exception const& e) { - JLOG(j_.info()) << "checkpath: exception (" << e.what() << ") " - << path.getJson(JsonOptions::none); + JLOG(j_.info()) << "checkpath: exception (" << e.what() << ") " << path.getJson(JsonOptions::none); return tefEXCEPTION; } } void -Pathfinder::computePathRanks( - int maxPaths, - std::function const& continueCallback) +Pathfinder::computePathRanks(int maxPaths, std::function const& continueCallback) { mRemainingAmount = convertAmount(mDstAmount, convert_all_); @@ -422,14 +392,12 @@ Pathfinder::computePathRanks( if (rc.result() == tesSUCCESS) { - JLOG(j_.debug()) - << "Default path contributes: " << rc.actualAmountIn; + JLOG(j_.debug()) << "Default path contributes: " << rc.actualAmountIn; mRemainingAmount -= rc.actualAmountOut; } else { - JLOG(j_.debug()) - << "Default path fails: " << transToken(rc.result()); + JLOG(j_.debug()) << "Default path fails: " << transToken(rc.result()); } } catch (std::exception const&) @@ -481,8 +449,7 @@ Pathfinder::rankPaths( std::vector& rankedPaths, std::function const& continueCallback) { - JLOG(j_.trace()) << "rankPaths with " << paths.size() << " candidates, and " - << maxPaths << " maximum"; + JLOG(j_.trace()) << "rankPaths with " << paths.size() << " candidates, and " << maxPaths << " maximum"; rankedPaths.clear(); rankedPaths.reserve(paths.size()); @@ -507,21 +474,18 @@ Pathfinder::rankPaths( { STAmount liquidity; uint64_t uQuality; - auto const resultCode = getPathLiquidity( - currentPath, saMinDstAmount, liquidity, uQuality); + auto const resultCode = getPathLiquidity(currentPath, saMinDstAmount, liquidity, uQuality); if (resultCode != tesSUCCESS) { - JLOG(j_.debug()) - << "findPaths: dropping : " << transToken(resultCode) - << ": " << currentPath.getJson(JsonOptions::none); + JLOG(j_.debug()) << "findPaths: dropping : " << transToken(resultCode) << ": " + << currentPath.getJson(JsonOptions::none); } else { JLOG(j_.debug()) << "findPaths: quality: " << uQuality << ": " << currentPath.getJson(JsonOptions::none); - rankedPaths.push_back( - {uQuality, currentPath.size(), liquidity, i}); + rankedPaths.push_back({uQuality, currentPath.size(), liquidity, i}); } } } @@ -532,9 +496,7 @@ Pathfinder::rankPaths( // length of path // A better PathRank is lower, best are sorted to the beginning. std::sort( - rankedPaths.begin(), - rankedPaths.end(), - [&](Pathfinder::PathRank const& a, Pathfinder::PathRank const& b) { + rankedPaths.begin(), rankedPaths.end(), [&](Pathfinder::PathRank const& a, Pathfinder::PathRank const& b) { // 1) Higher quality (lower cost) is better if (!convert_all_ && a.quality != b.quality) return a.quality < b.quality; @@ -560,17 +522,13 @@ Pathfinder::getBestPaths( AccountID const& srcIssuer, std::function const& continueCallback) { - JLOG(j_.debug()) << "findPaths: " << mCompletePaths.size() << " paths and " - << extraPaths.size() << " extras"; + JLOG(j_.debug()) << "findPaths: " << mCompletePaths.size() << " paths and " << extraPaths.size() << " extras"; if (mCompletePaths.empty() && extraPaths.empty()) return mCompletePaths; - XRPL_ASSERT( - fullLiquidityPath.empty(), - "xrpl::Pathfinder::getBestPaths : first empty path result"); - bool const issuerIsSender = - isXRP(mSrcCurrency) || (srcIssuer == mSrcAccount); + XRPL_ASSERT(fullLiquidityPath.empty(), "xrpl::Pathfinder::getBestPaths : first empty path result"); + bool const issuerIsSender = isXRP(mSrcCurrency) || (srcIssuer == mSrcAccount); std::vector extraPathRanks; rankPaths(maxPaths, extraPaths, extraPathRanks, continueCallback); @@ -585,8 +543,7 @@ Pathfinder::getBestPaths( auto pathsIterator = mPathRanks.begin(); auto extraPathsIterator = extraPathRanks.begin(); - while (pathsIterator != mPathRanks.end() || - extraPathsIterator != extraPathRanks.end()) + while (pathsIterator != mPathRanks.end() || extraPathsIterator != extraPathRanks.end()) { if (continueCallback && !continueCallback()) break; @@ -614,8 +571,7 @@ Pathfinder::getBestPaths( auto& pathRank = usePath ? *pathsIterator : *extraPathsIterator; - auto const& path = usePath ? mCompletePaths[pathRank.index] - : extraPaths[pathRank.index]; + auto const& path = usePath ? mCompletePaths[pathRank.index] : extraPaths[pathRank.index]; if (useExtraPath) ++extraPathsIterator; @@ -648,42 +604,33 @@ Pathfinder::getBestPaths( startsWithIssuer = true; } - if (iPathsLeft > 1 || - (iPathsLeft > 0 && pathRank.liquidity >= remaining)) + if (iPathsLeft > 1 || (iPathsLeft > 0 && pathRank.liquidity >= remaining)) // last path must fill { --iPathsLeft; remaining -= pathRank.liquidity; bestPaths.push_back(startsWithIssuer ? removeIssuer(path) : path); } - else if ( - iPathsLeft == 0 && pathRank.liquidity >= mDstAmount && - fullLiquidityPath.empty()) + else if (iPathsLeft == 0 && pathRank.liquidity >= mDstAmount && fullLiquidityPath.empty()) { // We found an extra path that can move the whole amount. fullLiquidityPath = (startsWithIssuer ? removeIssuer(path) : path); - JLOG(j_.debug()) << "Found extra full path: " - << fullLiquidityPath.getJson(JsonOptions::none); + JLOG(j_.debug()) << "Found extra full path: " << fullLiquidityPath.getJson(JsonOptions::none); } else { - JLOG(j_.debug()) << "Skipping a non-filling path: " - << path.getJson(JsonOptions::none); + JLOG(j_.debug()) << "Skipping a non-filling path: " << path.getJson(JsonOptions::none); } } if (remaining > beast::zero) { - XRPL_ASSERT( - fullLiquidityPath.empty(), - "xrpl::Pathfinder::getBestPaths : second empty path result"); - JLOG(j_.info()) << "Paths could not send " << remaining << " of " - << mDstAmount; + XRPL_ASSERT(fullLiquidityPath.empty(), "xrpl::Pathfinder::getBestPaths : second empty path result"); + JLOG(j_.info()) << "Paths could not send " << remaining << " of " << mDstAmount; } else { - JLOG(j_.debug()) << "findPaths: RESULTS: " - << bestPaths.getJson(JsonOptions::none); + JLOG(j_.debug()) << "findPaths: RESULTS: " << bestPaths.getJson(JsonOptions::none); } return bestPaths; } @@ -692,9 +639,8 @@ bool Pathfinder::issueMatchesOrigin(Issue const& issue) { bool matchingCurrency = (issue.currency == mSrcCurrency); - bool matchingAccount = isXRP(issue.currency) || - (mSrcIssuer && issue.account == mSrcIssuer) || - issue.account == mSrcAccount; + bool matchingAccount = + isXRP(issue.currency) || (mSrcIssuer && issue.account == mSrcIssuer) || issue.account == mSrcAccount; return matchingCurrency && matchingAccount; } @@ -740,13 +686,11 @@ Pathfinder::getPathsOut( } else if ( rspEntry.getBalance() <= beast::zero && - (!rspEntry.getLimitPeer() || - -rspEntry.getBalance() >= rspEntry.getLimitPeer() || + (!rspEntry.getLimitPeer() || -rspEntry.getBalance() >= rspEntry.getLimitPeer() || (bAuthRequired && !rspEntry.getAuth()))) { } - else if ( - isDstCurrency && dstAccount == rspEntry.getAccountIDPeer()) + else if (isDstCurrency && dstAccount == rspEntry.getAccountIDPeer()) { count += 10000; // count a path to the destination extra } @@ -776,8 +720,7 @@ Pathfinder::addLinks( int addFlags, std::function const& continueCallback) { - JLOG(j_.debug()) << "addLink< on " << currentPaths.size() - << " source(s), flags=" << addFlags; + JLOG(j_.debug()) << "addLink< on " << currentPaths.size() << " source(s), flags=" << addFlags; for (auto const& path : currentPaths) { if (continueCallback && !continueCallback()) @@ -787,12 +730,9 @@ Pathfinder::addLinks( } STPathSet& -Pathfinder::addPathsForType( - PathType const& pathType, - std::function const& continueCallback) +Pathfinder::addPathsForType(PathType const& pathType, std::function const& continueCallback) { - JLOG(j_.debug()) << "addPathsForType " - << CollectionAndDelimiter(pathType, ", "); + JLOG(j_.debug()) << "addPathsForType " << CollectionAndDelimiter(pathType, ", "); // See if the set of paths for this type already exists. auto it = mPaths.find(pathType); if (it != mPaths.end()) @@ -809,12 +749,10 @@ Pathfinder::addPathsForType( PathType parentPathType = pathType; parentPathType.pop_back(); - STPathSet const& parentPaths = - addPathsForType(parentPathType, continueCallback); + STPathSet const& parentPaths = addPathsForType(parentPathType, continueCallback); STPathSet& pathsOut = mPaths[pathType]; - JLOG(j_.debug()) << "getPaths< adding onto '" - << pathTypeToString(parentPathType) << "' to get '" + JLOG(j_.debug()) << "getPaths< adding onto '" << pathTypeToString(parentPathType) << "' to get '" << pathTypeToString(pathType) << "'"; int initialSize = mCompletePaths.size(); @@ -825,9 +763,7 @@ Pathfinder::addPathsForType( { case nt_SOURCE: // Source must always be at the start, so pathsOut has to be empty. - XRPL_ASSERT( - pathsOut.empty(), - "xrpl::Pathfinder::addPathsForType : empty paths"); + XRPL_ASSERT(pathsOut.empty(), "xrpl::Pathfinder::addPathsForType : empty paths"); pathsOut.push_back(STPath()); break; @@ -840,55 +776,36 @@ Pathfinder::addPathsForType( break; case nt_XRP_BOOK: - addLinks( - parentPaths, - pathsOut, - afADD_BOOKS | afOB_XRP, - continueCallback); + addLinks(parentPaths, pathsOut, afADD_BOOKS | afOB_XRP, continueCallback); break; case nt_DEST_BOOK: - addLinks( - parentPaths, - pathsOut, - afADD_BOOKS | afOB_LAST, - continueCallback); + addLinks(parentPaths, pathsOut, afADD_BOOKS | afOB_LAST, continueCallback); break; case nt_DESTINATION: // FIXME: What if a different issuer was specified on the // destination amount? // TODO(tom): what does this even mean? Should it be a JIRA? - addLinks( - parentPaths, - pathsOut, - afADD_ACCOUNTS | afAC_LAST, - continueCallback); + addLinks(parentPaths, pathsOut, afADD_ACCOUNTS | afAC_LAST, continueCallback); break; } if (mCompletePaths.size() != initialSize) { - JLOG(j_.debug()) << (mCompletePaths.size() - initialSize) - << " complete paths added"; + JLOG(j_.debug()) << (mCompletePaths.size() - initialSize) << " complete paths added"; } - JLOG(j_.debug()) << "getPaths> " << pathsOut.size() - << " partial paths found"; + JLOG(j_.debug()) << "getPaths> " << pathsOut.size() << " partial paths found"; return pathsOut; } bool -Pathfinder::isNoRipple( - AccountID const& fromAccount, - AccountID const& toAccount, - Currency const& currency) +Pathfinder::isNoRipple(AccountID const& fromAccount, AccountID const& toAccount, Currency const& currency) { - auto sleRipple = - mLedger->read(keylet::line(toAccount, fromAccount, currency)); + auto sleRipple = mLedger->read(keylet::line(toAccount, fromAccount, currency)); - auto const flag( - (toAccount > fromAccount) ? lsfHighNoRipple : lsfLowNoRipple); + auto const flag((toAccount > fromAccount) ? lsfHighNoRipple : lsfLowNoRipple); return sleRipple && (sleRipple->getFieldU32(sfFlags) & flag); } @@ -910,9 +827,7 @@ Pathfinder::isNoRippleOut(STPath const& currentPath) // If there's only one item in the path, return true if that item specifies // no ripple on the output. A path with no ripple on its output can't be // followed by a link with no ripple on its input. - auto const& fromAccount = (currentPath.size() == 1) - ? mSrcAccount - : (currentPath.end() - 2)->getAccountID(); + auto const& fromAccount = (currentPath.size() == 1) ? mSrcAccount : (currentPath.end() - 2)->getAccountID(); auto const& toAccount = endElement.getAccountID(); return isNoRipple(fromAccount, toAccount, endElement.getCurrency()); } @@ -959,8 +874,7 @@ Pathfinder::addLink( { if (mDstAmount.native() && !currentPath.empty()) { // non-default path to XRP destination - JLOG(j_.trace()) << "complete path found ax: " - << currentPath.getJson(JsonOptions::none); + JLOG(j_.trace()) << "complete path found ax: " << currentPath.getJson(JsonOptions::none); addUniquePath(mCompletePaths, currentPath); } } @@ -971,17 +885,13 @@ Pathfinder::addLink( if (sleEnd) { - bool const bRequireAuth( - sleEnd->getFieldU32(sfFlags) & lsfRequireAuth); - bool const bIsEndCurrency( - uEndCurrency == mDstAmount.getCurrency()); + bool const bRequireAuth(sleEnd->getFieldU32(sfFlags) & lsfRequireAuth); + bool const bIsEndCurrency(uEndCurrency == mDstAmount.getCurrency()); bool const bIsNoRippleOut(isNoRippleOut(currentPath)); bool const bDestOnly(addFlags & afAC_LAST); if (auto const lines = mRLCache->getRippleLines( - uEndAccount, - bIsNoRippleOut ? LineDirection::incoming - : LineDirection::outgoing)) + uEndAccount, bIsNoRippleOut ? LineDirection::incoming : LineDirection::outgoing)) { auto& rippleLines = *lines; @@ -1014,8 +924,7 @@ Pathfinder::addLink( // path is for correct currency and has not been // seen if (rs.getBalance() <= beast::zero && - (!rs.getLimitPeer() || - -rs.getBalance() >= rs.getLimitPeer() || + (!rs.getLimitPeer() || -rs.getBalance() >= rs.getLimitPeer() || (bRequireAuth && !rs.getAuth()))) { // path has no credit @@ -1033,18 +942,14 @@ Pathfinder::addLink( if (!currentPath.empty()) { JLOG(j_.trace()) - << "complete path found ae: " - << currentPath.getJson( - JsonOptions::none); - addUniquePath( - mCompletePaths, currentPath); + << "complete path found ae: " << currentPath.getJson(JsonOptions::none); + addUniquePath(mCompletePaths, currentPath); } } else if (!bDestOnly) { // this is a high-priority candidate - candidates.push_back( - {AccountCandidate::highPriority, acct}); + candidates.push_back({AccountCandidate::highPriority, acct}); } } else if (acct == mSrcAccount) @@ -1055,12 +960,7 @@ Pathfinder::addLink( { // save this candidate int out = getPathsOut( - uEndCurrency, - acct, - direction, - bIsEndCurrency, - mEffectiveDst, - continueCallback); + uEndCurrency, acct, direction, bIsEndCurrency, mEffectiveDst, continueCallback); if (out) candidates.push_back({out, acct}); } @@ -1073,10 +973,7 @@ Pathfinder::addLink( candidates.begin(), candidates.end(), std::bind( - compareAccountCandidate, - mLedger->seq(), - std::placeholders::_1, - std::placeholders::_2)); + compareAccountCandidate, mLedger->seq(), std::placeholders::_1, std::placeholders::_2)); int count = candidates.size(); // allow more paths from source @@ -1092,12 +989,8 @@ Pathfinder::addLink( return; // Add accounts to incompletePaths STPathElement pathElement( - STPathElement::typeAccount, - it->account, - uEndCurrency, - it->account); - incompletePaths.assembleAdd( - currentPath, pathElement); + STPathElement::typeAccount, it->account, uEndCurrency, it->account); + incompletePaths.assembleAdd(currentPath, pathElement); ++it; } } @@ -1115,35 +1008,24 @@ Pathfinder::addLink( if (addFlags & afOB_XRP) { // to XRP only - if (!bOnXRP && - app_.getOrderBookDB().isBookToXRP( - {uEndCurrency, uEndIssuer}, mDomain)) + if (!bOnXRP && app_.getOrderBookDB().isBookToXRP({uEndCurrency, uEndIssuer}, mDomain)) { - STPathElement pathElement( - STPathElement::typeCurrency, - xrpAccount(), - xrpCurrency(), - xrpAccount()); + STPathElement pathElement(STPathElement::typeCurrency, xrpAccount(), xrpCurrency(), xrpAccount()); incompletePaths.assembleAdd(currentPath, pathElement); } } else { bool bDestOnly = (addFlags & afOB_LAST) != 0; - auto books = app_.getOrderBookDB().getBooksByTakerPays( - {uEndCurrency, uEndIssuer}, mDomain); - JLOG(j_.trace()) - << books.size() << " books found from this currency/issuer"; + auto books = app_.getOrderBookDB().getBooksByTakerPays({uEndCurrency, uEndIssuer}, mDomain); + JLOG(j_.trace()) << books.size() << " books found from this currency/issuer"; for (auto const& book : books) { if (continueCallback && !continueCallback()) return; - if (!currentPath.hasSeen( - xrpAccount(), book.out.currency, book.out.account) && - !issueMatchesOrigin(book.out) && - (!bDestOnly || - (book.out.currency == mDstAmount.getCurrency()))) + if (!currentPath.hasSeen(xrpAccount(), book.out.currency, book.out.account) && + !issueMatchesOrigin(book.out) && (!bDestOnly || (book.out.currency == mDstAmount.getCurrency()))) { STPath newPath(currentPath); @@ -1151,39 +1033,28 @@ Pathfinder::addLink( { // to XRP // add the order book itself - newPath.emplace_back( - STPathElement::typeCurrency, - xrpAccount(), - xrpCurrency(), - xrpAccount()); + newPath.emplace_back(STPathElement::typeCurrency, xrpAccount(), xrpCurrency(), xrpAccount()); if (mDstAmount.getCurrency().isZero()) { // destination is XRP, add account and path is // complete - JLOG(j_.trace()) - << "complete path found bx: " - << currentPath.getJson(JsonOptions::none); + JLOG(j_.trace()) << "complete path found bx: " << currentPath.getJson(JsonOptions::none); addUniquePath(mCompletePaths, newPath); } else incompletePaths.push_back(newPath); } - else if (!currentPath.hasSeen( - book.out.account, - book.out.currency, - book.out.account)) + else if (!currentPath.hasSeen(book.out.account, book.out.currency, book.out.account)) { // Don't want the book if we've already seen the issuer // book -> account -> book - if ((newPath.size() >= 2) && - (newPath.back().isAccount()) && + if ((newPath.size() >= 2) && (newPath.back().isAccount()) && (newPath[newPath.size() - 2].isOffer())) { // replace the redundant account with the order book newPath[newPath.size() - 1] = STPathElement( - STPathElement::typeCurrency | - STPathElement::typeIssuer, + STPathElement::typeCurrency | STPathElement::typeIssuer, xrpAccount(), book.out.currency, book.out.account); @@ -1192,27 +1063,21 @@ Pathfinder::addLink( { // add the order book newPath.emplace_back( - STPathElement::typeCurrency | - STPathElement::typeIssuer, + STPathElement::typeCurrency | STPathElement::typeIssuer, xrpAccount(), book.out.currency, book.out.account); } - if (hasEffectiveDestination && - book.out.account == mDstAccount && + if (hasEffectiveDestination && book.out.account == mDstAccount && book.out.currency == mDstAmount.getCurrency()) { // We skipped a required issuer } - else if ( - book.out.account == mEffectiveDst && - book.out.currency == mDstAmount.getCurrency()) + else if (book.out.account == mEffectiveDst && book.out.currency == mDstAmount.getCurrency()) { // with the destination account, this path is // complete - JLOG(j_.trace()) - << "complete path found ba: " - << currentPath.getJson(JsonOptions::none); + JLOG(j_.trace()) << "complete path found ba: " << currentPath.getJson(JsonOptions::none); addUniquePath(mCompletePaths, newPath); } else @@ -1221,10 +1086,7 @@ Pathfinder::addLink( incompletePaths.assembleAdd( newPath, STPathElement( - STPathElement::typeAccount, - book.out.account, - book.out.currency, - book.out.account)); + STPathElement::typeAccount, book.out.account, book.out.currency, book.out.account)); } } } diff --git a/src/xrpld/app/paths/Pathfinder.h b/src/xrpld/app/paths/Pathfinder.h index b269cc868b..03f2d6f038 100644 --- a/src/xrpld/app/paths/Pathfinder.h +++ b/src/xrpld/app/paths/Pathfinder.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_PATHS_PATHFINDER_H_INCLUDED -#define XRPL_APP_PATHS_PATHFINDER_H_INCLUDED +#pragma once #include #include @@ -40,15 +39,11 @@ public: initPathTable(); bool - findPaths( - int searchLevel, - std::function const& continueCallback = {}); + findPaths(int searchLevel, std::function const& continueCallback = {}); /** Compute the rankings of the paths. */ void - computePathRanks( - int maxPaths, - std::function const& continueCallback = {}); + computePathRanks(int maxPaths, std::function const& continueCallback = {}); /* Get the best paths, up to maxPaths in number, from mCompletePaths. @@ -64,11 +59,11 @@ public: std::function const& continueCallback = {}); enum NodeType { - nt_SOURCE, // The source account: with an issuer account, if needed. - nt_ACCOUNTS, // Accounts that connect from this source/currency. - nt_BOOKS, // Order books that connect to this currency. - nt_XRP_BOOK, // The order book from this currency to XRP. - nt_DEST_BOOK, // The order book to the destination currency/issuer. + nt_SOURCE, // The source account: with an issuer account, if needed. + nt_ACCOUNTS, // Accounts that connect from this source/currency. + nt_BOOKS, // Order books that connect to this currency. + nt_XRP_BOOK, // The order book from this currency to XRP. + nt_DEST_BOOK, // The order book to the destination currency/issuer. nt_DESTINATION // The destination account only. }; @@ -116,9 +111,7 @@ private: // Add all paths of one type to mCompletePaths. STPathSet& - addPathsForType( - PathType const& type, - std::function const& continueCallback); + addPathsForType(PathType const& type, std::function const& continueCallback); bool issueMatchesOrigin(Issue const&); @@ -164,10 +157,7 @@ private: // Is the "no ripple" flag set from one account to another? bool - isNoRipple( - AccountID const& fromAccount, - AccountID const& toAccount, - Currency const& currency); + isNoRipple(AccountID const& fromAccount, AccountID const& toAccount, Currency const& currency); void rankPaths( @@ -220,5 +210,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/src/xrpld/app/paths/RippleCalc.cpp b/src/xrpld/app/paths/RippleCalc.cpp index 2b48a6ba5c..0667e1971c 100644 --- a/src/xrpld/app/paths/RippleCalc.cpp +++ b/src/xrpld/app/paths/RippleCalc.cpp @@ -44,22 +44,18 @@ RippleCalc::rippleCalculate( auto j = l.journal("Flow"); { - bool const defaultPaths = - !pInputs ? true : pInputs->defaultPathsAllowed; + bool const defaultPaths = !pInputs ? true : pInputs->defaultPathsAllowed; - bool const partialPayment = - !pInputs ? false : pInputs->partialPaymentAllowed; + bool const partialPayment = !pInputs ? false : pInputs->partialPaymentAllowed; auto const limitQuality = [&]() -> std::optional { - if (pInputs && pInputs->limitQuality && - saMaxAmountReq > beast::zero) + if (pInputs && pInputs->limitQuality && saMaxAmountReq > beast::zero) return Quality{Amounts(saMaxAmountReq, saDstAmountReq)}; return std::nullopt; }(); auto const sendMax = [&]() -> std::optional { - if (saMaxAmountReq >= beast::zero || - saMaxAmountReq.getCurrency() != saDstAmountReq.getCurrency() || + if (saMaxAmountReq >= beast::zero || saMaxAmountReq.getCurrency() != saDstAmountReq.getCurrency() || saMaxAmountReq.getIssuer() != uSrcAccountID) { return saMaxAmountReq; @@ -97,10 +93,8 @@ RippleCalc::rippleCalculate( } j.debug() << "RippleCalc Result> " - << " actualIn: " << flowOut.actualAmountIn - << ", actualOut: " << flowOut.actualAmountOut - << ", result: " << flowOut.result() - << ", dstAmtReq: " << saDstAmountReq + << " actualIn: " << flowOut.actualAmountIn << ", actualOut: " << flowOut.actualAmountOut + << ", result: " << flowOut.result() << ", dstAmtReq: " << saDstAmountReq << ", sendMax: " << saMaxAmountReq; flowSB.apply(view); diff --git a/src/xrpld/app/paths/RippleCalc.h b/src/xrpld/app/paths/RippleCalc.h index 0ef2641e36..a5cecc18bf 100644 --- a/src/xrpld/app/paths/RippleCalc.h +++ b/src/xrpld/app/paths/RippleCalc.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_PATHS_RIPPLECALC_H_INCLUDED -#define XRPL_APP_PATHS_RIPPLECALC_H_INCLUDED +#pragma once #include #include @@ -108,5 +107,3 @@ public: } // namespace path } // namespace xrpl - -#endif diff --git a/src/xrpld/app/paths/RippleLineCache.cpp b/src/xrpld/app/paths/RippleLineCache.cpp index ece4c4149a..aaef368cff 100644 --- a/src/xrpld/app/paths/RippleLineCache.cpp +++ b/src/xrpld/app/paths/RippleLineCache.cpp @@ -3,9 +3,7 @@ namespace xrpl { -RippleLineCache::RippleLineCache( - std::shared_ptr const& ledger, - beast::Journal j) +RippleLineCache::RippleLineCache(std::shared_ptr const& ledger, beast::Journal j) : ledger_(ledger), journal_(j) { JLOG(journal_.debug()) << "created for ledger " << ledger_->header().seq; @@ -13,23 +11,17 @@ RippleLineCache::RippleLineCache( RippleLineCache::~RippleLineCache() { - JLOG(journal_.debug()) << "destroyed for ledger " << ledger_->header().seq - << " with " << lines_.size() << " accounts and " - << totalLineCount_ << " distinct trust lines."; + JLOG(journal_.debug()) << "destroyed for ledger " << ledger_->header().seq << " with " << lines_.size() + << " accounts and " << totalLineCount_ << " distinct trust lines."; } std::shared_ptr> -RippleLineCache::getRippleLines( - AccountID const& accountID, - LineDirection direction) +RippleLineCache::getRippleLines(AccountID const& accountID, LineDirection direction) { auto const hash = hasher_(accountID); AccountKey key(accountID, direction, hash); AccountKey otherkey( - accountID, - direction == LineDirection::outgoing ? LineDirection::incoming - : LineDirection::outgoing, - hash); + accountID, direction == LineDirection::outgoing ? LineDirection::incoming : LineDirection::outgoing, hash); std::lock_guard sl(mLock); @@ -40,18 +32,13 @@ RippleLineCache::getRippleLines( // number of trust line objects held in memory. Ensure that there is // only a single set of trustlines in the cache per account. auto const size = otheriter->second ? otheriter->second->size() : 0; - JLOG(journal_.info()) - << "Request for " - << (direction == LineDirection::outgoing ? "outgoing" - : "incoming") - << " trust lines for account " << accountID << " found " << size - << (direction == LineDirection::outgoing ? " incoming" - : " outgoing") - << " trust lines. " - << (direction == LineDirection::outgoing - ? "Deleting the subset of incoming" - : "Returning the superset of outgoing") - << " trust lines. "; + JLOG(journal_.info()) << "Request for " << (direction == LineDirection::outgoing ? "outgoing" : "incoming") + << " trust lines for account " << accountID << " found " << size + << (direction == LineDirection::outgoing ? " incoming" : " outgoing") + << " trust lines. " + << (direction == LineDirection::outgoing ? "Deleting the subset of incoming" + : "Returning the superset of outgoing") + << " trust lines. "; if (direction == LineDirection::outgoing) { // This request is for the outgoing set, but there is already a @@ -59,9 +46,7 @@ RippleLineCache::getRippleLines( // to be replaced by the full set. The full set will be built // below, and will be returned, if needed, on subsequent calls // for either value of outgoing. - XRPL_ASSERT( - size <= totalLineCount_, - "xrpl::RippleLineCache::getRippleLines : maximum lines"); + XRPL_ASSERT(size <= totalLineCount_, "xrpl::RippleLineCache::getRippleLines : maximum lines"); totalLineCount_ -= size; lines_.erase(otheriter); } @@ -81,32 +66,22 @@ RippleLineCache::getRippleLines( if (inserted) { - XRPL_ASSERT( - it->second == nullptr, - "xrpl::RippleLineCache::getRippleLines : null lines"); - auto lines = - PathFindTrustLine::getItems(accountID, *ledger_, direction); + XRPL_ASSERT(it->second == nullptr, "xrpl::RippleLineCache::getRippleLines : null lines"); + auto lines = PathFindTrustLine::getItems(accountID, *ledger_, direction); if (lines.size()) { - it->second = std::make_shared>( - std::move(lines)); + it->second = std::make_shared>(std::move(lines)); totalLineCount_ += it->second->size(); } } XRPL_ASSERT( - !it->second || (it->second->size() > 0), - "xrpl::RippleLineCache::getRippleLines : null or nonempty lines"); + !it->second || (it->second->size() > 0), "xrpl::RippleLineCache::getRippleLines : null or nonempty lines"); auto const size = it->second ? it->second->size() : 0; - JLOG(journal_.trace()) << "getRippleLines for ledger " - << ledger_->header().seq << " found " << size - << (key.direction_ == LineDirection::outgoing - ? " outgoing" - : " incoming") - << " lines for " << (inserted ? "new " : "existing ") - << accountID << " out of a total of " - << lines_.size() << " accounts and " - << totalLineCount_ << " trust lines"; + JLOG(journal_.trace()) << "getRippleLines for ledger " << ledger_->header().seq << " found " << size + << (key.direction_ == LineDirection::outgoing ? " outgoing" : " incoming") << " lines for " + << (inserted ? "new " : "existing ") << accountID << " out of a total of " << lines_.size() + << " accounts and " << totalLineCount_ << " trust lines"; return it->second; } diff --git a/src/xrpld/app/paths/RippleLineCache.h b/src/xrpld/app/paths/RippleLineCache.h index c2763ca2b4..5dbdb414ee 100644 --- a/src/xrpld/app/paths/RippleLineCache.h +++ b/src/xrpld/app/paths/RippleLineCache.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_PATHS_RIPPLELINECACHE_H_INCLUDED -#define XRPL_APP_PATHS_RIPPLELINECACHE_H_INCLUDED +#pragma once #include #include @@ -17,9 +16,7 @@ namespace xrpl { class RippleLineCache final : public CountedObject { public: - explicit RippleLineCache( - std::shared_ptr const& l, - beast::Journal j); + explicit RippleLineCache(std::shared_ptr const& l, beast::Journal j); ~RippleLineCache(); std::shared_ptr const& @@ -57,10 +54,7 @@ private: LineDirection direction_; std::size_t hash_value_; - AccountKey( - AccountID const& account, - LineDirection direction, - std::size_t hash) + AccountKey(AccountID const& account, LineDirection direction, std::size_t hash) : account_(account), direction_(direction), hash_value_(hash) { } @@ -73,8 +67,7 @@ private: bool operator==(AccountKey const& lhs) const { - return hash_value_ == lhs.hash_value_ && account_ == lhs.account_ && - direction_ == lhs.direction_; + return hash_value_ == lhs.hash_value_ && account_ == lhs.account_ && direction_ == lhs.direction_; } std::size_t @@ -100,14 +93,8 @@ private: // most accounts are not going to have any entries (estimated over 90%), so // vectors will not need to be created for them. This should lead to far // less memory usage overall. - hash_map< - AccountKey, - std::shared_ptr>, - AccountKey::Hash> - lines_; + hash_map>, AccountKey::Hash> lines_; std::size_t totalLineCount_ = 0; }; } // namespace xrpl - -#endif diff --git a/src/xrpld/app/paths/TrustLine.cpp b/src/xrpld/app/paths/TrustLine.cpp index b6ce9d74b0..f34dcbdf81 100644 --- a/src/xrpld/app/paths/TrustLine.cpp +++ b/src/xrpld/app/paths/TrustLine.cpp @@ -6,9 +6,7 @@ namespace xrpl { -TrustLineBase::TrustLineBase( - std::shared_ptr const& sle, - AccountID const& viewAccount) +TrustLineBase::TrustLineBase(std::shared_ptr const& sle, AccountID const& viewAccount) : key_(sle->key()) , mLowLimit(sle->getFieldAmount(sfLowLimit)) , mHighLimit(sle->getFieldAmount(sfHighLimit)) @@ -30,9 +28,7 @@ TrustLineBase::getJson(int) } std::optional -PathFindTrustLine::makeItem( - AccountID const& accountID, - std::shared_ptr const& sle) +PathFindTrustLine::makeItem(AccountID const& accountID, std::shared_ptr const& sle) { if (!sle || sle->getType() != ltRIPPLE_STATE) return {}; @@ -42,22 +38,14 @@ PathFindTrustLine::makeItem( namespace detail { template std::vector -getTrustLineItems( - AccountID const& accountID, - ReadView const& view, - LineDirection direction = LineDirection::outgoing) +getTrustLineItems(AccountID const& accountID, ReadView const& view, LineDirection direction = LineDirection::outgoing) { std::vector items; - forEachItem( - view, - accountID, - [&items, &accountID, &direction]( - std::shared_ptr const& sleCur) { - auto ret = T::makeItem(accountID, sleCur); - if (ret && - (direction == LineDirection::outgoing || !ret->getNoRipple())) - items.push_back(std::move(*ret)); - }); + forEachItem(view, accountID, [&items, &accountID, &direction](std::shared_ptr const& sleCur) { + auto ret = T::makeItem(accountID, sleCur); + if (ret && (direction == LineDirection::outgoing || !ret->getNoRipple())) + items.push_back(std::move(*ret)); + }); // This list may be around for a while, so free up any unneeded // capacity items.shrink_to_fit(); @@ -67,18 +55,12 @@ getTrustLineItems( } // namespace detail std::vector -PathFindTrustLine::getItems( - AccountID const& accountID, - ReadView const& view, - LineDirection direction) +PathFindTrustLine::getItems(AccountID const& accountID, ReadView const& view, LineDirection direction) { - return detail::getTrustLineItems( - accountID, view, direction); + return detail::getTrustLineItems(accountID, view, direction); } -RPCTrustLine::RPCTrustLine( - std::shared_ptr const& sle, - AccountID const& viewAccount) +RPCTrustLine::RPCTrustLine(std::shared_ptr const& sle, AccountID const& viewAccount) : TrustLineBase(sle, viewAccount) , lowQualityIn_(sle->getFieldU32(sfLowQualityIn)) , lowQualityOut_(sle->getFieldU32(sfLowQualityOut)) @@ -88,9 +70,7 @@ RPCTrustLine::RPCTrustLine( } std::optional -RPCTrustLine::makeItem( - AccountID const& accountID, - std::shared_ptr const& sle) +RPCTrustLine::makeItem(AccountID const& accountID, std::shared_ptr const& sle) { if (!sle || sle->getType() != ltRIPPLE_STATE) return {}; diff --git a/src/xrpld/app/paths/TrustLine.h b/src/xrpld/app/paths/TrustLine.h index a0a58c2bde..a0fce8847a 100644 --- a/src/xrpld/app/paths/TrustLine.h +++ b/src/xrpld/app/paths/TrustLine.h @@ -1,5 +1,4 @@ -#ifndef XRPL_APP_PATHS_RIPPLESTATE_H_INCLUDED -#define XRPL_APP_PATHS_RIPPLESTATE_H_INCLUDED +#pragma once #include #include @@ -36,9 +35,7 @@ class TrustLineBase protected: // This class should not be instantiated directly. Use one of the derived // classes. - TrustLineBase( - std::shared_ptr const& sle, - AccountID const& viewAccount); + TrustLineBase(std::shared_ptr const& sle, AccountID const& viewAccount); ~TrustLineBase() = default; TrustLineBase(TrustLineBase const&) = default; @@ -96,15 +93,13 @@ public: LineDirection getDirection() const { - return getNoRipple() ? LineDirection::incoming - : LineDirection::outgoing; + return getNoRipple() ? LineDirection::incoming : LineDirection::outgoing; } LineDirection getDirectionPeer() const { - return getNoRipplePeer() ? LineDirection::incoming - : LineDirection::outgoing; + return getNoRipplePeer() ? LineDirection::incoming : LineDirection::outgoing; } /** Have we set the freeze flag on our peer */ @@ -170,8 +165,7 @@ protected: }; // This wrapper is used for the path finder -class PathFindTrustLine final : public TrustLineBase, - public CountedObject +class PathFindTrustLine final : public TrustLineBase, public CountedObject { using TrustLineBase::TrustLineBase; @@ -182,25 +176,19 @@ public: makeItem(AccountID const& accountID, std::shared_ptr const& sle); static std::vector - getItems( - AccountID const& accountID, - ReadView const& view, - LineDirection direction); + getItems(AccountID const& accountID, ReadView const& view, LineDirection direction); }; // This wrapper is used for the `AccountLines` command and includes the quality // in and quality out values. -class RPCTrustLine final : public TrustLineBase, - public CountedObject +class RPCTrustLine final : public TrustLineBase, public CountedObject { using TrustLineBase::TrustLineBase; public: RPCTrustLine() = delete; - RPCTrustLine( - std::shared_ptr const& sle, - AccountID const& viewAccount); + RPCTrustLine(std::shared_ptr const& sle, AccountID const& viewAccount); Rate const& getQualityIn() const @@ -228,5 +216,3 @@ private: }; } // namespace xrpl - -#endif diff --git a/src/xrpld/app/paths/detail/AMMLiquidity.cpp b/src/xrpld/app/paths/detail/AMMLiquidity.cpp index 2042467923..ebbb51ce25 100644 --- a/src/xrpld/app/paths/detail/AMMLiquidity.cpp +++ b/src/xrpld/app/paths/detail/AMMLiquidity.cpp @@ -37,15 +37,12 @@ AMMLiquidity::fetchBalances(ReadView const& view) const template TAmounts -AMMLiquidity::generateFibSeqOffer( - TAmounts const& balances) const +AMMLiquidity::generateFibSeqOffer(TAmounts const& balances) const { TAmounts cur{}; - cur.in = toAmount( - getIssue(balances.in), - InitialFibSeqPct * initialBalances_.in, - Number::rounding_mode::upward); + cur.in = + toAmount(getIssue(balances.in), InitialFibSeqPct * initialBalances_.in, Number::rounding_mode::upward); cur.out = swapAssetIn(initialBalances_, cur.in, tradingFee_); if (ammContext_.curIters() == 0) @@ -58,18 +55,13 @@ AMMLiquidity::generateFibSeqOffer( 196418, 317811, 514229, 832040, 1346269}; // clang-format on - XRPL_ASSERT( - !ammContext_.maxItersReached(), - "xrpl::AMMLiquidity::generateFibSeqOffer : maximum iterations"); + XRPL_ASSERT(!ammContext_.maxItersReached(), "xrpl::AMMLiquidity::generateFibSeqOffer : maximum iterations"); cur.out = toAmount( - getIssue(balances.out), - cur.out * fib[ammContext_.curIters() - 1], - Number::rounding_mode::downward); + getIssue(balances.out), cur.out * fib[ammContext_.curIters() - 1], Number::rounding_mode::downward); // swapAssetOut() returns negative in this case if (cur.out >= balances.out) - Throw( - "AMMLiquidity: generateFibSeqOffer exceeds the balance"); + Throw("AMMLiquidity: generateFibSeqOffer exceeds the balance"); cur.in = swapAssetOut(balances, cur.out, tradingFee_); @@ -100,16 +92,13 @@ maxOut(T const& out, Issue const& iss) template std::optional> -AMMLiquidity::maxOffer( - TAmounts const& balances, - Rules const& rules) const +AMMLiquidity::maxOffer(TAmounts const& balances, Rules const& rules) const { if (!rules.enabled(fixAMMOverflowOffer)) { return AMMOffer( *this, - {maxAmount(), - swapAssetIn(balances, maxAmount(), tradingFee_)}, + {maxAmount(), swapAssetIn(balances, maxAmount(), tradingFee_)}, balances, Quality{balances}); } @@ -118,19 +107,13 @@ AMMLiquidity::maxOffer( auto const out = maxOut(balances.out, issueOut()); if (out <= TOut{0} || out >= balances.out) return std::nullopt; - return AMMOffer( - *this, - {swapAssetOut(balances, out, tradingFee_), out}, - balances, - Quality{balances}); + return AMMOffer(*this, {swapAssetOut(balances, out, tradingFee_), out}, balances, Quality{balances}); } } template std::optional> -AMMLiquidity::getOffer( - ReadView const& view, - std::optional const& clobQuality) const +AMMLiquidity::getOffer(ReadView const& view, std::optional const& clobQuality) const { // Can't generate more offers if multi-path. if (ammContext_.maxItersReached()) @@ -145,10 +128,8 @@ AMMLiquidity::getOffer( return std::nullopt; } - JLOG(j_.trace()) << "AMMLiquidity::getOffer balances " - << to_string(initialBalances_.in) << " " - << to_string(initialBalances_.out) << " new balances " - << to_string(balances.in) << " " + JLOG(j_.trace()) << "AMMLiquidity::getOffer balances " << to_string(initialBalances_.in) << " " + << to_string(initialBalances_.out) << " new balances " << to_string(balances.in) << " " << to_string(balances.out); // Can't generate AMM with a better quality than CLOB's @@ -159,9 +140,8 @@ AMMLiquidity::getOffer( // to the requested clobQuality but not exactly and potentially SPQ may keep // on approaching clobQuality for many iterations. Checking for the quality // threshold prevents this scenario. - if (auto const spotPriceQ = Quality{balances}; clobQuality && - (spotPriceQ <= clobQuality || - withinRelativeDistance(spotPriceQ, *clobQuality, Number(1, -7)))) + if (auto const spotPriceQ = Quality{balances}; + clobQuality && (spotPriceQ <= clobQuality || withinRelativeDistance(spotPriceQ, *clobQuality, Number(1, -7)))) { JLOG(j_.trace()) << "AMMLiquidity::getOffer, higher clob quality"; return std::nullopt; @@ -175,8 +155,7 @@ AMMLiquidity::getOffer( auto const amounts = generateFibSeqOffer(balances); if (clobQuality && Quality{amounts} < clobQuality) return std::nullopt; - return AMMOffer( - *this, amounts, balances, Quality{amounts}); + return AMMOffer(*this, amounts, balances, Quality{amounts}); } else if (!clobQuality) { @@ -187,18 +166,14 @@ AMMLiquidity::getOffer( // nullopt if the pool is small. return maxOffer(balances, view.rules()); } - else if ( - auto const amounts = changeSpotPriceQuality( - balances, *clobQuality, tradingFee_, view.rules(), j_)) + else if (auto const amounts = changeSpotPriceQuality(balances, *clobQuality, tradingFee_, view.rules(), j_)) { - return AMMOffer( - *this, *amounts, balances, Quality{*amounts}); + return AMMOffer(*this, *amounts, balances, Quality{*amounts}); } else if (view.rules().enabled(fixAMMv1_2)) { if (auto const maxAMMOffer = maxOffer(balances, view.rules()); - maxAMMOffer && - Quality{maxAMMOffer->amount()} > *clobQuality) + maxAMMOffer && Quality{maxAMMOffer->amount()} > *clobQuality) return maxAMMOffer; } } @@ -219,22 +194,16 @@ AMMLiquidity::getOffer( if (offer) { - if (offer->amount().in > beast::zero && - offer->amount().out > beast::zero) + if (offer->amount().in > beast::zero && offer->amount().out > beast::zero) { - JLOG(j_.trace()) - << "AMMLiquidity::getOffer, created " - << to_string(offer->amount().in) << "/" << issueIn_ << " " - << to_string(offer->amount().out) << "/" << issueOut_; + JLOG(j_.trace()) << "AMMLiquidity::getOffer, created " << to_string(offer->amount().in) << "/" << issueIn_ + << " " << to_string(offer->amount().out) << "/" << issueOut_; return offer; } - JLOG(j_.debug()) << "AMMLiquidity::getOffer, no valid offer " - << ammContext_.multiPath() << " " - << ammContext_.curIters() << " " - << (clobQuality ? clobQuality->rate() : STAmount{}) - << " " << to_string(balances.in) << " " - << to_string(balances.out); + JLOG(j_.debug()) << "AMMLiquidity::getOffer, no valid offer " << ammContext_.multiPath() << " " + << ammContext_.curIters() << " " << (clobQuality ? clobQuality->rate() : STAmount{}) << " " + << to_string(balances.in) << " " << to_string(balances.out); } return std::nullopt; diff --git a/src/xrpld/app/paths/detail/AMMOffer.cpp b/src/xrpld/app/paths/detail/AMMOffer.cpp index 1152b673da..dd6b021689 100644 --- a/src/xrpld/app/paths/detail/AMMOffer.cpp +++ b/src/xrpld/app/paths/detail/AMMOffer.cpp @@ -11,11 +11,7 @@ AMMOffer::AMMOffer( TAmounts const& amounts, TAmounts const& balances, Quality const& quality) - : ammLiquidity_(ammLiquidity) - , amounts_(amounts) - , balances_(balances) - , quality_(quality) - , consumed_(false) + : ammLiquidity_(ammLiquidity), amounts_(amounts), balances_(balances), quality_(quality), consumed_(false) { } @@ -42,9 +38,7 @@ AMMOffer::amount() const template void -AMMOffer::consume( - ApplyView& view, - TAmounts const& consumed) +AMMOffer::consume(ApplyView& view, TAmounts const& consumed) { // Consumed offer must be less or equal to the original if (consumed.in > amounts_.in || consumed.out > amounts_.out) @@ -60,10 +54,7 @@ AMMOffer::consume( template TAmounts -AMMOffer::limitOut( - TAmounts const& offerAmount, - TOut const& limit, - bool roundUp) const +AMMOffer::limitOut(TAmounts const& offerAmount, TOut const& limit, bool roundUp) const { // Change the offer size proportionally to the original offer quality // to keep the strands quality order unchanged. The taker pays slightly @@ -85,16 +76,12 @@ AMMOffer::limitOut( template TAmounts -AMMOffer::limitIn( - TAmounts const& offerAmount, - TIn const& limit, - bool roundUp) const +AMMOffer::limitIn(TAmounts const& offerAmount, TIn const& limit, bool roundUp) const { // See the comments above in limitOut(). if (ammLiquidity_.multiPath()) { - if (auto const& rules = getCurrentTransactionRules(); - rules && rules->enabled(fixReducedOffersV2)) + if (auto const& rules = getCurrentTransactionRules(); rules && rules->enabled(fixReducedOffersV2)) return quality().ceil_in_strict(offerAmount, limit, roundUp); return quality().ceil_in(offerAmount, limit); @@ -108,45 +95,33 @@ AMMOffer::getQualityFunc() const { if (ammLiquidity_.multiPath()) return QualityFunction{quality(), QualityFunction::CLOBLikeTag{}}; - return QualityFunction{ - balances_, ammLiquidity_.tradingFee(), QualityFunction::AMMTag{}}; + return QualityFunction{balances_, ammLiquidity_.tradingFee(), QualityFunction::AMMTag{}}; } template bool -AMMOffer::checkInvariant( - TAmounts const& consumed, - beast::Journal j) const +AMMOffer::checkInvariant(TAmounts const& consumed, beast::Journal j) const { if (consumed.in > amounts_.in || consumed.out > amounts_.out) { - JLOG(j.error()) << "AMMOffer::checkInvariant failed: consumed " - << to_string(consumed.in) << " " - << to_string(consumed.out) << " amounts " - << to_string(amounts_.in) << " " + JLOG(j.error()) << "AMMOffer::checkInvariant failed: consumed " << to_string(consumed.in) << " " + << to_string(consumed.out) << " amounts " << to_string(amounts_.in) << " " << to_string(amounts_.out); return false; } Number const product = balances_.in * balances_.out; - auto const newBalances = TAmounts{ - balances_.in + consumed.in, balances_.out - consumed.out}; + auto const newBalances = TAmounts{balances_.in + consumed.in, balances_.out - consumed.out}; Number const newProduct = newBalances.in * newBalances.out; - if (newProduct >= product || - withinRelativeDistance(product, newProduct, Number{1, -7})) + if (newProduct >= product || withinRelativeDistance(product, newProduct, Number{1, -7})) return true; - JLOG(j.error()) << "AMMOffer::checkInvariant failed: balances " - << to_string(balances_.in) << " " - << to_string(balances_.out) << " new balances " - << to_string(newBalances.in) << " " - << to_string(newBalances.out) << " product/newProduct " - << product << " " << newProduct << " diff " - << (product != Number{0} - ? to_string((product - newProduct) / product) - : "undefined"); + JLOG(j.error()) << "AMMOffer::checkInvariant failed: balances " << to_string(balances_.in) << " " + << to_string(balances_.out) << " new balances " << to_string(newBalances.in) << " " + << to_string(newBalances.out) << " product/newProduct " << product << " " << newProduct << " diff " + << (product != Number{0} ? to_string((product - newProduct) / product) : "undefined"); return false; } diff --git a/src/xrpld/app/paths/detail/AmountSpec.h b/src/xrpld/app/paths/detail/AmountSpec.h index 5249bd30e0..690e67ae22 100644 --- a/src/xrpld/app/paths/detail/AmountSpec.h +++ b/src/xrpld/app/paths/detail/AmountSpec.h @@ -1,5 +1,4 @@ -#ifndef XRPL_PATH_IMPL_AMOUNTSPEC_H_INCLUDED -#define XRPL_PATH_IMPL_AMOUNTSPEC_H_INCLUDED +#pragma once #include #include @@ -106,8 +105,7 @@ template <> inline IOUAmount& get(EitherAmount& amt) { - XRPL_ASSERT( - !amt.native, "xrpl::get(EitherAmount&) : is not XRP"); + XRPL_ASSERT(!amt.native, "xrpl::get(EitherAmount&) : is not XRP"); return amt.iou; } @@ -131,8 +129,7 @@ template <> inline IOUAmount const& get(EitherAmount const& amt) { - XRPL_ASSERT( - !amt.native, "xrpl::get(EitherAmount const&) : is not XRP"); + XRPL_ASSERT(!amt.native, "xrpl::get(EitherAmount const&) : is not XRP"); return amt.iou; } @@ -140,8 +137,7 @@ template <> inline XRPAmount const& get(EitherAmount const& amt) { - XRPL_ASSERT( - amt.native, "xrpl::get(EitherAmount const&) : is XRP"); + XRPL_ASSERT(amt.native, "xrpl::get(EitherAmount const&) : is XRP"); return amt.xrp; } @@ -152,8 +148,7 @@ toAmountSpec(STAmount const& amt) amt.mantissa() < std::numeric_limits::max(), "xrpl::toAmountSpec(STAmount const&) : maximum mantissa"); bool const isNeg = amt.negative(); - std::int64_t const sMant = - isNeg ? -std::int64_t(amt.mantissa()) : amt.mantissa(); + std::int64_t const sMant = isNeg ? -std::int64_t(amt.mantissa()) : amt.mantissa(); AmountSpec result; result.native = isXRP(amt); @@ -201,5 +196,3 @@ toAmountSpec(EitherAmount const& ea, std::optional const& c) } } // namespace xrpl - -#endif diff --git a/src/xrpld/app/paths/detail/BookStep.cpp b/src/xrpld/app/paths/detail/BookStep.cpp index baef42a492..b9c8aa4e67 100644 --- a/src/xrpld/app/paths/detail/BookStep.cpp +++ b/src/xrpld/app/paths/detail/BookStep.cpp @@ -109,8 +109,7 @@ public: DebtDirection debtDirection(ReadView const& sb, StrandDirection dir) const override { - return ownerPaysTransferFee_ ? DebtDirection::issues - : DebtDirection::redeems; + return ownerPaysTransferFee_ ? DebtDirection::issues : DebtDirection::redeems; } std::optional @@ -120,8 +119,7 @@ public: } std::pair, DebtDirection> - qualityUpperBound(ReadView const& v, DebtDirection prevStepDir) - const override; + qualityUpperBound(ReadView const& v, DebtDirection prevStepDir) const override; std::pair, DebtDirection> getQualityFunc(ReadView const& v, DebtDirection prevStepDir) const override; @@ -130,22 +128,13 @@ public: offersUsed() const override; std::pair - revImp( - PaymentSandbox& sb, - ApplyView& afView, - boost::container::flat_set& ofrsToRm, - TOut const& out); + revImp(PaymentSandbox& sb, ApplyView& afView, boost::container::flat_set& ofrsToRm, TOut const& out); std::pair - fwdImp( - PaymentSandbox& sb, - ApplyView& afView, - boost::container::flat_set& ofrsToRm, - TIn const& in); + fwdImp(PaymentSandbox& sb, ApplyView& afView, boost::container::flat_set& ofrsToRm, TIn const& in); std::pair - validFwd(PaymentSandbox& sb, ApplyView& afView, EitherAmount const& in) - override; + validFwd(PaymentSandbox& sb, ApplyView& afView, EitherAmount const& in) override; // Check for errors frozen constraints. TER @@ -163,9 +152,7 @@ protected: { std::ostringstream ostr; ostr << name << ": " - << "\ninIss: " << book_.in.account - << "\noutIss: " << book_.out.account - << "\ninCur: " << book_.in.currency + << "\ninIss: " << book_.in.account << "\noutIss: " << book_.out.account << "\ninCur: " << book_.in.currency << "\noutCur: " << book_.out.currency; return ostr.str(); } @@ -193,11 +180,7 @@ private: // Return the unfunded and bad offers and the number of offers consumed. template std::pair, std::uint32_t> - forEachOffer( - PaymentSandbox& sb, - ApplyView& afView, - DebtDirection prevStepDebtDir, - Callback& callback) const; + forEachOffer(PaymentSandbox& sb, ApplyView& afView, DebtDirection prevStepDebtDir, Callback& callback) const; // Offer is either TOffer or AMMOffer template